language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 591 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
"""Support for discovering Wordpress robots."""
from lib.request import *
class wprobots(Request):
def __init__(self,url,data,kwargs):
self.url = url
self.data = data
self.kwargs = kwargs
Request.__init__(self,kwargs)
def run(self):
if self.kwargs['verbose'] is True:
info('Checking robots paths...')
url = Path(self.url,'robots.txt')
resp = self.send(url=url,method="GET")
if resp.status_code == 200 and resp.content != ("" or None):
if resp.url == url:
plus('Robots was found at: %s'%resp.url)
print("-"*40+"\n%s\n"%resp.content.decode('utf-8')+"-"*40)
|
PHP
|
UTF-8
| 3,627 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
<?php
function encrypt($str) {
return base64_encode($str);
}
function decrypt($str) {
return base64_decode($str);
}
function scan($dir) {
return array_values(array_diff(scandir($dir), array('..', '.')));
}
function isLocalhost() {
$whitelist = array(
'127.0.0.1',
'::1'
);
if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
return false;
}
return true;
}
function jsonToDebug($jsonText = '')
{
$arr = json_decode($jsonText, true);
$html = "";
if ($arr && is_array($arr)) {
$html .= htmlTable($arr);
}
return $html;
}
function singleTable($array) {
$html = '<table>';
foreach(array_chunk($array, 3) as $row) {
$html .= "<tr>";
foreach($row as $cell) {
$html .= "<td>$cell</td>";
}
$html .= "</tr>";
}
$html .= "</table>";
return $html;
}
function multiTable($array){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . htmlspecialchars($key) . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
function randomIP() {
return long2ip(mt_rand());
}
function filterInput($input, $lowercase = false) {
if($lowercase) {
return strtolower( stripslashes( htmlspecialchars($input) ) );
}
return stripslashes( htmlspecialchars($input) );
}
function rrmdir($directory, $delete = false)
{
$contents = glob($directory . '*');
foreach($contents as $item)
{
if (is_dir($item))
rrmdir($item . '/', true);
else
unlink($item);
}
if ($delete === true)
rmdir($directory);
}
function get_http_response_code($url) {
$headers = get_headers($url);
return substr($headers[0], 9, 3);
}
function getUserLocation() {
$user_ip = getIP();
if($user_ip) {
$user_location = getLocationByIp($user_ip);
}
if($user_location) {
return $user_location;
} else {
return $user_ip;
}
}
function getIP()
{
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
if ( ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) )
{
if(get_http_response_code("https://api.ipify.org") === "200"){
$ip = file_get_contents('https://api.ipify.org');
}
}
}
return $ip;
}
function getLocationByIp($ip) {
if(get_http_response_code("http://ipinfo.io/{$ip}") != "200"){
return false;
}
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
if(!$details->bogon) {
return "{$details->city}, {$details->country}";
}
return false;
}
function lastVisit() {
$inTwoMonths = 60 * 60 * 24 * 60 + time();
return setcookie('session_visit', date("H:i - m/d/y"), $inTwoMonths);
}
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
|
TypeScript
|
UTF-8
| 910 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
import * as Objects from '../objects'
import { APIBase } from '../APIBase'
import { IChastiKeyParam } from '../ChastiKey'
interface ILockeeDataGetParams extends IChastiKeyParam {
username?: string
discordid?: string
showdeleted?: number | boolean
}
/**
* **Query the API for the specified user**
* @export
* @class LockeeData
* @extends {APIBase}
*/
export class LockeeData extends APIBase {
protected repo = 'api'
protected name = 'LockeeData'
/**
* **Fetches the specified user's locks & Basic account data/stats**
* @param {ILockeeDataGetParams} params
* @returns {Promise<Objects.LockeeDataResponse>}
* @memberof LockeeData
*/
public async get(params: ILockeeDataGetParams): Promise<Objects.LockeeDataResponse> {
return new Objects.LockeeDataResponse(
await this.request<Objects.LockeeDataResponse, ILockeeDataGetParams>('lockeedata.php', params)
)
}
}
|
C++
|
UTF-8
| 5,960 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
/**
* @file SortPackageCtrl.h
* @author Philip Zellweger (philip.zellweger@hsr.ch)
* @brief The sort package controll class controlls the FSM to sort the current package in the available box
* To sort the package in the box it calls the navigation controll and chassis controll of the sortic
* and communicate to the robotarm
* @version 1.1
* @date 2019-12-16
*
* @copyright Copyright (c) 2019
*
*/
#ifndef SORTPACKAGECTRL_H_
#define SORTPACKAGECTRL_H_
#include <Arduino.h>
#include "LogConfiguration.h"
/**
* @brief Class to controll the FSM of the sort package controll
*
*/
class SortPackageCtrl
{
//======================Public===========================================================
public:
/**
* @brief Enum class which holds all positions
*
*/
enum class Line
{
UploadLine,
Line1,
Line2,
Line3,
ErrorLine
};
/**
* @brief Enum class which holds all events
*
*/
enum class Event
{
UploadPackage,
UnloadPackage,
PackageUnloaded,
Error,
Resume,
Reset,
NoEvent
};
/**
* @brief Construct a new Sort Package Ctrl object
*
* @param actualLine
* @param targetLine
*/
SortPackageCtrl(int *actualLine, int *targetLine);
/**
* @brief Destroy the Sort Package Ctrl object
*
*/
~SortPackageCtrl();
/**
* @brief Calls the do-function of the active state and hence generates Event
*
*/
void loop();
/**
* @brief Calls the do-function of the active state and hence generates Event
*
* @param event
*/
void loop(Event event);
//======================PRIVATE==========================================================
private:
/**
* @brief Enum class holds all possible states
*
*/
enum class State
{
waitForSort,
uploadPackage,
unloadPackage,
errorState,
resetState
};
State lastStateBeforeError; ///< holds the lastState bevor error to resume after error
State currentState; ///< holds the currentState of the FSM
State lastState; ///< holds the lastState of the FSM
Event currentEvent; ///< holds the currentEvent of the FSM
int *pActualLine = nullptr; ///< holds the acutal line of the sortic
int *pTargetLine = nullptr; ///< holds the target line of the sotic
/**
* @brief functionpointer to call the current states do-function
*
*/
Event (SortPackageCtrl::*doActionFPtr)(void) = nullptr;
/**
* @brief changes the state of the FSM based on the event
*
* @param e
*/
void process(Event e);
/**
* @brief entry action of the state wait for sort
*
*/
void entryAction_waitForSort();
/**
* @brief main action of the state wait for sort
*
* - do nothing and wait for I2C Event
*
* @return SortPackageCtrl::Event
*/
SortPackageCtrl::Event doAction_waitForSort();
/**
* @brief exit action of the state wait for sort
*
*/
void exitAction_waitForSort();
/**
* @brief entry action of the state upload package
*
*/
void entryAction_uploadPackage();
/**
* @brief main action of the state upload package
*
* - if is sortic not at the upload line, call navigation controll and driv to them
* - communicate with the robot arm to upload the package
*
* @todo integrate navigation controll and communication to robot arm
*
* @return SortPackageCtrl::Event
*/
SortPackageCtrl::Event doAction_uploadPackage();
/**
* @brief exit action of the state upload package
*
*/
void exitAction_uploadPackage();
/**
* @brief entry action of the state unload package
*
*/
void entryAction_unloadPackage();
/**
* @brief main action of the state unload package
* - call navigation controll with target line to drive to target line
* - communicate with the robot arm to unload the package
* - call navigation controll with upload line to drive back to upload line
*
* @todo integrate navigation controll and communication with robot arm
*
* @return SortPackageCtrl::Event
*/
SortPackageCtrl::Event doAction_unloadPackage();
/**
* @brief exit action of the state unload package
*
*/
void exitAction_unloadPackage();
/**
* @brief entry action of the state error state
*
*/
void entryAction_errorState();
/**
* @brief main action of the state error state
*
* @todo implement error state
*
* @return SortPackageCtrl::Event
*/
SortPackageCtrl::Event doAction_errorState();
/**
* @brief exit action of the state error state
*
*/
void exitAction_errorState();
/**
* @brief entry action of the state reset state
*
*/
void entryAction_resetState();
/**
* @brief main action of the state reset state
*
* @todo implement reset state
*
* @return Event
*/
Event doAction_resetState();
/**
* @brief exit action of the state reset state
*
*/
void exitAction_resetState();
/**
* @brief decodes the state of the sort package controll
*
* @param s
* @return String
*/
String decodeState(State s);
/**
* @brief decodes the event of the sort package controll
*
* @param e
* @return String
*/
String decodeEvent(Event e);
};
#endif // SORTPACKAGECTRL_H__
|
C++
|
UTF-8
| 787 | 2.890625 | 3 |
[] |
no_license
|
#define POT A3
#define MI_LED 11
#define MI_SERVO 9
int lectura=0;
int escritura=0;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
// initialize the digital pin as an output.
pinMode(MI_LED, OUTPUT);
pinMode(POT, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
lectura=analogRead(POT);
escritura=(255./1023.)*lectura;
//Ilumina led
analogWrite(MI_LED,escritura);
//Regular la salida no menor a 65, no mayor a 200
if ( escritura < 65 ) {
analogWrite(MI_SERVO,65);
} else {
if ( escritura > 200 ) {
analogWrite(MI_SERVO,200);
} else {
analogWrite(MI_SERVO,escritura);
}
}
//Imprimir el valor registrado
Serial.println(escritura);
delay(100);
}
|
Markdown
|
UTF-8
| 4,023 | 3.140625 | 3 |
[] |
no_license
|
# 18.07.04
#### 큰 그림
```
- JQuery 이용
- 말 장난치는 프로그램 만들기 (hangul js github)
```
#### 수업 흐름
~~~html
- rails는 jquery가 설정되어있음. ( 버전 : Rails 5.0.7 )
- 어떤 것을 쓸 것이냐? $ : $ 표시에 jQuery가 모두 들어있다고 보면 됨!
- jQuery 연습
* 3가지 형태
1 $('css파일').이벤트명(on은 안붙임!)(function() {} 이벤트 핸들러 );
$('.btn').mouseover(function() {alert ("안녕ㅋㅋ") });
2 $('.btn').on('이벤트명', function() {} 이벤트 핸들러 );
$('.btn').on('mouseover', function() { console.log("안녕ㅋㅋ") });
3
ex) mouse가 버튼위에 올라갔을 때, 버튼에 있는 btn-primary 클래스를 삭제하고, btn-danger 클래스 를준다.버튼에서 마우스가 내려왔을 때 다시 btn-danger 클래스를 삭제하고 btn-primary 클래스 를 추가한다. : 여러개의 이벤트 등록하기
요소에 class를 넣고 빼는 jquery function을 찾기.
var btn = $('.btn')
btn.on('mouseenter mouseout', function() {
// 2개의 이벤트 리스너 / 1개의 이벤트 핸들러
btn.removeClass("btn-primary").addClass("btn-danger") });
var btn = $('.btn')
btn.on('mouseenter mouseout', function() {
if (btn.hasClass('btn-danger')) {
btn.removeClass('btn-danger').addClass('btn-primary');
} else {
btn.removeClass('btn-primary').addClass('btn-danger');
}});
var btn = $('.btn')
btn.on('mouseenter mouseout', function() {
btn.toggleClass('btn-danger').toggleClass('btn-primary');
});
var btn = $('.btn')
btn.on('mouseenter mouseout', function() {
$(this).toggleClass('btn-danger').toggleClass('btn-primary');
console.dir(this); // => 일반 요소
console.dir($(this)); // => jquery 요소
}); // 이벤트 핸들러 내 this = 이벤트가 발생한 그 대상을 가리킴!
ex) 버튼에 마우스가 오버되었을 떄, 상단에 있는 이미지의 속성에 style 속성과 `width`:100px;의 속 성값을 부여한다.
var btn = $('.btn');
btn.on('mouseover'이벤트가 발생했을 때, function()을 작동시킴 {
$('img').attr('style', 'width: 100px;');
});
ex) innerText 바꾸는 법
var btn = $('.btn');
btn.on('mouseover', function(){
$('.card-title').text("안녕 ㅋㅋ");
});
(요소) (이벤트) (이벤트 리스너)
ex) jquery siblings / parent / find : 버튼에 마우스가 오버 됬을 때, 이벤트가 발생한 버튼 ($(this))과 상위 수준에 있는 요소(parent) 중에서 '.card-title'의 속성을 가진 친구를 찾아 (find) 텍스트를 변경 (text)시킨다.
btn.on('mouseover', function() {
// console.log($(this).siblings()); // 그 이벤트가 발생한 것의 조카들.
console.log($(this).siblings().find('.card-title'));
// 값을 못 찾음... find = 하위요소 밖에 안됨. sibling = 같은 위치, parents = 상위요소
$(this).parent().find('.card-title');
});
ex) 텍스트 변환기 ( 오타치는 사람 놀리기 )
index.html
````
<text area id="input" placeholder="변환할 텍스트를 입력해주세요."></text>
<button class="translate">바꿔줘</button>
<h3></h3>
= 해야할일 : input에 들어있는 텍스트 중에서
'관리'=> "고나리", "확인 => "호가인", "훤하다" => "허누하다"의 방식으로
텍스트를 오타로 바꾸는 이벤트 핸들러 작성하기.
https://github.com/e-/Hangul.js/ 에서 라이브러리를 받아서 자음과 모음을 분리하고, 다시 단어로 합치는 기능 살펴보기
=> 분리 해서 합치고
String.split('')
Array.map(function(el){});
Array.map(function(el){});
~~~
1. attom
2. jquery cdn uncompressed 된것 불러오기. header 부분에 넣어주기
|
PHP
|
UTF-8
| 4,467 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace Lemo\Bootstrap\Form\View\Helper;
use Laminas\Form\Element\Checkbox;
use Laminas\Form\Element\Hidden;
use Laminas\Form\Element\MultiCheckbox;
use Laminas\Form\Element\Radio;
use Laminas\Form\ElementInterface;
class FormGroupElement extends AbstractHelper
{
protected ?FormControlLabel $helperControlLabel = null;
protected ?FormControls $helperControls = null;
protected string $templateCloseTag = '</div>';
protected string $templateOpenTag = '<div class="form-group form-group-sm%s%s" id="form-group-%s">';
/**
* Display a Form
*
* @param ElementInterface $element
* @return string
*/
public function __invoke(ElementInterface $element): string
{
return $this->render($element);
}
/**
* @param ElementInterface $element
* @return string
*/
public function render(ElementInterface $element): string
{
$helperLabel = $this->getHelperControlLabel();
$helperControls = $this->getHelperControls();
$markup = '';
if ('' != $element->getLabel()) {
$markup .= $helperLabel($element);
}
// Add class to value options for multicheckbox and radio elements
$classCheckbox = null;
if ($element instanceof Checkbox && !$element instanceof MultiCheckbox) {
$classCheckbox = ' checkbox';
}
$id = $this->getId($element);
$id = trim(strtr($id, array('[' => '-', ']' => '')), '-');
// Add ID to value options
if ($element instanceof MultiCheckbox || $element instanceof Radio) {
$valueOptions = [];
foreach ($element->getValueOptions() as $value => $label) {
if (!is_array($label)) {
$valueOptions[$value] = [
'value' => $value,
'label' => $label,
'attributes' => [
'id' => $id . '-' . $value,
]
];
} else {
$valueOptions[$value] = $label;
}
}
$element->setValueOptions($valueOptions);
}
$markup .= '<div class="col-md-' . $this->getSizeForElement() . $classCheckbox . '">' . $helperControls($element) . '</div>';
return $this->openTag($element) . $markup . $this->closeTag();
}
/**
* Generate an opening form tag
*
* @param ElementInterface $element
* @return string
*/
public function openTag(ElementInterface $element): string
{
$id = $this->getId($element);
$id = trim(strtr($id, array('[' => '-', ']' => '')), '-');
$classHide = $element->getOption('hidden') ? ' hidden' : null;
$classError = null;
if ($element instanceof Hidden) {
$classHide = ' hidden';
}
if (count($element->getMessages()) > 0) {
$classError = ' has-error';
}
return sprintf(
$this->templateOpenTag,
$classHide,
$classError,
$id
);
}
/**
* Generate a closing form tag
*
* @return string
*/
public function closeTag(): string
{
return $this->templateCloseTag;
}
/**
* Retrieve the FormControlLabel helper
*
* @return FormControlLabel
*/
protected function getHelperControlLabel(): FormControlLabel
{
if ($this->helperControlLabel) {
return $this->helperControlLabel;
}
if (!$this->helperControlLabel instanceof FormControlLabel) {
$this->helperControlLabel = new FormControlLabel();
}
$this->helperControlLabel->setTranslator($this->getTranslator());
$this->helperControlLabel->setView($this->getView());
return $this->helperControlLabel;
}
/**
* Retrieve the FormControls helper
*
* @return FormControls
*/
protected function getHelperControls(): FormControls
{
if ($this->helperControls) {
return $this->helperControls;
}
if (!$this->helperControls instanceof FormControls) {
$this->helperControls = new FormControls();
}
$this->helperControls->setTranslator($this->getTranslator());
$this->helperControls->setView($this->getView());
return $this->helperControls;
}
}
|
Java
|
UTF-8
| 197 | 1.992188 | 2 |
[] |
no_license
|
package com.mycompany.l8q4;
public class TestFraction {
public static void main(String[] args) {
Fraction a = new Fraction(7,49);
System.out.println(a.reduced());
}
}
|
JavaScript
|
UTF-8
| 1,319 | 2.796875 | 3 |
[] |
no_license
|
const jwt = require("jsonwebtoken");
//acces check throw error if the user is not Authorized
//if user is authorized then req.userId is exist
exports.accesCheck = (req, res, next) => {
let check = req.get("Authorization");
if (!check) {
let error = new Error("Acces Denied");
error.statusCode = 401;
throw error;
}
const token = req.get("Authorization").split(" ")[1];
let decoded;
try {
decoded = jwt.verify(token, "thisissecretkey");
} catch (err) {
err.statusCode = 500;
throw err;
}
if (!decoded) {
let error = new Error("Acces Denied");
error.statusCode = 401;
throw error;
}
req.userId = decoded.userId;
next();
};
//userCheck does not give an error even if user is not Authorized, but the system will not recognised req.userId
exports.userCheck = (req, res, next) => {
let check = req.get("Authorization");
if (!check) {
next();
} else {
const token = req.get("Authorization").split(" ")[1];
let decoded;
try {
decoded = jwt.verify(token, "thisissecretkey");
} catch (err) {
err.statusCode = 500;
throw err;
}
if (!decoded) {
let error = new Error("Acces Denied");
error.statusCode = 401;
throw error;
}
req.userId = decoded.userId;
next();
}
};
|
Java
|
UTF-8
| 2,733 | 2.796875 | 3 |
[] |
no_license
|
package com.sy.emotion.judge.impl;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sy.emotion.judge.IJudge;
import com.sy.word.util.ResourceLoader;
import lombok.extern.slf4j.Slf4j;
/**
*
* @author cck
*/
@Slf4j
public abstract class AbstractJudge implements IJudge {
private static final String DENY_WORD_PATH = "classpath:deny";
private static final String DEGREE_WORD_PATH = "classpath:degree";
private static final String EMOTION_WORD_PATH = "classpath:emotion_word";
public final static int OTHTERS = 0;
public final static int DENY_WORD = 1;
public final static int DEGREE_WORD = 2;
public final static int EMOTION_WORD = 3;
/** 否定词 */
protected static Set<String> DENY_WORDS = new HashSet<>();
/** 程度词 */
protected static Map<String, Double> DEGREE_WORDS = new HashMap<>();
/** 情感词 */
protected static Map<String, Double> EMOTION_WORDS = new HashMap<>();
static {
init();
}
private static void init() {
List<String> denyWordList = ResourceLoader.load(DENY_WORD_PATH);
buildSet(DENY_WORDS, denyWordList);
List<String> emotionWordList = ResourceLoader.load(EMOTION_WORD_PATH);
buildMap(EMOTION_WORDS, emotionWordList);
List<String> degreeWordList = ResourceLoader.load(DEGREE_WORD_PATH);
buildMap(DEGREE_WORDS, degreeWordList);
}
private static void buildSet(Set<String> set, List<String> wordList) {
for (String word : wordList) {
DENY_WORDS.add(word);
}
}
private static void buildMap(Map<String, Double> map, List<String> wordList) {
for (String word : wordList) {
String[] split = word.split(":");
BigDecimal temVal = new BigDecimal(Double.valueOf(split[1]));
Double val = temVal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
map.put(split[0], val);
}
}
/** 判断是否是程度词或是反转词 */
protected static int judgeDenyOrDegreeWord(String word) {
if (DENY_WORDS.contains(word)) {
return DENY_WORD;
}
if (DEGREE_WORDS.containsKey(word)) {
return DEGREE_WORD;
}
return OTHTERS;
}
public static void main(String[] args) {
log.info("{}", DENY_WORDS);
log.info("{}", EMOTION_WORDS);
log.info("{}", DEGREE_WORDS);
}
}
|
Java
|
UTF-8
| 32,702 | 1.625 | 2 |
[] |
no_license
|
package br.edu.utfpr.dv.siacoes.window;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.vaadin.dialogs.ConfirmDialog;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.server.FontAwesome;
import com.vaadin.ui.Button;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Grid;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.Upload;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;
import com.vaadin.ui.renderers.DateRenderer;
import com.vaadin.ui.themes.ValoTheme;
import br.edu.utfpr.dv.siacoes.Session;
import br.edu.utfpr.dv.siacoes.bo.CampusBO;
import br.edu.utfpr.dv.siacoes.bo.InternshipBO;
import br.edu.utfpr.dv.siacoes.bo.InternshipJuryBO;
import br.edu.utfpr.dv.siacoes.bo.InternshipReportBO;
import br.edu.utfpr.dv.siacoes.bo.SigesConfigBO;
import br.edu.utfpr.dv.siacoes.components.CampusComboBox;
import br.edu.utfpr.dv.siacoes.components.CompanyComboBox;
import br.edu.utfpr.dv.siacoes.components.CompanySupervisorComboBox;
import br.edu.utfpr.dv.siacoes.components.DepartmentComboBox;
import br.edu.utfpr.dv.siacoes.components.FileUploader;
import br.edu.utfpr.dv.siacoes.components.FileUploaderListener;
import br.edu.utfpr.dv.siacoes.components.SupervisorComboBox;
import br.edu.utfpr.dv.siacoes.components.StudentComboBox;
import br.edu.utfpr.dv.siacoes.model.Campus;
import br.edu.utfpr.dv.siacoes.model.Internship;
import br.edu.utfpr.dv.siacoes.model.Document.DocumentType;
import br.edu.utfpr.dv.siacoes.model.Internship.InternshipType;
import br.edu.utfpr.dv.siacoes.model.InternshipJury;
import br.edu.utfpr.dv.siacoes.model.InternshipJuryFormReport;
import br.edu.utfpr.dv.siacoes.model.InternshipReport;
import br.edu.utfpr.dv.siacoes.model.JuryFormAppraiserDetailReport;
import br.edu.utfpr.dv.siacoes.model.JuryFormAppraiserReport;
import br.edu.utfpr.dv.siacoes.model.SigesConfig;
import br.edu.utfpr.dv.siacoes.model.InternshipReport.ReportType;
import br.edu.utfpr.dv.siacoes.model.Module.SystemModule;
import br.edu.utfpr.dv.siacoes.util.DateUtils;
import br.edu.utfpr.dv.siacoes.view.ListView;
public class EditInternshipWindow extends EditWindow {
private final Internship internship;
private final CampusComboBox comboCampus;
private final DepartmentComboBox comboDepartment;
private final StudentComboBox comboStudent;
private final SupervisorComboBox comboSupervisor;
private final CompanyComboBox comboCompany;
private final CompanySupervisorComboBox comboCompanySupervisor;
private final NativeSelect comboType;
private final TextArea textComments;
private final DateField startDate;
private final DateField endDate;
private final TextField textTotalHours;
private final TextField textReportTitle;
private final FileUploader uploadInternshipPlan;
private final Button buttonDownloadInternshipPlan;
private final FileUploader uploadFinalReport;
private final Button buttonDownloadFinalReport;
private final TabSheet tabContainer;
private Grid gridStudentReport;
private Grid gridSupervisorReport;
private Grid gridCompanySupervisorReport;
private final VerticalLayout layoutStudentReport;
private final VerticalLayout layoutSupervisorReport;
private final VerticalLayout layoutCompanySupervisorReport;
private final Upload uploadStudentReport;
private final Upload uploadSupervisorReport;
private final Upload uploadCompanySupervisorReport;
private final Button buttonDownloadStudentReport;
private final Button buttonDownloadSupervisorReport;
private final Button buttonDownloadCompanySupervisorReport;
private final Button buttonDeleteStudentReport;
private final Button buttonDeleteSupervisorReport;
private final Button buttonDeleteCompanySupervisorReport;
private SigesConfig config;
public EditInternshipWindow(Internship i, ListView parentView){
super("Editar Estágio", parentView);
if(i == null){
this.internship = new Internship();
}else{
this.internship = i;
}
try {
this.config = new SigesConfigBO().findByDepartment(this.internship.getDepartment().getIdDepartment());
} catch (Exception e) {
this.config = new SigesConfig();
}
this.comboCampus = new CampusComboBox();
this.comboCampus.setEnabled(false);
this.comboCampus.setRequired(true);
this.comboDepartment = new DepartmentComboBox(0);
this.comboDepartment.setEnabled(false);
this.comboDepartment.setRequired(true);
this.comboStudent = new StudentComboBox("Acadêmico");
this.comboStudent.setRequired(true);
this.comboSupervisor = new SupervisorComboBox("Orientador", Session.getSelectedDepartment().getDepartment().getIdDepartment(), new SigesConfigBO().getSupervisorFilter(Session.getSelectedDepartment().getDepartment().getIdDepartment()));
this.comboSupervisor.setRequired(true);
this.comboCompanySupervisor = new CompanySupervisorComboBox();
this.comboCompanySupervisor.setRequired(true);
this.comboCompany = new CompanyComboBox();
this.comboCompany.setRequired(true);
this.comboCompany.addValueChangeListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
if(comboCompany.getCompany() == null){
comboCompanySupervisor.setIdCompany(0);
}else{
comboCompanySupervisor.setIdCompany(comboCompany.getCompany().getIdCompany());
}
}
});
this.comboType = new NativeSelect("Tipo de Estágio");
this.comboType.setWidth("200px");
this.comboType.addItem(InternshipType.NONREQUIRED);
this.comboType.addItem(InternshipType.REQUIRED);
this.comboType.select(InternshipType.NONREQUIRED);
this.comboType.setNullSelectionAllowed(false);
this.comboType.setRequired(true);
this.startDate = new DateField("Data de Início");
this.startDate.setDateFormat("dd/MM/yyyy");
this.startDate.setRequired(true);
this.endDate = new DateField("Data de Término");
this.endDate.setDateFormat("dd/MM/yyyy");
this.textTotalHours = new TextField("Horas");
this.textTotalHours.setWidth("100px");
this.textTotalHours.setRequired(true);
this.textReportTitle = new TextField("Título do Relatório Final");
this.textReportTitle.setWidth("810px");
this.uploadInternshipPlan = new FileUploader("(Formato PDF, " + this.config.getMaxFileSizeAsString() + ")");
this.uploadInternshipPlan.setButtonCaption("Enviar Plano de Estágio");
this.uploadInternshipPlan.getAcceptedDocumentTypes().add(DocumentType.PDF);
this.uploadInternshipPlan.setMaxBytesLength(this.config.getMaxFileSize());
this.uploadInternshipPlan.setFileUploadListener(new FileUploaderListener() {
@Override
public void uploadSucceeded() {
if(uploadInternshipPlan.getUploadedFile() != null) {
internship.setInternshipPlan(uploadInternshipPlan.getUploadedFile());
}
buttonDownloadInternshipPlan.setVisible(true);
}
});
this.buttonDownloadInternshipPlan = new Button("Baixar Plano de Estágio", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
downloadInternshipPlan();
}
});
this.uploadFinalReport = new FileUploader("(Formato PDF, " + this.config.getMaxFileSizeAsString() + ")");
this.uploadFinalReport.setButtonCaption("Enviar Relatório Final");
this.uploadFinalReport.getAcceptedDocumentTypes().add(DocumentType.PDF);
this.uploadFinalReport.setMaxBytesLength(this.config.getMaxFileSize());
this.uploadFinalReport.setFileUploadListener(new FileUploaderListener() {
@Override
public void uploadSucceeded() {
if(uploadFinalReport.getUploadedFile() != null) {
internship.setFinalReport(uploadFinalReport.getUploadedFile());
}
buttonDownloadFinalReport.setVisible(true);
}
});
this.buttonDownloadFinalReport = new Button("Baixar Relatório Final", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
downloadFinalReport();
}
});
this.textComments = new TextArea();
this.textComments.setWidth("810px");
this.textComments.setHeight("350px");
HorizontalLayout h1 = new HorizontalLayout(this.comboCampus, this.comboDepartment);
h1.setSpacing(true);
HorizontalLayout h2 = new HorizontalLayout(this.comboStudent, this.comboSupervisor);
h2.setSpacing(true);
HorizontalLayout h3 = new HorizontalLayout(this.comboCompany, this.comboCompanySupervisor);
h3.setSpacing(true);
HorizontalLayout h4 = new HorizontalLayout(this.comboType, this.startDate, this.endDate, this.textTotalHours);
h4.setSpacing(true);
HorizontalLayout h5 = new HorizontalLayout(this.uploadInternshipPlan, this.uploadFinalReport);
h5.setSpacing(true);
VerticalLayout tab1 = new VerticalLayout(h1, h2, h3, h4, this.textReportTitle);
if(Session.isUserManager(SystemModule.SIGES)){
tab1.addComponent(h5);
}
tab1.setSpacing(true);
this.layoutStudentReport = new VerticalLayout();
ReportUploader studentReportUploader = new ReportUploader(ReportType.STUDENT);
this.uploadStudentReport = new Upload(null, studentReportUploader);
this.uploadStudentReport.addSucceededListener(studentReportUploader);
this.uploadStudentReport.setButtonCaption("Upload");
this.uploadStudentReport.setWidth("150px");
this.uploadStudentReport.setImmediate(true);
this.buttonDownloadStudentReport = new Button("Download", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
downloadStudentReport();
}
});
this.buttonDownloadStudentReport.setIcon(FontAwesome.DOWNLOAD);
this.buttonDownloadStudentReport.setWidth("150px");
this.buttonDeleteStudentReport = new Button("Excluir", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
deleteStudentReport();
}
});
this.buttonDeleteStudentReport.setIcon(FontAwesome.TRASH_O);
this.buttonDeleteStudentReport.addStyleName(ValoTheme.BUTTON_DANGER);
this.buttonDeleteStudentReport.setWidth("150px");
HorizontalLayout h6 = new HorizontalLayout(this.uploadStudentReport, this.buttonDownloadStudentReport, this.buttonDeleteStudentReport);
h6.setSpacing(true);
VerticalLayout tab2 = new VerticalLayout(this.layoutStudentReport, h6);
tab2.setSpacing(true);
this.layoutSupervisorReport = new VerticalLayout();
ReportUploader supervisorReportUploader = new ReportUploader(ReportType.SUPERVISOR);
this.uploadSupervisorReport = new Upload(null, supervisorReportUploader);
this.uploadSupervisorReport.addSucceededListener(supervisorReportUploader);
this.uploadSupervisorReport.setButtonCaption("Upload");
this.uploadSupervisorReport.setWidth("150px");
this.uploadSupervisorReport.setImmediate(true);
this.buttonDownloadSupervisorReport = new Button("Download", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
downloadSupervisorReport();
}
});
this.buttonDownloadSupervisorReport.setIcon(FontAwesome.DOWNLOAD);
this.buttonDownloadSupervisorReport.setWidth("150px");
this.buttonDeleteSupervisorReport = new Button("Excluir", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
deleteSupervisorReport();
}
});
this.buttonDeleteSupervisorReport.setIcon(FontAwesome.TRASH_O);
this.buttonDeleteSupervisorReport.addStyleName(ValoTheme.BUTTON_DANGER);
this.buttonDeleteSupervisorReport.setWidth("150px");
HorizontalLayout h7 = new HorizontalLayout(this.uploadSupervisorReport, this.buttonDownloadSupervisorReport, this.buttonDeleteSupervisorReport);
h7.setSpacing(true);
VerticalLayout tab3 = new VerticalLayout(this.layoutSupervisorReport, h7);
tab3.setSpacing(true);
this.layoutCompanySupervisorReport = new VerticalLayout();
ReportUploader companySupervisorReportUploader = new ReportUploader(ReportType.COMPANY);
this.uploadCompanySupervisorReport = new Upload(null, companySupervisorReportUploader);
this.uploadCompanySupervisorReport.addSucceededListener(companySupervisorReportUploader);
this.uploadCompanySupervisorReport.setButtonCaption("Upload");
this.uploadCompanySupervisorReport.setWidth("150px");
this.uploadCompanySupervisorReport.setImmediate(true);
this.buttonDownloadCompanySupervisorReport = new Button("Download", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
downloadCompanySupervisorReport();
}
});
this.buttonDownloadCompanySupervisorReport.setIcon(FontAwesome.DOWNLOAD);
this.buttonDownloadCompanySupervisorReport.setWidth("150px");
this.buttonDeleteCompanySupervisorReport = new Button("Excluir", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
deleteCompanySupervisorReport();
}
});
this.buttonDeleteCompanySupervisorReport.setIcon(FontAwesome.TRASH_O);
this.buttonDeleteCompanySupervisorReport.addStyleName(ValoTheme.BUTTON_DANGER);
this.buttonDeleteCompanySupervisorReport.setWidth("150px");
HorizontalLayout h8 = new HorizontalLayout(this.uploadCompanySupervisorReport, this.buttonDownloadCompanySupervisorReport, this.buttonDeleteCompanySupervisorReport);
h8.setSpacing(true);
VerticalLayout tab4 = new VerticalLayout(this.layoutCompanySupervisorReport, h8);
tab4.setSpacing(true);
this.tabContainer = new TabSheet();
this.tabContainer.setWidth("820px");
this.tabContainer.addStyleName(ValoTheme.TABSHEET_FRAMED);
this.tabContainer.addStyleName(ValoTheme.TABSHEET_EQUAL_WIDTH_TABS);
this.tabContainer.addStyleName(ValoTheme.TABSHEET_PADDED_TABBAR);
this.tabContainer.addTab(tab1, "Estágio");
this.tabContainer.addTab(tab2, "Acadêmico");
this.tabContainer.addTab(tab3, "Orientador");
this.tabContainer.addTab(tab4, "Supervisor");
this.tabContainer.addTab(this.textComments, "Observações");
this.addField(this.tabContainer);
this.addButton(this.buttonDownloadInternshipPlan);
this.addButton(this.buttonDownloadFinalReport);
this.buttonDownloadInternshipPlan.setWidth("250px");
this.buttonDownloadFinalReport.setWidth("250px");
if(!Session.isUserManager(SystemModule.SIGES)){
this.setSaveButtonEnabled(false);
this.uploadStudentReport.setVisible(false);
this.uploadSupervisorReport.setVisible(false);
this.uploadCompanySupervisorReport.setVisible(false);
this.buttonDeleteStudentReport.setVisible(false);
this.buttonDeleteSupervisorReport.setVisible(false);
this.buttonDeleteCompanySupervisorReport.setVisible(false);
}
this.loadInternship();
this.comboStudent.focus();
}
private void loadInternship(){
try{
CampusBO bo = new CampusBO();
Campus campus = bo.findByDepartment(this.internship.getDepartment().getIdDepartment());
if(campus != null){
this.comboCampus.setCampus(campus);
this.comboDepartment.setIdCampus(campus.getIdCampus());
this.comboDepartment.setDepartment(this.internship.getDepartment());
}else{
this.comboCampus.setCampus(Session.getSelectedDepartment().getDepartment().getCampus());
this.comboDepartment.setIdCampus(Session.getSelectedDepartment().getDepartment().getCampus().getIdCampus());
this.comboDepartment.setDepartment(Session.getSelectedDepartment().getDepartment());
}
}catch(Exception e){
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
}
this.comboStudent.setStudent(this.internship.getStudent());
this.comboSupervisor.setProfessor(this.internship.getSupervisor());
this.comboCompany.setCompany(this.internship.getCompany());
this.comboCompanySupervisor.setSupervisor(this.internship.getCompanySupervisor());
this.comboType.setValue(this.internship.getType());
this.startDate.setValue(this.internship.getStartDate());
this.endDate.setValue(this.internship.getEndDate());
this.textTotalHours.setValue(String.valueOf(this.internship.getTotalHours()));
this.textComments.setValue(this.internship.getComments());
this.textReportTitle.setValue(this.internship.getReportTitle());
this.internship.setReports(null);
this.loadReports();
this.buttonDownloadInternshipPlan.setVisible(this.internship.getInternshipPlan() != null);
this.buttonDownloadFinalReport.setVisible(this.internship.getFinalReport() != null);
if(this.internship.getIdInternship() != 0) {
try {
this.loadGrades();
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
this.showErrorNotification("Carregar Notas", "Não foi possível carregar as notas atribuídas pela banca.");
}
}
}
private void loadReports(){
this.gridStudentReport = new Grid();
this.gridStudentReport.addColumn("Relatório", Integer.class);
this.gridStudentReport.addColumn("Data de Upload", Date.class).setRenderer(new DateRenderer(new SimpleDateFormat("dd/MM/yyyy")));
this.gridStudentReport.setWidth("810px");
this.gridStudentReport.setHeight("300px");
this.gridSupervisorReport = new Grid();
this.gridSupervisorReport.addColumn("Relatório", Integer.class);
this.gridSupervisorReport.addColumn("Data de Upload", Date.class).setRenderer(new DateRenderer(new SimpleDateFormat("dd/MM/yyyy")));
this.gridSupervisorReport.setWidth("810px");
this.gridSupervisorReport.setHeight("300px");
this.gridCompanySupervisorReport = new Grid();
this.gridCompanySupervisorReport.addColumn("Relatório", Integer.class);
this.gridCompanySupervisorReport.addColumn("Data de Upload", Date.class).setRenderer(new DateRenderer(new SimpleDateFormat("dd/MM/yyyy")));
this.gridCompanySupervisorReport.setWidth("810px");
this.gridCompanySupervisorReport.setHeight("300px");
if(this.internship.getReports() == null){
try {
InternshipReportBO bo = new InternshipReportBO();
List<InternshipReport> list = bo.listByInternship(this.internship.getIdInternship());
this.internship.setReports(list);
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
this.showErrorNotification("Carregar Relatórios", e.getMessage());
}
}
if(this.internship.getReports() != null){
int student = 1, supervisor = 1, company = 1;
for(InternshipReport report : this.internship.getReports()){
if(report.getType() == ReportType.STUDENT){
this.gridStudentReport.addRow(student, report.getDate());
student++;
}else if(report.getType() == ReportType.SUPERVISOR){
this.gridSupervisorReport.addRow(supervisor, report.getDate());
supervisor++;
}else if(report.getType() == ReportType.COMPANY){
this.gridCompanySupervisorReport.addRow(company, report.getDate());
company++;
}
}
}
this.layoutStudentReport.removeAllComponents();
this.layoutStudentReport.addComponent(this.gridStudentReport);
this.layoutSupervisorReport.removeAllComponents();
this.layoutSupervisorReport.addComponent(this.gridSupervisorReport);
this.layoutCompanySupervisorReport.removeAllComponents();
this.layoutCompanySupervisorReport.addComponent(this.gridCompanySupervisorReport);
}
private void downloadInternshipPlan() {
try {
this.showReport(this.internship.getInternshipPlan());
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
this.showErrorNotification("Download do Plano de Estágio", e.getMessage());
}
}
private void downloadFinalReport() {
try {
this.showReport(this.internship.getFinalReport());
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
this.showErrorNotification("Download do Relatório Final", e.getMessage());
}
}
private int getStudentReportSelectedIndex(){
return getReportSelectedIndex(this.gridStudentReport.getSelectedRow(), ReportType.STUDENT);
}
private int getSupervisorReportSelectedIndex(){
return getReportSelectedIndex(this.gridSupervisorReport.getSelectedRow(), ReportType.SUPERVISOR);
}
private int getCompanySupervisorReportSelectedIndex(){
return getReportSelectedIndex(this.gridCompanySupervisorReport.getSelectedRow(), ReportType.COMPANY);
}
private int getReportSelectedIndex(Object itemId, ReportType type){
if(itemId == null){
return -1;
}else{
int selected = ((int)itemId) - 1, index = 0;;
for(int i = 0; i < this.internship.getReports().size(); i++){
if(this.internship.getReports().get(i).getType() == type){
if(index == selected){
return i;
}else{
index++;
}
}
}
return -1;
}
}
private void deleteStudentReport(){
this.deleteReport(this.getStudentReportSelectedIndex());
}
private void deleteSupervisorReport(){
this.deleteReport(this.getSupervisorReportSelectedIndex());
}
private void deleteCompanySupervisorReport(){
this.deleteReport(this.getCompanySupervisorReportSelectedIndex());
}
private void deleteReport(int index){
if(index == -1){
this.showWarningNotification("Selecionar Relatório", "Selecione o relatório para excluir.");
}else{
ConfirmDialog.show(UI.getCurrent(), "Confirma a exclusão do relatório?", new ConfirmDialog.Listener() {
public void onClose(ConfirmDialog dialog) {
if (dialog.isConfirmed()) {
internship.getReports().remove(index);
loadReports();
}
}
});
}
}
private void downloadStudentReport(){
this.downloadReport(this.getStudentReportSelectedIndex());
}
private void downloadSupervisorReport(){
this.downloadReport(this.getSupervisorReportSelectedIndex());
}
private void downloadCompanySupervisorReport(){
this.downloadReport(this.getCompanySupervisorReportSelectedIndex());
}
private void downloadReport(int index) {
if(index == -1) {
this.showWarningNotification("Selecionar Relatório", "Selecione o relatório para baixar.");
} else {
try {
this.showReport(this.internship.getReports().get(index).getReport());
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
this.showErrorNotification("Download do Relatório de Estágio", e.getMessage());
}
}
}
@Override
public void save() {
try{
InternshipBO bo = new InternshipBO();
if(this.uploadInternshipPlan.getUploadedFile() != null) {
this.internship.setInternshipPlan(this.uploadInternshipPlan.getUploadedFile());
}
if(this.uploadFinalReport.getUploadedFile() != null) {
this.internship.setFinalReport(this.uploadFinalReport.getUploadedFile());
}
this.internship.setDepartment(this.comboDepartment.getDepartment());
this.internship.setStudent(this.comboStudent.getStudent());
this.internship.setSupervisor(this.comboSupervisor.getProfessor());
this.internship.setCompany(this.comboCompany.getCompany());
this.internship.setCompanySupervisor(this.comboCompanySupervisor.getSupervisor());
this.internship.setType((InternshipType)this.comboType.getValue());
this.internship.setStartDate(this.startDate.getValue());
this.internship.setEndDate(this.endDate.getValue());
this.internship.setTotalHours(Integer.parseInt(this.textTotalHours.getValue()));
this.internship.setComments(this.textComments.getValue());
this.internship.setReportTitle(this.textReportTitle.getValue());
bo.save(Session.getIdUserLog(), this.internship);
this.showSuccessNotification("Salvar Estágio", "Estágio salvo com sucesso.");
this.parentViewRefreshGrid();
this.close();
}catch(Exception e){
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
this.showErrorNotification("Salvar Estágio", e.getMessage());
}
}
private Label buildLabel(String text, String width, boolean border, boolean center, boolean bold) {
Label label = new Label(text);
label.setWidth(width);
if(border)
label.addStyleName("Border");
if(center)
label.addStyleName("CenterText");
if(bold)
label.addStyleName("BoldText");
return label;
}
private void loadGrades() throws Exception {
if(this.internship.getIdInternship() != 0) {
SigesConfig config = new SigesConfig();
if(Session.isUserStudent()) {
SigesConfigBO sbo = new SigesConfigBO();
config = sbo.findByDepartment(this.internship.getDepartment().getIdDepartment());
}
if(config.isShowGradesToStudent() || Session.isUserProfessor()) {
InternshipJuryBO bo = new InternshipJuryBO();
InternshipJury jury = bo.findByInternship(this.internship.getIdInternship());
if((jury.getIdInternshipJury() != 0) && (bo.hasScores(jury.getIdInternshipJury()))) {
InternshipJuryFormReport report = bo.getJuryFormReport(jury.getIdInternshipJury());
TabSheet tab = new TabSheet();
tab.setSizeFull();
HorizontalLayout h1 = new HorizontalLayout();
h1.setWidth("100%");
h1.addComponent(this.buildLabel("Itens Avaliados", "100%", true, false, true));
h1.addComponent(this.buildLabel("Peso", "75px", true, true, true));
h1.addComponent(this.buildLabel("Aval. 1", "75px", true, true, true));
h1.addComponent(this.buildLabel("Aval. 2", "75px", true, true, true));
h1.setExpandRatio(h1.getComponent(0), 1f);
HorizontalLayout h2 = new HorizontalLayout();
h2.setWidth("100%");
h2.addComponent(this.buildLabel("Banca examinadora – avaliação do relatório e da apresentação da defesa (esta última se houver), com notas atribuídas seguindo os critérios descritos na ficha de avalição individual.", "100%", true, false, false));
h2.addComponent(this.buildLabel(String.format("%.2f", report.getAppraiser1Score()), "75px", true, true, false));
h2.addComponent(this.buildLabel(String.format("%.2f", report.getAppraiser2Score()), "75px", true, true, false));
h2.setExpandRatio(h2.getComponent(0), 1f);
h2.getComponent(1).setHeight("100%");
h2.getComponent(2).setHeight("100%");
HorizontalLayout h3 = new HorizontalLayout();
h3.setWidth("100%");
h3.addComponent(this.buildLabel("Nota banca examinadora (média aritmética)", "100%", true, false, true));
h3.addComponent(this.buildLabel(String.format("%.1f", report.getAppraisersPonderosity()), "75px", true, true, false));
h3.addComponent(this.buildLabel(String.format("%.2f", (report.getAppraiser1Score() + report.getAppraiser2Score()) / 2), "150px", true, true, false));
h3.setExpandRatio(h3.getComponent(0), 1f);
HorizontalLayout h4 = new HorizontalLayout();
h4.setWidth("100%");
h4.addComponent(this.buildLabel("Supervisão - Nota atribuída a partir do relatório de avaliação do supervisor.", "100%", true, false, false));
h4.addComponent(this.buildLabel(String.format("%.1f", report.getCompanySupervisorPonderosity()), "75px", true, true, false));
h4.addComponent(this.buildLabel(String.format("%.2f", report.getCompanySupervisorScore()), "150px", true, true, false));
h4.setExpandRatio(h4.getComponent(0), 1f);
HorizontalLayout h5 = new HorizontalLayout();
h5.setWidth("100%");
h5.addComponent(this.buildLabel("Orientação - Nota atribuída a partir do relatório de acompanhamento e relatório final.", "100%", true, false, false));
h5.addComponent(this.buildLabel(String.format("%.1f", report.getSupervisorPonderosity()), "75px", true, true, false));
h5.addComponent(this.buildLabel(String.format("%.2f", report.getSupervisorScore()), "150px", true, true, false));
h5.setExpandRatio(h5.getComponent(0), 1f);
HorizontalLayout h6 = new HorizontalLayout();
h6.setWidth("100%");
h6.addComponent(this.buildLabel("NOTA FINAL (MÉDIA PONDERADA)", "100%", true, false, true));
h6.addComponent(this.buildLabel(String.format("%.2f", report.getFinalScore()), "150px", true, true, false));
h6.setExpandRatio(h6.getComponent(0), 1f);
VerticalLayout layoutGrades = new VerticalLayout(h1, h2, h3, h4, h5, h6);
layoutGrades.setWidth("100%");
TextArea textComments = new TextArea("Comentários");
textComments.setWidth("100%");
textComments.setHeight("75px");
textComments.setEnabled(false);
textComments.setValue(report.getComments());
VerticalLayout tab1 = new VerticalLayout(layoutGrades, textComments);
tab1.setSpacing(true);
tab.addTab(tab1, "Geral");
for(JuryFormAppraiserReport appraiser : report.getAppraisers()) {
if(!appraiser.getName().equals(this.internship.getSupervisor().getName()) || jury.isSupervisorFillJuryForm()) {
TextField textAppraiser = new TextField("Avaliador:");
textAppraiser.setWidth("100%");
textAppraiser.setEnabled(false);
textAppraiser.setValue(appraiser.getName());
Grid gridScores = new Grid();
gridScores.setWidth("100%");
gridScores.setHeight("150px");
gridScores.addColumn("Quesito", String.class);
gridScores.addColumn("Peso", Double.class);
gridScores.addColumn("Nota", Double.class);
for(JuryFormAppraiserDetailReport scores : appraiser.getDetail()) {
gridScores.addRow(scores.getEvaluationItem(), scores.getPonderosity(), scores.getScore());
}
TextArea textAppraiserComments = new TextArea("Comentários");
textAppraiserComments.setWidth("100%");
textAppraiserComments.setHeight("75px");
textAppraiserComments.setEnabled(false);
textAppraiserComments.setValue(appraiser.getComments());
VerticalLayout tabAppraiser = new VerticalLayout(textAppraiser, gridScores, textAppraiserComments);
tabAppraiser.setSpacing(true);
tab.addTab(tabAppraiser, appraiser.getDescription());
}
}
this.tabContainer.addTab(tab, "Avaliação");
}
}
}
}
@SuppressWarnings("serial")
class ReportUploader implements Receiver, SucceededListener {
private File tempFile;
private ReportType type;
public ReportUploader(ReportType type){
this.type = type;
}
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
try {
if(DocumentType.fromMimeType(mimeType) != DocumentType.PDF){
throw new Exception("O arquivo precisa estar no formato PDF.");
}
tempFile = File.createTempFile(filename, "tmp");
tempFile.deleteOnExit();
return new FileOutputStream(tempFile);
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
showErrorNotification("Carregamento do Arquivo", e.getMessage());
}
return null;
}
@Override
public void uploadSucceeded(SucceededEvent event) {
try {
FileInputStream input = new FileInputStream(tempFile);
if(input.available() > (10 * 1024 * 1024)){
throw new Exception("O arquivo precisa ter um tamanho máximo de 5 MB.");
}
byte[] buffer = new byte[input.available()];
input.read(buffer);
InternshipReport report = new InternshipReport();
report.setDate(DateUtils.getToday().getTime());
report.setType(this.type);
report.setReport(buffer);
internship.getReports().add(report);
loadReports();
showSuccessNotification("Carregamento do Arquivo", "O arquivo foi enviado com sucesso.\\n\\nClique em SALVAR para concluir a submissão.");
} catch (Exception e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
showErrorNotification("Carregamento do Arquivo", e.getMessage());
}
}
}
}
|
Python
|
UTF-8
| 611 | 3.71875 | 4 |
[] |
no_license
|
from tkinter import *
class DisplayGrid:
def __init__(self):
window = Tk()
window.title('Display Grid')
self.canvas = Canvas(window, width = 300, height = 300, bg = 'white')
self.canvas.pack()
for i in range(9):
self.canvas.create_line(10, 10 + i * 20,
170, 10 + i * 20, fill = 'blue')
for j in range(9):
self.canvas.create_line(10 + j * 20, 10,
10 + j * 20, 170, fill = 'red')
window.mainloop()
DisplayGrid()
|
C++
|
UTF-8
| 15,695 | 3.546875 | 4 |
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
/*******************************************************************\
Module: Unit tests for range
Author: Romain Brenguier, romain.brenguier@diffblue.com
\*******************************************************************/
#include <list>
#include <vector>
#include <testing-utils/use_catch.h>
#include <util/range.h>
/// Trivial example template function requiring a container to have a
/// `value_type`.
template <typename containert>
typename containert::value_type front(containert container)
{
return *container.begin();
}
SCENARIO("range tests", "[core][util][range]")
{
GIVEN("A vector with three strings")
{
std::vector<std::string> list;
list.emplace_back("abc");
list.emplace_back("cdef");
list.emplace_back("acdef");
THEN("Use range-for to compute the total length")
{
const auto range = make_range(list);
std::size_t total_length = 0;
for(const auto &s : range)
total_length += s.length();
REQUIRE(total_length == 12);
}
THEN("Use map to compute individual lengths")
{
const auto length_range =
make_range(list).map([](const std::string &s) { return s.length(); });
auto it = length_range.begin();
REQUIRE(*it == 3);
++it;
REQUIRE(*it == 4);
++it;
REQUIRE(*it == 5);
++it;
REQUIRE(it == length_range.end());
}
THEN("Filter using lengths")
{
const auto filtered_range = make_range(list).filter(
[&](const std::string &s) { return s.length() == 4; });
auto it = filtered_range.begin();
REQUIRE(*it == "cdef");
++it;
REQUIRE(it == filtered_range.end());
}
THEN("Drop first 2 elements")
{
auto range = make_range(list);
auto drop_range = range.drop(2);
auto it = drop_range.begin();
REQUIRE(*it == "acdef");
drop_range = std::move(drop_range).drop(1);
REQUIRE(drop_range.empty());
// Check the original is unmodified
REQUIRE(!range.empty());
REQUIRE(*range.begin() == "abc");
}
THEN("Drop first 5 elements")
{
auto range = make_range(list);
auto skip_range = range.drop(5);
REQUIRE(skip_range.empty());
// Check the original is unmodified
REQUIRE(!range.empty());
REQUIRE(*range.begin() == "abc");
}
THEN("Drop first 2 elements, move version")
{
auto range = make_range(list);
range = std::move(range).drop(2);
REQUIRE(!range.empty());
auto it = range.begin();
REQUIRE(*it == "acdef");
range = std::move(range).drop(1);
REQUIRE(range.empty());
}
THEN("Drop first 5 elements, move version")
{
auto range = make_range(list);
range = std::move(range).drop(5);
REQUIRE(range.empty());
}
THEN(
"A const instance of a `filter_iteratort` can mutate the input "
"collection.")
{
const auto it =
make_range(list)
.filter([&](const std::string &s) { return s.length() == 3; })
.begin();
*it += "x";
REQUIRE(*list.begin() == "abcx");
}
THEN("Filter, map and use range-for on the same list")
{
const auto range =
make_range(list)
.filter([&](const std::string &s) -> bool { return s[0] == 'a'; })
.map([&](const std::string &s) { return s.length(); });
// Note that everything is performed on the fly, so none of the filter
// and map functions have been computed yet, and no intermediary container
// is created.
std::size_t total = 0;
for(const auto &l : range)
total += l;
REQUIRE(total == 8);
}
}
GIVEN("A const vector of ints")
{
const std::vector<int> input{1, 2, 3, 4};
THEN("Filter the vector using range.")
{
const auto odds_range =
make_range(input).filter([](const int number) { return number % 2; });
const std::vector<int> odds{odds_range.begin(), odds_range.end()};
const std::vector<int> expected_odds{1, 3};
REQUIRE(odds == expected_odds);
}
THEN(
"The unit testing template function requiring `value_type` works with "
"`std::vector`.")
{
REQUIRE(front(input) == 1);
}
THEN(
"A range can be used with a template function expecting a container "
"which has a `value_type`.")
{
REQUIRE(front(make_range(input)) == 1);
}
THEN("Map over the vector using range.")
{
const auto plus_one_range =
make_range(input).map([](const int number) { return number + 1; });
const std::vector<int> plus_one_collection{plus_one_range.begin(),
plus_one_range.end()};
const std::vector<int> expected_output{2, 3, 4, 5};
REQUIRE(plus_one_collection == expected_output);
};
}
GIVEN("Two const vectors of ints")
{
const std::vector<int> input1{1, 2};
const std::vector<int> input2{3, 4};
THEN("Concat the vectors using range.")
{
const auto range = make_range(input1).concat(make_range(input2));
const std::vector<int> output{range.begin(), range.end()};
const std::vector<int> expected{1, 2, 3, 4};
REQUIRE(output == expected);
};
}
GIVEN("Two non-const vectors of ints.")
{
std::vector<int> input1{1, 2};
std::vector<int> input2{3, 4};
THEN(
"Const instances of `concat_iteratort` should enable the input "
"collections to be mutated.")
{
const auto concat_range = make_range(input1).concat(make_range(input2));
int x = 5;
for(auto it = concat_range.begin(); it != concat_range.end(); ++it, ++x)
{
const auto const_it = it;
*const_it = x;
}
std::vector<int> expected_result1{5, 6};
std::vector<int> expected_result2{7, 8};
REQUIRE(input1 == expected_result1);
REQUIRE(input2 == expected_result2);
}
}
GIVEN("A vectors of int and a list of strings of same sizes.")
{
std::vector<int> int_vector{1, 2};
std::list<std::string> string_list{"foo", "bar"};
WHEN("We zip the vector and the list")
{
auto range = make_range(int_vector).zip(string_list);
REQUIRE(!range.empty());
THEN("First pair is (1, foo)")
{
const std::pair<int, std::string> first_pair = *range.begin();
REQUIRE(first_pair.first == 1);
REQUIRE(first_pair.second == "foo");
}
range = std::move(range).drop(1);
THEN("Second pair is (2, bar)")
{
const std::pair<int, std::string> second_pair = *range.begin();
REQUIRE(second_pair.first == 2);
REQUIRE(second_pair.second == "bar");
}
range = std::move(range).drop(1);
THEN("Range is empty")
{
REQUIRE(range.empty());
}
}
}
GIVEN("A constant vectors of int and a list of strings of same sizes.")
{
const std::vector<int> int_vector{41, 27};
const std::list<std::string> string_list{"boo", "far"};
WHEN("We zip the vector and the list")
{
auto range = make_range(int_vector).zip(string_list);
REQUIRE(!range.empty());
THEN("First pair is (1, foo)")
{
const std::pair<int, std::string> first_pair = *range.begin();
REQUIRE(first_pair.first == 41);
REQUIRE(first_pair.second == "boo");
}
range = std::move(range).drop(1);
THEN("Second pair is (2, bar)")
{
const std::pair<int, std::string> second_pair = *range.begin();
REQUIRE(second_pair.first == 27);
REQUIRE(second_pair.second == "far");
}
range = std::move(range).drop(1);
THEN("Range is empty")
{
REQUIRE(range.empty());
}
}
}
GIVEN("Two vectors, where the first is shorter.")
{
const std::vector<int> int_vector{814, 51};
const std::vector<std::string> string_vector{"foo", "bar", "baz", "bay"};
WHEN("We zip the vectors with same_size=false")
{
auto range = make_range(int_vector).zip<false>(string_vector);
REQUIRE(!range.empty());
THEN("First pair is (814, foo)")
{
const std::pair<int, std::string> first_pair = *range.begin();
REQUIRE(first_pair.first == 814);
REQUIRE(first_pair.second == "foo");
}
auto second_range = range.drop(1);
THEN("Begin iterator when first element is dropped is different")
{
REQUIRE(second_range.begin() != range.begin());
}
THEN("Second pair is (51, bar)")
{
const std::pair<int, std::string> second_pair = *second_range.begin();
REQUIRE(second_pair.first == 51);
REQUIRE(second_pair.second == "bar");
}
auto third_range = second_range.drop(1);
THEN("Range is empty")
{
REQUIRE(third_range.begin() != second_range.begin());
REQUIRE(third_range.empty());
}
}
WHEN("We zip the vectors with same_size=true")
{
auto range = make_range(int_vector).zip<true>(string_vector);
REQUIRE(!range.empty());
THEN("First pair is (814, foo)")
{
const std::pair<int, std::string> first_pair = *range.begin();
REQUIRE(first_pair.first == 814);
REQUIRE(first_pair.second == "foo");
}
auto second_range = range.drop(1);
THEN("Begin iterator when first element is dropped is different")
{
REQUIRE(second_range.begin() != range.begin());
}
THEN("Second pair is (51, bar)")
{
const std::pair<int, std::string> second_pair = *second_range.begin();
REQUIRE(second_pair.first == 51);
REQUIRE(second_pair.second == "bar");
}
THEN("An invariant throw as we reach the end of the first range")
{
cbmc_invariants_should_throwt invariants_throw;
REQUIRE_THROWS_AS(second_range.drop(1), invariant_failedt);
}
}
}
GIVEN("Two vectors, where the second is shorter.")
{
const std::vector<std::string> string_vector{"foo", "bar", "baz", "bay"};
const std::vector<int> int_vector{814, 51};
WHEN("We zip the vectors with same_size=false")
{
auto range = make_range(string_vector).zip<false>(int_vector);
REQUIRE(!range.empty());
THEN("First pair is (foo, 814)")
{
const std::pair<std::string, int> first_pair = *range.begin();
REQUIRE(first_pair.first == "foo");
REQUIRE(first_pair.second == 814);
}
auto second_range = range.drop(1);
THEN("Begin iterator when first element is dropped is different")
{
REQUIRE(second_range.begin() != range.begin());
}
THEN("Second pair is (51, bar)")
{
const std::pair<std::string, int> second_pair = *second_range.begin();
REQUIRE(second_pair.first == "bar");
REQUIRE(second_pair.second == 51);
}
auto third_range = second_range.drop(1);
THEN("Range is empty")
{
REQUIRE(third_range.begin() != second_range.begin());
REQUIRE(third_range.empty());
}
}
WHEN("We zip the vectors with same_size=true")
{
auto range = make_range(string_vector).zip<true>(int_vector);
REQUIRE(!range.empty());
THEN("First pair is (foo, 814)")
{
const std::pair<std::string, int> first_pair = *range.begin();
REQUIRE(first_pair.first == "foo");
REQUIRE(first_pair.second == 814);
}
auto second_range = range.drop(1);
THEN("Begin iterator when first element is dropped is different")
{
REQUIRE(second_range.begin() != range.begin());
}
THEN("Second pair is (bar, 51)")
{
const std::pair<std::string, int> second_pair = *second_range.begin();
REQUIRE(second_pair.first == "bar");
REQUIRE(second_pair.second == 51);
}
THEN("An invariant throw as we reach the end of the first range")
{
cbmc_invariants_should_throwt invariants_throw;
REQUIRE_THROWS_AS(second_range.drop(1), invariant_failedt);
}
}
}
}
class move_onlyt
{
public:
move_onlyt(move_onlyt &&) = default;
move_onlyt &operator=(move_onlyt &&) = default;
move_onlyt(const move_onlyt &) = delete;
move_onlyt &operator=(const move_onlyt &) = delete;
explicit move_onlyt(int value) : value{value} {};
int value = 0;
};
bool is_odd(const move_onlyt &move_only)
{
return move_only.value % 2 != 0;
}
const auto add = [](int left) {
return [=](const move_onlyt &right) { return left + right.value; };
};
SCENARIO(
"Range tests, with collections of move only typed values.",
"[core][util][range]")
{
GIVEN("A vector of move only typed values.")
{
std::vector<move_onlyt> input;
for(int i = 1; i <= 10; ++i)
input.emplace_back(i);
THEN("Values from a range of made from the vector can be moved.")
{
const auto input_range = make_range(input);
move_onlyt destination{std::move(*input_range.begin())};
REQUIRE(destination.value == 1);
}
THEN("A range of made from the vector can be filtered.")
{
const auto odds_filter = make_range(input).filter(is_odd);
const std::size_t total =
std::distance(odds_filter.begin(), odds_filter.end());
REQUIRE(total == 5);
auto iterator = odds_filter.begin();
REQUIRE((iterator++)->value == 1);
REQUIRE((iterator++)->value == 3);
REQUIRE((iterator++)->value == 5);
REQUIRE((iterator++)->value == 7);
REQUIRE((iterator++)->value == 9);
}
THEN("Values from a filtered range made from the vector can be moved.")
{
std::vector<move_onlyt> odds;
for(move_onlyt &odd : make_range(input).filter(is_odd))
odds.emplace_back(std::move(odd));
REQUIRE(odds.size() == 5);
REQUIRE(odds[0].value == 1);
REQUIRE(odds[1].value == 3);
REQUIRE(odds[2].value == 5);
REQUIRE(odds[3].value == 7);
REQUIRE(odds[4].value == 9);
}
THEN("Map can be applied to a range of move only typed values.")
{
std::vector<int> results;
for(int result : make_range(input).map(add(1)))
results.push_back(result);
const std::vector<int> expected_results{2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
REQUIRE(results == expected_results);
}
}
GIVEN("Two vectors containing move only types values.")
{
std::vector<move_onlyt> input1;
for(int i = 1; i <= 3; ++i)
input1.emplace_back(i);
std::vector<move_onlyt> input2;
for(int i = 7; i <= 9; ++i)
input2.emplace_back(i);
THEN("Values from concatenated ranges made from the vector can be moved.")
{
std::vector<move_onlyt> both_inputs;
for(move_onlyt &input : make_range(input1).concat(make_range(input2)))
both_inputs.emplace_back(std::move(input));
REQUIRE(both_inputs.size() == 6);
REQUIRE(both_inputs[0].value == 1);
REQUIRE(both_inputs[1].value == 2);
REQUIRE(both_inputs[2].value == 3);
REQUIRE(both_inputs[3].value == 7);
REQUIRE(both_inputs[4].value == 8);
REQUIRE(both_inputs[5].value == 9);
}
}
GIVEN("A const vector of ints.")
{
const std::vector<int> input{1, 2, 3, 4, 5};
THEN("The vector can be mapped into a range of move-only types")
{
std::vector<move_onlyt> results;
const auto make_move_only = [](int i) { return move_onlyt{i}; };
for(auto &incremented : make_range(input).map(make_move_only))
results.emplace_back(std::move(incremented));
REQUIRE(results.size() == 5);
REQUIRE(results[0].value == 1);
REQUIRE(results[1].value == 2);
REQUIRE(results[2].value == 3);
REQUIRE(results[3].value == 4);
REQUIRE(results[4].value == 5);
}
}
}
|
C++
|
UTF-8
| 18,808 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
//
// Created by Han Zhao on 5/7/15.
//
#include "SPNetwork.h"
#include <set>
#include <stack>
#include <queue>
#include <random>
namespace SPN {
// Constructor of SPN
SPNetwork::SPNetwork(SPNNode *root) {
root_ = root;
}
// Destructor of SPN
SPNetwork::~SPNetwork() {
// Delete all the nodes
bfs_traverse([](SPNNode *node) {
delete node;
});
}
double SPNetwork::inference(const std::vector<double> &input, bool verbose) {
std::vector<std::vector<double>> inputs;
inputs.push_back(input);
const std::vector<double> &probs = inference(inputs, verbose);
return probs[0];
}
// Batch mode method for inference
std::vector<double> SPNetwork::inference(const std::vector<std::vector<double>> &inputs, bool verbose) {
size_t num_inputs = inputs.size();
std::vector<bool> mask(inputs[0].size(), false);
std::vector<double> probs;
for (size_t n = 0; n < num_inputs; ++n) {
probs.push_back(exp(EvalDiff(inputs[n], mask)));
}
return probs;
}
double SPNetwork::logprob(const std::vector<double> &input, bool verbose) {
std::vector<std::vector<double>> inputs;
inputs.push_back(input);
const std::vector<double> &logps = logprob(inputs, verbose);
return logps[0];
}
std::vector<double> SPNetwork::logprob(const std::vector<std::vector<double>> &inputs, bool verbose) {
size_t num_inputs = inputs.size();
std::vector<bool> mask(inputs[0].size(), false);
std::vector<double> logps;
for (size_t n = 0; n < num_inputs; ++n) {
logps.push_back(EvalDiff(inputs[n], mask));
}
return logps;
}
void SPNetwork::init() {
// Recursive remove connected sum nodes and product nodes
std::unordered_set<SPNNode *> visited;
visited.insert(root_);
condense_(root_, visited);
// Re-build mappings and compute network statistics
compute_statistics_();
// Check structure
assert(check_structure_());
build_order_();
}
void SPNetwork::build_order_() {
// Build top-down order and bottom-up order using topological ordering algorithm.
std::queue<SPNNode *> active_list;
// r_parents records the number of parents of a specific node during the topological
// ordering algorithm.
size_t r_parents[num_nodes_];
for (size_t i = 0; i < num_nodes_; ++i) {
r_parents[i] = id2node_[i]->num_parents();
}
SPNNode *pt = nullptr;
active_list.push(root_);
assert (r_parents[root_->id_] == 0);
while (!active_list.empty()) {
pt = active_list.front();
backward_order_.push_back(pt);
if (pt->type() == SPNNodeType::VARNODE) {
dist_nodes_.push_back((VarNode *) pt);
}
for (SPNNode *child : pt->children()) {
r_parents[child->id_] -= 1;
if (r_parents[child->id_] == 0) {
active_list.push(child);
}
}
active_list.pop();
}
assert (backward_order_.size() == num_nodes_);
for (auto iter = backward_order_.rbegin(); iter != backward_order_.rend(); ++iter) {
forward_order_.push_back(*iter);
}
// Using the forward order to build the scope of each node.
for (auto node : forward_order_) {
if (node->type() == SPNNodeType::SUMNODE) {
assert(node->scope().size() == 0);
for (int t : node->children()[0]->scope()) {
node->add_to_scope(t);
}
} else if (node->type() == SPNNodeType::PRODNODE) {
assert(node->scope().size() == 0);
for (SPNNode *child : node->children()) {
for (int t : child->scope())
node->add_to_scope(t);
}
} else {
// SPNNodeType == VARNODE
assert(node->scope().size() == 1);
}
}
// Check
std::cout << "Type of root node = " << root_->type_string() << std::endl;
std::cout << "Size of scope = " << root_->scope().size() << ". Scope of the root node: " << std::endl;
for (int t : root_->scope())
std::cout << t << " ";
std::cout << std::endl;
}
void SPNetwork::condense_(SPNNode *node, std::unordered_set<SPNNode *> &visited) {
if (node->num_children() == 0) return;
// Post processing
for (const auto &child : node->children()) {
// Condense unvisited children
if (visited.find(child) == visited.end()) {
visited.insert(child);
condense_(child, visited);
}
}
// All the sub-SPNs have been condensed
size_t num_children = node->num_children();
bool is_grandson = false;
// Depends on whether current node is SumNode or not
if (node->type() == SPNNodeType::SUMNODE) {
double node_weight = 0.0, son_weight = 0.0;
std::vector<SPNNode *> new_children;
std::vector<double> new_weights;
for (size_t i = 0; i < num_children; ++i) {
if (node->children_[i]->type() == node->type()) {
node_weight = ((SumNode *) node)->weights_[i];
size_t num_grandsons = node->children_[i]->children_.size();
for (size_t j = 0; j < num_grandsons; ++j) {
// Check whether the grandson to be added already existed
is_grandson = false;
son_weight = ((SumNode *) node->children_[i])->weights_[j];
for (size_t k = 0; k < new_children.size(); ++k) {
if (new_children[k] == node->children_[i]->children_[j]) {
// the grandson has already been added, then update the weight directly
is_grandson = true;
new_weights[k] += node_weight * son_weight;
break;
}
}
if (is_grandson) continue;
new_children.push_back(node->children_[i]->children_[j]);
new_weights.push_back(node_weight * son_weight);
// Update parent list of newly added grandson
node->children_[i]->children_[j]->add_parent(node);
}
// Update parent list of children[i]
node->children_[i]->remove_parent(node);
} else {
new_children.push_back(node->children_[i]);
new_weights.push_back(((SumNode *) node)->weights_[i]);
}
// If there is no parent of children_[i], delete it
if (node->children_[i]->num_parents() == 0) {
for (SPNNode *grandson : node->children_[i]->children_)
grandson->remove_parent(node->children_[i]);
delete node->children_[i];
}
}
// Reset children and weights
node->set_children(new_children);
((SumNode *) node)->set_weights(new_weights);
} else {
// One main difference for product node is that we don't need to consider whether a grandson
// has already been added or not due to the decomposability constraint at the product node.
// We can make the following claim to simplify the code:
// For any two branches i, j of a product node p, there is not any edge connection one node
// from sub-SPN rooted at i to another node from sub-SPN rooted at j.
std::vector<SPNNode *> new_children;
for (size_t i = 0; i < num_children; ++i) {
if (node->children_[i]->type() == node->type()) {
// Add all the grandsons to be new children and delete children_[i] from the parent list
// of grandsons
for (SPNNode *grandson : node->children_[i]->children_) {
new_children.push_back(grandson);
// Update parent list of grandson
grandson->add_parent(node);
}
// Delete node from the parent list of children_[i]
node->children_[i]->remove_parent(node);
} else {
new_children.push_back(node->children_[i]);
}
// If current node has no parent, delete it
if (node->children_[i]->num_parents() == 0) {
for (SPNNode *grandson : node->children_[i]->children_)
grandson->remove_parent(node->children_[i]);
delete node->children_[i];
}
}
// Reset children
node->set_children(new_children);
}
}
// BFS
void SPNetwork::compute_statistics_() {
// Initialize
size_ = 0;
height_ = 0;
num_nodes_ = 0;
num_edges_ = 0;
num_var_nodes_ = 0;
num_sum_nodes_ = 0;
num_prod_nodes_ = 0;
id2node_.clear();
int id = 0;
std::unordered_set<SPNNode *> visited;
std::queue<std::pair<SPNNode *, int>> forward;
visited.insert(root_);
forward.push(std::make_pair(root_, 0));
switch (root_->type()) {
case SPNNodeType::SUMNODE:
num_sum_nodes_ += 1;
break;
case SPNNodeType::PRODNODE:
num_prod_nodes_ += 1;
break;
case SPNNodeType::VARNODE:
num_var_nodes_ += 1;
break;
}
num_nodes_ += 1;
id2node_.insert({id, root_});
size_ += 1;
root_->id_ = id;
id += 1;
while (!forward.empty()) {
auto pair = forward.front();
forward.pop();
for (SPNNode *child : pair.first->children()) {
if (visited.find(child) == visited.end()) {
visited.insert(child);
forward.push(std::make_pair(child, pair.second + 1));
switch (child->type()) {
case SPNNodeType::SUMNODE:
num_sum_nodes_ += 1;
break;
case SPNNodeType::PRODNODE:
num_prod_nodes_ += 1;
break;
case SPNNodeType::VARNODE:
num_var_nodes_ += 1;
break;
}
num_nodes_ += 1;
id2node_.insert({id, child});
size_ += 1;
child->id_ = id;
id += 1;
height_ = std::max(height_, pair.second + 1);
}
num_edges_ += 1;
size_ += 1;
}
}
// Sanity check
assert(num_nodes_ == num_var_nodes_ + num_sum_nodes_ + num_prod_nodes_);
assert(size_ == num_nodes_ + num_edges_);
assert(num_nodes_ == id2node_.size());
}
// Check that there are no connected nodes of the same type in SPN
bool SPNetwork::check_structure_() {
for (SPNNode *pt : bottom_up_order()) {
for (SPNNode *child : pt->children()) {
if (pt->type() == child->type()) return false;
}
}
return true;
}
// Output
void SPNetwork::print(std::ostream &out) {
bfs_traverse([&](SPNNode *node) {
out << node->string() << '\n';
});
}
template<typename Callable>
void SPNetwork::bfs_traverse(Callable &&callable) {
std::queue<SPNNode *> forward;
std::unordered_set<SPNNode *> visited;
forward.push(root_);
visited.insert(root_);
while (!forward.empty()) {
SPNNode *node = forward.front();
forward.pop();
for (SPNNode *child : node->children()) {
if (visited.find(child) == visited.end()) {
forward.push(child);
visited.insert(child);
}
}
callable(node);
}
}
void SPNetwork::set_random_params(uint seed) {
// Construct random number generator using seed.
std::mt19937 gen(seed);
std::uniform_real_distribution<double> dis(0.0, 1.0);
for (SPNNode *pt : bottom_up_order()) {
if (pt->type() == SPNNodeType::SUMNODE) {
double nz = 0.0;
for (size_t i = 0; i < pt->num_children(); ++i) {
((SumNode *) pt)->set_weight(i, dis(gen));
}
for (size_t i = 0; i < pt->num_children(); ++i) {
nz += ((SumNode *) pt)->weights()[i];
}
// Renormalization
for (size_t i = 0; i < pt->num_children(); ++i) {
((SumNode *) pt)->set_weight(i, ((SumNode *) pt)->weights()[i] / nz);
}
}
}
}
void SPNetwork::weight_projection(double smooth) {
// First set the values of all the indicators to 1.
std::vector<double> input(root_->scope_.size(), 0.0);
std::vector<bool> mask(root_->scope_.size(), true);
EvalDiff(input, mask);
// Locally normalization.
for (SPNNode *pt : top_down_order()) {
if (pt->type() == SPNNodeType::SUMNODE) {
// Projection w'_k <- w_k * S_k.
double ssz = 0.0, sz, max_logp = -std::numeric_limits<double>::infinity();
for (size_t k = 0; k < pt->num_children(); ++k) {
if (pt->children_[k]->fr_ > max_logp) {
max_logp = pt->children_[k]->fr_;
}
}
for (size_t k = 0; k < pt->num_children(); ++k)
ssz += ((SumNode*)pt)->weights_[k] * exp(pt->children_[k]->fr_ - max_logp) + smooth;
// Local weight normalization.
for (size_t k = 0; k < pt->num_children(); ++k) {
sz = ((SumNode*)pt)->weights_[k] * exp(pt->children_[k]->fr_ - max_logp) + smooth;
((SumNode *) pt)->set_weight(k, sz / ssz);
}
}
}
}
double SPNetwork::EvalDiff(const std::vector<double> &input, const std::vector<bool> &mask) {
// Bottom-up evaluation pass, process in log-space to avoid numeric issue.
// Set the value of leaf nodes first
int var_index, cindex;
double max_logp, sum_exp, tmp_val;
// Compute forward values for the rest of internal nodes.
for (VarNode *pt : dist_nodes_) {
var_index = pt->var_index();
if (mask[var_index]) {
pt->fr_ = 0.0;
} else {
pt->fr_ = pt->log_prob(input[var_index]);
}
}
for (SPNNode *pt : forward_order_) {
if (pt->type() == SPNNodeType::SUMNODE) {
// Avoid underflow
max_logp = -std::numeric_limits<double>::infinity();
for (size_t j = 0; j < pt->children_.size(); ++j)
if (pt->children_[j]->fr_ > max_logp)
max_logp = pt->children_[j]->fr_;
if (max_logp == -std::numeric_limits<double>::infinity()) {
pt->fr_ = -std::numeric_limits<double>::infinity();
} else {
sum_exp = 0.0;
for (size_t j = 0; j < pt->children_.size(); ++j)
sum_exp += ((SumNode *) pt)->weights_[j] * exp(pt->children_[j]->fr_ - max_logp);
pt->fr_ = max_logp + log(sum_exp);
}
} else if (pt->type() == SPNNodeType::PRODNODE) {
pt->fr_ = 0.0;
for (size_t j = 0; j < pt->children_.size(); ++j)
pt->fr_ += pt->children_[j]->fr_;
}
}
// Top-down differentiation pass, process in log-space to avoid the numeric issue.
root_->dr_ = 0.0;
for (SPNNode *pt : backward_order_) {
if (pt == root_) {
continue;
}
pt->dr_ = 0.0;
max_logp = -std::numeric_limits<double>::infinity();
for (SPNNode *parent : pt->parents_) {
// Find the index of current node in his parent.
cindex = -1;
for (int j = 0; j < parent->children_.size(); ++j) {
if (pt == parent->children_[j]) {
cindex = j;
break;
}
}
// Determine the shifting size.
if (parent->type() == SPNNodeType::SUMNODE) {
tmp_val = parent->dr_ + log(((SumNode *) parent)->weights_[cindex]);
if (tmp_val > max_logp) {
max_logp = tmp_val;
}
} else if (parent->type() == SPNNodeType::PRODNODE) {
tmp_val = parent->dr_ + parent->fr_ - pt->fr_;
if (tmp_val > max_logp) {
max_logp = tmp_val;
}
}
}
// Avoid overflow.
for (SPNNode *parent : pt->parents_) {
// Find the index of current node in his parent.
cindex = -1;
for (int j = 0; j < parent->children_.size(); ++j) {
if (pt == parent->children_[j]) {
cindex = j;
break;
}
}
// Determine the shifting size.
if (parent->type() == SPNNodeType::SUMNODE) {
tmp_val = parent->dr_ + log(((SumNode *) parent)->weights_[cindex]);
pt->dr_ += exp(tmp_val - max_logp);
} else if (parent->type() == SPNNodeType::PRODNODE) {
tmp_val = parent->dr_ + parent->fr_ - pt->fr_;
pt->dr_ += exp(tmp_val - max_logp);
}
}
pt->dr_ = log(pt->dr_) + max_logp;
}
return root_->fr_;
}
}
|
Markdown
|
UTF-8
| 6,910 | 2.90625 | 3 |
[] |
no_license
|
# 登录接口开发
登录的逻辑其实很简答,只需要接受账号密码,然后把用户的id生成jwt,返回给前段,为了后续的jwt的延期,所以我们把jwt放在header上。具体代码如下:
- com.gychen.controller.AccountController
```java
@RestController
public class AccountController {
@Autowired
JwtUtils jwtUtils;
@Autowired
UserService userService;
/**
* 默认账号密码:gychen / 111111
*
*/
@CrossOrigin
@PostMapping("/login")
public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
Assert.notNull(user, "用户不存在");
if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
return Result.fail("密码错误!");
}
String jwt = jwtUtils.generateToken(user.getId());
response.setHeader("Authorization", jwt);
response.setHeader("Access-Control-Expose-Headers", "Authorization");
// 用户可以另一个接口
return Result.succ(MapUtil.builder()
.put("id", user.getId())
.put("username", user.getUsername())
.put("avatar", user.getAvatar())
.put("email", user.getEmail())
.map()
);
}
// 退出
@GetMapping("/logout")
@RequiresAuthentication
public Result logout() {
SecurityUtils.getSubject().logout();
return Result.succ(null);
}
}
```
- 在postman软件里写接口请求测试
请求类型为POST,URL为http://localhost:8081/login,依次选择Body->raw->JSON
```json
{
"_comment":"postman清求数据",
"username":"gychen",
"password":"111111"
}
{
"_comment":"服务器返回数据",
"code": "0",
"msg": "操作成功",
"data": {
"id": 1,
"avatar": "https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg",
"email": null,
"username": "gychen"
}
}
```
# 博客接口开发
我们的骨架已经完成,接下来,我们就可以添加我们的业务接口了,下面我以一个简单的博客列表、博客详情页为例子开发:
- com.gychen.controller.BlogController
```java
package com.gychen.controller;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gychen.common.lang.Result;
import com.gychen.entity.Blog;
import com.gychen.service.BlogService;
import com.gychen.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
/**
* <p>
* 前端控制器
* </p>
*
* @author gychen
* @since 2020-07-28
*/
@RestController
public class BlogController {
@Autowired
BlogService blogService;
@GetMapping("/blogs")
public Result blogs(Integer currentPage) {
if(currentPage == null || currentPage < 1) currentPage = 1;
Page page = new Page(currentPage, 5);
IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
return Result.succ(pageData);
}
@GetMapping("/blog/{id}")
public Result detail(@PathVariable(name = "id") Long id) {
Blog blog = blogService.getById(id);
Assert.notNull(blog, "该博客已删除!");
return Result.succ(blog);
}
@RequiresAuthentication // 此接口必须要通过登录认证才能访问
@PostMapping("/blog/edit")
public Result edit(@Validated @RequestBody Blog blog) {
System.out.println(blog.toString());
Blog temp = null;
if(blog.getId() != null) {
// 在数据库中查找传入id的博客存不存在
temp = blogService.getById(blog.getId());
// Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");
Assert.isTrue(temp.getUserId().equals(ShiroUtil.getProfile().getId()), "没有权限编辑");
} else {
temp = new Blog();
temp.setUserId(ShiroUtil.getProfile().getId());
temp.setCreated(LocalDateTime.now());
temp.setStatus(0);
}
// 把blog复制到temp并忽略id、userId、created、status
BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
blogService.saveOrUpdate(temp);
return Result.succ(null);
}
}
```
- 在postman软件里写接口请求测试
1. 先进行登录请求,登陆成功后在返回数据的请求头Headers里找到Authorization的value,复制value值
2. 新建一个请求,请求类型为POST,URL为http://localhost:8081/blog/edit,在Headers里新建key:Authorization,value:复制的value值,依次选择Body->raw->JSON
3. 测试代码
- ```json
{
"title":"测试标题3333333333",
"description":"description333333333",
"content":"content33333333333"
}
```
- ```json
{
"title":"测试标题3333333333",
"description":"description333333333"
}
```
- ```json
{
"id":11,
"title":"测试标题3333333333",
"description":"description333333333",
"content":"content33333333333"
}
```
- ```json
{
"id":11,
"title":"修改测试标题3333333333",
"description":"description333333333",
"content":"content1111111"
}
```
4. 暂时在这里出现了登录验证的问题,待解决
5. 找了大概一个小时,在JwtFilter的onAcessDenied方法里发现发起请求时,后端根本在Header请求头里找不到jwt,后来发现原来是在postman里把token放Params里传给后端了。
6. 测试结果
- ```json
{
"code": "0",
"msg": "操作成功",
"data": null
}
```
- ```json
{
"code": "-1",
"msg": "内容不能为空",
"data": null
}
```
- ```json
{
"code": "0",
"msg": "操作成功",
"data": null
}
```
- ```json
{
"code": "0",
"msg": "操作成功",
"data": null
}
```
注意@RequiresAuthentication说明需要登录之后才能访问的接口,其他需要权限的接口可以添加shiro的相关注解。 接口比较简单,我们就不多说了,基本增删改查而已。注意的是edit方法是需要登录才能操作的受限资源。
|
Markdown
|
UTF-8
| 352 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
---
title: Hello Lambda!
date: 2018-09-12 00:00:00 -0500
presentation_url: https://www.slideshare.net/DavidRoberts38/hello-lambda-how-to-call-lambdas-on-aws
---
An introduction to the many ways to call a Lambda function on Amazon Web Services. We'll cover various options such as API Gateway, SNS, SQS, Kinesis and discuss the best use cases for each.
|
Java
|
UTF-8
| 2,711 | 2.265625 | 2 |
[] |
no_license
|
package com.rahuljanagouda.popularmoviesone.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.rahuljanagouda.popularmoviesone.R;
import com.rahuljanagouda.popularmoviesone.pojo.movie.MovieApiResponse;
import com.rahuljanagouda.popularmoviesone.pojo.movie.Result;
import com.rahuljanagouda.popularmoviesone.ui.DetailsActivity;
import com.rahuljanagouda.popularmoviesone.utils.Network;
/**
* Created by rahuljanagouda on 24/07/16.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private final Context mContext;
private final MovieApiResponse pageResponse;
public RecyclerAdapter(Context mContext, MovieApiResponse response) {
this.mContext = mContext;
pageResponse = response;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item_card,parent,false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Result movie = pageResponse.getResults().get(position);
holder.movieName.setText(movie.getTitle());
if (movie.getPosterPath() != null) {
Glide
.with(mContext)
.load(Network.TMDB_IMAGE_BASE_URL + movie.getPosterPath())
.error(R.drawable.placeholder)
.into(holder.card_image);
} else {
Glide
.with(mContext)
.load(R.drawable.placeholder)
.into(holder.card_image);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(mContext, DetailsActivity.class);
i.putExtra("movieResult", movie);
mContext.startActivity(i);
}
});
}
@Override
public int getItemCount() {
return pageResponse.getResults().size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView card_image;
TextView movieName;
public ViewHolder(View itemView) {
super(itemView);
card_image = (ImageView) itemView.findViewById(R.id.card_image);
movieName = (TextView) itemView.findViewById(R.id.movieName);
}
}
}
|
Python
|
UTF-8
| 87 | 3.1875 | 3 |
[] |
no_license
|
def dis(no):
for x in range(1,no+1):
print "Hello"
x=input("ENter number")
dis(x)
|
Shell
|
UTF-8
| 333 | 3.25 | 3 |
[] |
no_license
|
#!/usr/bin/env bash
# a simple script that resists death with a few messages
echo $$ > /var/run/holbertonscript.pid
sigterm() {
echo "I hate the kill command"
rm -r "/var/run/holbertonscript.pid"
exit
}
sigint() {
echo "Y U no love me?!"
exit
}
trap SIGTERM
trap SIGINT
while :
do
echo "To infinity and beyond"
done
|
C
|
UTF-8
| 439 | 3.484375 | 3 |
[] |
no_license
|
#include <stdio.h>
int main()
{
int pz[100], n,i,j;
printf("Enter the number of elements\n");
scanf("%d", &n);
printf("Enter the elements\n", n);
for (i = 0; i < n; i++)
scanf("%d", &pz[i]);
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0 ; j < n ; i++ )
{
if(pz[i]==pz[j])
printf("\n %d",pz[i]);
break;
}
break;
}
return 0;
}
|
C++
|
SHIFT_JIS
| 716 | 2.890625 | 3 |
[] |
no_license
|
#pragma once
#include "Vertex.h"
class CShape
{
public:
CShape();
~CShape();
private:
CShape* pre_shape;
CShape* next_shape;
CVertex* vertex_head;
CVertex* vertex_final;
public:
//}`Ă邩
bool close = false;
//Vertex̐
int VertexNum = 0;
//OVertex擾
CShape* GetPreShape();
//OVertexݒ
CShape* SetPreShape(CShape* shape);
//Vertex擾
CShape* GetNextShape();
//Vertexݒ
CShape* SetNextShape(CShape* shape);
//Shape̍폜
void FreeShape();
//Vertex̒lj
CVertex* AppendVertex(float x, float y);
//ŏVertex擾
CVertex* GetVertexHead();
//ŌVertex擾
CVertex* GetVertexFinal();
};
|
Markdown
|
UTF-8
| 916 | 2.96875 | 3 |
[] |
no_license
|
# Challenge 4
## Purpose
As A coding boot camp student I want to take a timed quiz on JavaScript fundamentals that stores high scores so that I can gauge my progress compared to my peers
## Built With
* HTML
* JavaScript
## Requirements/Notes
* GIVEN I am taking a code quiz
* WHEN I click the start button
* THEN a timer starts and I am presented with a question
* WHEN I answer a question
* THEN I am presented with another question
* WHEN I answer a question incorrectly
* THEN time is subtracted from the clock
* WHEN all questions are answered or the timer reaches 0
* THEN the game is over
* WHEN the game is over
* THEN I can save my initials to local storage
## Link
https://leticiaaldaco.github.io/Ch4_CodeQuiz/
## Pictures

|
Python
|
UTF-8
| 522 | 4.34375 | 4 |
[] |
no_license
|
"""
String Looping
As we've mentioned, strings are like lists with characters as elements. You can loop through strings the same way you loop through lists! While we won't ask you to do that in this section, we've put an example in the editor of how looping through a string might work."""
for letter in "Codecademy":
print (letter)
# Empty lines to make the output pretty
print
print
word = "Programming is fun!"
for letter in word:
# Only print out the letter i
if letter == "i":
print (letter)
|
C#
|
UTF-8
| 3,279 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
namespace Manila.AirFrog.Common.Terminal
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Command
{
public string Name { get; private set; }
public string Description { get; private set; }
public string CommandText { get; private set; }
private Action<List<string>, IBaseTerminal> action;
public Command(string name, string commandText, string description, Action<List<string>, IBaseTerminal> action)
{
Name = name;
Description = description;
CommandText = commandText;
this.action = action;
}
public void RunSync(List<string> cmd, IBaseTerminal term)
{
action(cmd, term);
}
public async Task RunAsync(List<string> cmd, IBaseTerminal term)
{
await Task.Run(() => action(cmd, term)).ConfigureAwait(false);
}
}
class CmdExecutor
{
private Dictionary<string, Command> cmdList = new Dictionary<string, Command>();
private static CmdExecutor instance = null;
#region Buildin Actions
// note: basic actions must be sync
private void CmdHelpText(List<string> cmd, IBaseTerminal term)
{
term.OutputLine("Commands\tDescription");
// TODO: add another class for format actions.
// TODO: add mutex for terminal output
// TODO: next feature add parallel tasks & batch process & task manager
foreach (var singleCmd in cmdList)
{
term.OutputLine(string.Format("{0}\t{1}", singleCmd.Value.CommandText, singleCmd.Value.Description));
}
}
private void McsList(List<string> cmd, IBaseTerminal term)
{
;
// TODO: implement this function
}
private void RegisterBuildinCmds()
{
cmdList.Add("?", new Command("?", "?", "Type to Monitor this message", CmdHelpText));
cmdList.Add("help", new Command("help", "help", "Type to Monitor this message", CmdHelpText));
}
#endregion Buildin Actions
private CmdExecutor()
{
RegisterBuildinCmds();
}
public void RunSync(List<string> cmd, IBaseTerminal term)
{
try
{
cmdList[cmd[0]].RunSync(cmd.Skip(1).ToList(), term);
}
catch (Exception)
{
term.OutputLine("Error in execute the command");
}
}
public async Task RunAsync(List<string> cmd, IBaseTerminal term)
{
try
{
await cmdList[cmd[0]].RunAsync(cmd.Skip(1).ToList(), term).ConfigureAwait(false);
}
catch (Exception)
{
term.OutputLine("Error in execute the command");
}
}
public static CmdExecutor Instance
{
get
{
if (instance == null)
{
instance = new CmdExecutor();
}
return instance;
}
}
}
}
|
Java
|
UTF-8
| 1,012 | 2.5625 | 3 |
[] |
no_license
|
package ind.rubilacz.tools.acleaner.detector;
import ind.rubilacz.tools.acleaner.model.ColorDebris;
import ind.rubilacz.tools.acleaner.model.Debris;
import ind.rubilacz.tools.acleaner.model.Document;
public class ColorDetector extends CharactersDetector {
private static ColorDetector sDetector;
public static synchronized ColorDetector getInstance() {
if (sDetector == null) {
sDetector = new ColorDetector();
}
return sDetector;
}
private ColorDetector() {
}
@Override
public String identifier() {
return "color";
}
@Override
protected Debris obtain(String name, Document container) {
return new ColorDebris(name, container);
}
@Override
protected boolean shouldDirProcessDeeply(String relativePath) {
return relativePath.matches("^res/color$") || relativePath.matches("^res\\\\color$");
}
@Override
protected boolean isDeepProcessingNeeded() {
return true;
}
}
|
Python
|
UTF-8
| 12,451 | 3.265625 | 3 |
[] |
no_license
|
# valueIterationAgents.py
# -----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
# valueIterationAgents.py
# -----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
import mdp, util
from learningAgents import ValueEstimationAgent
import collections
class ValueIterationAgent(ValueEstimationAgent):
"""
* Please read learningAgents.py before reading this.*
A ValueIterationAgent takes a Markov decision process
(see mdp.py) on initialization and runs value iteration
for a given number of iterations using the supplied
discount factor.
"""
def __init__(self, mdp, discount = 0.9, iterations = 100):
"""
Your value iteration agent should take an mdp on
construction, run the indicated number of iterations
and then act according to the resulting policy.
Some useful mdp methods you will use:
mdp.getStates()
mdp.getPossibleActions(state)
mdp.getTransitionStatesAndProbs(state, action)
mdp.getReward(state, action, nextState)
mdp.isTerminal(state)
"""
self.mdp = mdp
self.discount = discount
self.iterations = iterations
self.values = util.Counter() # A Counter is a dict with default 0
self.runValueIteration()
def runValueIteration(self):
# Write value iteration code here
"*** YOUR CODE HERE ***"
# go through each iteration
for i in range(self.iterations):
# get all possible states
states = self.mdp.getStates()
cur_values = self.values.copy()
# go though each state
for i in range(len(states)):
# get current state
cur_state = states[i]
# get all possible actions for current state
cur_actions = self.mdp.getPossibleActions(cur_state)
q_values = util.Counter()
# determine if current state is not a terminal
if not self.mdp.isTerminal(cur_state):
# determine q value for each action
for action in cur_actions:
q_values[action] = self.computeQValueFromValues(cur_state, action)
# get the maximum q value
cur_values[cur_state] = max(q_values.values())
# copy cur_values into self.values
self.values = cur_values
def getValue(self, state):
"""
Return the value of the state (computed in __init__).
"""
return self.values[state]
def computeQValueFromValues(self, state, action):
"""
Compute the Q-value of action in state from the
value function stored in self.values.
"""
"*** YOUR CODE HERE ***"
# get all transitions
transitions = self.mdp.getTransitionStatesAndProbs(state, action)
q_value = 0
# go through each transition, and calculate q value
for i in range(len(transitions)):
nextState = transitions[i][0]
prob = transitions[i][1]
reward = self.mdp.getReward(state, action, nextState)
discount = self.discount
value = self.values[nextState]
q_value += prob * (reward + discount * value)
return q_value
util.raiseNotDefined()
def computeActionFromValues(self, state):
"""
The policy is the best action in the given state
according to the values currently stored in self.values.
You may break ties any way you see fit. Note that if
there are no legal actions, which is the case at the
terminal state, you should return None.
"""
"*** YOUR CODE HERE ***"
# get all possible actions for state
actions = self.mdp.getPossibleActions(state)
# determine if state is a terminal
if self.mdp.isTerminal(state):
return None
q_values = util.Counter()
# go through each action
for action in actions:
# compute the q value for each action
q_values[action] = self.computeQValueFromValues(state, action)
return q_values.argMax()
def getPolicy(self, state):
return self.computeActionFromValues(state)
def getAction(self, state):
"Returns the policy at the state (no exploration)."
return self.computeActionFromValues(state)
def getQValue(self, state, action):
return self.computeQValueFromValues(state, action)
class AsynchronousValueIterationAgent(ValueIterationAgent):
"""
* Please read learningAgents.py before reading this.*
An AsynchronousValueIterationAgent takes a Markov decision process
(see mdp.py) on initialization and runs cyclic value iteration
for a given number of iterations using the supplied
discount factor.
"""
def __init__(self, mdp, discount = 0.9, iterations = 1000):
"""
Your cyclic value iteration agent should take an mdp on
construction, run the indicated number of iterations,
and then act according to the resulting policy. Each iteration
updates the value of only one state, which cycles through
the states list. If the chosen state is terminal, nothing
happens in that iteration.
Some useful mdp methods you will use:
mdp.getStates()
mdp.getPossibleActions(state)
mdp.getTransitionStatesAndProbs(state, action)
mdp.getReward(state)
mdp.isTerminal(state)
"""
ValueIterationAgent.__init__(self, mdp, discount, iterations)
def runValueIteration(self):
"*** YOUR CODE HERE ***"
# go through each iteration
for i in range(self.iterations):
# get all states
states = self.mdp.getStates()
num_states = len(states)
cur_values = self.values.copy()
# get current state
cur_state = states[i % num_states]
# get all possible actions for current state
cur_actions = self.mdp.getPossibleActions(cur_state)
q_values = util.Counter()
# determine if current state is not a terminal
if not self.mdp.isTerminal(cur_state):
# go through each action
for action in cur_actions:
# compute the q value for each action
q_values[action] = self.computeQValueFromValues(cur_state, action)
# get the maximum q value
cur_values[cur_state] = max(q_values.values())
# copy cur_values into self.values
self.values = cur_values
class PrioritizedSweepingValueIterationAgent(AsynchronousValueIterationAgent):
"""
* Please read learningAgents.py before reading this.*
A PrioritizedSweepingValueIterationAgent takes a Markov decision process
(see mdp.py) on initialization and runs prioritized sweeping value iteration
for a given number of iterations using the supplied parameters.
"""
def __init__(self, mdp, discount = 0.9, iterations = 100, theta = 1e-5):
"""
Your prioritized sweeping value iteration agent should take an mdp on
construction, run the indicated number of iterations,
and then act according to the resulting policy.
"""
self.theta = theta
ValueIterationAgent.__init__(self, mdp, discount, iterations)
def runValueIteration(self):
"*** YOUR CODE HERE ***"
states = self.mdp.getStates()
# compute all predecessors
predecessors = {}
for state in states:
if not self.mdp.isTerminal(state):
actions = self.mdp.getPossibleActions(state)
for action in actions:
transitions = self.mdp.getTransitionStatesAndProbs(state, action)
for transition in transitions:
nextState = transition[0]
prob = transition[1]
if prob != 0:
if nextState in predecessors:
predecessors[nextState].add(state)
else:
predecessors[nextState] = {state}
# initialize empty priority queue
pqueue = util.PriorityQueue()
# iterate through each state
for s in states:
s_qvalues = util.Counter()
# determine if state is a terminal or not
if not self.mdp.isTerminal(s):
# get possible actions for current state
actions = self.mdp.getPossibleActions(s)
# determine each q value for each action
for action in actions:
s_qvalues[action] = self.computeQValueFromValues(s, action)
# find the maximum q value
max_s_qvalue = max(s_qvalues.values())
# find the absolute difference between current value of s in self.values and highest Q-value across all possible actions from s
diff = abs(max_s_qvalue - self.values[s])
# push s into priority queue with priority -diff
pqueue.update(s, -diff)
# go through each iteration
for i in range(self.iterations):
# if priority queue is empty, then terminate
if pqueue.isEmpty():
break
# pop a state s off the priority queue
s = pqueue.pop()
s_qvalues = util.Counter()
# determine if state is a terminal or not
if not self.mdp.isTerminal(s):
# get possible actions for current state
actions = self.mdp.getPossibleActions(s)
# determine each q value for each action
for action in actions:
s_qvalues[action] = self.computeQValueFromValues(s, action)
# find the maximum q value
max_s_qvalue = max(s_qvalues.values())
# update s's value in self.values
self.values[s] = max_s_qvalue
# go through each predecessor p of s
for p in predecessors[s]:
# get all possible actions for p
actions = self.mdp.getPossibleActions(p)
p_qvalues = util.Counter()
# determine each q value for each action
for action in actions:
p_qvalues[action] = self.computeQValueFromValues(p, action)
# find the maximum q value
max_p_qvalue = max(p_qvalues.values())
# find absolute difference between current value of p in self.values and highest q-value across all possible actions from p
diff = abs(self.values[p] - max_p_qvalue)
# determine if diff is greater than theta
if diff > self.theta:
# push p into the priority queue with priority -diff
pqueue.update(p, -diff)
|
Swift
|
UTF-8
| 2,941 | 3.046875 | 3 |
[] |
no_license
|
//
// UIColor+Ext.swift
// TikiTest
//
// Created by Ho Trung Toan on 11/13/18.
// Copyright © 2018 Ho Trung Toan. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
public convenience init?(hexString: String) {
let r, g, b, a: CGFloat
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = String(hexString[start...])
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
static func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
extension UIColor {
@nonobjc class var backgroundColor1: UIColor {
return UIColor(hexString: "#16702e") ?? UIColor.clear
}
@nonobjc class var backgroundColor2: UIColor {
return UIColor(hexString: "#005a51") ?? UIColor.clear
}
@nonobjc class var backgroundColor3: UIColor {
return UIColor(hexString: "#996c00") ?? UIColor.clear
}
@nonobjc class var backgroundColor4: UIColor {
return UIColor(hexString: "#5c0a6b") ?? UIColor.clear
}
@nonobjc class var backgroundColor5: UIColor {
return UIColor(hexString: "#006d90") ?? UIColor.clear
}
@nonobjc class var backgroundColor6: UIColor {
return UIColor(hexString: "#974e06") ?? UIColor.clear
}
@nonobjc class var backgroundColor7: UIColor {
return UIColor(hexString: "#99272e") ?? UIColor.clear
}
@nonobjc class var backgroundColor8: UIColor {
return UIColor(hexString: "#89221f") ?? UIColor.clear
}
@nonobjc class var backgroundColor9: UIColor {
return UIColor(hexString: "#00345d") ?? UIColor.clear
}
}
|
Java
|
UTF-8
| 834 | 1.976563 | 2 |
[] |
no_license
|
package com.lanou.web.controller;
import com.lanou.entity.dto.NewsDto;
import com.lanou.service.IDownNewsService;
import com.lanou.util.Result;
import com.lanou.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class DownNewsController {
@Autowired
IDownNewsService service;
@RequestMapping("/newsinfo")
@ResponseBody
public Result newsInfo(NewsDto newsDto){
NewsDto news = service.selectforNews(newsDto);
if (news == null){
return ResultGenerator.genFailResult("暂无数据!");
}
return ResultGenerator.genSuccessResult(news);
}
}
|
Java
|
UTF-8
| 912 | 2.453125 | 2 |
[] |
no_license
|
package com.arteck;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
// Hibernate Named Query
Query query = session.getNamedQuery("xyz");
//Query query = session.getNamedQuery("findEmployeeByName");
query.setParameter("name", "morya");
//List<Employee> employees = query.getResultList();
List re = query.list();
Iterator itr = re.iterator();
while (itr.hasNext()) {
Employee e = (Employee) itr.next();
System.out.println(e.getName());
}
session.close();
}
}
|
Java
|
UTF-8
| 1,290 | 2.296875 | 2 |
[] |
no_license
|
package com.clound.battery.model.bean;
/**
* author cowards
* created on 2018\10\18 0018
**/
public class HlBean {
/**
* 回路号
**/
private String hl_number;
/**
* 回路状态
**/
private String hl_state;
/**
* 回路时间
**/
private String hl_time;
/**
* 0:线上卡 1:微信
**/
private int payType;
public int getPayType() {
return payType;
}
public void setPayType(int payType) {
this.payType = payType;
}
public String getHl_number() {
return hl_number;
}
public void setHl_number(String hl_number) {
this.hl_number = hl_number;
}
public String getHl_state() {
return hl_state;
}
public void setHl_state(String hl_state) {
this.hl_state = hl_state;
}
public String getHl_time() {
return hl_time;
}
public void setHl_time(String hl_time) {
this.hl_time = hl_time;
}
@Override
public String toString() {
return "HlBean{" +
"hl_number='" + hl_number + '\'' +
", hl_state='" + hl_state + '\'' +
", hl_time='" + hl_time + '\'' +
", payType=" + payType +
'}';
}
}
|
Java
|
UTF-8
| 3,116 | 2.390625 | 2 |
[] |
no_license
|
package com.todo.bootstrap;
import com.todo.domain.Todo;
import com.todo.domain.TodoBucket;
import com.todo.domain.UserDetails;
import com.todo.security.utils.ROLES;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.*;
@Component
@Slf4j
@Transactional
public class TodoDataLoad implements CommandLineRunner {
private final SessionFactory sessionFactory;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
public TodoDataLoad(SessionFactory sessionFactory, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.sessionFactory = sessionFactory;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
private void createUsers() {
UserDetails userDetails = UserDetails.builder()
.username("test")
.password(bCryptPasswordEncoder.encode("test"))
.role(ROLES.ADMIN.getRole())
.build();
UserDetails userDetailsTest = UserDetails.builder()
.username("test1")
.password(bCryptPasswordEncoder.encode("test1"))
.role(ROLES.ADMIN.getRole())
.build();
List<UserDetails> userDetailList = new ArrayList() {{
add(userDetails);
add(userDetailsTest);
}};
userDetailList.forEach(val -> getSession().saveOrUpdate(val));
}
private void createTodoBuckets() {
Arrays.asList(getBucket("Football", "Score an overhead goal?", "play without breaking ankle?"
, "three top bins"),
getBucket("Trips", "London", "Alaska", "azkaban if possible?"),
getBucket("All time", "sleep sound", "sleep well", "try to sleep"))
.forEach(val -> getSession().saveOrUpdate(val));
}
private TodoBucket getBucket(String bucketName, String... todos) {
TodoBucket bucket = TodoBucket.builder()
.name(bucketName)
.user("test")
.build();
Set<Todo> todoSet = new HashSet<>();
Arrays.stream(todos).forEach(todoText -> {
Todo todo = Todo.builder()
.completed(false)
.todoBucket(bucket)
.name(todoText)
.build();
todoSet.add(todo);
});
bucket.setTodoSet(todoSet);
return bucket;
}
@Override
public void run(String... args) throws Exception {
log.info("Started Data loading on start up....");
createUsers();
log.info("Loading users completed....");
createTodoBuckets();
log.info("All Data load Completed....");
}
}
|
Python
|
UTF-8
| 1,140 | 3.296875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import sys
def print_level_order_and_id(tree, indent=0, printable=[]):
if tree.__class__ in printable:
print '{1}:{0}'.format(' '*indent, tree.getLine()), tree.text, "0x%x"%id(tree), str(tree)
else:
print '{1}:{0}'.format(' '*indent, tree.getLine()), tree.text, "0x%x"%id(tree)
for child in tree.getChildren():
print_level_order_and_id(child, indent+1)
def print_level_order(tree, indent=0,printable=["Ident", "List", "Number", "Ltrue", "Lfalse"]):
classname = str(tree.__class__)
if classname.find(".") != -1:
classname = classname[classname.rfind(".")+1:]
if classname in printable:
print '{1}:{0}'.format(' '*indent, tree.getLine()), tree.text, str(tree)
else:
print '{1}:{0}'.format(' '*indent, tree.getLine()), tree.text
for child in tree.getChildren():
print_level_order(child, indent+1, printable)
def print_tree(tree):
sys.stdout.write(str(tree.text)+"(")
i = 0
for child in tree.getChildren():
if i != 0:
sys.stdout.write(",")
i = i + 1
print_tree(child)
sys.stdout.write(')')
|
Java
|
UTF-8
| 2,421 | 1.945313 | 2 |
[] |
no_license
|
package auto.pages;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import auto.utility.Services;
import org.openqa.selenium.interactions.touch.TouchActions;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.List;
import java.util.Properties;
import static org.testng.Assert.assertEquals;
/**
* Created with IntelliJ IDEA.
* User: Nadun Ilamperuma
* Date: 10/4/19
* Time: 1:58 PM
* To change this template use File | Settings | File Templates.
*
*/
public class createprojectPage extends Services {
String Menulistbutton = "android.widget.ImageButton";
String AddProjectIcon = "android.widget.ImageButton";
String ProjectsIcon = "//android.widget.TextView[@resource-id='com.todoist:id/name']";
String ProjectNamefield = "//android.widget.EditText[@resource-id='com.todoist:id/name']";
String ProjectAddbutton = "//android.widget.TextView[@resource-id='com.todoist:id/menu_form_submit']";
String VerifyProjectLabel = "android.widget.TextView";
final static String NewProjectName = "New Project";
//WebDriver driver;
public createprojectPage(WebDriver driver) {
super(driver);
}
public createprojectPage NavigateToNewProject() throws InterruptedException {
ListClick(0,Menulistbutton);
WaitforElementPresentXpath(ProjectsIcon);
ListClick(0,AddProjectIcon);
return this;
}
public createprojectPage CreateNewProject() throws InterruptedException {
driver.findElement(By.xpath(ProjectNamefield)).sendKeys("New Project");
driver.findElement(By.xpath(ProjectAddbutton)).click();
return this;
}
public createprojectPage VerifyAddNewProject() throws InterruptedException {
assertEquals(ListgetText(2,VerifyProjectLabel),NewProjectName);
return this;
}
// public static void main(String args[])throws IOException, XmlPullParserException
// {
// System.out.println("Hello, World" );
// MavenXpp3Reader reader = new MavenXpp3Reader();
// Model model = reader.read(new FileReader("pom.xml"));
// System.out.println(model.getProperties().getProperty("device.name"));
// }
}
|
Python
|
UTF-8
| 879 | 3.203125 | 3 |
[] |
no_license
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import pandas as pd
def save_snv_table(df,file_out, pkl = False,txt = False):
"""
saves snv table as .tsv file, .pkl file, or both
INPUTS
df:
SNV table pandas DataFrame object
file_out:
file name. e.g. "path/to/file"
pkl:
if True, df is saved as a pickle file
txt:
if True, df is saved as a .txt tab-delimited file
"""
file_out = file_out.replace(".txt","").replace(".pkl","")
if (pkl==False) & (txt==False):
raise ValueError("pkl and txt cannot both be false")
if txt:
df.to_csv(file_out+".txt",sep='\t',index=False)
print(("\nText file {}.txt generated".format(file_out)))
if pkl:
df.to_pickle(file_out+".pkl")
print(("\nPickle file {}.pkl generated".format(file_out)))
|
Python
|
UTF-8
| 190 | 2.59375 | 3 |
[] |
no_license
|
import pandas as pd
import os
import sys
s = int(sys.argv[1])
e = int(sys.argv[2])
for i in range(s,e):
os.system("python3 test.py %s" %(i))
df = pd.read_csv("output.csv")
print(df)
|
PHP
|
UTF-8
| 4,350 | 2.828125 | 3 |
[] |
no_license
|
<?php
namespace libs;
//路由类
class Route{
private $controller="index";
private $action="index";
//解析路由
//c 表示控制器 a 表示方法名
//控制器名称后缀 Controller index=>indexController
//方法名 不变 action index=>index
public function routeParse(){
list($c,$a)=$this->getRoute();
// $c=isset($_GET['c']) ? trim($_GET['c']) : "";
// $a=isset($_GET['a']) ? trim($_GET['a']) : "";
// var_dump($c,$a);
// var_dump($_GET);
//&& 与关系,前一个成立才能走下一个
$c != "" && $this->controller=$c;
$a != "" && $this->action=$a;
//返回控制器和方法
$this->controller=ucfirst($this->controller)."Controller";
$this->action=$this->action;
// var_dump($this->controller,$this->action);die;
// var_dump($this->controller,$this->action,$_SERVER);
return [$this->controller,$this->action];
}
protected function getRoute(){
//直接通过地址中的参数c和a获取对应的控制器
$controller="";
$action="";
list($controller,$action)= $this->getRouteByUrl();
//通过pathinfo来获取
$controller || $action || list($controller,$action)=$this->getRouteByPathInfo();
//通过正则匹配
$controller || $action || list($controller,$action)=$this->getRouteByUri();
// var_dump($controller,$action);die;
// 通过通用规则来获取
$controller || $action || list($controller,$action) = $this->getRouteByParams();
return [$controller,$action];
}
protected function getRouteByUrl(){
$c=requset()->all('c',"");
$a=requset()->all('a',"");
return [$c,$a];
}
protected function getRouteByPathInfo(){
$controller="";
$action="";
$pathinfo=$_SERVER['PATH_INFO'] ?? "";
//如果确实存在
if($pathinfo){
$path=explode("/",$pathinfo);
// var_dump($path);
$controller=$path[1] ?? "";
$action=$path[2] ?? "";
// var_dump($controller);
for($i=3;$i<count($path);$i=$i+2){
$_GET[$path[$i]]=$path[$i+1] ?? "";
}
// var_dump($_GET);
}
return [$controller,$action];
}
protected function getRouteByUri(){
$controller="";
$action="";
// var_dump($_SERVER);
$uri=$_SERVER['REQUEST_URI'];
// echo($uri);
//正则匹配
$regs=$this->regExpForRoute();
foreach($regs as $reg=>$replace){
if(preg_match($reg,$uri)){
$newUri=preg_replace($reg,$replace,$uri);
// echo $newUri;die;
$params=explode("&",$newUri);
foreach($params as $param){
$p=explode("=",$param);
if($p[0]=='c'){
$controller=$p[1];
}elseif($p[0] == 'a'){
$action=$p[1];
}else{
$_GET[$p[0]]=$p[1];
}
}
break;
}
}
return [$controller,$action];
}
protected function regExpForRoute(){
return[
"#^/(\w+)/(\d+)\?(.*)$#"=>"c=$1&a=index&id=$2&$3",
"#^/(\w+)/(\d+)$#" => "c=$1&a=index&id=$2",
"#^/(\w+)/(\w+)\?(.*)$#" => "c=$1&a=$2&$3",
"#^/(\w+)/(\w+)$#" => "c=$1&a=$2",
"#^/(\w+)$#"=>"c=$1&a=index",
"#^/(\w+)\?(.*)$#"=>"c=$1&a=index&$2",
];
}
protected function getRouteByParams(){
$controller="";
$action="";
$uri=$_SERVER['REQUEST_URI'];
$uri=explode("?",$uri);
//处理?后半个部分
if(isset($uri[1])){
$params=explode("&",$uri[1]);
foreach($params as $v){
$v=explode('=',$v);
$_GET[$v[0]]=$v[1];
}
}
//?前半部分
$path=explode('/',$uri[0]);
$controller=$path[1] ?? "";
$action=$path[2] ?? "";
for($i=3;$i<count($path);$i+=2){
$_GET[$path[$i]]=$path[$i+1] ?? "";
}
return [$controller,$action];
}
}
?>
|
JavaScript
|
UTF-8
| 3,962 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
// document ready
$(function () {
MAIN.Init();
});
// Define namespace
var MAIN = MAIN || {};
// Init
MAIN.Init = function () {
with (MAIN) {
let socket;
// [Connect] click
$("button[name='buttConnect']").click(function () {
console.log("buttConnect clicked");
// Connect to server
socket = io.connect();
// Map the messages to event listener
const arr = ['gameList', 'gameUpdate', 'generalUpdate'];
for (let k in arr) {
socket.on(arr[k], function (data) { OnDataReceived(arr[k], data); });
}
});
// [syncGameList] click
$("button[name='buttSyncGameList']").click(function () {
console.log("buttSyncGameList clicked");
socket.emit('syncGameList');
});
// [createGame] click
$("button[name='buttCreateGame']").click(function () {
const strPlayerName = $("#txtCreateGamePlayerName").val();
console.log("buttCreateGame clicked. strPlayerName=" + strPlayerName);
socket.emit('createGame', strPlayerName);
});
// [startGame] click
$("button[name='buttStartGame']").click(function () {
const strGameId = $("#txtStartGameGameId").val();
console.log("buttStartGame clicked. strGameId=" + strGameId);
socket.emit('startGame', strGameId);
});
// [joinGame] click
$("button[name='buttJoinGame']").click(function () {
const strPlayerName = $("#txtJoinGamePlayerName").val();
const strGameId = $("#txtJoinGameGameId").val();
console.log("buttJoinGame clicked. strPlayerName=" + strPlayerName + ", strGameId=" + strGameId);
socket.emit('joinGame', strPlayerName, strGameId);
});
// [chooseGenerals] click
$("button[name='buttChooseGenerals']").click(function () {
const strGameId = $("#txtChooseGeneralsGameId").val();
const strGeneralName = $("#txtChooseGeneralsGenName").val();
const generalArray = strGeneralName.split(',', 2);
console.log("buttChooseGenerals clicked. strGameId=" + strGameId + ", strGeneralName=" + strGeneralName, generalArray);
socket.emit('chooseGenerals', strGameId, generalArray);
});
}
}
// Function to handle all messages sent from server
MAIN.OnDataReceived = function (message, data) {
console.log(message + " received");
// Convert data to string
const strJson = JSON.stringify(data);
// Get current time
const strTime = new Date().toLocaleTimeString();
// Generate dr and add to table
const dr = $("<tr class='receive' onclick='MAIN.msgClick(this)'> <td class='message'>" + message + "</td> <td class='content'>" + strJson + "</td> <td class='time'>" + strTime + "</td> </tr>");
$(".clickable-table > tbody").append(dr);
// Auto scroll to bottom
$("#divSc").scrollTop($("#divSc")[0].scrollHeight);
// Display latest gameStatus to JSON-Viewer for reading easily
if (message == 'gameUpdate') {
var options = {
collapsed: $('#collapsed').is(':checked'),
withQuotes: $('#with-quotes').is(':checked')
};
$("#jviewlastGameStatus").jsonViewer(data, options);
$("#labLastGameStatusTime").html(strTime);
}
}
// Message row click
MAIN.msgClick = function (dr) {
// Get data in string
const strData = $(dr).find("td.content").html();
try {
// Convert to object
const input = eval('(' + strData + ')');
// Display in JSON-Viewer for reading easily
$('#jviewRow').jsonViewer(input);
}
catch (error) {
return console.log("Cannot eval JSON: " + error);
}
}
|
PHP
|
UTF-8
| 581 | 2.796875 | 3 |
[] |
no_license
|
<?php
namespace Dnoegel\Rules\Rule\Container;
use Dnoegel\Rules\Rule;
/**
* Container defines the interface for special rules, which conjunct child rules
*
* Interface Container
* @package Dnoegel\Rules\Rule\Container
*/
interface Container extends Rule
{
/**
* Set the internal rule collection to $rules
*
* @param $rules
* @return mixed
*/
public function setRules($rules);
/**
* Add one rule to the internal rule collection
*
* @param Rule $rule
* @return mixed
*/
public function addRule(Rule $rule);
}
|
Python
|
UTF-8
| 780 | 2.859375 | 3 |
[] |
no_license
|
import warnings
warnings.filterwarnings("ignore", category=FutureWarning, module="sklearn")
import numpy as np
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
iris=datasets.load_iris()
log_model = LogisticRegression()
scores = cross_val_score(log_model, iris.data, iris.target, cv=10)
print(scores)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
from sklearn.model_selection import LeaveOneOut
loo = LeaveOneOut()
accuracy = 0
for train, test in loo.split(iris.data):
log_model.fit(iris.data[train], iris.target[train]) # fitting
y_p = log_model.predict(iris.data[test])
if y_p == iris.target[test] : accuracy += 1
print(accuracy / np.shape(iris.data)[0])
|
Python
|
UTF-8
| 175 | 3.09375 | 3 |
[] |
no_license
|
from random import *
lists=["deep","dev","ashish"]
tup=("deep","dev","ashish")
def names(l,t):
print(l[0])
print(t[0])
print(choice(l))
print(choice(t))
names(lists,tup)
|
Python
|
UTF-8
| 4,924 | 2.8125 | 3 |
[] |
no_license
|
import numpy
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import Dropout
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras.optimizers import SGD
# Размер мини-выборки
batch_size = 32
# Количество классов изображений
nb_classes = 10
# Количество эпох для обучения
nb_epoch = 25
# Размер изображений
img_rows, img_cols = 32, 32
# Количество каналов в изображении: RGB
img_channels = 3
numpy.random.seed(42)
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
"""
Необходимо выполнить предварительную обработку данных.
Данные об интенсивности пикселей изображения необходимо нормализовать, чтобы все они находились в диапазоне
от 0 до 1, для этого этого преобразуем их в тип float32 и делим на 255.
"""
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
"""
Метки классов необходимо преобразовать в категории. На выходе наша сеть имеет 10 нейронов и выходной сигнал
нейронов, соответствует вероятности того, что изображение принадлежит к данному классу, соответственно номера классов в
метках мы должны преобразовать в представления по категориям.
"""
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
model = Sequential()
"""
Convolution2D - свёрточный слой, который работает с двухмерными данными, этот слой будет иметь 32 карты признаков
размер ядра свёртки на каждой карте 3 на 3, размер входных данных 3 на 32 на 32, что соответствует 3м каналам изображения
для кодов трёх цветов ргб, размер изображения 32 на 32.
"""
model.add(Conv2D(32, (3, 3), padding='same', input_shape=(32, 32, 3), activation='relu'))
# Второй слой
model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
# Слой подвыборки, pool_size - размер уменьшения размерности 2 на 2.
# MaxPooling2D из квадратика 2 на 2 выбирается макс. значение
model.add(MaxPooling2D(pool_size=(2, 2)))
"""
После каскада из двух свёрточных слоёв и слоя подвыборки, мы добавляем слой регуляризации.
"""
model.add(Dropout(0.25))
# Третий слой, больше карт признаков - 64
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
# Четвёртый слой
model.add(Conv2D(64, (3, 3), activation='relu'))
# Второй слой подвыборки
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# Слой преобразования данных из 2D представления в плоское
model.add(Flatten())
"""
Классификатор, по признакам найденных свёрточной сетью, выполняет определение к какому конкретно классу
принадлежит объект на картинке.
Начало нужно преобразовать сеть из двумерного представления в плоское - слой Flatten
Затем добавляем два полно связных слоя Dense.
Суммарное значение всех 10 нейронов = 1
"""
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5)) # выключает нейроны с вероятностью 50%
model.add(Dense(10, activation='softmax'))
# Компилируем сеть
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(
loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy']
)
# Обучаем сесть
# shuffle - перемешивать данные в начале каждой эпохи
model.fit(
X_train, Y_train,
batch_size=batch_size,
epochs=nb_epoch,
validation_split=0.1,
shuffle=True, verbose=2
)
scores = model.evaluate(X_test, Y_test, verbose=0)
print("Точность работы на тестовых данных: %.2f%%" % (scores[1]*100))
|
C#
|
UTF-8
| 15,823 | 3.25 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Specialized;
using static Auxiliary.Primitives;
namespace Auxiliary
{
public static partial class BasicStringDrawer
{
private static readonly List<MultilineString> multilineStringCache = new List<MultilineString>();
/// <summary>
/// Clears the cache of multiline string. Then runs garbage collector. (Searching the cache is faster than drawing a multiline string from cache, but if the cache has too many unused entries, searching it is slow.)
/// </summary>
public static void ClearStringCache()
{
multilineStringCache.Clear();
GC.Collect();
}
/// <summary>
/// Draws a multiline text using the Primitives spritebatch.
/// </summary>
/// <param name="text">Text to be drawn.</param>
/// <param name="rectangle">The rectangle bounding the text.</param>
/// <param name="color">Text color.</param>
/// <param name="font">Text font (Verdana 14, if null).</param>
/// <param name="alignment">Text alignment.</param>
public static void DrawMultiLineText(
string text,
Rectangle rectangle,
Color color,
SpriteFont font = null,
TextAlignment alignment = TextAlignment.TopLeft,
bool shadowed = false)
{
if (font == null) font = Library.FontVerdana;
MultilineString ms = new MultilineString(text, rectangle, alignment, font, Vector2.Zero, true, null);
foreach (MultilineString msCache in multilineStringCache)
{
if (ms.Equals(msCache))
{
foreach (MultilineLine line in msCache.CachedLines)
{
if (shadowed)
{
Color shadowColor = Color.White;/*
if (color.IsLight())
{
shadowColor = Color.Black;
}*/
Primitives.SpriteBatch.DrawString(font, line.Text, new Vector2(rectangle.X + line.PositionOffset.X + 1, rectangle.Y + line.PositionOffset.Y -1), shadowColor);
Primitives.SpriteBatch.DrawString(font, line.Text, new Vector2(rectangle.X + line.PositionOffset.X - 1, rectangle.Y + line.PositionOffset.Y - 1), shadowColor);
Primitives.SpriteBatch.DrawString(font, line.Text, new Vector2(rectangle.X + line.PositionOffset.X + 1, rectangle.Y + line.PositionOffset.Y + 1), shadowColor);
Primitives.SpriteBatch.DrawString(font, line.Text, new Vector2(rectangle.X + line.PositionOffset.X - 1, rectangle.Y + line.PositionOffset.Y + 1), shadowColor);
}
Primitives.SpriteBatch.DrawString(font, line.Text, new Vector2(rectangle.X + line.PositionOffset.X, rectangle.Y + line.PositionOffset.Y), color);
}
return;
}
}
DrawMultiLineTextDetailedParameters(Primitives.SpriteBatch, font, text, rectangle, color, alignment, true, new Vector2(0, 0), out Rectangle empty, out List<MultilineLine> cachedLines, shadowed: true);
multilineStringCache.Add(new MultilineString(text, rectangle, alignment, font, Vector2.Zero, true, cachedLines));
}
/// <summary>
/// If the text were written to the specified rectangle, how much width and height would it actually use?
/// This method ignores the rectangle's X and Y properties.
/// </summary>
/// <param name="text">Text to draw.</param>
/// <param name="rectangle">Rectangle bounding the text.</param>
/// <param name="font">Font to use.</param>
public static Rectangle GetMultiLineTextBounds(string text, Rectangle rectangle, SpriteFont font = null)
{
if (font == null) font = Library.FontVerdana;
DrawMultiLineTextDetailedParameters(Primitives.SpriteBatch, font, text, rectangle, Color.Black, TextAlignment.TopLeft, true, new Vector2(0, 0), out Rectangle bounds, out List<MultilineLine> empty, shadowed: false, onlyGetBounds: true);
return bounds;
}
/// <summary>
/// Draws a multi-string.
/// WARNING! This grows more CPU-intensive as the number of words grow (only if word wrap enabled). It is recommended to use the DrawMultiLineText method instead - it uses caching.
/// </summary>
/// <param name="sb">A reference to a SpriteBatch object that will draw the text.</param>
/// <param name="fnt">A reference to a SpriteFont object.</param>
/// <param name="text">The text to be drawn. <remarks>If the text contains \n it
/// will be treated as a new line marker and the text will drawn acordingy.</remarks></param>
/// <param name="r">The screen rectangle that the rext should be drawn inside of.</param>
/// <param name="col">The color of the text that will be drawn.</param>
/// <param name="align">Specified the alignment within the specified screen rectangle.</param>
/// <param name="performWordWrap">If true the words within the text will be aranged to rey and
/// fit within the bounds of the specified screen rectangle.</param>
/// <param name="offsett">Draws the text at a specified offset relative to the screen
/// rectangles top left position. </param>
/// <param name="textBounds">Returns a rectangle representing the size of the bouds of
/// the text that was drawn.</param>
/// <param name="cachedLines">This parameter is internal. Do not use it, merely throw away the variable.</param>
/// <param name="onlyGetBounds">Do not actually draw the text. Instead, merely return (in textBounds) the bounds.</param>
public static void DrawMultiLineTextDetailedParameters(SpriteBatch sb, SpriteFont fnt, string text, Rectangle r,
Color col, TextAlignment align, bool performWordWrap, Vector2 offsett, out Rectangle textBounds, out List<MultilineLine> cachedLines, bool shadowed, bool onlyGetBounds = false)
{
// check if there is text to draw
textBounds = r;
cachedLines = new List<MultilineLine>();
if (text == null) return;
if (text == string.Empty) return;
StringCollection lines = new StringCollection();
lines.AddRange(text.Split(new string[] { "\\n", Environment.NewLine, "\n" }, StringSplitOptions.None));
// calc the size of the rectangle for all the text
Rectangle tmprect = ProcessLines(fnt, r, performWordWrap, lines);
if (onlyGetBounds) { textBounds = tmprect; return; }
// setup the position where drawing will start
Vector2 pos = new Vector2(r.X, r.Y);
int aStyle = 0;
switch (align)
{
case TextAlignment.Bottom:
pos.Y = r.Bottom - tmprect.Height;
aStyle = 1;
break;
case TextAlignment.BottomLeft:
pos.Y = r.Bottom - tmprect.Height;
aStyle = 0;
break;
case TextAlignment.BottomRight:
pos.Y = r.Bottom - tmprect.Height;
aStyle = 2;
break;
case TextAlignment.Left:
pos.Y = r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 0;
break;
case TextAlignment.Middle:
pos.Y = r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 1;
break;
case TextAlignment.Right:
pos.Y = r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 2;
break;
case TextAlignment.Top:
aStyle = 1;
break;
case TextAlignment.TopLeft:
aStyle = 0;
break;
case TextAlignment.TopRight:
aStyle = 2;
break;
}
// draw text
foreach (string txt in lines)
{
Vector2 size = fnt.MeasureString(txt);
switch (aStyle)
{
case 0:
pos.X = r.X;
break;
case 1:
pos.X = r.X + (r.Width / 2 - (size.X / 2));
break;
case 2:
pos.X = r.Right - size.X;
break;
}
if (pos.Y + fnt.LineSpacing > r.Y + r.Height) { break; }
// draw the line of text
pos = new Vector2((int)pos.X, (int)pos.Y);
if (shadowed)
{
sb.DrawString(fnt, txt, pos + offsett + new Vector2(1, -1), Color.Black);
}
sb.DrawString(fnt, txt, pos + offsett, col);
cachedLines.Add(new MultilineLine(txt, pos + offsett - new Vector2(r.X, r.Y)));
pos.Y += fnt.LineSpacing;
}
textBounds = tmprect;
}
internal static Rectangle ProcessLines(SpriteFont fnt, Rectangle r, bool performWordWrap, StringCollection lines)
{
// loop through each line in the collection
Rectangle bounds = r;
bounds.Width = 0;
bounds.Height = 0;
int index = 0;
bool lineInserted = false;
while (index < lines.Count)
{
// get a line of text
string linetext = lines[index];
//measure the line of text
Vector2 size = fnt.MeasureString(linetext);
// check if the line of text is geater then then the rectangle we want to draw it inside of
if (performWordWrap && size.X > r.Width)
{
// find last space character in line
string endspace = string.Empty;
// deal with trailing spaces
if (linetext.EndsWith(" "))
{
endspace = " ";
linetext = linetext.TrimEnd();
}
// get the index of the last space character
int i = linetext.LastIndexOf(" ", StringComparison.Ordinal);
if (i != -1)
{
// if there was a space grab the last word in the line
string lastword = linetext.Substring(i + 1);
// move word to next line
if (index == lines.Count - 1)
{
lines.Add(lastword);
lineInserted = true;
}
else
{
// prepend last word to begining of next line
if (lineInserted)
{
lines[index + 1] = lastword + endspace + lines[index + 1];
}
else
{
lines.Insert(index + 1, lastword);
lineInserted = true;
}
}
// crop last word from the line that is being processed
lines[index] = linetext.Substring(0, i + 1);
}
else
{
// there appear to be no space characters on this line s move to the next line
lineInserted = false;
// size = fnt.MeasureString(lines[index]);
bounds.Height += fnt.LineSpacing;// size.Y - 1;
index++;
}
}
else
{
// this line will fit so we can skip to the next line
lineInserted = false;
size = fnt.MeasureString(lines[index]);
if (size.X > bounds.Width) bounds.Width = (int)size.X;
bounds.Height += fnt.LineSpacing;//size.Y - 1;
index++;
}
}
// returns the size of the text
return bounds;
}
/// <summary>
/// Do not use this class outside Auxiliary 3.
/// </summary>
public class MultilineLine
{
/// <summary>
/// Do not use this class outside Auxiliary 3.
/// </summary>
public string Text;
/// <summary>
/// Do not use this class outside Auxiliary 3.
/// </summary>
public Vector2 PositionOffset;
/// <summary>
/// Do not use this class outside Auxiliary 3.
/// </summary>
public MultilineLine(string text, Vector2 position)
{
Text = text;
PositionOffset = position;
}
}
private class MultilineString
{
private readonly string text;
private readonly Rectangle rectangle;
private readonly TextAlignment textAlignment;
private readonly SpriteFont font;
private readonly Vector2 offset;
private readonly bool wordWrap;
public readonly List<MultilineLine> CachedLines;
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
MultilineString ms = (MultilineString)obj;
return offset == ms.offset && wordWrap == ms.wordWrap && text == ms.text &&
rectangle.Width == ms.rectangle.Width &&
rectangle.Height == ms.rectangle.Height
&& textAlignment == ms.textAlignment && font == ms.font;
}
public override int GetHashCode()
{
// Does this hash really work?
// Also, we are using implicit modulo.
return (
33 * 33 * 33 * 33 * 33 * 33 * text.GetHashCode() +
33 * 33 * 33 * 33 * 33 * rectangle.GetHashCode() +
33 * 33 * 33 * 33 * textAlignment.GetHashCode() +
33 * 33 * 33 * font.GetHashCode() +
33 * 33 * offset.GetHashCode() +
33 * wordWrap.GetHashCode());
}
public MultilineString(string text, Rectangle rect, TextAlignment alignment, SpriteFont font, Vector2 offset, bool wordWrap, List<MultilineLine> cachedLines)
{
this.CachedLines = cachedLines;
this.text = text;
rectangle = rect;
textAlignment = alignment;
this.font = font;
this.offset = offset;
this.wordWrap = wordWrap;
CachedLines = cachedLines;
}
}
}
}
|
Java
|
UTF-8
| 465 | 2.109375 | 2 |
[] |
no_license
|
package questions.booking;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import ui.booking.BookingPage;
public class BookingMessage implements Question<String> {
@Override
public String answeredBy(Actor actor) {
return BookingPage.SEARCH_SUCCESS_MESSAGE.resolveFor(actor).waitUntilVisible().getText();
}
public static BookingMessage getSuccessMessage() {
return new BookingMessage();
}
}
|
Java
|
UTF-8
| 800 | 2.671875 | 3 |
[] |
no_license
|
package test;
import bean.Bean1;
import bean.Bean2;
import bean.Bean3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取bean对象
Bean1 bean1 = (Bean1) context.getBean("bean1");
Bean2 bean2 = (Bean2) context.getBean("bean2");
Bean3 bean3 = (Bean3) context.getBean("bean3");
// 输出bean对象地址
System.out.println("Bean1对象的地址为:"+bean1);
System.out.println("Bean2对象的地址为:"+bean2);
System.out.println("Bean3对象的地址为:"+bean3);
}
}
|
Java
|
UTF-8
| 1,971 | 2.21875 | 2 |
[] |
no_license
|
package com.tu.ziik.lms.recommender.engines;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;
import org.apache.mahout.cf.taste.impl.model.jdbc.ReloadFromJDBCDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.JDBCDataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
@Service
public class RecommenderEngine {
@Autowired
private JDBCDataSource jdbc;
public List<RecommendedItem> getRecommendation(int user_id, int number_of_item) throws TasteException {
MysqlDataSource dataSource = jdbc.getDataSource();
JDBCDataModel dataModel = new MySQLJDBCDataModel(dataSource, "user_rating", "user_id", "item_id", "rating",
"timestamp");
ReloadFromJDBCDataModel datamodel2 = new ReloadFromJDBCDataModel(dataModel);
UserSimilarity sim = new PearsonCorrelationSimilarity(datamodel2);
UserNeighborhood nbh = new NearestNUserNeighborhood(40, sim, datamodel2);
Recommender recsys = new GenericUserBasedRecommender(datamodel2, nbh, sim);
recsys.refresh(null);
List<RecommendedItem> recommendations = recsys.recommend(user_id, number_of_item);
System.out.println("____________________________");
for(RecommendedItem item:recommendations){
System.out.println(item.getItemID()+","+item.getValue());
}
return recommendations;
}
}
|
Python
|
UTF-8
| 11,640 | 3.828125 | 4 |
[] |
no_license
|
class Property:
"""Class of property"""
def __init__(self, square_feet='', beds='',
baths='', **kwargs):
"""
Initialize all arguments.
:param square_feet: int
:param beds: int
:param baths: int
:param kwargs:
"""
super().__init__(**kwargs)
self.square_feet = square_feet
self.num_bedrooms = beds
self.num_baths = baths
def display(self):
"""
Function show all info about property.
:return:
"""
print("\nPROPERTY DETAILS")
print("================")
print("square footage: {}".format(self.square_feet))
print("bedrooms: {}".format(self.num_bedrooms))
print("bathrooms: {}".format(self.num_baths))
print()
def prompt_init():
"""
Function return dict with square_feet, beds, baths that input.
:return: dict
"""
return dict(square_feet=input("Enter the square feet: "),
beds=input("Enter number of bedrooms: "),
baths=input("Enter number of baths: "))
prompt_init = staticmethod(prompt_init)
class Apartment(Property):
"""Class of apartment that inherit class Property"""
valid_laundries = ("coin", "ensuite", "none")
valid_balconies = ("yes", "no", "solarium")
def __init__(self, balcony='', laundry='', **kwargs):
"""
Initialize all arguments.
:param balcony: str
:param laundry: str
:param kwargs:
"""
super().__init__(**kwargs)
self.balcony = balcony
self.laundry = laundry
def display(self):
"""
Show all necessary info about apartment details.
:return:
"""
super().display()
print("\nAPARTMENT DETAILS")
print("laundry: %s" % self.laundry)
print("has balcony: %s" % self.balcony)
def prompt_init():
"""
Function determine info about laundry and balcony and add them
to the dict from prompt_init in class Property
:return: dict
"""
parent_init = Property.prompt_init()
laundry = ''
while laundry.lower() not in \
Apartment.valid_laundries:
laundry = input("What laundry facilities does "
"the property have? ({})".format(
", ".join(Apartment.valid_laundries)))
balcony = ''
while balcony.lower() not in \
Apartment.valid_balconies:
balcony = input(
"Does the property have a balcony? "
"({})".format(
", ".join(Apartment.valid_balconies)))
parent_init.update({
"laundry": laundry,
"balcony": balcony
})
return parent_init
prompt_init = staticmethod(prompt_init)
def get_valid_input(input_string, valid_options):
"""
Function get valid input to know info about laundry and balcony.
:param input_string: str
:param valid_options: list
:return: str
"""
input_string += " ({}) ".format(", ".join(valid_options))
response = input(input_string)
while response.lower() not in valid_options:
response = input(input_string)
return response
def prompt_init():
"""
Function add values of landry and balcony into dict from prompt_init
of class Property.
:return: dict
"""
parent_init = Property.prompt_init()
laundry = get_valid_input(
"What laundry facilities does "
"the property have? ",
Apartment.valid_laundries)
balcony = get_valid_input(
"Does the property have a balcony? ",
Apartment.valid_balconies)
parent_init.update({
"laundry": laundry,
"balcony": balcony
})
return parent_init
prompt_init = staticmethod(prompt_init)
class House(Property):
"""Class of house that inherit class Property"""
valid_garage = ("attached", "detached", "none")
valid_fenced = ("yes", "no")
def __init__(self, num_stories='',
garage='', fenced='', **kwargs):
"""
Initialize all arguments.
:param num_stories: str
:param garage: str
:param fenced: str
:param kwargs:
"""
super().__init__(**kwargs)
self.garage = garage
self.fenced = fenced
self.num_stories = num_stories
def display(self):
"""
Show all necessary info about house details.
:return:
"""
super().display()
print("\nHOUSE DETAILS")
print("# of stories: {}".format(self.num_stories))
print("garage: {}".format(self.garage))
print("fenced yard: {}".format(self.fenced))
def prompt_init():
"""
Function add info about garage, fence, stories in dict from prompt_init
of class Property
:return: dict
"""
parent_init = Property.prompt_init()
fenced = get_valid_input("Is the yard fenced? ",
House.valid_fenced)
garage = get_valid_input("Is there a garage? ",
House.valid_garage)
num_stories = input("How many stories? ")
parent_init.update({
"fenced": fenced,
"garage": garage,
"num_stories": num_stories
})
return parent_init
prompt_init = staticmethod(prompt_init)
class Purchase:
"""
Class of purchase.
"""
def __init__(self, price='', taxes='', **kwargs):
"""
Initialize all arguments.
:param price: str
:param taxes: str
:param kwargs:
"""
super().__init__(**kwargs)
self.price = price
self.taxes = taxes
def display(self):
"""
Show all necessary info about purchase details.
:return:
"""
super().display()
print("\nPURCHASE DETAILS")
print("selling price: {}".format(self.price))
print("estimated taxes: {}".format(self.taxes))
def prompt_init():
"""
Function make dict with price and taxes as key.
:return: dict
"""
return dict(
price=input("What is the selling price? "),
taxes=input("What are the estimated taxes? "))
prompt_init = staticmethod(prompt_init)
class Rental:
"""
Class of rental.
"""
def __init__(self, furnished='', utilities='',
rent='', **kwargs):
"""
Initialize all arguments.
:param furnished: str
:param utilities: str
:param rent: str
:param kwargs:
"""
super().__init__(**kwargs)
self.furnished = furnished
self.rent = rent
self.utilities = utilities
def display(self):
"""
Show all necessary info about rental details
:return:
"""
super().display()
print("\nRENTAL DETAILS")
print("rent: {}".format(self.rent))
print("estimated utilities: {}".format(self.utilities))
print("furnished: {}".format(self.furnished))
def prompt_init():
"""
Function make dict with rent, utilities and furnished as key.
:return: dict
"""
return dict(
rent=input("What is the monthly rent? "),
utilities=input("What are the estimated utilities? "),
furnished=get_valid_input("Is the property furnished? ",
("yes", "no")))
prompt_init = staticmethod(prompt_init)
class HouseRental(Rental, House):
"""
Class of house rental that inherit two classes: Rental and House.
"""
def prompt_init():
"""
Update dict from class House by dict from class Rental.
:return: dict
"""
init = House.prompt_init()
init.update(Rental.prompt_init())
return init
prompt_init = staticmethod(prompt_init)
class ApartmentRental(Rental, Apartment):
"""
Class of apartment rental that inherit two classes: Rental and Apartment.
"""
def prompt_init():
"""
Update dict from class Apartment by dict from class Rental.
:return: dict
"""
init = Apartment.prompt_init()
init.update(Rental.prompt_init())
return init
prompt_init = staticmethod(prompt_init)
class ApartmentPurchase(Purchase, Apartment):
"""
Class of apartment purchase that inherit two classes: Purchase and Apartment.
"""
def prompt_init():
"""
Update dict from class Apartment by dict from class Purchase.
:return: dict
"""
init = Apartment.prompt_init()
init.update(Purchase.prompt_init())
return init
prompt_init = staticmethod(prompt_init)
class HousePurchase(Purchase, House):
"""
Class of house purchase that inherit two classes: Purchase and House.
"""
def prompt_init():
"""
Update dict from class House by dict from class Purchase.
:return: dict
"""
init = House.prompt_init()
init.update(Purchase.prompt_init())
return init
prompt_init = staticmethod(prompt_init)
class Agent:
"""
Class of agent.
"""
def __init__(self):
"""
Initialize property list.
"""
self.property_list = []
def start(self):
"""
Function return yes or no and choose start the program or not.
:return: str
"""
print("Hello, I'am your online agent")
choice = get_valid_input("Can we start?",
("yes", "no")).lower()
if choice == "yes":
print("\nOkey. Let`s start.")
else:
print("\nGoodbye. Hope to see you soon.")
exit()
return choice
def display_properties(self):
"""
Show property from property list
:return:
"""
for property in self.property_list:
property.display()
type_map = {
("house", "rental"): HouseRental,
("house", "purchase"): HousePurchase,
("apartment", "rental"): ApartmentRental,
("apartment", "purchase"): ApartmentPurchase
}
def add_property(self):
"""
:return:
"""
property_type = get_valid_input(
"What type of property? ",
("house", "apartment")).lower()
payment_type = get_valid_input(
"What payment type? ",
("purchase", "rental")).lower()
PropertyClass = self.type_map[
(property_type, payment_type)]
init_args = PropertyClass.prompt_init()
self.property_list.append(PropertyClass(**init_args))
def main(self):
"""
Function to start the program.
:return:
"""
step1 = self.start()
step2 = self.add_property()
step3 = self.display_properties()
if step1 == "yes":
print(step1, step2, step3)
else:
exit()
agent = Agent()
print(agent.main())
|
Java
|
GB18030
| 1,192 | 2.25 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
package elf.server.ems.mock.ui.deal.manual.transform;
import org.springframework.stereotype.Service;
import elf.api.ems.consts.EmsPriceModeConsts;
@Service
public class PriceModeTransform {
public String transform(String priceMode) {
if (EmsPriceModeConsts.MARKET_IMMEDIATE_OTHER_CANCEL.equals(priceMode)) {
return "мۼʣ";
} else if (EmsPriceModeConsts.MARKET_FIVE_LEVEL_OTHER_CANCEL.equals(priceMode)) {
return "м嵵ʣ";
} else if (EmsPriceModeConsts.MARKET_FIVE_LEVEL_OTHER_CHANGE.equals(priceMode)) {
return "м嵵ʣת ";
} else if (EmsPriceModeConsts.MARKET_ALL_OR_CANCEL.equals(priceMode)) {
return "ȫɻ";
} else if (EmsPriceModeConsts.MARKET_OUR_BEST.equals(priceMode)) {
return "";
} else if (EmsPriceModeConsts.MARKET_COUNTERPARTY_BEST.equals(priceMode)) {
return "ַ";
} else if (EmsPriceModeConsts.LIMIT_IMMEDIATE_OTHER_CHANGE.equals(priceMode)) {
return "ۼʣת";
} else if (EmsPriceModeConsts.LIMIT_IMMEDIATE_OTHER_CANCEL.equals(priceMode)) {
return "ۼʣ";
} else {
return null;
}
}
}
|
Java
|
UTF-8
| 10,391 | 2.609375 | 3 |
[] |
no_license
|
package com.sinopoc.myspring.servlet;
import com.sinopoc.annotation.KAutowired;
import com.sinopoc.annotation.KController;
import com.sinopoc.annotation.KRequestMapping;
import com.sinopoc.annotation.KService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
public class KDispatcherServlet extends HttpServlet{
private Properties p=new Properties();
private List<String> classNames=new ArrayList<String>();
private Map<String,Object> Ioc=new HashMap<String,Object>();
private Map<String,Method> handlerMapping=new HashMap<String,Method>();
private Map<String,Object> controllerMap=new HashMap<>();
//初始化阶段调用的 方法
@Override
public void init(ServletConfig config) throws ServletException {
//1.加载配置文件
String contextConfigLocation = config.getInitParameter("contextConfigLocation");
doLoad(contextConfigLocation);
//2.扫描所有配置类
doScanner(p.getProperty("scannerPackage"));
//3.实例化所有配置类,并放入IOC容器中,map<String,Object>
doInstance();
//4.实现依赖注入
doAutowired();
//5.初始化HandlerMapping
try {
initHandlerMapping();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
super.init(config);
}
private void initHandlerMapping() throws IllegalAccessException, InstantiationException {
//1.判断IOC是否为空
if(Ioc.isEmpty()){return;}
//2.遍历Ioc容器,探讨每一个带controller注解的类
for (Map.Entry<String,Object> realClass:Ioc.entrySet() ) {
//如果不带controller注解的,继续
Class<?> clazz = realClass.getValue().getClass();
if(!clazz.isAnnotationPresent(KController.class)){
continue;
}
//反射获取类上的requestmapping
String baseUrl="";
if(clazz.isAnnotationPresent(KRequestMapping.class)){
baseUrl = clazz.getAnnotation(KRequestMapping.class).value().replaceAll("/+", "/");
}
//获取所有方法方法,和方法上的 requestmapping 路径名:方法对象,存到map中
Method[] methods = clazz.getMethods();
for (Method method:methods) {
//判断是否有requestmapping
if(!method.isAnnotationPresent(KRequestMapping.class)){continue;}
String methodUrl = method.getAnnotation(KRequestMapping.class).value().replaceAll("/+", "/");
//baseurl+methodurl 作为k,method作为v 赋值给Handlermapping
String url=baseUrl+methodUrl;
handlerMapping.put(url,method);
controllerMap.put(url,clazz.newInstance());
}
}
}
private void doAutowired() {
//1.ioc是否为空,返回
if(Ioc.isEmpty()){return;}
//遍历Ioc容器,找出每个类中的每个field
for (Map.Entry<String,Object> entry:Ioc.entrySet()) {
//获取到每个类对象
Object object = entry.getValue();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field:fields) {
System.out.println(field.getName());
//找出所有有注解的成员变量
if(!field.isAnnotationPresent(KAutowired.class)){ continue;}
//过滤出autowired下的,获取成员变量的value,判断是否指明注入方,否则就是接口注入
String objectName = field.getAnnotation(KAutowired.class).value().trim();
if ("".equals(objectName)){
//意味着是接口注入
objectName=field.getType().getName();
}
//前期都是为了根据autowired确定k值
//接下来根据k从ioc中匹配,给field赋值
//首先暴力反射
field.setAccessible(true);
//赋值
try {
field.set(object,Ioc.get(objectName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
private void doInstance() {
//判断集合是否为空,是则返回
if(classNames.isEmpty()){return;}
//遍历list集合,通过反射进行实例化,并放到map中
try {
for (String className:classNames) {
Class<?> realClass = Class.forName(className);
String objectName =null;
//只有有注解的才实例化
if(realClass.isAnnotationPresent(KController.class)){
//controller使用默认的开头小写
objectName=lowerFirstCase(realClass.getSimpleName());
Ioc.put(objectName,realClass.newInstance());
}else if(realClass.isAnnotationPresent(KService.class)){
//2.如果指定名,用指定的名字 获得注解对象的value
KService kService = realClass.getAnnotation(KService.class);
objectName = kService.value();
if("".equals(objectName.trim())){
//如果没有指定
objectName =lowerFirstCase(realClass.getSimpleName());
}
Ioc.put(objectName,realClass.newInstance());
//3.如果是接口,用接口的类型作为k
Class<?>[] interfaces = realClass.getInterfaces();
for (Class i:interfaces) {
Ioc.put(i.getName(),realClass.newInstance()) ;
}
}else{
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String lowerFirstCase(String simpleName) {
char[] chars = simpleName.toCharArray();
chars[0]+=32;
return String.valueOf(chars);
}
private void doScanner(String scannerPackage) {
//进行递归扫描
URL url = this.getClass().getClassLoader().getResource("/" + scannerPackage.replaceAll("\\.", "/"));
File classDir = new File(url.getFile());
for (File file:classDir.listFiles()) {
if(file.isDirectory()){
//scannerPackage: com.keviv
doScanner(scannerPackage+"."+file.getName());
}else{
//记录所有类的全路径名,且是不带.class的
classNames.add(scannerPackage+"."+file.getName().replaceAll("\\.class",""));
}
}
}
private void doLoad(String contextConfigLocation) {
//用classloader获取该文件的stream
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
try {
p.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null!=resourceAsStream){
try {
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
//运行时阶段执行的方法
//6.等待请求
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
doDispatch(req,resp);
}catch(Exception e){
resp.getWriter().write("500 ! the server is crackdown");
}
}
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//根据uri匹配handlerMapping中对应的方法,并调用
// /myspring/query
String requestURI = req.getRequestURI();
///myspring
String contextPath = req.getContextPath();
String realUri = requestURI.replace(contextPath, "").replaceAll("/+", "/");
//判断handlermapping中是否包含
if(!handlerMapping.containsKey(realUri)){
resp.getWriter().write("404! not found!");
return ;
}
//获取方法的参数列表
Method method = handlerMapping.get(realUri);
Class<?>[] parameterTypes = method.getParameterTypes();
Map<String,String[]> parameterMap = req.getParameterMap();
Object[] patamsValues = new Object[parameterTypes.length];
for (int i = 0; i <parameterTypes.length ; i++) {
String simpleName = parameterTypes[i].getSimpleName();
if("HttpServletRequest".equals(simpleName)){
patamsValues[i]=req;
continue;
}
if("HttpServletResponse".equals(simpleName)){
patamsValues[i]=resp;
continue;
}
if("String".equals(simpleName)){
//如果是一般参数,就遍历所有request携带的参数,分别赋值给object[]
for (Map.Entry<String,String[]> param:parameterMap.entrySet()){
patamsValues[i]=Arrays.toString( param.getValue());
}
continue;
}
}
//最后调用方法
try {
Object o = this.controllerMap.get(realUri);
System.out.println(o);
method.invoke(o, patamsValues);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
PHP
|
UTF-8
| 474 | 2.875 | 3 |
[] |
no_license
|
<?php
function connexionBd($SERVEUR = 'localhost', $USER = 'root', $MDP = '', $BD = 'Pizzeria')
{
try {
$connexion= new PDO('mysql:host='.$SERVEUR.';dbname='.$BD, $USER, $MDP);
$connexion->exec("SET CHARACTER SET utf8"); //Gestion des accents
return $connexion;
}
//gestion des erreurs
catch(Exception $e) {
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
}
?>
|
Java
|
UTF-8
| 222 | 1.734375 | 2 |
[] |
no_license
|
package com.xxx.messaging.filtering;
import com.xxx.messaging.Context;
import com.xxx.messaging.Notification;
public interface Filter {
boolean accept(Context context, Notification notification);
String name();
}
|
Markdown
|
UTF-8
| 2,317 | 3.34375 | 3 |
[] |
no_license
|
# GloVe: Global Vectors for Word Representation
Jeffrey Pennington, Richard Socher, Christopher Manning
(https://nlp.stanford.edu/pubs/glove.pdf, 2014)
### TL;DR
- A new global log-bilinear regression model that obtains vector representation of words. It combines benefits of word2vec model AND exploits global corpus information using co-occurence matrix (75% on word analogy task).
### Main Contributions
- Current Techniques & their problems:
- LSA (latent semantic analysis) - problem is bad on analogies (poor vector space structure)
- word2vec, skip-gram model - problem is it doesn't use global statistics.
- Solution is a weighted least squares model that trains on global word-word co-occurrence counts.
- The unsupervised learning algorithm produces results better than word2vec in most cases - but is also much faster, which is very important.
**My takeaway**: The key insight appears to be that relationship of words can be examined by calculating the ratio of their co-occurrence probabilities, while at the same time working on analogies.
### Relevant Architecture
The training objective of GloVe is to learn word vectors such that their dot product equals the logarithm of the words' probability of co-occurrence.
General idea: Ratios of words illustrate relationship. If P(k|w) is probability that word k appears in the context of word w, ratio of P(solid | ice) / P(solid | steam) will be large, indicating solid is related to ice more than steam. Note that the formula operates on difference between word vectors (rather than individual words)
<img src="https://github.com/sviswana/deeplearning-paper-summaries/blob/master/paper-imgs/glove.png" width="40%">
#### Certain training details
- Use a weighting function to ensure rare co-occurrences are not weighted as often.
- Complexity of the model is O(C^0.8) - where C is size of corpus. This is much better than O(C) which is typical of window based approaches.
### Results
GloVe does very well on the word analogy task (SOTA - 75%). Also succeeds on word similarity and entity recognition tasks. For same corpus, vocabulary size, and training time, GloVe outperforms word2vec.
### Future Work
Not explicitly mentioned in paper, but researchers have different preferences between predictive model used by word2vec vs/ the count-based model supported by this paper.
|
Java
|
UTF-8
| 317 | 1.632813 | 2 |
[] |
no_license
|
package com.example.todolist.test.runner;
import junit.framework.TestSuite;
public class Runner1 extends CommonRunner{
@Override
public TestSuite getAllTests() {
TestSuite suite = new TestSuite();
suite.addTest(LoginRunner.geTestSuite());
suite.addTest(TodoListSuite.geTestSuite());
return suite;
}
}
|
C++
|
SHIFT_JIS
| 3,958 | 2.734375 | 3 |
[] |
no_license
|
//=============================================================================
//
// CAttacjManagerNX [CAttacManager.cpp]
// Author : ˖{@rF
//
//=============================================================================
//*****************************************************************************
// CN[h
//*****************************************************************************
#include "CAttackNormal.h"
#include "../EFFECT/CEffectManager.h"
#include "../PLAYER/CPlayer.h"
//*****************************************************************************
// }N
//*****************************************************************************
// 蔻̎n܂鎞
static const short ATTACK_NORMAL_HIT_START_TIME = 5;
// 蔻̏I鎞
static const short ATTACK_NORMAL_HIT_END_TIME = 30;
// 蔻 蕝,
static const float ATTACK_NORMAL_HIT_WIDTH = 50;
static const float ATTACK_NORMAL_HIT_HEIGHT = 50;
// vCƍUGtFNg̋
static const float ATTACK_NORMAL_RANGE = 50;
static const float ATTACK_DAMAGE = -200.f;
//*****************************************************************************
// ÓIoϐ
//*****************************************************************************
//*****************************************************************************
// RXgN^
//*****************************************************************************
CAttackNormal::CAttackNormal(LPDIRECT3DDEVICE9 *pDevice) : CAttackBase(pDevice)
{
// ϐ
m_AttackType = ATTACK_TYPE_NORMAL;
// ̍ǓŗLXe[^X
m_fWidth = ATTACK_NORMAL_HIT_WIDTH;
m_fHeight = ATTACK_NORMAL_HIT_HEIGHT;
m_vRot = D3DXVECTOR3(0, 0, 0);
m_nEndTime = ATTACK_NORMAL_END_TIME;
m_nHitStartTime = ATTACK_NORMAL_HIT_START_TIME;
m_nHitEndTime = ATTACK_NORMAL_HIT_END_TIME;
}
//*****************************************************************************
// fXgN^
//*****************************************************************************
CAttackNormal ::~CAttackNormal(void)
{
}
//*****************************************************************************
//
//*****************************************************************************
HRESULT CAttackNormal::Init()
{
CAttackBase::Init();
CManager::PlaySoundA(SOUND_LABEL_SE_NORMAL_ATTACK);
return S_OK;
}
//*****************************************************************************
// I
//*****************************************************************************
void CAttackNormal::Uninit(void)
{
CAttackBase::Uninit();
}
//*****************************************************************************
// XV
//*****************************************************************************
void CAttackNormal::Update(void)
{
CAttackBase::Update();
}
//*****************************************************************************
// NGCg
//*****************************************************************************
CAttackNormal* CAttackNormal::Create(
LPDIRECT3DDEVICE9 *pDevice,
short nPlayerNum,
D3DXVECTOR3 pos,
D3DXVECTOR3 velocity)
{
// 쐬
CAttackNormal* p = new CAttackNormal(pDevice);
p->m_nPlayerNum = nPlayerNum;
p->m_vPos = pos + (velocity * ATTACK_NORMAL_RANGE);
//
p->Init();
// GtFNg
CEffectManager::CreateEffect(p->m_vPos, EFFECT_NORMAL_ATTACK_CAP, velocity);
return p;
}
//*****************************************************************************
// UqbgۂɌĂяo
// @@qbgvC[̃vC[ԍ
//*****************************************************************************
void CAttackNormal::HitPlayer(CPlayer* pPlayer)
{
pPlayer->AddHp(ATTACK_DAMAGE);
CAttackBase::HitPlayer(pPlayer);
}
//----EOF-------
|
Java
|
UTF-8
| 325 | 2.1875 | 2 |
[] |
no_license
|
package constants;
public final class FrameworkConstants {
private FrameworkConstants() {
}
private static final String PROPERTYFILEPATH = System.getProperty("user.dir") + "/src/main/resources/configProps.properties";
public static String getPropertyFilePath() {
return PROPERTYFILEPATH;
}
}
|
Java
|
UTF-8
| 1,245 | 2.1875 | 2 |
[] |
no_license
|
package vn.media.controller.music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import vn.media.controller.DBConnector;
import vn.media.models.DiaNhac;
import vn.media.view.MainFrame;
import vn.media.view.music.EditMusicView;
import vn.media.view.music.TableMusicPanel;
public class EditMusicController {
private JButton btnSua;
private TableMusicPanel tableMusicPanel;
public EditMusicController(MainFrame mainFrame, DBConnector db) {
btnSua = mainFrame.getFuncMusicPanel().getBtnSua();
tableMusicPanel = mainFrame.getTabbedProduct().getTableMusicPanel();
btnSua.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int index = tableMusicPanel.getTable().getSelectedRow();
// if a row is chosen
if (index >= 0) {
String id = tableMusicPanel.getTable().getModel().getValueAt(index, 0).toString();
DiaNhac dianhac = db.getMusic(id);
new EditMusicView(mainFrame,db, tableMusicPanel, dianhac);
} else {
JOptionPane.showMessageDialog(null, "Vui lòng chọn sách cần sửa !", "Thông báo",
JOptionPane.WARNING_MESSAGE);
}
}
});
}
}
|
Python
|
UTF-8
| 2,593 | 3.21875 | 3 |
[] |
no_license
|
from .Matrix import Matrix
from .Vector import Vector
from ._global import is_zero
class LinearSystem(object):
# 构建增广矩阵(argument matrix),增广矩阵结构为:Matix|Vector
def __init__(self, A, b):
assert A.row_num() == len(b), \
"row number of A must be equal to the length of b"
# 记录矩阵的行数和列数
self._r = A.row_num()
self._c = A.col_num()
self.pivots = []
if isinstance(b, Vector):
self.Ab = [Vector(A.row_vector(i).underlying_list() + [b[i]]) for i in range(self._r)]
elif isinstance(b, Matrix):
self.Ab = [Vector(A.row_vector(i).underlying_list() + b.row_vector(i).underlying_list()) for i in range(self._r)]
def _max_row(self, row, col):
"""返回元素往下所在列中的最大元素的下标"""
max_value, ret = self.Ab[row][col], row
for i in range(row + 1, self._r):
if self.Ab[i][col] > max_value:
max_value, ret = self.Ab[i][col], i
return ret
def _forward(self):
row = 0
col = 0
while row < self._r and col < self._c:
max_row = self._max_row(row, col)
if is_zero(self.Ab[max_row][col]):
col += 1
continue
self.Ab[row], self.Ab[max_row] = self.Ab[max_row], self.Ab[row]
# 主元归1
self.Ab[row] /= self.Ab[row][col]
self.pivots.append([row, col])
for i in range(row + 1, self._r):
self.Ab[i] -= self.Ab[row] * self.Ab[i][col]
row += 1
def _backward(self):
for n in range(len(self.pivots) - 1, -1, -1):
for i in range(0, self.pivots[n][0]):
self.Ab[i] -= self.Ab[self.pivots[n][0]] * self.Ab[i][self.pivots[n][1]]
def gauss_jordan_elimination(self):
"""如果有解返回True;如果没解,返回False"""
self._forward()
self._backward()
for i in range(len(self.pivots),self._r):
if not is_zero(self.Ab[i][self._c]):
return False
return True
def fancy_print(self):
print()
for i in range(self._r):
print(" ".join(str(self.Ab[i][j]) for j in range(self._c)), end=" ")
print("|", self.Ab[i][self._c])
def inv(A):
n = A.row_num()
if n!= A.col_num():
return None
ls = LinearSystem(A, Matrix.identity(n))
if not ls.gauss_jordan_elimination():
return None
invA = [row[n:] for row in ls.Ab]
return Matrix(invA)
|
Java
|
UTF-8
| 2,503 | 2.203125 | 2 |
[] |
no_license
|
package com.mio780308.multipleimagepicker;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
public class MainActivity extends Activity implements
ImageFolderFragment.ImageFolderFragmentListener,
ImageFragment.ImageFragmentListener{
//Constants
public final static String RESULT_ALL_PATHS="result_all_paths";
private boolean justOne;//true if only one image needs to be chosen
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_picker);
initializeImageLoader();
if(getIntent().getAction().equals(Intent.ACTION_PICK)){
justOne=true;
}
if(savedInstanceState==null){
ImageFolderFragment f=new ImageFolderFragment();
getFragmentManager().beginTransaction().add(R.id.relativeLayout1, f).commit();
}
}
private void initializeImageLoader(){
ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(getApplicationContext()).build();
ImageLoader.getInstance().init(config);
}
@Override
public void OnFolderClicked(final ImageFolder folder) {
Bundle arg=new Bundle();
arg.putBoolean(ImageFragment.ARG_JUST_ONE, justOne);
arg.putStringArray(ImageFragment.ARG_IMG_PATHS, folder.getImagePathArray());
ImageFragment f=new ImageFragment();
f.setArguments(arg);
getFragmentManager().beginTransaction().replace(R.id.relativeLayout1, f).addToBackStack(null).commit();
}
@Override
public void onSelectionComplete(String[] uris) {
if(justOne){
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { uris[0] }, null);
cursor.moveToFirst();
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
Intent result=new Intent();
result.setData(Uri.withAppendedPath(baseUri, "" + id));
setResult(RESULT_OK, result);
finish();
}else{
Intent result=new Intent();
result.putExtra(RESULT_ALL_PATHS, uris);
setResult(RESULT_OK, result);
finish();
}
}
}
|
C
|
UTF-8
| 2,917 | 2.71875 | 3 |
[] |
no_license
|
#include "worklog.h"
#include <stdlib.h>
#include <string.h>
#define WL_DEFAULT_CAPACITY 128
#define WL_CAPACITY_GROW_STEP 32
#define WL_NOT_FOUND (-1)
static int wl_capacity = WL_DEFAULT_CAPACITY;
static int wl_size = 0;
static double wl_total_spent = 0;
static double *wl_spent = NULL;
static wl_task_t *wl_task = NULL;
void wl_init() {
wl_spent = malloc(wl_capacity * sizeof(double));
wl_task = malloc(wl_capacity * sizeof(wl_task_t));
}
void wl_grow() {
wl_capacity += WL_CAPACITY_GROW_STEP;
wl_spent = realloc(wl_spent, wl_capacity);
wl_task = realloc(wl_task, wl_capacity);
}
int wl_task_index(const char *task) {
for (int i = 0; i < wl_size; ++i) {
if (strcmp(task, wl_task[i]) == 0) {
return i;
}
}
return WL_NOT_FOUND;
}
void wl_set_task(int index, const char* task) {
strcpy(wl_task[index], task);
}
void wl_log(double seconds, const char *task) {
int index = wl_task_index(task);
if (WL_NOT_FOUND == index) {
if (wl_size == wl_capacity) {
wl_grow();
}
index = wl_size;
wl_spent[index] = 0;
wl_set_task(index, task);
wl_size += 1;
}
wl_spent[index] += seconds;
wl_total_spent += seconds;
}
double wl_log_since(time_t *since, const char *task) {
time_t current = time(NULL);
double delta = difftime(current, *since);
*since = current;
wl_log(delta, task);
return delta;
}
void wl_delete(int index) {
wl_total_spent -= wl_spent[index];
wl_size -= 1;
if (index != wl_size) {
wl_spent[index] = wl_spent[wl_size];
wl_set_task(index, wl_task[wl_size]);
}
}
int wl_unlog(double seconds, const char *task) {
int index = wl_task_index(task);
if (index == WL_NOT_FOUND) {
return 0;
}
if (seconds >= wl_spent[index]) {
wl_delete(index);
} else {
wl_spent[index] -= seconds;
wl_total_spent -= seconds;
}
return 1;
}
wl_summary_t wl_get_summary() {
return (wl_summary_t) {wl_size, wl_total_spent, wl_spent, wl_task};
}
double wl_get_time_spent(const char *task) {
int index = wl_task_index(task);
return index != WL_NOT_FOUND ? wl_spent[index] : 0;
}
int wl_exists(const char *task) {
return wl_task_index(task) != WL_NOT_FOUND;
}
int wl_rename_task(const char *task, const char *new_name) {
int index = wl_task_index(task);
if (index == WL_NOT_FOUND || wl_task_index(new_name) != WL_NOT_FOUND) {
return 0;
}
strcpy(wl_task[index], new_name);
return 1;
}
int wl_delete_task(const char *task) {
int index = wl_task_index(task);
if (index == WL_NOT_FOUND) {
return 0;
}
wl_delete(index);
return 1;
}
void wl_clear() {
wl_size = 0;
wl_total_spent = 0;
}
void wl_free() {
if (wl_spent) {
free(wl_spent);
}
if (wl_task) {
free(wl_task);
}
}
|
C
|
UTF-8
| 533 | 3.890625 | 4 |
[] |
no_license
|
#include <stdio.h>
int counting(int x) {
int div_counter = 1;
int half_x = x / 2;
for (int i = 1; i <= half_x; i++) {
if (x % i == 0) {
div_counter++;
}
}
return div_counter;
}
// Условия задания:
// Подсчитайте количество натуральных делителей числа x (включая 1 и само число; x <= 30000).
int main() {
int x;
scanf("%d", &x);
printf("%d\n", counting(x));
return 0;
}
|
Python
|
UTF-8
| 472 | 3.171875 | 3 |
[] |
no_license
|
list = [
{"min_salary": 200, "max_salary": 1000, "date_posted": "2001-10-25"},
{"min_salary": 100, "max_salary": 5000, "date_posted": "2015-05-10"},
{"min_salary": 300, "max_salary": 2000, "date_posted": "2010-05-10"},
]
print(
[
min_list["min_salary"]
for min_list in sorted(list, key=lambda x: x.get("min_salary"))
]
)
print([100, 200, 300] == [100, 200, 300])
if "":
print("deu none")
teste = "aqui"
print("deu fora{teste}")
|
Markdown
|
UTF-8
| 2,718 | 3.640625 | 4 |
[] |
no_license
|
# 插入区间
> 题目来源: [LintCode 算法题库](https://www.lintcode.com/problem/insert-interval/?utm_source=sc-github-wzz)
## 题目描述
<p>给出一个<font color="#e76363"><b>无重叠的</b></font><span style="line-height: 1.42857143;">按照区间起始端点排序的区间列表。</span></p><p>在列表中插入一个新的区间,你要确保列表中的区间仍然有序且<font color="#e76363"><b>不重叠</b></font>(如果有必要的话,可以合并区间)。</p>
### 样例说明
**样例 1:**
```
输入:
(2, 5) into [(1,2), (5,9)]
输出:
[(1,9)]
```
**样例 2:**
```
输入:
(3, 4) into [(1,2), (5,9)]
输出:
[(1,2), (3,4), (5,9)]
```
### 参考代码
定位到区间集与待插入的区间开始重合的部分,然后开始求交集。
交集一直延伸到相交区间的最末端。
```java
public class Solution {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
if (newInterval == null || intervals == null) {
return intervals;
}
List<Interval> results = new ArrayList<Interval>();
int insertPos = 0;
for (Interval interval : intervals) {
if (interval.end < newInterval.start) {
results.add(interval);
insertPos++;
} else if (interval.start > newInterval.end) {
results.add(interval);
} else {
newInterval.start = Math.min(interval.start, newInterval.start);
newInterval.end = Math.max(interval.end, newInterval.end);
}
}
results.add(insertPos, newInterval);
return results;
}
}
// version: 高频题班
public class Solution {
/*
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
// write your code here
List<Interval> ans = new ArrayList<>();
int idx = 0;
while (idx < intervals.size() && intervals.get(idx).start < newInterval.start) {
idx++;
}
intervals.add(idx, newInterval);
Interval last = null;
for (Interval item : intervals) {
if (last == null || last.end < item.start) {
ans.add(item);
last = item;
} else {
last.end = Math.max(last.end, item.end); // Modify the element already in list
}
}
return ans;
}
}
```
更多题解请参考: [LintCode 提供 2000+ 算法题和名企阶梯训练](https://www.lintcode.com/problem/?utm_source=sc-github-wzz)
|
C++
|
UTF-8
| 634 | 3.703125 | 4 |
[] |
no_license
|
#include <iostream>
template <typename T>
void swap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int i = 10;
int j = 20;
swap(i, j);
std::cout << "compiler generated int swapper:\n";
std::cout << "i: " << i << " j: " << j << "\n\n";
double x = 27.1;
double y = 81.3;
swap(x, y);
std::cout << "compiler generated double swapper:\n";
std::cout << "x: " << x << " y: " << y << "\n\n";
float u = 0.99;
float v = 0.38;
swap(u, v);
std::cout << "compiler generated float swapper:\n";
std::cout << "u: " << u << " v: " << v << "\n\n";
return 0;
}
|
Java
|
UTF-8
| 5,133 | 1.9375 | 2 |
[] |
no_license
|
package com.vvn.vocavocani.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import com.vvn.vocavocani.R;
import com.vvn.vocavocani.user.ProfileActivity;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutInit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_bar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void layoutInit() {
setToolbarLayout();
setContentLayout();
}
private void setToolbarLayout() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
private void setContentLayout() {
ViewPager viewPager = (ViewPager) findViewById(R.id.main_view_pager);
MainPagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.main_tab);
tabLayout.setupWithViewPager(viewPager);
setTabIcons(tabLayout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View header = navigationView.getHeaderView(0);
ImageButton userSetting = (ImageButton) header.findViewById(R.id.user_setting);
userSetting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.made_of:
// TODO
break;
case R.id.backup_setting:
// TODO
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
private void setTabIcons(TabLayout tabLayout) {
final int[] iconList = {
R.drawable.ic_add_black_24dp,
R.drawable.ic_add_black_24dp
};
final int[] selectedIconList = {
R.drawable.checkmark,
R.drawable.checkmark
};
for (int i = 0; i < tabLayout.getTabCount(); i++) {
// Set tab's default icon
if (i == tabLayout.getSelectedTabPosition())
tabLayout.getTabAt(i).setIcon(selectedIconList[i]);
else
tabLayout.getTabAt(i).setIcon(iconList[i]);
// Set tab's select/unselect action
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.setIcon(selectedIconList[tab.getPosition()]);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.setIcon(iconList[tab.getPosition()]);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
tab.setIcon(selectedIconList[tab.getPosition()]);
}
});
}
}
}
|
C++
|
UTF-8
| 637 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#pragma once
#include <memory>
#include "sentinel-core/transport/command/command_request.h"
#include "sentinel-core/transport/command/command_response.h"
namespace Sentinel {
namespace Transport {
class CommandHandler {
public:
CommandHandler(const std::string& name) : command_name_(name) {}
virtual ~CommandHandler() = default;
virtual CommandResponsePtr Handle(const CommandRequest& request) = 0;
const std::string& command_name() const { return command_name_; }
protected:
std::string command_name_;
};
using CommandHandlerPtr = std::unique_ptr<CommandHandler>;
} // namespace Transport
} // namespace Sentinel
|
Markdown
|
UTF-8
| 1,388 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
# Install Vagrant box CentOS7
## Overview
This is Vagrant file to
* Create a plain CentOS 7 machine.
* Make the /vagrant directory on the CentOS guest synchronize with the Vagrant directory on the Windows host.
Other note
* This file is tested on Windows 10 host with Oracle Virtual Box.
* To make CentOS 7 box synchronize with Windows, you need install plugin vagrant-vbguest.
* In this document, command run on Windows is started with `>`, and command run on CentOS is started with `$`.
## Create CentOS 7 Vagrant box
* Download [Vagrantfile](./Vagrantfile), save it into a directory.
* Go to that directory and install vagrant-vbguest plugin.
```shell
> vagrant plugin install vagrant-vbguest
```
* Vagrant up. This will create the Vagrant box and install LAMP.
```shell
> vagrant up
```
## Disable SELinux
* ssh into Vagrant box, configure `SELINUX=disabled` in the `/etc/selinux/config` file.
```shell
> vagrant ssh
```
* Reboot your system by logout the Vagrant box and run
```shell
> vagrant reload
```
* After reboot, ssh into Vagrant box, confirm that the `getenforce` command returns `Disabled`.
```shell
> vagrant ssh
$ getenforce
Disabled
```
## Another command
### ssh into the Vagrant box
```shell
> vagrant ssh
```
### Reload provision (when update provision in Vagrantfile)
```shell
> vagrant provision
```
|
Java
|
UTF-8
| 237 | 3 | 3 |
[] |
no_license
|
package AlexLink.HomeWork.HomeworkStream.Task1;
@FunctionalInterface
public interface Run {
void run(Animal pet);
default void info(Animal pet) {
System.out.println(pet.getClass().getSimpleName() + " running");
}
}
|
Java
|
UTF-8
| 4,072 | 2.046875 | 2 |
[] |
no_license
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 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 frc.robot;
import edu.wpi.first.wpilibj.kinematics.DifferentialDriveKinematics;
public final class Constants {
public final static class Motors {
public static final double SPEED = 1;
public static final int PNEUMATIC_CONTROL_PANEL = 6; // PCM
public static final int MOTOR_RIGHT_1 = 10; // Talon
public static final int MOTOR_RIGHT_2 = 11; // Talon
public static final int MOTOR_LEFT_1 = 12; // Talon
public static final int MOTOR_LEFT_2 = 13; // Talon
public static final int TELEWINCH = 14; // Talon
public static final int FLYWHEEL_1 = 15; // Talon
public static final int FLYWHEEL_2 = 16; // Talon
public static final int INDEXER = 17; // Talon
public static final int INTAKEWHEEL = 18; // Talon
public static final int CLIMBWINCH = 19; // Victor
}
public final static class Pneumatics {
public static final int SOLENOID_1_ON = 0;
public static final int SOLENOID_1_OFF = 1;
}
public final static class Controller {
public static final int CONTROLLER_PORT = 0;
public static final int BUTTON_A = 1;
public static final int BUTTON_B = 2;
public static final int BUTTON_X = 3;
public static final int BUTTON_Y = 4;
public static final int LEFT_STICK_X = 0;
public static final int LEFT_STICK_Y = 1;
public static final int RIGHT_STICK_X = 4;
public static final int RIGHT_STICK_Y = 5;
public static final int LEFT_TRIGGER = 2;
public static final int RIGHT_TRIGGER = 3;
public static final int LEFT_BUMPER = 5;
public static final int RIGHT_BUMPER = 6;
public static final int BUTTON_START = 7;
public static final int BUTTON_MENU = 8;
}
public final static class Measurements {
public static final int ENCODER_PULSE = 4096;
public static final double SVOLTS = 1.07;
public static final double SVOLT_SECOND_PER_METER = 2.95;
public static final double SVOLT_SECOND_PER_METER_SQUARED = 0.0124;
public static final double KP_DRIVE_VELOCITY = 0.0254;
public static final double TRACKWIDTH = 0.44; // meters
public static final double WHEELDIAMETER = 0.152; // meters
public static final double MAX_SPEED = 1.5; // m/s
public static final double MAX_ACCELERATION = 1.5; // m/s²
public static final double RAMSETE_B = 2;
public static final double RAMSETE_ZETA = 0.7;
public static final double DISTANCE_PER_PULSE = (WHEELDIAMETER * Math.PI) / (double) ENCODER_PULSE;
public static final DifferentialDriveKinematics DRIVE_KINEMATICS = new DifferentialDriveKinematics(TRACKWIDTH);
public static final double LIMELIGHT_HEIGHT = 0.2; // m
public static final double LIMELIGHT_ANGLE = 35; // degrees
public static final double TARGET_HEIGHT = 2.; // m
public static final double AIR_DENSITY = 1.2; // kg/m³
public static final double BALL_AREA = Math.sqrt(0.89) * Math.PI; // m²
public static final double BALL_DRAG = 0.47;
public static final int MIN_DRIVEBASE_SPEED = 500;
public static final double SHOOTING_RANGE = 6.7; // m
}
public final static class Autonomous {
public final static int TIMEOUT = 30;
public final static int REMOTE_0 = 0;
public final static int REMOTE_1 = 1;
public final static int PID_PRIMARY = 0;
public final static int PID_TURN = 1;
public final static int SLOT_0 = 0;
public final static int SLOT_1 = 1;
public final static int SLOT_2 = 2;
public final static int SLOT_3 = 3;
public final static int kSlot_Distanc = 0;
public final static int kSlot_Turning = 1;
public final static int kSlot_Velocit = 2;
public final static int kSlot_MotProf = 3;
public final static boolean INVERTED_GYRO = true;
}
}
|
Markdown
|
UTF-8
| 35,943 | 3.78125 | 4 |
[
"MIT"
] |
permissive
|
# Stream
<!-- toc -->
## 定义
流 (Stream)允许我们以声明性方式(declarative way)处理数据集合。流的简短定义为:a sequence of elements from a source that supports data processing operations(从支持数据处理操作的源生成的元素序列),我们来详细看下这个定义:
* Sequence of elements(元素序列)- 流提供了类似于集合(Collection)的接口,额可以操作特定元素类型的一组有序值。不过两者的关注点不同,集合主要关注数据(data),流主要关注计算(computation)。
* Source(源)- 流需要一个提供数据的源,这个源可以是 collections,arrays 或者 I/O resources. 从有序集合生成的流会保留原有的数据。
* Data processing operations(数据处理操作)- 流的数据处理功能支持类似于数据库的操作,以及函数式编程语言中的常用操作,例如 filter、map、reduce、find、match、sort 等。流操作可以顺序执行,也可以并行执行。
另外,流操作还有两个重要的特点:
* Pipelining(流水线) - 很多流操作本身会返回一个流,这样多个操作就可以链接起来,形成一个大的流水线,流水线的操作支持延迟(laziness)和短路(short-circuiting)。流水线的操作可以看作对数据源进行数据库式的查询。
* Internal iteration(内部迭代)- 和集合使用显式的的迭代器不同,流的迭代操作是在背后执行的,对于用户来说是透明的。
下面是一个使用示例:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class HelloWorld {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(10);
list.add(1);
list.add(-1);
list.add(1000);
list.add(100);
List<Integer> result = list.stream()
.filter(i -> i > 10)
.sorted()
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
```
## 使用流
### 创建流
下面是创建流的几种方式:
* 由值创建流
* 由数组 / 集合创建流
* 由文件生成流
* 由函数生成流,该操作生成的流属于无限流
- `Stream.iterate`:接受一个初始值,每次迭代在之前迭代的结果上应用传入 lambda 表达式
```java
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)`
```
- `Stream.generate`:根据传入的 s 生成结果值
```java
public static<T> Stream<T> generate(Supplier<T> s)
```
下面是一个使用示例:
```java
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CreateStream {
@Test
public void fromValue() {
Stream<String> stream = Stream.of("aaa", "bbb", "ccc", "ddd");
stream.map(String::toUpperCase).forEach(System.out::println);
}
@Test
public void fromCollection() {
List<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
Integer sum = list.stream()
.map(Integer::parseInt)
.reduce(Integer::sum).get();
System.out.println(sum);
}
@Test
public void fromArray() {
int[] arr = new int[]{1, 3, 5, 7};
IntStream stream = Arrays.stream(arr);
int sum = stream.sum();
System.out.println(sum);
String[] strArr = new String[]{"aaa", "bbb", "ccc", "ddd"};
Stream<String> stringStream = Arrays.stream(strArr);
stringStream.map(String::toUpperCase).forEach(System.out::println);
}
@Test
public void fromFile() {
long uniqueWords = 0;
try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) {
uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" "))).distinct().count();
System.out.println(uniqueWords);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 由函数生成流
*/
@Test
public void fromIterate() {
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);
}
@Test
public void fromGenerate() {
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
}
}
```
<br />
### 只能遍历一次
流只能被遍历一次,当遍历完之后,我们就说这个流被消费掉了。下面是一个示例:
```java
@Test
public void streamTest() {
Stream<Integer> stream = Stream.of(1, 3, 5);
stream.filter(i -> i > 1).forEach(System.out::println);
// 下面的代码会报错,因为流已经关闭了
stream.filter(i -> i > 1).forEach(System.out::println);
}
```
### 流操作
流操作可以分为两大类:中间操作(intermediate operations)和终端操作(terminal operation)。中间操作是延迟(lazy)计算的,在触发一个终端操作之前,中间操作不会进行任何处理。下面是一个示意图:

中间操作一般可以合并起来,在终端操作时一次性全部处理。在使用流时一般会包含下面三个部分:
* 执行查询的 **数据源(data source)**
* 组成流水线的 **中间操作链(chain of intermediate operations)**
* 执行流水线并且生成最终结果的 **终端操作(terminal operation)**
下面是常用的流操作列表
| 操作 | 操作类型 | 返回类型 | 参数类型 | 函数描述符 |
| --- | --- | --- | --- | --- | --- |
| `filter`| 中间 | `Stream<T>` | `Predicate<T>` | `T -> boolean` |
| `distinct` | 中间 <br>有状态-无界 | `Stream<T>` | | |
| `skip`| 中间 <br>有状态-有界| `Stream<T>` | long | |
| `limit` | 中间<br>有状态-有界 | `Stream<T>` | | |
| `map` | 中间 | `Stream<R>` | `Function<T, R>` | `T -> R` |
| `flatMap`| 中间 | `Stream<R>` | `Function<T, Stream<R>>` | `T -> Stream<R>` |
| `sorted` | 中间 | `Stream<T>` | `Comparator<T>` | `(T, T) -> int`|
| `anyMatch` | 终端 | `boolean` | `Predicate<T>` | `T -> boolean` |
| `noneMatch` | 终端 | `boolean` | `Predicate<T>` | `T -> boolean` |
| `allMatch` | 终端 | `boolean` | `Predicate<T>` | `T -> boolean` |
| `findAny` | 终端 | `Optional<T>` | | |
| `findFirst` | 终端 | `Optional<T>` | | |
| `forEach` | 终端 | `void` | `Comsumer<T>`| `T -> void` |
| `collect` | 终端 | `R` | `Collector<T, A, R>` | |
| `reduce` | 终端 <br> 有状态-有界| `Optional<T>` | `BinaryOperator<T>` | `(T, T) -> T` |
| `count` | 终端 | `long` | | | |
下面是部分流操作的示例
```java
public void streamOperations() {
Integer[] arr = new Integer[]{1, 2, 6, 1, 3, 8, 10};
// filter: 根据条件过滤
// forEach: 遍历流中的元素
Arrays.stream(arr).filter(i -> i > 1).forEach(System.out::println);
System.out.println();
// distinct: 去重
Arrays.stream(arr).distinct().forEach(System.out::println);
System.out.println();
// sorted: 排序
Arrays.stream(arr).sorted().forEach(System.out::println);
System.out.println();
// skip: 跳过前面的元素
Arrays.stream(arr).skip(2).forEach(System.out::println);
System.out.println();
// limit: 限制获取的元素数量
Arrays.stream(arr).limit(2).forEach(System.out::println);
System.out.println();
// map: 元素映射, T -> R
Arrays.stream(arr).map(String::valueOf).forEach(v -> System.out.println(v.length()));
System.out.println();
// anyMatch:任一元素匹配
boolean result = Arrays.stream(arr).anyMatch(i -> i > 5);
System.out.println(result);
// noneMatch: 无元素匹配
result = Arrays.stream(arr).noneMatch(i -> i > 5);
System.out.println(result);
// allMatch: 全部元素匹配
result = Arrays.stream(arr).allMatch(i -> i > 5);
System.out.println(result);
// findAny: 返回流中任一元素
Optional<Integer> optional = Arrays.stream(arr).findAny();
System.out.println(optional.get());
// findFirst: 返回流中的第一个元素
optional = Arrays.stream(arr).findFirst();
System.out.println(optional.get());
// count: 统计流中元素个数
long count = Arrays.stream(arr).count();
System.out.println(count);
}
```
### flatMap
map 主要的的功能是用来做映射,即将输入的 T 类型转为 R 类型。map 主要针对一维的数据结构(例如一维数组),当数据结构为二维的时候(比如二维数组或者集合数组),map 也会将其作为一维数据结构处理,比如下面的二维数组,map 会将内层的一维数组看作是一个整体。
```
[
[1, 3, 4],
[1, 2, 3],
[2, 2, 6]
]
```
但是我们可能希望对二维数组中的全部数据进行处理,那么一个简单的办法就是将二维数组展平为一维数组,即下面的形式:
```
[1, 3, 4, 1, 2, 3, 2, 2, 6]
```
这样在 map 时就是针对的数组中的全部数据。Java 8 为我们提供了 flatMap 来完成上面的工作。我们首先看下 flatMap 的定义:
```java
/**
* Returns a stream consisting of the results of replacing each element of
* this stream with the contents of a mapped stream produced by applying
* the provided mapping function to each element. Each mapped stream is
* {@link java.util.stream.BaseStream#close() closed} after its contents
* have been placed into this stream. (If a mapped stream is {@code null}
* an empty stream is used, instead.)
*/
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
```
我们看到 flatMap 接受的参数为 `Function<? super T, ? extends Stream<? extends R>`,这个 Function 的功能是将 T 转换为 `Stream<R>` (super 和 extends 一会再说)。flatMap 的功能就是通过转换函数 mapper,将之前流中的每个元素转换成一个流,然后把所有的流连接成一个流。下面是一个示例:
```java
public void useFlatMap() {
Integer[][] array = new Integer[][]{
new Integer[]{1, 3, 4},
new Integer[]{1, 2, 3},
new Integer[]{2, 2, 6}
};
List<Integer[]> results = Arrays.stream(array).distinct().collect(Collectors.toList());
results.forEach(arr -> System.out.println(Arrays.toString(arr)));
List<Integer> results2 = Arrays.stream(array).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
results2.forEach(System.out::println);
}
```
在上面的例子中,通过 Arrays.stream 可以将二维数组 array 转换为一个流 s,其中流中的元素数据类型为 `Integer[]`,当调用 flatMap 之后, 流 s 中的每个元素都通过 `Arrays.stream` 方法转换为一个流,记为 ss1, ss2, ss3,流 ss1, ss2, ss3 中数据类型为 `Integer`,然后 flatMap 将 ss1, ss2 和 ss3 合并成一个新的流 s2,流 s2 中就包含了 array 的所有元素(相当于把 array 展平为了一维数组)。
下面是一个示意图:

我们再来看下泛型中的 super 和 extends,
```java
// 这里只看泛型,所以省略 ? extends Stream
Function<? super T, Stream<? extends R> mapper
```
`? super T` 表示接受的类型是 T 或者 T 的父类,`? extends R` 表示接受的类型为 R 或者 R 的子类。假设我们有下面的继承关系:
```java
class Animal {
public void run() {
System.out.println("animal run");
}
}
class Cat extends Animal {
public void jump() {
System.out.println("cat jump");
}
}
class WhiteCat extends Animal {
public void printColor() {
System.out.println("white");
}
}
```
我们先来看 super,假设 Stream 中元素类型都是 Cat 类型,即 mapper 的输入类型是 Cat,假设我们不加 `? super T` 限制,将参数的定义改为 `Function mapper`, 那么将下面的 Function m 传入 flatMap 时,编译时不会报错,但是执行的时候会报错,因为 Function m 接受的类型是 WhiteCat,但是我们给 m 传的 Cat 类型,Cat 类中根本没有 printColor 函数。
```java
// 这里忽略输出类型
Function<WhiteCat, ?> m = (c, ?) -> c.printColor();
```
如果我们将下面的 Function m2 传入 flatMap,那么编译和运行时都不会报错,因为 Cat 是 Animal 的子类,会继承 Animal 的 run 方法。
```java
Function<Animal, ?> m2 = (a, ?) -> a.run();
```
由此我们可以知道当 Stream 中类型为 Cat 时,我们传入的 Function 接受类型可以是 Cat 或者 Cat 的父类,但不能是 Cat 的子类,所以在参数定义时加上 `? super T`,以便在编译阶段就可以发现错误。
下面我们在看下 extends,mapper 的用法大致如下面的代码所示,流 s 中的数据类型要为 R 或者 R 的子类,所以在参数定义中使用 `? extends R` 表明 mapper 返回流中的数据必须为 R 或者 R 的子类。
```java
Stream<R> s = mapper(t);
```
上面的用法就是我们所说的 PECS (Producer Extends Consumer Super)元素:
* 如果要从对象或者集合中获取 T 类型的数据,并且不需要写入,可以使用 `? extends` 通配符
* 如果要向对象或者集合中写入 T 类型的数据,并且不需要读取,可以使用 `? super` 通配符
* 如果既要存又要取,那么就不要用任何通配符。
在上面的例子中,我们要向 mapper 对象中传入 T 类型,获取 `Stream<R>` 类型,所以统配符使用
```java
Function<? super T, ? extends Stream<? extends R>> mapper
```
### reduce
reduce 操作将流中所有的值规约成一个值(比如求和、求最大最小值),用函数式编程语言的术语来说,这也称为折叠(fold)。下面是一个使用示例:
```java
public void useReduce() {
Integer[] numbers = new Integer[] {1, 2, 4, 6, 10};
// 求和
int sum = Arrays.stream(numbers).reduce(0, Integer::sum);
System.out.println(sum);
// 求最大值
Optional<Integer> o = Arrays.stream(numbers).reduce(Integer::max);
System.out.println(o.get());
// 求最小值
o = Arrays.stream(numbers).reduce(Integer::min);
System.out.println(o.get());
}
```
reduce 将外部迭代的过程抽象到了内部迭代中,有利于并行化的实现。
### 操作状态
* 对于 map 或者 filter 这样的流操作来说,它们操作的对象是流中的单个元素,在执行操作的时候,各个元素之间不会相互影响,这些操作一般都是无状态的(stateless),这里假设用户提供的 Lambda 表达式中没有内部状态。无状态的操作更利于并行。
* 诸如 reduce、sum、max 等操作,需要内部状态来累积结果,但是这种情况下内部状态很小,在 reduce 中就是一个int 或者 double。不论流中有多少元素要处理,内部状态都是有界的。
* 对于 sort 或者 distinct 操作来说,操作时都需要知道之前操作的结果,这种操作的存储要求是无界的,我们通常把这些操作称为有状态操作(stateful)
## 收集数据
使用 Stream 的 collect 方法可以收集流中的数据,collect 方法接收一个 Collector 类型的参数,用于指定收集的逻辑,下面是 collect 方法的定义:
```java
<R, A> R collect(Collector<? super T, A, R> collector);
```
Java 8 中 Collectors 提供了一些预定义的收集器,主要包含下面四个功能:
* 收集为集合
* 规约和汇总:Reducing and summarizing stream elements to a single value
* 分组:Grouping elements
* 分区:Partitioning elements
### 集合
流中的数据可以被收集成 List、Set 或者 Map 的集合类,下面是相关函数的定义:
```java
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code Collection}, in encounter order. The {@code Collection} is
* created by the provided factory.
* @param collectionFactory a {@code Supplier} which returns a new, empty
*/
public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory)
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code List}. There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code List} returned; if more
* control over the returned {@code List} is required, use {@link #toCollection(Supplier)}.
*/
public static <T> Collector<T, ?, List<T>> toList()
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code Set}. There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Set} returned; if more
* control over the returned {@code Set} is required, use
* {@link #toCollection(Supplier)}.
*/
public static <T> Collector<T, ?, Set<T>> toSet()
/**
* Returns a {@code Collector} that accumulates elements into a
* {@code Map} whose keys and values are the result of applying the provided
* mapping functions to the input elements.
*
* <p>If the mapped
* keys contains duplicates (according to {@link Object#equals(Object)}),
* the value mapping function is applied to each equal element, and the
* results are merged using the provided merging function. The {@code Map}
* is created by a provided supplier function.
*
* @implNote
* The returned {@code Collector} is not concurrent. For parallel stream
* pipelines, the {@code combiner} function operates by merging the keys
* from one map into another, which can be an expensive operation. If it is
* not required that results are merged into the {@code Map} in encounter
* order, using {@link #toConcurrentMap(Function, Function, BinaryOperator, Supplier)}
* may offer better parallel performance.
*
* @param keyMapper a mapping function to produce keys
* @param valueMapper a mapping function to produce values
* @param mergeFunction a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object, BiFunction)}
* @param mapSupplier a function which returns a new, empty {@code Map} into
* which the results will be inserted
*/
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier)
/**
* Returns a {@code Collector} that accumulates elements into a
* {@code Map} whose keys and values are the result of applying the provided
* mapping functions to the input elements.
*
* <p>If the mapped
* keys contains duplicates (according to {@link Object#equals(Object)}),
* the value mapping function is applied to each equal element, and the
* results are merged using the provided merging function.
*
* @param keyMapper a mapping function to produce keys
* @param valueMapper a mapping function to produce values
* @param mergeFunction a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object, BiFunction)}
*/
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction) {
return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
}
/**
* Returns a {@code Collector} that accumulates elements into a
* {@code Map} whose keys and values are the result of applying the provided
* mapping functions to the input elements.
*
* <p>If the mapped keys contains duplicates (according to
* {@link Object#equals(Object)}), an {@code IllegalStateException} is
* thrown when the collection operation is performed. If the mapped keys
* may have duplicates, use {@link #toMap(Function, Function, BinaryOperator)}
* instead.
*
* @param keyMapper a mapping function to produce keys
* @param valueMapper a mapping function to produce values
*/
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}
```
下面是使用示例:
```java
public void testCollection() {
Integer[] array = new Integer[]{1, 3, 1, 4, 6, 4, 7};
// 收集为 List(ArrayList),输出结果为:[1, 3, 1, 4, 6, 4, 7]
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
System.out.println(list);
// 收集为 Set(HashSet),输出结果为 [1, 3, 4, 6, 7]
Set<Integer> set = Arrays.stream(array).collect(Collectors.toSet());
System.out.println(set);
/*
* 在前面的示例中,toList 只能生成 ArrayList, toSet 只能生成 HashSet
* 所以又额外提供了一个 toCollection 允许用户传入一个 Supplier 对象,用于自定义集合类的类型
*/
Collection<Integer> c = Arrays.stream(array).collect(Collectors.toCollection(LinkedList::new));
System.out.println(c);
/*
* 收集为 map(HashMap),第一个参数为 key 的映射,第二个参数为 value 的映射。
* 这里需要注意的是 key 值不能有重复。输出结果为:{1=1, 3=1, 4=1, 6=1, 7=1}
*/
array = new Integer[]{1, 3, 6, 4, 7};
Map<Integer, Integer> map = Arrays.stream(array).collect(Collectors.toMap(i -> i, i -> 1));
System.out.println(map);
/*
* 第三个参数为冲突合并函数,当 key 值冲突时,会调用该函数合并 value 值
* 输出结果为:{1=2, 3=3, 4=8, 6=6, 7=7}
*/
array = new Integer[]{1, 3, 1, 4, 6, 4, 7};
map = Arrays.stream(array).collect(Collectors.toMap(i -> i, i -> i, (a, b) -> a + b));
System.out.println(map);
/*
* 第四个参数用来自定义 Map 的类型
*/
map = Arrays.stream(array).collect(Collectors.toMap(i -> i, i -> i, (a, b) -> a + b, TreeMap::new));
System.out.println(map);
}
```
Collectors 也提供了 toConcurrentMap 的方法,这里不再赘述。
### 规约和汇总
下面是使用预定义收集器进行规约和汇总的一些示例:
```java
public void summarize() {
Integer[] array = new Integer[]{1, 3, 6, 8, 3, 2};
// 求和
long count = Arrays.stream(array).collect(Collectors.counting());
System.out.println(count);
// 求最大值
Optional<Integer> max = Arrays.stream(array).collect(Collectors.maxBy(Comparator.comparing(i -> i)));
System.out.println(max.get());
// 求最小值
Optional<Integer> min = Arrays.stream(array).collect(Collectors.minBy(Comparator.comparing(i -> i)));
System.out.println(min.get());
// 求和, Collectors.summingLong 和 Collectors.summingDouble 用于 long 和 double 类型的求和
int total = Arrays.stream(array).collect(Collectors.summingInt(i -> i));
System.out.println(total);
// 求平均数, Collectors.averagingLong 和 Collectors.averagingDouble 用于求 long 和 double 类型的平均值
// 需要注意的是返回值均为 double
double average = Arrays.stream(array).collect(Collectors.averagingInt(i -> i));
System.out.println(average);
// 字符串连接
String text = Arrays.stream(array).map(String::valueOf).collect(Collectors.joining(", "));
System.out.println(text);
/**
* 获得多个统计信息,包括 sum, average, min, max 和 count
*
* Collectors.summarizingLong 和 Collectors.summarizingDouble 用于统计 long 和 double 类型
*/
IntSummaryStatistics statistics = Arrays.stream(array).collect(Collectors.summarizingInt(i -> i));
System.out.println(statistics);
}
```
Collectors 中提供了一个更为通用的 reducing 方法来实现规约功能,上面的方法可以看作是 reducing 方法的特例,我们来看下 reducing 方法的定义:
```java
/**
* Returns a {@code Collector} which performs a reduction of its
* input elements under a specified {@code BinaryOperator}. The result
* is described as an {@code Optional<T>}.
*
* @param op a {@code BinaryOperator<T>} used to reduce the input elements
*/
public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op)
/**
* Returns a {@code Collector} which performs a reduction of its
* input elements under a specified {@code BinaryOperator} using the
* provided identity.
*
* @param identity the identity value for the reduction (also, the value
* that is returned when there are no input elements)
* @param op a {@code BinaryOperator<T>} used to reduce the input elements
*/
public static <T> Collector<T, ?, T> reducing(T identity, BinaryOperator<T> op)
/**
* Returns a {@code Collector} which performs a reduction of its
* input elements under a specified mapping function and
* {@code BinaryOperator}. This is a generalization of
* {@link #reducing(Object, BinaryOperator)} which allows a transformation
* of the elements before reduction.
*
* @apiNote
* The {@code reducing()} collectors are most useful when used in a
* multi-level reduction, downstream of {@code groupingBy} or
* {@code partitioningBy}. To perform a simple map-reduce on a stream,
* use {@link Stream#map(Function)} and {@link Stream#reduce(Object, BinaryOperator)}
* instead.
*
* @param identity the identity value for the reduction (also, the value
* that is returned when there are no input elements)
* @param mapper a mapping function to apply to each input value
* @param op a {@code BinaryOperator<U>} used to reduce the mapped values
*/
public static <T, U> Collector<T, ?, U> reducing(U identity,
Function<? super T, ? extends U> mapper, BinaryOperator<U> op)
```
我们来看下最后一个方法中的参数
* `U indentity`: 规约操作的初始值,当流中没有元素时会返回该值。
* `Function<> mapper`: 映射函数
* `BinaryOperator<T> op`: 进行规约时使用的函数
```java
public void reducing() {
Integer[] array = new Integer[]{1, 3, 6, 8, 3, 2};
int total = Arrays.stream(array).collect(Collectors.reducing(0, Integer::sum));
System.out.println(total);
Optional<Integer> optional = Arrays.stream(array).collect(Collectors.reducing(Integer::sum));
System.out.println(optional.get());
}
```
### 分组
可以使用 groupingBy 对数据进行分组处理。分组的结果是一个 Map,key 作为组别,value 作为值。下面看一下 groupingBy 的定义:
```java
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, grouping elements according to a
* classification function, and then performing a reduction operation on
* the values associated with a given key using the specified downstream
* {@code Collector}. The {@code Map} produced by the Collector is created
* with the supplied factory function.
*
* <p>The classification function maps elements to some key type {@code K}.
* The downstream collector operates on elements of type {@code T} and
* produces a result of type {@code D}. The resulting collector produces a
* {@code Map<K, D>}.
*
* @param classifier a classifier function mapping input elements to keys
* @param downstream a {@code Collector} implementing the downstream reduction
* @param mapFactory a function which, when called, produces a new empty
* {@code Map} of the desired type
*/
public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(
Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory,
Collector<? super T, A, D> downstream){}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, grouping elements according to a
* classification function, and then performing a reduction operation on
* the values associated with a given key using the specified downstream
* {@code Collector}.
*
* <p>The classification function maps elements to some key type {@code K}.
* The downstream collector operates on elements of type {@code T} and
* produces a result of type {@code D}. The resulting collector produces a
* {@code Map<K, D>}.
*
* <p>There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Map} returned.
*
* @param classifier a classifier function mapping input elements to keys
* @param downstream a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded group-by operation
*/
public static <T, K, A, D>
Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, A, D> downstream) {
return groupingBy(classifier, HashMap::new, downstream);
}
/**
* Returns a {@code Collector} implementing a "group by" operation on
* input elements of type {@code T}, grouping elements according to a
* classification function, and returning the results in a {@code Map}.
*
* <p>The classification function maps elements to some key type {@code K}.
* The collector produces a {@code Map<K, List<T>>} whose keys are the
* values resulting from applying the classification function to the input
* elements, and whose corresponding values are {@code List}s containing the
* input elements which map to the associated key under the classification
* function.
*
* <p>There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Map} or {@code List} objects returned.
*
* @param classifier the classifier function mapping input elements to keys
* @return a {@code Collector} implementing the group-by operation
*
*/
public static <T, K> Collector<T, ?, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K> classifier) {
return groupingBy(classifier, toList());
}
```
我们看到 groupingBy 有三个重载的方法,我们主要看第一个方法中的参数:
* `Function<? super T, ? extends K> classifier`:根据该函数的结果值来进行分类
* `Supplier<M> mapFactory`: 生成 Map 对象,用于自定义 Map 类型
* `Collector<? super T, A, D> downstream`: 对于分到同一组的对象,使用 downstream 函数进行 reduce
我们来看下具体的示例。首先定义一个 Person 类,代码如下所示:
```java
public class Person {
private String name;
private String country;
private String gender;
public Person() {
}
public Person(String name, String country, String gender) {
this.name = name;
this.country = country;
this.gender = gender;
}
// 省略 getter 和 setter
}
```
下面是使用示例:
```java
public void testGroup() {
List<Person> persons = new ArrayList<>();
persons.add(new Person("1", "aaa", "male"));
persons.add(new Person("2", "bbb", "female"));
persons.add(new Person("3", "ccc", "female"));
persons.add(new Person("4", "aaa", "female"));
persons.add(new Person("5", "bbb", "male"));
persons.add(new Person("6", "bbb", "male"));
persons.add(new Person("7", "aaa", "male"));
persons.add(new Person("8", "ccc", "male"));
// 按 country 分组
Map<String, List<Person>> personsByCity = persons.stream().collect(Collectors.groupingBy(Person::getCountry));
System.out.println(personsByCity);
// 多级分组,先按 country,再按 gender 分组
Map<String, Map<String, List<Person>>> personsByCityGender = persons.stream().collect(
Collectors.groupingBy(Person::getCountry, Collectors.groupingBy(Person::getGender)));
System.out.println(personsByCityGender);
// 按照 subgroup 分组收集
Map<String, Long> countriesCount = persons.stream().collect(
Collectors.groupingBy(Person::getCountry, Collectors.counting()));
System.out.println(countriesCount);
}
```
下面是输出结果:
```java
{aaa=[Person{name='1', country='aaa', gender='male'}, Person{name='4', country='aaa', gender='female'}, Person{name='7', country='aaa', gender='male'}], ccc=[Person{name='3', country='ccc', gender='female'}, Person{name='8', country='ccc', gender='male'}], bbb=[Person{name='2', country='bbb', gender='female'}, Person{name='5', country='bbb', gender='male'}, Person{name='6', country='bbb', gender='male'}]}
{aaa={female=[Person{name='4', country='aaa', gender='female'}], male=[Person{name='1', country='aaa', gender='male'}, Person{name='7', country='aaa', gender='male'}]}, ccc={female=[Person{name='3', country='ccc', gender='female'}], male=[Person{name='8', country='ccc', gender='male'}]}, bbb={female=[Person{name='2', country='bbb', gender='female'}], male=[Person{name='5', country='bbb', gender='male'}, Person{name='6', country='bbb', gender='male'}]}}
{aaa=3, ccc=2, bbb=3}
```
### 分区
分区是分组的一个特殊形式,分区使用一个 Predication 作为分类函数。分区将数据分为两组,true 和 false。下面是 partitaionBy 的定义:
```java
/**
* Returns a {@code Collector} which partitions the input elements according
* to a {@code Predicate}, and organizes them into a
* {@code Map<Boolean, List<T>>}.
*
* There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Map} returned.
*
* @param <T> the type of the input elements
* @param predicate a predicate used for classifying input elements
*
*/
public static <T>
Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {
return partitioningBy(predicate, toList());
}
/**
* Returns a {@code Collector} which partitions the input elements according
* to a {@code Predicate}, reduces the values in each partition according to
* another {@code Collector}, and organizes them into a
* {@code Map<Boolean, D>} whose values are the result of the downstream
* reduction.
*
* <p>There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Map} returned.
*
* @param predicate a predicate used for classifying input elements
* @param downstream a {@code Collector} implementing the downstream
* reduction
*
*/
public static <T, D, A>
Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
Collector<? super T, A, D> downstream)
```
### Collectors 类常用的静态方法
| 方法名称 | 返回类型 | 功能 |
| --- | --- | --- |
| `toList` | `List<T>` | 收集为 List |
|`toSet`|`Set<T>`|收集为 Set|
|`toCollection`|`Collection<T>`| 收集为 Collection|
|`counting`| `Long` | 计算流中的元素个数|
| `summingInt`|`Integer`| 对整数流求和 |
| `averagingInt`| `Double` | 对整数流求平均数 |
| `summarizingInt`|`IntSummaryStatistics`| 收集流中属性的统计值,例如最大,最小,和以及平均数|
| `joining` | `String` | 将流中的元素连接成字符串 |
|`maxBy`| `Optional<T>`| 选出最大值 |
|`minBy`| `Optional<T>`| 选出最小值 |
|`reducing`| 规约操作产生的类型 |将流中的元素规约为一个值|
|`collectingAndThen`|转换函数返回的类型|包裹另外一个收集器, 并对齐结果应用转换函数|
|`groupingBy`|`Map<K, List<T>>`|分组|
|`partitionBy`|`Map<Boolean, List<T>>`|分区|
|
Python
|
UTF-8
| 471 | 2.703125 | 3 |
[] |
no_license
|
import json
import datetime
from bson import ObjectId
# Функция для получения времени в необходимом формате
def getCurrTime():
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
# Класс для перевода в JSON
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)
|
C++
|
UTF-8
| 2,796 | 2.96875 | 3 |
[] |
no_license
|
#ifndef MEMORIACOMPARTIDA_H_
#define MEMORIACOMPARTIDA_H_
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#include <iostream>
#include <cerrno>
using namespace std;
template <class T> class MemoriaCompartida {
private:
int shmId;
T *ptrDatos;
int cantidadProcesosAdosados() const;
public:
MemoriaCompartida();
~MemoriaCompartida();
int crear(const string archivo, const char letra, size_t tamanio);
void liberar();
void desadosar();
void escribir(const T& dato);
T leer() const;
};
template <class T> MemoriaCompartida<T> :: MemoriaCompartida() {
this->shmId = 0;
this->ptrDatos = NULL;
}
template <class T> MemoriaCompartida<T> :: ~MemoriaCompartida () {
}
template <class T> int MemoriaCompartida<T> :: crear(const string archivo, const char letra, size_t tamanio) {
key_t clave = ftok(archivo.c_str(), letra);
if (clave < 0) {
cerr << "Error al generar la clave para la memoria compartida: " << strerror(errno) << endl;
return -1;
}
else {
this->shmId = shmget(clave, tamanio, 0644 | IPC_CREAT);
if (this->shmId < 0) {
cerr << "Error al crear la memoria compartida: " << strerror(errno) << endl;
return -1;
}
else {
void *ptrTemporal = shmat(this->shmId, NULL, 0);
if (ptrTemporal == (void *) -1) {
cerr << "Error al adosar la memoria compartida: " << strerror(errno) << endl;
return -1;
}
this->ptrDatos = static_cast<T*> (ptrTemporal);
return 0;
}
}
}
template <class T> void MemoriaCompartida<T> :: liberar() {
int procesosAdosados = this->cantidadProcesosAdosados();
if (procesosAdosados != 0) {
int resuladoDetach = shmdt(static_cast<void *> (this->ptrDatos));
if (resuladoDetach < 0) {
cerr << "Error al desadosar la memoria compartida: " << strerror(errno) << endl;
}
}
procesosAdosados = this->cantidadProcesosAdosados();
if (procesosAdosados == 0) {
int resultado = shmctl(this->shmId, IPC_RMID, NULL);
if (resultado < 0) {
cerr << "Error al destruir la memoria compartida: " << strerror(errno) << endl;
}
}
}
template <class T> void MemoriaCompartida<T> :: desadosar() {
int resuladoDetach = shmdt(static_cast<void *> (this->ptrDatos));
if (resuladoDetach < 0) {
cerr << "Error al desadosar la memoria compartida: " << strerror(errno) << endl;
}
}
template <class T> void MemoriaCompartida<T> :: escribir(const T& dato) {
*(this->ptrDatos) = dato;
}
template <class T> T MemoriaCompartida<T> :: leer() const {
return *(this->ptrDatos);
}
template <class T> int MemoriaCompartida<T> :: cantidadProcesosAdosados() const {
shmid_ds estado;
shmctl(this->shmId, IPC_STAT, &estado);
return estado.shm_nattch;
}
#endif /* MEMORIACOMPARTIDA_H_ */
|
C#
|
UTF-8
| 1,267 | 2.796875 | 3 |
[] |
no_license
|
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
public static class Utils
{
public static T PickRandom<T>(T[] array)
{
return array[UnityEngine.Random.Range(0, array.Length)];
}
public static Vector3 FindIntercept(Vector3 origin1, float speed1, Vector3 targetPos, Vector3 targetVel)
{
Vector3 dirToTarget = Vector3.Normalize(targetPos - origin1);
Vector3 targetVelOrth = Vector3.Dot(targetVel, dirToTarget) * dirToTarget;
Vector3 targetVelTang = targetVel - targetVelOrth;
Vector3 shotVelTang = targetVelTang;
float shotVelSpeed = shotVelTang.magnitude;
if (shotVelSpeed > speed1)
{
return Vector3.zero; // too slow to intercept target, it will never catch up, so return zero
}
else
{
float shotSpeedOrth = Mathf.Sqrt(speed1 * speed1 - shotVelSpeed * shotVelSpeed);
Vector3 shotVelOrth = dirToTarget * shotSpeedOrth;
float timeToCollision = ((origin1 - targetPos).magnitude) / (shotVelOrth.magnitude - targetVelOrth.magnitude);
Vector3 shotVel = shotVelOrth + shotVelTang;
return origin1 + shotVel * timeToCollision;
}
}
}
|
Shell
|
UTF-8
| 1,320 | 3.109375 | 3 |
[] |
no_license
|
#!/usr/bin/env bash
set -x
export DEBIAN_FRONTEND=noninteractive
if [ ! -e "/home/vagrant/.firstboot" ]; then
# update us. -> ph. in apt sources.list to use APT server from Finland
perl -i -p -e 's/\/\/us\./\/\/ph./g' /etc/apt/sources.list
# install mongodb repo
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list
# remove ufw firewall
dpkg --purge ufw
apt-get update
# install required packages
apt-get install -y --force-yes git vim curl unzip software-properties-common python-software-properties
# install ruby dev env
curl -L https://get.rvm.io | bash -s stable --ruby
source /usr/local/rvm/scripts/rvm
echo "gem: --no-ri --no-rdoc" > /etc/gemrc
gem install bundler rails execjs mongoid rspec-rails cucumber-rails database_cleaner rack mongodb mongo bson bson_ext
usermod -a -G rvm vagrant
# install mongodb
apt-get install mongodb-10gen
echo "mongodb-10gen hold" | dpkg --set-selections
service mongodb start
mkdir -p /data/db/
chown vagrant /data/db
# config local datetime
mv /etc/localtime /etc/localtime.bak
ln -s /usr/share/zoneinfo/Asia/Manila /etc/localtime
touch /home/vagrant/.firstboot
reboot
fi
|
TypeScript
|
UTF-8
| 295 | 2.75 | 3 |
[] |
no_license
|
namespace L11_Inheritance {
export class DavidStar2 extends DavidStar {
constructor(_color: string) {
super(_color);
}
move(): void {
this.x += Math.random() * 2 - 1;
this.y += Math.random() * 2 - 1;
}
}
}
|
PHP
|
UTF-8
| 7,143 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
<?php
//Controlador: esta aplicación solo realiza una accion
include("modelo.php");
include("vista.php");
class Controlador{
protected $user;
public function __construct(){
$this->user = new Usuarios();
}
//Inicia la conexion, todas las peticiones pasan por aqui.
public function iniciar_conexon(){
session_start();
if (isset($_REQUEST["do"])) { // La variable "do" controla el estado de la aplicación
$do = $_REQUEST["do"];
} else {
$do = "mostrar_formulario"; // Estado por defecto
}
$this->$do(); // Ejecuta la función con el nombre $do.
// P. ej: si $do vale "showFormLogin", ejecuta $this->showFormLogin()
}
//Muestra la página de inicio con el login y el registrarse.
public function mostrar_formulario(){
$data["mensaje"] = (isset($_REQUEST["mensaje"]) ? $_REQUEST["mensaje"] : null);
View::show("vista_principal", $data);
}
public function logearse(){
$username = $_REQUEST["usuario"];
$pasword = $_REQUEST["contraseña"];
$userOk = $this->user->getForUsername($username, $pasword);
if ($userOk) {
View::redirect("mostrar_datos");
} else {
$data["mensaje"] = "Nombre de usuario o contraseña incorrecto";
View::show("vista_principal", $data);
}
}
public function mostrar_datos(){
if (isset($_SESSION["nombre"]) && $_SESSION["tipo"] == "0") {
// Tipo de usuario 0 (administador)
$data["usersList"] = $this->user->getAll();
$data["nombreUsuarioLogueado"] = $_SESSION["nombre"];
View::show("vista_administrador", $data);
} else if (isset($_SESSION["nombre"]) && $_SESSION["tipo"] == "1") {
// Tipo de usuario 1 (usuario normal)
$usurname = $_SESSION["nombre"];
$data["datosUsuario"] = $this->user->getUsuarioAll($usurname);
View::show("vista_usuario", $data);
} else {
// Tipo de usuario desconocido O no se ha hecho login
$data["mensaje"] = "No tienes permiso para hacer esto";
View::redirect("mostrar_formulario", $data);
}
}
public function registrarse(){
$data['usuario'] = $_REQUEST['usuario'];
$data['pasword'] = $_REQUEST['contraseña'];
$data['nombre'] = $_REQUEST['nombre'];
$data['apellidos'] = $_REQUEST['apellidos'];
$data['correo'] = $_REQUEST['correo'];
$userOk = $this->user->getUsuarioAll( $data['usuario']);
if($userOk){
$data["mensaje"] = "Nombre de usuario ya creado, elija otro.";
View::redirect("mostrar_formulario", $data);
}else {
$resultInsert = $this->user->insert($data);
if ($resultInsert == 1) {
$data["mensaje"] = "Usuario creado con éxito";
View::redirect("mostrar_formulario", $data);
} else {
$data["mensaje"] = "Error, no se puedo crear el usuario";
View::redirect("mostrar_formulario", $data);
}
}
}
public function anadir_usuario(){
$data['usuario'] = $_REQUEST['usuario'];
$data['pasword'] = $_REQUEST['contraseña'];
$data["tipo"] = $_REQUEST["tipo"];
$data['nombre'] = $_REQUEST['nombre'];
$data['apellidos'] = $_REQUEST['apellidos'];
$data['correo'] = $_REQUEST['correo'];
$resultInsert = $this->user->insertAdmin($data);
$data = null;
if ($resultInsert == 1) {
$data["mensaje"] = "Usuario creado con éxito";
View::redirect("mostrar_datos", $data);
} else {
$data["mensaje"] = "Error, no se puedo crear el usuario";
View::redirect("mostrar_datos", $data);
}
}
public function mostrar_usuario_modificar(){
$usurname = $_REQUEST["usuario"];
$data["datosUsuario"] = $this->user->getUsuarioAll($usurname);
$data["mensaje"] = (isset($_REQUEST["mensaje"]) ? $_REQUEST["mensaje"] : null);
View::show("vista_modificar_usuario", $data);
}
public function modificar_usuario(){
$data['usuario'] = $_REQUEST['usuario'];
$data['pasword'] = $_REQUEST['contraseña'];
$data['nombre'] = $_REQUEST['nombre'];
$data['apellidos'] = $_REQUEST['apellidos'];
$data['correo'] = $_REQUEST['correo'];
$data["tipo"] = $_REQUEST["tipo"];
$resultInsert = $this->user->updateAdmin($data);
$data = null;
if ($resultInsert == 1) {
$data["mensaje"] = "Usuario modificado con éxito";
View::redirect("mostrar_datos", $data);
} else {
$data["mensaje"] = "Error, no se puedo modificar el usuario";
View::redirect("mostrar_datos", $data);
}
}
public function desconectar(){
session_destroy();
header("Location: index.php");
}
public function modificara_datos(){
$data['usuario'] = $_REQUEST['usuario'];
$data['pasword'] = $_REQUEST['contraseña'];
$data['nombre'] = $_REQUEST['nombre'];
$data['apellidos'] = $_REQUEST['apellidos'];
$data['correo'] = $_REQUEST['correo'];
$resultInsert = $this->user->update($data);
$data = null;
if ($resultInsert == 1) {
$data["mensaje"] = "Usuario modificado con éxito";
View::redirect("mostrar_datos", $data);
} else {
$data["mensaje"] = "Error, no se puedo modificar los datos";
View::redirect("mostrar_datos", $data);
}
}
public function eliminar_cuenta(){
if($_SESSION["tipo"]== 0){
$data["usuario"]=$_REQUEST["usuario"];
$resultInsert = $this->user->delete($data);
if($resultInsert){
$data["mensaje"] = "Usuario eliminado con exito";
}else {
$data["mensaje"] = "No se pudo borrar al usuario";
}
View::redirect("mostrar_datos", $data);
}else{
$data["usuario"] = $_SESSION["nombre"];
$resultInsert = $this->user->delete($data);
if($resultInsert){
$data["mensaje"] = "Usuario eliminado con exito";
View::redirect("mostrar_formulario", $data);
}else {
$data["mensaje"] = "Error al borrar";
View::redirect("mostrar_datos", $data);
}
}
}
}
|
JavaScript
|
UTF-8
| 4,200 | 2.703125 | 3 |
[] |
no_license
|
let playerStats = new Map([
["attack", 1],
["strength", 1],
["defence", 1],
["ranged", 1],
["prayer", 1],
["magic", 1],
["runecrafting", 1],
["construction", 1],
["hitpoints", 10],
["agility", 1],
["herblore", 1],
["thieving", 1],
["crafting", 1],
["fletching", 1],
["slayer", 1],
["hunter", 1],
["mining", 1],
["smithing", 1],
["fishing", 1],
["cooking", 1],
["firemaking", 1],
["woodcutting", 1],
["farming", 1]
])
const statsInput = document.getElementById('stats-input-table')
const table = document.getElementById('quest-table')
const h2 = document.querySelector('h2')
const h3 = document.querySelector('h3')
const eligibleQuests = document.getElementById('eligible-quests')
const explanationText = document.getElementById('tool-explanation')
// Player stats interface
const attackLv = document.querySelector('#attackLv')
const strengthLv = document.querySelector('#strengthLv')
const defenceLv = document.querySelector('#defenceLv')
const rangedLv = document.querySelector('#rangedLv')
const prayerLv = document.querySelector('#prayerLv')
const magicLv = document.querySelector('#magicLv')
const runecraftingLv = document.querySelector('#runecraftingLv')
const constructionLv = document.querySelector('#constructionLv')
const hitpointsLv = document.querySelector('#hitpointsLv')
const agilityLv = document.querySelector('#agilityLv')
const herbloreLv = document.querySelector('#herbloreLv')
const thievingLv = document.querySelector('#thievingLv')
const craftingLv = document.querySelector('#craftingLv')
const fletchingLv = document.querySelector('#fletchingLv')
const slayerLv = document.querySelector('#slayerLv')
const hunterLv = document.querySelector('#hunterLv')
const miningLv = document.querySelector('#miningLv')
const smithingLv = document.querySelector('#smithingLv')
const fishingLv = document.querySelector('#fishingLv')
const cookingLv = document.querySelector('#cookingLv')
const firemakingLv = document.querySelector('#firemakingLv')
const woodcuttingLv = document.querySelector('#woodcuttingLv')
const farmingLv = document.querySelector('#farmingLv')
// generateQuestList()
// Listen for player stats input and submission
statsInput.addEventListener('submit', function (e) {
e.preventDefault()
while (table.firstChild) {
table.removeChild(table.firstChild)
}
playerStats.set("attack", e.target.elements.attackLv.value)
playerStats.set("strength", e.target.elements.strengthLv.value)
playerStats.set("defence", e.target.elements.defenceLv.value)
playerStats.set("ranged", e.target.elements.rangedLv.value)
playerStats.set("prayer", e.target.elements.prayerLv.value)
playerStats.set("magic", e.target.elements.magicLv.value)
playerStats.set("runecrafting", e.target.elements.runecraftingLv.value)
playerStats.set("construction", e.target.elements.constructionLv.value)
playerStats.set("hitpoints", e.target.elements.hitpointsLv.value)
playerStats.set("agility", e.target.elements.agilityLv.value)
playerStats.set("herblore", e.target.elements.herbloreLv.value)
playerStats.set("thieving", e.target.elements.thievingLv.value)
playerStats.set("crafting", e.target.elements.craftingLv.value)
playerStats.set("fletching", e.target.elements.fletchingLv.value)
playerStats.set("slayer", e.target.elements.slayerLv.value)
playerStats.set("hunter", e.target.elements.hunterLv.value)
playerStats.set("mining", e.target.elements.miningLv.value)
playerStats.set("smithing", e.target.elements.smithingLv.value)
playerStats.set("fishing", e.target.elements.fishingLv.value)
playerStats.set("cooking", e.target.elements.cookingLv.value)
playerStats.set("firemaking", e.target.elements.firemakingLv.value)
playerStats.set("woodcutting", e.target.elements.woodcuttingLv.value)
playerStats.set("farming", e.target.elements.farmingLv.value)
checkStats(playerStats, quests)
h3.textContent = "Your stats are eligible to start the following quests:"
generateEligibleQuests()
})
|
C#
|
UTF-8
| 1,042 | 2.734375 | 3 |
[
"MS-PL"
] |
permissive
|
namespace Grace.DependencyInjection.Conditions
{
/// <summary>
/// Simple condition true when delegate returns true
/// </summary>
public class WhenCondition : IExportCondition
{
private readonly ExportConditionDelegate condition;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="condition"></param>
public WhenCondition(ExportConditionDelegate condition)
{
this.condition = condition;
}
/// <summary>
/// Called to determine if the export strategy meets the condition to be activated
/// </summary>
/// <param name="scope">injection scope that this export exists in</param>
/// <param name="injectionContext">injection context for this request</param>
/// <param name="exportStrategy">export strategy being tested</param>
/// <returns>true if the export meets the condition</returns>
public bool ConditionMeet(IInjectionScope scope, IInjectionContext injectionContext, IExportStrategy exportStrategy)
{
return condition(scope, injectionContext, exportStrategy);
}
}
}
|
Python
|
UTF-8
| 360 | 2.921875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# @Time : 2019/7/11 0:39
# @Author : liuqi
# @FileName: tutleTest.py
# @Software: PyCharm
import turtle
import time
# 同时设置pencolor=color1, fillcolor=color2
turtle.color("red", "yellow")
turtle.begin_fill()
for _ in range(50):
turtle.forward(200)
turtle.left(170)
turtle.end_fill()
turtle.mainloop()
|
TypeScript
|
UTF-8
| 4,687 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
import {
useRef,
// Types
MutableRefObject,
useEffect,
} from 'react'
import { Keys } from '../components/keyboard'
import { focusElement, focusIn, Focus, FocusResult } from '../utils/focus-management'
import { useWindowEvent } from './use-window-event'
import { useIsMounted } from './use-is-mounted'
export enum Features {
/** No features enabled for the `useFocusTrap` hook. */
None = 1 << 0,
/** Ensure that we move focus initially into the container. */
InitialFocus = 1 << 1,
/** Ensure that pressing `Tab` and `Shift+Tab` is trapped within the container. */
TabLock = 1 << 2,
/** Ensure that programmatically moving focus outside of the container is disallowed. */
FocusLock = 1 << 3,
/** Ensure that we restore the focus when unmounting the component that uses this `useFocusTrap` hook. */
RestoreFocus = 1 << 4,
/** Enable all features. */
All = InitialFocus | TabLock | FocusLock | RestoreFocus,
}
export function useFocusTrap(
container: MutableRefObject<HTMLElement | null>,
features: Features = Features.All,
{
initialFocus,
containers,
}: {
initialFocus?: MutableRefObject<HTMLElement | null>
containers?: MutableRefObject<Set<MutableRefObject<HTMLElement | null>>>
} = {}
) {
let restoreElement = useRef<HTMLElement | null>(
typeof window !== 'undefined' ? (document.activeElement as HTMLElement) : null
)
let previousActiveElement = useRef<HTMLElement | null>(null)
let mounted = useIsMounted()
let featuresRestoreFocus = Boolean(features & Features.RestoreFocus)
let featuresInitialFocus = Boolean(features & Features.InitialFocus)
// Capture the currently focused element, before we enable the focus trap.
useEffect(() => {
if (!featuresRestoreFocus) return
restoreElement.current = document.activeElement as HTMLElement
}, [featuresRestoreFocus])
// Restore the focus when we unmount the component.
useEffect(() => {
if (!featuresRestoreFocus) return
return () => {
focusElement(restoreElement.current)
restoreElement.current = null
}
}, [featuresRestoreFocus])
// Handle initial focus
useEffect(() => {
if (!featuresInitialFocus) return
if (!container.current) return
let activeElement = document.activeElement as HTMLElement
if (initialFocus?.current) {
if (initialFocus?.current === activeElement) {
previousActiveElement.current = activeElement
return // Initial focus ref is already the active element
}
} else if (container.current.contains(activeElement)) {
previousActiveElement.current = activeElement
return // Already focused within Dialog
}
// Try to focus the initialFocus ref
if (initialFocus?.current) {
focusElement(initialFocus.current)
} else {
if (focusIn(container.current, Focus.First) === FocusResult.Error) {
throw new Error('There are no focusable elements inside the <FocusTrap />')
}
}
previousActiveElement.current = document.activeElement as HTMLElement
}, [container, initialFocus, featuresInitialFocus])
// Handle `Tab` & `Shift+Tab` keyboard events
useWindowEvent('keydown', event => {
if (!(features & Features.TabLock)) return
if (!container.current) return
if (event.key !== Keys.Tab) return
event.preventDefault()
if (
focusIn(
container.current,
(event.shiftKey ? Focus.Previous : Focus.Next) | Focus.WrapAround
) === FocusResult.Success
) {
previousActiveElement.current = document.activeElement as HTMLElement
}
})
// Prevent programmatically escaping the container
useWindowEvent(
'focus',
event => {
if (!(features & Features.FocusLock)) return
let allContainers = new Set(containers?.current)
allContainers.add(container)
if (!allContainers.size) return
let previous = previousActiveElement.current
if (!previous) return
if (!mounted.current) return
let toElement = event.target as HTMLElement | null
if (toElement && toElement instanceof HTMLElement) {
if (!contains(allContainers, toElement)) {
event.preventDefault()
event.stopPropagation()
focusElement(previous)
} else {
previousActiveElement.current = toElement
focusElement(toElement)
}
} else {
focusElement(previousActiveElement.current)
}
},
true
)
}
function contains(containers: Set<MutableRefObject<HTMLElement | null>>, element: HTMLElement) {
for (let container of containers) {
if (container.current?.contains(element)) return true
}
return false
}
|
Markdown
|
UTF-8
| 2,159 | 3.296875 | 3 |
[] |
no_license
|
```bash
# 列出所有本地分支
git branch
# 列出所有远程分支
git branch -r
# 新建一个分支,但依然停留在当前分支
git branch [branch-name]
# 新建一个分支,并切换到该分支
git checkout -b [branch]
# 合并指定分支到当前分支
$ git merge [branch]
# 删除分支
$ git branch -d [branch-name]
# 删除远程分支
$ git push origin --delete [branch-name]
$ git branch -dr [remote/branch]
```
```bash
#初始化
git init
#删除初始化
rm -rf .git
#连接远程仓库
git remote add origin 仓库地址
#查看连接的仓库
git remote -v
#创建并切换到分支
git checkout -b 分支名
#添加本地需要提交的代码
git add . (.表示所有代码)
#提交代码并添加说明
git commit -m “说明内容”
#上传代码到新分支
git push origin 本地分支名:远程分支名
(若远程分支不存在会新建)
#查看本地分支
git branch
#查看远程分支
git branch -a
```
```bash
git branch //查看本地分支
git branch -r //查看远程分支
git branch -a //查看本地和远程分支
git checkout <branch-name> //从当前分支,切换到其他分支
git checkout -b <branch-name> //创建并切换新建分支
git branch -d <branch-name> //删除本地分支(本地)
git branch -D <branch-name> //强制删除分支(提交记录并没合并过 -d是删除不了 )
git merge <branch-name> //当前分支与指定分支合并
git merge --abort //合并冲突时(merging),取消git合并分支
git branch --merged //查看哪些分支已经合并到当前分支
git branch --no-merged //查看哪些分支没有合并到当前分支
git branch -v //查看各个分支最后一个提交对象信息
git push origin --delete <branch> //删除远程分支
git branch -m <old-name> <new-name> //重命名分支
git checkout -b 本地分支 origin/远程分支 //拉取远程分支并创建本地分支
git rebase <branch-name> //衍合指定分支记录到当前分支(不产生分支合并-推荐用)
git rebase --abort //衍合冲突(rebase)的时候,取消衍合
```
|
Java
|
UTF-8
| 4,979 | 2.265625 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cz.certicon.routing.parser.model;
import cz.certicon.routing.parser.model.commands.DataTypeCommand;
import cz.certicon.routing.parser.model.commands.ParsedSourceDbFileCommand;
import cz.certicon.routing.parser.model.commands.ParsedTargetSqliteFileCommand;
import cz.certicon.routing.parser.model.commands.SourcePbfFileCommand;
import cz.certicon.routing.parser.model.commands.TargetDbFileCommand;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author Michael Blaha {@literal <michael.blaha@certicon.cz>}
*/
public class ArgumentsParser {
public static List<Command> parse( String... args ) {
final List<Command> commands = new ArrayList<>();
Group<String> settings = new XorGroup<>();
settings.addChainLink( new CommandChainLink( "parallel" ) {
@Override
public void onSuccess( String value ) {
commands.add( new SourcePbfFileCommand( value ) );
}
} );
settings.addChainLink( new CommandChainLink( "data_type" ) {
@Override
public void onSuccess( String value ) {
commands.add( new DataTypeCommand( DataType.valueOfIgnoreCase( value ) ) );
}
} );
for ( String arg : args ) {
settings.execute( arg );
}
Group<String> files = new XorGroup<>();
files.addChainLink( new CommandChainLink( "source_pbf_file" ) {
@Override
public void onSuccess( String value ) {
commands.add( new SourcePbfFileCommand( value ) );
}
} );
files.addChainLink( new CommandChainLink( "target_db_file" ) {
@Override
public void onSuccess( String value ) {
commands.add( new TargetDbFileCommand( value ) );
}
} );
files.addChainLink( new CommandChainLink( "source_db_file" ) {
@Override
public void onSuccess( String value ) {
commands.add( new ParsedSourceDbFileCommand( value ) );
}
} );
files.addChainLink( new CommandChainLink( "target_sqlite_file" ) {
@Override
public void onSuccess( String value ) {
commands.add( new ParsedTargetSqliteFileCommand( value ) );
}
} );
for ( String arg : args ) {
files.execute( arg );
}
return commands;
}
private static abstract class CommandChainLink implements ChainLink<String> {
private final String key;
public CommandChainLink( String key ) {
this.key = key + "=";
}
@Override
public boolean execute( String t ) {
if ( t.startsWith( key ) ) {
onSuccess( t.substring( key.length() ) );
return true;
}
return false;
}
abstract public void onSuccess( String value );
}
private interface ChainLink<Traveller> {
public boolean execute( Traveller t );
}
private interface Group<Traveller> extends ChainLink<Traveller> {
public void addChainLink( ChainLink cl );
public boolean next( Traveller t );
}
private static abstract class SimpleGroup<Traveller> implements Group<Traveller> {
private final List<ChainLink<Traveller>> list = new LinkedList<>();
private Iterator<ChainLink<Traveller>> iterator = null;
@Override
public void addChainLink( ChainLink cl ) {
list.add( cl );
}
@Override
public boolean execute( Traveller t ) {
iterator = list.iterator();
return next( t );
}
@Override
public boolean next( Traveller t ) {
if ( !getIterator().hasNext() ) {
return false;
}
ChainLink<Traveller> next = getIterator().next();
return executeNext( next, t );
}
abstract protected boolean executeNext( ChainLink<Traveller> next, Traveller t );
protected Iterator<ChainLink<Traveller>> getIterator() {
return iterator;
}
}
private static class XorGroup<Traveller> extends SimpleGroup<Traveller> {
@Override
protected boolean executeNext( ChainLink<Traveller> next, Traveller t ) {
if ( !next.execute( t ) ) {
return next( t );
} else {
return true;
}
}
}
private static class OrGroup<Traveller> extends SimpleGroup<Traveller> {
@Override
protected boolean executeNext( ChainLink<Traveller> next, Traveller t ) {
return next.execute( t );
}
}
}
|
Java
|
UTF-8
| 3,559 | 2.078125 | 2 |
[] |
no_license
|
package com.wine.to.up.notification.service.mobile.fcm;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.wine.to.up.notification.service.components.NotificationServiceMetricsCollector;
import com.wine.to.up.notification.service.domain.model.fcm.FcmPushNotificationRequest;
import com.wine.to.up.user.service.api.message.UserTokensOuterClass.UserTokens;
import com.wine.to.up.user.service.api.message.WinePriceUpdatedWithTokensEventOuterClass.WinePriceUpdatedWithTokensEvent;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase
public class FcmTest {
@Autowired
private FcmService fcmService;
@MockBean
private NotificationServiceMetricsCollector notificationServiceMetricsCollector;
@Before
public void initializeTestFcm() {
FirebaseOptions options = FirebaseOptions.builder().setProjectId("project-id-1")
.setCredentials(new MockGoogleCredentials()).build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
}
}
@Test
public void testSendMessage() {
FcmPushNotificationRequest fcmPushNotificationRequest = new FcmPushNotificationRequest();
fcmPushNotificationRequest.setTitle("sample");
fcmPushNotificationRequest.setMessage("sample");
fcmPushNotificationRequest.setClientToken("sample");
Throwable thrown = catchThrowable(() -> {
fcmService.sendMessage(fcmPushNotificationRequest);
});
assertThat(thrown).isInstanceOf(ExecutionException.class).hasMessageContaining("401"); // Because we're using mock creds
}
@Test
public void testSendAll() {
List<UserTokens> tokens = new ArrayList<>();
tokens.add(
UserTokens.newBuilder()
.addFcmTokens("123")
.addFcmTokens("456")
.setUserId(1L)
.build()
);
WinePriceUpdatedWithTokensEvent event = WinePriceUpdatedWithTokensEvent.newBuilder()
.setWineId("1")
.setWineName("test")
.setNewWinePrice((float)1)
.addAllUserTokens(tokens)
.build();
fcmService.sendAll(event); // Assure the error is not thrown
}
/**
* Recommended way to test Firebase apps. That's how it's actually done in firebase-admin tests.
*/
private static class MockGoogleCredentials extends GoogleCredentials {
@Override
public AccessToken refreshAccessToken() {
Date expiry = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1));
return new AccessToken(UUID.randomUUID().toString(), expiry);
}
}
}
|
Python
|
UTF-8
| 4,291 | 3.1875 | 3 |
[] |
no_license
|
"""
The rail network data and methods for loading, saving etc
"""
from persist import Serializable, Multidict, tupleify
from random import uniform
from math import sqrt, radians, sin, cos
__author__ = 'tomas.liden@liu.se'
def _move(point, r_min, r_max, d_min, d_max):
"""
Perform a polar move of the point, using a radius in [r_min, r_max] and a degree in |d_min, d_max]
"""
r = uniform(r_min, r_max)
phi = radians(uniform(d_min, d_max))
return tuple([point[0] + r * cos(phi), point[1] + r * sin(phi)])
def dist(a, b):
"""
Distance between two points a and b
"""
return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
class Nodes(dict):
"""
A dictionary of nodes, keyed by the name and with a tuple of x, y coordinates as value.
When adding nodes they are checked for overlapping and adjusted so as to get a clear plotting.
The x, y coordinates are given in the [0, 1] range
"""
def add(self, name, point=None, placement=0):
if not point:
if placement == 0:
point = (uniform(0, 1), uniform(0, 1))
elif placement < 0:
point = _move((0.5, 0.5), 0.2, 0.4, 120, 240)
else:
point = _move((0.5, 0.5), 0.2, 0.4, -60, 60)
i = 0
while i < 5 and self.overlap(point):
point = _move(point, 0.1, 0.1, 0, 360)
assert not self.overlap(point), "Node %s still overlaps others after trying to adjust: (%.4f, %.4f)" % \
(name, point[0], point[1])
self[name] = point
def overlap(self, point):
for n in self.itervalues():
if dist(n, point) < 0.01:
return True
return False
def __str__(self):
return str({k: (round(v[0], 4), round(v[1], 4)) for k, v in self.items()})
class Network(Serializable):
"""
A rail network with nodes, links, capacities (over links) and routes together with:
- route_links: links per route (L_r)
- route_nodes: nodes in route r (N_r)
- route_dirs: travel dir. per route (d_l for l in L_r)
"""
def __init__(self, nodes, links, routes, capacity, route_links, route_nodes, route_dirs):
Serializable.__init__(self)
self.nodes = nodes
self.links = links
self.routes = routes
self.capacity = capacity
self.route_links = route_links
self.route_nodes = route_nodes
self.route_dirs = route_dirs
def od_routes(self):
# find all OD pairs and their possible routes
od_r = {}
cancellation = False
for r, nodes in self.route_nodes.items():
if len(nodes):
k = (nodes[0], nodes[-1])
if k not in od_r:
od_r[k] = []
od_r[k].append(r)
else:
cancellation = r
if cancellation:
od_r = {k: rl + [cancellation] for k, rl in od_r.items()}
return od_r
def single_track(self, l):
return l in self.capacity and self.capacity[l][1] < 2 * self.capacity[l][0]
def __str__(self):
return "\n".join([
"Nodes: %s" % str(self.nodes),
"Links: %s" % str(self.links),
"Normal cap : %s" % self.capacity,
"Route nodes: %s" % self.route_nodes,
"Route links: %s" % self.route_links,
"Route dirs : %s" % self.route_dirs
])
def to_json(self):
return self.rep({
"nodes": self.nodes,
"links": self.links,
"routes": self.routes,
"capacity": Multidict(self.capacity),
"route_links": self.route_links, # dict will be stored as list
"route_nodes": self.route_nodes, # -"-
"route_dirs": self.route_dirs # -"-
})
@staticmethod
def from_json(chunk):
return Network(
chunk["nodes"],
tupleify(chunk["links"]),
chunk["routes"],
{k: tuple(v) for k, v in chunk["capacity"].data.items()},
{k: tupleify(v) for k, v in chunk["route_links"].items()},
{k: tuple(v) for k, v in chunk["route_nodes"].items()},
{k: tuple(v) for k, v in chunk["route_dirs"].items()}
)
|
PHP
|
UTF-8
| 1,328 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* This file is part of phplrt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Phplrt\Position;
use Phplrt\Contracts\Position\IntervalInterface;
use Phplrt\Contracts\Position\PositionInterface;
class Interval implements IntervalInterface
{
use IntervalFactoryTrait;
/**
* @var PositionInterface
*/
private PositionInterface $from;
/**
* @var PositionInterface
*/
private PositionInterface $to;
/**
* @param PositionInterface $from
* @param PositionInterface $to
*/
public function __construct(PositionInterface $from, PositionInterface $to)
{
if ($from->getOffset() > $to->getOffset()) {
[$from, $to] = [$to, $from];
}
$this->from = $from;
$this->to = $to;
}
/**
* {@inheritDoc}
*/
public function getFrom(): PositionInterface
{
return $this->from;
}
/**
* {@inheritDoc}
*/
public function getTo(): PositionInterface
{
return $this->to;
}
/**
* {@inheritDoc}
*/
public function getLength(): int
{
return $this->to->getOffset() - $this->from->getOffset();
}
}
|
TypeScript
|
UTF-8
| 2,354 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import { AnyAction } from 'redux';
import { ISittersState } from '../sitters.state';
import { createReducerHash } from '../../common';
import { SITTERS } from '../actions';
export const initialState: ISittersState = {
sitters: {},
isLoading: false,
error: null,
};
const startLoadingReducer = (state: ISittersState): ISittersState => ({
...state,
isLoading: true,
});
const loadSuccessReducer = (state: ISittersState, action: AnyAction): ISittersState => ({
...state,
isLoading: false,
sitters: {
...state.sitters,
...action.payload.reduce((map, sitter) => {
map[sitter.id] = sitter;
return map;
}, {}),
},
});
const loadFailedReducer = (state: ISittersState, action: AnyAction): ISittersState => ({
...state,
isLoading: false,
error: action.payload,
});
const saveSuccessReducer = (state: ISittersState, action: AnyAction): ISittersState => ({
...state,
isLoading: false,
sitters: {
...state.sitters,
[action.payload.id]: {
...state.sitters[action.payload.id],
...action.payload,
},
},
});
const saveFailedReducer = (state: ISittersState, action: AnyAction): ISittersState => ({
...state,
isLoading: false,
error: action.payload,
});
const addBeginReducer = (state: ISittersState): ISittersState => ({
...state,
isAdding: true,
});
const addCancelledReducer = (state: ISittersState): ISittersState => ({
...state,
isAdding: false,
});
const addSuccessReducer = (state: ISittersState, action: AnyAction) => ({
...state,
isAdding: false,
isLoading: false,
sitters: {
...state.sitters,
[action.payload.id]: action.payload,
},
});
const addFailedReducer = (state: ISittersState, action: AnyAction) => ({
...state,
isLoading: false,
error: action.payload,
});
export const sittersReducer = createReducerHash(
{
[SITTERS.LOAD]: startLoadingReducer,
[SITTERS.LOAD_SUCCESS]: loadSuccessReducer,
[SITTERS.LOAD_FAILED]: loadFailedReducer,
[SITTERS.SAVE]: startLoadingReducer,
[SITTERS.SAVE_SUCCESS]: saveSuccessReducer,
[SITTERS.SAVE_FAILED]: saveFailedReducer,
[SITTERS.ADD_BEGIN]: addBeginReducer,
[SITTERS.ADD_CANCELLED]: addCancelledReducer,
[SITTERS.ADD]: startLoadingReducer,
[SITTERS.ADD_SUCCESS]: addSuccessReducer,
[SITTERS.ADD_FAILED]: addFailedReducer,
},
initialState
);
|
JavaScript
|
UTF-8
| 460 | 3.515625 | 4 |
[] |
no_license
|
// Function that recieves data from the form on button click and filters out the data based on form criteria then builds the table.
function filterData() {
var searchDate = d3.select("#datetime").property("value");
var searchFilters = data;
searchFilters = searchFilters.filter(ufo => ufo.datetime === searchDate);
tbody.html(''); // Cleans HTML incase multiple searches are made
buildTable(searchFilters); // Builds table from results
};
|
Java
|
UTF-8
| 9,654 | 1.851563 | 2 |
[
"Apache-2.0"
] |
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.apache.flink.streaming.connectors.dis;
import com.huaweicloud.dis.DISConfig;
import com.huaweicloud.dis.adapter.common.Utils;
import com.huaweicloud.dis.adapter.kafka.clients.producer.ProducerRecord;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.streaming.connectors.dis.partitioner.FlinkDisPartitioner;
import org.apache.flink.streaming.connectors.dis.partitioner.FlinkFixedPartitioner;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchema;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper;
import javax.annotation.Nullable;
import java.util.Properties;
/**
* Flink Sink to produce data into a DIS stream.
*/
@PublicEvolving
public class FlinkDisProducer<T> extends FlinkDisProducerBase<T> {
private static final long serialVersionUID = 1L;
/**
* Flag controlling whether we are writing the Flink record's timestamp into DIS.
*/
private boolean writeTimestampToKafka = false;
// ---------------------- Regular constructors------------------
/**
* Creates a FlinkDisProducer for a given stream. the sink produces a DataStream to
* the stream.
*
* <p>Using this constructor, the default {@link FlinkFixedPartitioner} will be used as
* the partitioner. This default partitioner maps each sink subtask to a single DIS
* partition (i.e. all records received by a sink subtask will end up in the same
* DIS partition).
*
* <p>To use a custom partitioner, please use
* {@link #FlinkDisProducer(String, SerializationSchema, DISConfig, FlinkDisPartitioner)} instead.
*
* @param streamName
* StreamName of DIS.
* @param serializationSchema
* User defined key-less serialization schema.
* @param producerConfig
* Properties with the producer configuration.
*/
public FlinkDisProducer(String streamName, SerializationSchema<T> serializationSchema, Properties producerConfig) {
this(streamName, new KeyedSerializationSchemaWrapper<>(serializationSchema), Utils.newDisConfig(producerConfig));
}
/**
* Creates a FlinkDisProducer for a given stream. the sink produces a DataStream to
* the stream.
*
* <p>Using this constructor, the default {@link FlinkFixedPartitioner} will be used as
* the partitioner. This default partitioner maps each sink subtask to a single DIS
* partition (i.e. all records received by a sink subtask will end up in the same
* DIS partition).
*
* <p>To use a custom partitioner, please use
* {@link #FlinkDisProducer(String, SerializationSchema, DISConfig, FlinkDisPartitioner)} instead.
*
* @param streamName
* StreamName of DIS.
* @param serializationSchema
* User defined key-less serialization schema.
* @param disConfig
* Properties with the producer configuration.
*/
public FlinkDisProducer(String streamName, SerializationSchema<T> serializationSchema, DISConfig disConfig) {
this(streamName, new KeyedSerializationSchemaWrapper<>(serializationSchema), disConfig, new FlinkFixedPartitioner<T>());
}
/**
* Creates a FlinkDisProducer for a given stream. The sink produces its input to
* the stream. It accepts a key-less {@link SerializationSchema} and possibly a custom {@link FlinkDisPartitioner}.
*
* <p>Since a key-less {@link SerializationSchema} is used, all records sent to DIS will not have an
* attached key. Therefore, if a partitioner is also not provided, records will be distributed to DIS
* partitions in a round-robin fashion.
*
* @param streamName The DIS Stream to write data to
* @param serializationSchema A key-less serializable serialization schema for turning user objects into a DIS-consumable byte[]
* @param disConfig Configuration properties for the DISKafkaProducer.
* @param customPartitioner A serializable partitioner for assigning messages to DIS partitions.
* If set to {@code null}, records will be distributed to DIS partitions
* in a round-robin fashion.
*/
public FlinkDisProducer(
String streamName,
SerializationSchema<T> serializationSchema,
DISConfig disConfig,
@Nullable FlinkDisPartitioner<T> customPartitioner) {
this(streamName, new KeyedSerializationSchemaWrapper<>(serializationSchema), disConfig, customPartitioner);
}
// ------------------- Key/Value serialization schema constructors ----------------------
/**
* Creates a FlinkDisProducer for a given topic. The sink produces a DataStream to
* the stream.
*
* <p>Using this constructor, the default {@link FlinkFixedPartitioner} will be used as
* the partitioner. This default partitioner maps each sink subtask to a single DIS
* partition (i.e. all records received by a sink subtask will end up in the same
* DIS partition).
*
* <p>To use a custom partitioner, please use
* {@link #FlinkDisProducer(String, KeyedSerializationSchema, DISConfig, FlinkDisPartitioner)} instead.
*
* @param streamName
* StreamName of DIS.
* @param serializationSchema
* User defined serialization schema supporting key/value messages
* @param disConfig
* Properties with the producer configuration.
*/
public FlinkDisProducer(String streamName, KeyedSerializationSchema<T> serializationSchema, DISConfig disConfig) {
this(streamName, serializationSchema, disConfig, new FlinkFixedPartitioner<T>());
}
/**
* Creates a FlinkDisProducer for a given stream. The sink produces its input to
* the stream. It accepts a keyed {@link KeyedSerializationSchema} and possibly a custom {@link FlinkDisPartitioner}.
*
* <p>If a partitioner is not provided, written records will be partitioned by the attached key of each
* record (as determined by {@link KeyedSerializationSchema#serializeKey(Object)}). If written records do not
* have a key (i.e., {@link KeyedSerializationSchema#serializeKey(Object)} returns {@code null}), they
* will be distributed to DIS partitions in a round-robin fashion.
*
* @param streamName The DIS Stream to write data to
* @param serializationSchema A serializable serialization schema for turning user objects into a DIS-consumable byte[] supporting key/value messages
* @param disConfig Configuration properties for the DISKafkaProducer.
* @param customPartitioner A serializable partitioner for assigning messages to DIS partitions.
* If set to {@code null}, records will be partitioned by the key of each record
* (determined by {@link KeyedSerializationSchema#serializeKey(Object)}). If the keys
* are {@code null}, then records will be distributed to DIS partitions in a
* round-robin fashion.
*/
public FlinkDisProducer(
String streamName,
KeyedSerializationSchema<T> serializationSchema,
DISConfig disConfig,
@Nullable FlinkDisPartitioner<T> customPartitioner) {
super(streamName, serializationSchema, disConfig, customPartitioner);
}
// ------------------- User configuration ----------------------
/**
* If set to true, Flink will write the (event time) timestamp attached to each record into DIS.
* Timestamps must be positive for DIS to accept them.
*
* @param writeTimestampToKafka Flag indicating if Flink's internal timestamps are written to Kafka.
*/
public void setWriteTimestampToKafka(boolean writeTimestampToKafka) {
this.writeTimestampToKafka = writeTimestampToKafka;
}
// ----------------------------- Generic element processing ---------------------------
@Override
public void invoke(T value, Context context) throws Exception {
checkErroneous();
byte[] serializedKey = schema.serializeKey(value);
byte[] serializedValue = schema.serializeValue(value);
String targetTopic = schema.getTargetTopic(value);
if (targetTopic == null) {
targetTopic = defaultStreamName;
}
Long timestamp = null;
if (this.writeTimestampToKafka) {
timestamp = context.timestamp();
}
ProducerRecord<byte[], byte[]> record;
int[] partitions = topicPartitionsMap.get(targetTopic);
if (null == partitions) {
partitions = getPartitionsByTopic(targetTopic, producer);
topicPartitionsMap.put(targetTopic, partitions);
}
if (flinkDisPartitioner == null) {
record = new ProducerRecord<>(targetTopic, null, timestamp, serializedKey, serializedValue);
} else {
record = new ProducerRecord<>(targetTopic, flinkDisPartitioner.partition(value, serializedKey, serializedValue, targetTopic, partitions), timestamp, serializedKey, serializedValue);
}
if (flushOnCheckpoint) {
synchronized (pendingRecordsLock) {
pendingRecords++;
}
}
producer.send(record, callback);
}
@Override
protected void flush() {
if (this.producer != null) {
producer.flush();
}
}
}
|
C++
|
UTF-8
| 25,615 | 2.796875 | 3 |
[] |
no_license
|
#include <utility>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <tuple>
#include <algorithm>
#include <iostream>
#include "AI_player.h"
#include "Basic_BK_AI_player.h"
using namespace std;
#ifndef __SETTING__
#define __SETTING__
#define EMPTY 0
#define BLACK 1
#define WHITE 2
#define BOARD_SIZE 19 // from 0 to 18
#define MAX_TURN 180
#endif
bool _compare(tuple<int,int,int,int,int> a, tuple<int,int,int,int,int> b){
return get<0>(a) > get<0>(b);
}
Basic_BK_AI_player::Basic_BK_AI_player(){
// weight for first half move
this->my_weight[0][0] = 0;
this->my_weight[0][1] = 10000;
this->my_weight[0][2] = 20000;
this->my_weight[0][3] = 30000; //fix
this->my_weight[0][4] = 27000000; //fix
this->my_weight[0][5] = 27000000; //fix
this->my_weight[0][6] = 0;
// weight for second half move
this->my_weight[1][0] = 0;
this->my_weight[1][1] = 10000;
this->my_weight[1][2] = 20000;
this->my_weight[1][3] = 30000;
this->my_weight[1][4] = 30000; // second turn's 4 is not important (making new move 4 is more valuable than making move 4 to move 5)
this->my_weight[1][5] = 27000000; //fix
this->my_weight[1][6] = 0;
this->op_weight[0] = 0;
this->op_weight[1] = 10000;
this->op_weight[2] = 20000;
this->op_weight[3] = 30000;
this->op_weight[4] = 900000; // fix
this->op_weight[5] = 900000; // fix
this->op_weight[6] = 0;
this->cand_size_1 = 10;
this->cand_size_2 = 10;
this->discount_factor = 1;
}
Basic_BK_AI_player::Basic_BK_AI_player(int cand_size_1, int cand_size_2, float discount_factor){
// weight for first half move
this->my_weight[0][0] = 100;
this->my_weight[0][1] = 10000;
this->my_weight[0][2] = 20000;
this->my_weight[0][3] = 30000; //fix
this->my_weight[0][4] = 27000000; //fix
this->my_weight[0][5] = 27000000; //fix
this->my_weight[0][6] = 27000000;
// weight for second half move
this->my_weight[1][0] = 100;
this->my_weight[1][1] = 10000;
this->my_weight[1][2] = 20000;
this->my_weight[1][3] = 30000;
this->my_weight[1][4] = 30000; // second turn's 4 is not important (making new move 4 is more valuable than making move 4 to move 5)
this->my_weight[1][5] = 27000000; //fix
this->my_weight[1][6] = 27000000;
this->op_weight[0] = 100;
this->op_weight[1] = 10000;
this->op_weight[2] = 20000;
this->op_weight[3] = 30000;
this->op_weight[4] = 900000; // fix
this->op_weight[5] = 900000; // fix
this->op_weight[6] = 900000;
this->cand_size_1 = cand_size_1;
this->cand_size_2 = cand_size_2;
this->discount_factor = discount_factor;
}
void Basic_BK_AI_player::init_board(){
for(int i = 0; i<BOARD_SIZE; i++){
for(int j = 0; j<BOARD_SIZE; j++){
this->board[i][j] = EMPTY;
}
}
return;
}
void Basic_BK_AI_player::init_live_line_count(){
int tmp;
for(int x = 0; x<BOARD_SIZE; x++){
for(int y = 0; y<BOARD_SIZE; y++){
this->my_live_line_count[x][y][0] = 0;
//hor
if((6<=x)&&(x<=12)) this->my_live_line_count[x][y][0] += 6;
else if(x < 6) this->my_live_line_count[x][y][0] += (x+1);
else this->my_live_line_count[x][y][0] += (BOARD_SIZE-x);
//ver
if((6<=y)&&(y<=12)) this->my_live_line_count[x][y][0] += 6;
else if(y < 6) this->my_live_line_count[x][y][0] += (y+1);
else this->my_live_line_count[x][y][0] += (BOARD_SIZE-y);
//top left down right diag ---------------------------------------------------> this part should be improved
tmp = 0;
for(int z = 0; z < 6; z++){
if( (x-z >= 0 && y+z < BOARD_SIZE) && (x-z+5 < BOARD_SIZE && y+z-5 >=0) ){
tmp++;
}
}
this->my_live_line_count[x][y][0] += tmp;
//top right down left diag ---------------------------------------------------> this part should be improved
tmp = 0;
for(int z = 0; z < 6; z++){
if( (x-z >= 0 && y-z >= 0) && (x-z+5 < BOARD_SIZE && y-z+5 < BOARD_SIZE) ){
tmp++;
}
}
this->my_live_line_count[x][y][0] += tmp;
this->op_live_line_count[x][y][0] = this->my_live_line_count[x][y][0];
for(int z = 1; z<7; z++){
this->my_live_line_count[x][y][z] = this->op_live_line_count[x][y][z] = 0;
}
}
}
return;
}
void Basic_BK_AI_player::init_player(int my_color, int op_color){
this->my_color = my_color;
this->op_color = op_color;
this->turn = 0;
init_live_line_count();
init_board(); // should be executed after init_live_line_count()
return;
}
void Basic_BK_AI_player::set_forced_move(int color, int x, int y){
pair< pair<int,int>, pair<int,int> > result;
set_move_update_live_line(this->board, this->my_live_line_count, this->op_live_line_count, color, x, y);
if(this->my_color == color){
result.first.first = result.second.first = x;
result.first.second = result.second.second = y;
this->last_my_move = result;
}
return;
}
pair< pair<int, int>, pair<int, int> > Basic_BK_AI_player::return_fixed_start_move(){
pair< pair<int, int>, pair<int, int> > result;
result.first.first = BOARD_SIZE/2 - 2;
result.first.second = BOARD_SIZE/2;
result.second.first = BOARD_SIZE/2 - 1;
result.second.second = BOARD_SIZE/2 + 1;
return result;
}
int Basic_BK_AI_player::future_reward(int board[][BOARD_SIZE], int my_live_line_count[][BOARD_SIZE][7], int op_live_line_count[][BOARD_SIZE][7]){
int x,y,z,score,max,max_x,max_y,tmp1,tmp2;
int scored_board[BOARD_SIZE][BOARD_SIZE];
// best first move for op
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if(board[x][y] == EMPTY){
score = 0;
for(z=0;z<7;z++){
tmp1 = op_live_line_count[x][y][z]*this->my_weight[0][z];
tmp2 = my_live_line_count[x][y][z]*this->op_weight[z];
score += tmp1 + tmp2;
}
scored_board[x][y] = score;
}
}
}
max = -1000;
max_x = -1;
max_y = -1;
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if((board[x][y] == EMPTY) && (max < scored_board[x][y])){
max = scored_board[x][y];
max_x = x;
max_y = y;
}
}
}
if(max == -1000) return 0;
set_move_update_live_line(board, my_live_line_count, op_live_line_count, this->op_color, max_x, max_y);
// best second move for op
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if(board[x][y] == EMPTY){
score = 0;
for(z=0;z<7;z++){
tmp1 = op_live_line_count[x][y][z]*this->my_weight[0][z];
tmp2 = my_live_line_count[x][y][z]*this->op_weight[z];
score += tmp1 + tmp2;
}
scored_board[x][y] = score;
}
}
}
max = -1000;
max_x = -1;
max_y = -1;
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if((board[x][y] == EMPTY) && (max < scored_board[x][y])){
max = scored_board[x][y];
max_x = x;
max_y = y;
}
}
}
set_move_update_live_line(board, my_live_line_count, op_live_line_count, this->op_color, max_x, max_y);
// best move for my
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if(board[x][y] == EMPTY){
score = 0;
for(z=0;z<7;z++){
tmp1 = op_live_line_count[x][y][z]*this->my_weight[0][z];
tmp2 = my_live_line_count[x][y][z]*this->op_weight[z];
score += tmp1 + tmp2;
}
scored_board[x][y] = score;
}
}
}
max = -1000;
max_x = -1;
max_y = -1;
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if((board[x][y] == EMPTY) && (max < scored_board[x][y])){
max = scored_board[x][y];
max_x = x;
max_y = y;
}
}
}
////////////////////////////////////////// can customize
if(max == -1000) return 0;
else return max;
}
tuple<int,int,int> Basic_BK_AI_player::best_cand_for_move(int board[][BOARD_SIZE], int my_live_line_count[][BOARD_SIZE][7], int op_live_line_count[][BOARD_SIZE][7]){
int i,j,k,x,y,z,f,tmp1,tmp2,score;
int tmp_board[BOARD_SIZE][BOARD_SIZE];
int tmp_my_live_line_count[BOARD_SIZE][BOARD_SIZE][7];
int tmp_op_live_line_count[BOARD_SIZE][BOARD_SIZE][7];
int my_scored_board[BOARD_SIZE][BOARD_SIZE];
vector< tuple<int,int,int,int,int> > top_k_pos;
tuple<int,int,int,int,int> top_pos;
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if(board[x][y] == EMPTY){
score = 0;
for(z=0;z<7;z++){
tmp1 = my_live_line_count[x][y][z]*this->my_weight[1][z];
tmp2 = op_live_line_count[x][y][z]*this->op_weight[z];
score += tmp1 + tmp2;
}
my_scored_board[x][y] = score;
}
}
}
top_k_pos.push_back( make_tuple(-1000,-1,-1,-1,-1) );
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if((board[x][y] == EMPTY) && (get<0>(top_k_pos.back()) < my_scored_board[x][y]) ){
if( top_k_pos.size() < this->cand_size_2 ) top_k_pos.push_back( make_tuple(my_scored_board[x][y], x, y, -1, -1) ); // use cand_size_2
else{
top_k_pos.pop_back();
top_k_pos.push_back( make_tuple(my_scored_board[x][y], x, y, -1, -1) );
}
sort(top_k_pos.begin(), top_k_pos.end(), _compare);
}
}
}
while(get<0>(top_k_pos.back()) < 0) top_k_pos.pop_back();
if(get<0>(top_k_pos.front()) >= this->op_weight[4]){
while( get<0>(top_k_pos.back()) < this->op_weight[4] ) top_k_pos.pop_back();
}
for(int i=0;i<top_k_pos.size();i++){
x = get<1>(top_k_pos[i]);
y = get<2>(top_k_pos[i]);
memcpy(tmp_board, board, sizeof(int)*BOARD_SIZE*BOARD_SIZE);
memcpy(tmp_my_live_line_count, my_live_line_count, sizeof(int)*BOARD_SIZE*BOARD_SIZE*7);
memcpy(tmp_op_live_line_count, op_live_line_count, sizeof(int)*BOARD_SIZE*BOARD_SIZE*7);
set_move_update_live_line(tmp_board, tmp_my_live_line_count, tmp_op_live_line_count, this->my_color, x, y);
f = future_reward(tmp_board, tmp_my_live_line_count, tmp_op_live_line_count);
top_k_pos[i] = make_tuple( get<0>(top_k_pos[i]) + (int)(this->discount_factor * (float)(f)), x, y, -1, -1);
}
sort(top_k_pos.begin(), top_k_pos.end(), _compare);
top_pos = top_k_pos.front();
return make_tuple( get<0>(top_pos), get<1>(top_pos), get<2>(top_pos));
}
pair< pair<int, int>, pair<int, int> > Basic_BK_AI_player::return_whole_move(pair< pair<int, int>, pair<int, int> > last_op_move){
bool flag;
int x, y, z, max, max_x, max_y, tmp1, tmp2, score, top_score;
int tmp_board[BOARD_SIZE][BOARD_SIZE];
int tmp_my_live_line_count[BOARD_SIZE][BOARD_SIZE][7];
int tmp_op_live_line_count[BOARD_SIZE][BOARD_SIZE][7];
int my_scored_board[BOARD_SIZE][BOARD_SIZE];
tuple<int,int,int> best_cand;
pair< pair<int, int>, pair<int, int> > result;
vector< tuple<int,int,int,int,int> > top_k_pos; // tuple : score, x, y & desc order
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if(this->board[x][y] == EMPTY){
score = 0;
for(z=0;z<7;z++){
tmp1 = this->my_live_line_count[x][y][z]*this->my_weight[0][z];
tmp2 = this->op_live_line_count[x][y][z]*this->op_weight[z];
score += tmp1 + tmp2;
}
my_scored_board[x][y] = score;
}
}
}
//get top-k element
top_k_pos.push_back( make_tuple(-1000,-1,-1,-1,-1) );
for(x=0;x<BOARD_SIZE;x++){
for(y=0;y<BOARD_SIZE;y++){
if( (this->board[x][y] == EMPTY) && (get<0>(top_k_pos.back()) < my_scored_board[x][y]) ){
if( top_k_pos.size() < this->cand_size_1 ) top_k_pos.push_back( make_tuple(my_scored_board[x][y], x, y, -1, -1) );
else{
top_k_pos.pop_back();
top_k_pos.push_back( make_tuple(my_scored_board[x][y], x, y, -1, -1) );
}
sort(top_k_pos.begin(), top_k_pos.end(), _compare);
}
}
}
while(get<0>(top_k_pos.back()) < 0) top_k_pos.pop_back();
if(get<0>(top_k_pos.front()) >= this->op_weight[4]){
while( get<0>(top_k_pos.back()) < this->op_weight[4] ) top_k_pos.pop_back();
}
//=====================SIMULATION======================
/*
// make two pairs from top_k_pos
int len = top_k_pos.size();
for( int i = 0; i < len; i++ ) {
for ( int j = 0; j < len; j++ ) {
if ( i == j ) continue;
int x1 = get<1>( top_k_pos[i] );
int y1 = get<2>( top_k_pos[i] );
int x2 = get<1>( top_k_pos[j] );
int y2 = get<2>( top_k_pos[j] );
// copy current state
memcpy(tmp_board, this->board, sizeof(int)*BOARD_SIZE*BOARD_SIZE);
memcpy(tmp_my_live_line_count, this->my_live_line_count, sizeof(int)*BOARD_SIZE*BOARD_SIZE*7);
memcpy(tmp_op_live_line_count, this->op_live_line_count, sizeof(int)*BOARD_SIZE*BOARD_SIZE*7);
set_move_update_live_line( tmp_board, tmp_my_live_line_count, tmp_op_live_line_count, this->my_color, x1, y1 );
set_move_update_live_line( tmp_board, tmp_my_live_line_count, tmp_op_live_line_count, this->my_color, x2, y2 );
}
}*/
//start simul for each move
for(int i=0;i<top_k_pos.size();i++){
// candidate
x = get<1>(top_k_pos[i]);
y = get<2>(top_k_pos[i]);
// copy current state
memcpy(tmp_board, this->board, sizeof(int)*BOARD_SIZE*BOARD_SIZE);
memcpy(tmp_my_live_line_count, this->my_live_line_count, sizeof(int)*BOARD_SIZE*BOARD_SIZE*7);
memcpy(tmp_op_live_line_count, this->op_live_line_count, sizeof(int)*BOARD_SIZE*BOARD_SIZE*7);
// update threat
set_move_update_live_line(tmp_board, tmp_my_live_line_count, tmp_op_live_line_count, this->my_color, x, y);
//
best_cand = best_cand_for_move(tmp_board, tmp_my_live_line_count, tmp_op_live_line_count);
top_k_pos[i] = make_tuple( get<0>(top_k_pos[i]) + (int)(this->discount_factor * (float)(get<0>(best_cand))), x, y, get<1>(best_cand), get<2>(best_cand));
}
sort(top_k_pos.begin(), top_k_pos.end(), _compare);
result.first.first = get<1>(top_k_pos.front());
result.first.second = get<2>(top_k_pos.front());
result.second.first = get<3>(top_k_pos.front());
result.second.second = get<4>(top_k_pos.front());
return result;
}
pair< pair<int, int>, pair<int, int> > Basic_BK_AI_player::return_move(pair< pair<int, int>, pair<int, int> > last_op_move){
pair< pair<int, int>, pair<int, int> > result;
// save opponent's move
if(!(this->my_color == WHITE && this->turn == 0)){
set_move_update_live_line( this->board, this->my_live_line_count, this->op_live_line_count, this->op_color , last_op_move.first.first, last_op_move.first.second);
set_move_update_live_line( this->board, this->my_live_line_count, this->op_live_line_count, this->op_color , last_op_move.second.first, last_op_move.second.second);
}
if(this->my_color == WHITE && this->turn == 0) result = return_fixed_start_move();
else result = return_whole_move(last_op_move);
set_move_update_live_line( this->board, this->my_live_line_count, this->op_live_line_count, this->my_color , result.first.first, result.first.second);
set_move_update_live_line( this->board, this->my_live_line_count, this->op_live_line_count, this->my_color , result.second.first, result.second.second);
// save player's move
this->turn++;
this->last_my_move = result;
return result;
}
void Basic_BK_AI_player::set_move_update_live_line(int board[][BOARD_SIZE], int my_live_line_count[][BOARD_SIZE][7], int op_live_line_count[][BOARD_SIZE][7], int color, int x, int y){ // should add checking over 6
int current_my_count, current_op_count, current_my_color, current_op_color, tmp, b;
int (*current_my_live_line_count)[BOARD_SIZE][7];
int (*current_op_live_line_count)[BOARD_SIZE][7];
if(color == this->my_color){
current_my_live_line_count = my_live_line_count;
current_op_live_line_count = op_live_line_count;
current_my_color = this->my_color;
current_op_color = this->op_color;
}else{
current_my_live_line_count = op_live_line_count;
current_op_live_line_count = my_live_line_count;
current_my_color = this->op_color;
current_op_color = this->my_color;
}
// set move
if(board[x][y] != EMPTY){
cout << "error:basic_bk_ai_player received overlapped move" << endl;
return;
}
//============================================= check horizontal live4,5 =============================================
for( int i = ((x-5 > 0) ? x-5 : 0); i<=x; i++){
if( i+5 >= BOARD_SIZE) continue;
// check my live line first
current_my_count = 0;
if( ( i-1 < 0 || board[i-1][y]!=current_my_color ) && ( i+6 >= BOARD_SIZE || board[i+6][y]!=current_my_color) ){ // if not, it means over 6
for(b=0; b<6 ;b++){
if(board[i+b][y] == current_my_color) current_my_count++;
else if(board[i+b][y] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=0; b<6 ;b++){
if(board[i+b][y] == EMPTY){
current_my_live_line_count[i+b][y][current_my_count] -= 1;
current_my_live_line_count[i+b][y][current_my_count+1] += 1;
}
}
}
}
// check op live line first
current_op_count = 0;
if( ( i-1 < 0 || board[i-1][y]!=current_op_color ) && ( i+6 >= BOARD_SIZE || board[i+6][y]!=current_op_color) ){ //----------------------check later
for(b=0; b<6 ;b++){
if(board[i+b][y] == current_op_color) current_op_count++;
else if(board[i+b][y] == current_my_color){
current_op_count = -1;
break;
}
}
if(current_op_count != -1){
for(b=0; b<6 ;b++){
if(board[i+b][y] == EMPTY){
current_op_live_line_count[i+b][y][current_op_count] -= 1;
}
}
}
}
}
//============================================= check vertical live4,5 =============================================
for( int j = ((y-5 > 0) ? y-5 : 0); j<=y; j++){
if( j+5 >= BOARD_SIZE) continue;
// check my live line first
current_my_count = 0;
if( ( j-1 < 0 || board[x][j-1]!=current_my_color ) && ( j+6 >= BOARD_SIZE || board[x][j+6]!=current_my_color) ){ // if not, it means over 6
for(b=0; b<6 ;b++){
if(board[x][j+b] == current_my_color) current_my_count++;
else if(board[x][j+b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=0; b<6 ;b++){
if(board[x][j+b] == EMPTY){
current_my_live_line_count[x][j+b][current_my_count] -= 1;
current_my_live_line_count[x][j+b][current_my_count+1] += 1;
}
}
}
}
// check op live line first
current_op_count = 0;
if( ( j-1 < 0 || board[x][j-1]!=current_op_color ) && ( j+6 >= BOARD_SIZE || board[x][j+6]!=current_op_color) ){
for(b=0; b<6 ;b++){
if(board[x][j+b] == current_op_color) current_op_count++;
else if(board[x][j+b] == current_my_color){
current_op_count = -1;
break;
}
}
if(current_op_count != -1){
for(b=0; b<6 ;b++){
if(board[x][j+b] == EMPTY){
current_op_live_line_count[x][j+b][current_op_count] -= 1;
}
}
}
}
}
//============================================= check top left down right diag live4,5 =============================================
tmp = ( BOARD_SIZE - y - 1 < x ) ? BOARD_SIZE - y - 1 : x;
if(tmp > 5) tmp = 5;
for( int i = 0; i <= tmp; i++){
if( (x-i+5 >= BOARD_SIZE) || (y+i-5 < 0)) continue;
// check my live line first
current_my_count = 0;
if( ( x-i-1 < 0 || y+i+1 >= BOARD_SIZE || board[x-i-1][y+i+1]!=current_my_color ) && ( x-i+6 >= BOARD_SIZE || y+i-6 < 0 || board[x-i+6][y+i-6]!=current_my_color) ){ // if not, it means over 6
for(b=0; b<6 ;b++){
if(board[x-i+b][y+i-b] == current_my_color) current_my_count++;
else if(board[x-i+b][y+i-b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=0; b<6 ;b++){
if(board[x-i+b][y+i-b] == EMPTY){
current_my_live_line_count[x-i+b][y+i-b][current_my_count] -= 1;
current_my_live_line_count[x-i+b][y+i-b][current_my_count+1] += 1;
}
}
}
}
// check op live line first
current_op_count = 0;
if( ( x-i-1 < 0 || y+i+1 >= BOARD_SIZE || board[x-i-1][y+i+1]!=current_op_color ) && ( x-i+6 >= BOARD_SIZE || y+i-6 < 0 || board[x-i+6][y+i-6]!=current_op_color) ){
for(b=0; b<6 ;b++){
if(board[x-i+b][y+i-b] == current_op_color) current_op_count++;
else if(board[x-i+b][y+i-b] == current_my_color){
current_op_count = -1;
break;
}
}
if(current_op_count != -1){
for(b=0; b<6 ;b++){
if(board[x-i+b][y+i-b] == EMPTY){
current_op_live_line_count[x-i+b][y+i-b][current_op_count] -= 1;
}
}
}
}
}
//============================================= check top right down left diag live4,5 =============================================
tmp = ( x < y ) ? x : y;
if(tmp > 5) tmp = 5;
for( int i = 0; i <= tmp; i++){
if( (x-i+5 >= BOARD_SIZE) || (y-i+5 >= BOARD_SIZE)) continue;
// check my live line first
current_my_count = 0;
if( ( x-i-1 < 0 || y-i-1 < 0 || board[x-i-1][y-i-1]!=current_my_color ) && ( x-i+6 >= BOARD_SIZE || y-i+6 >= BOARD_SIZE || board[x-i+6][y-i+6]!=current_my_color) ){ // if not, it means over 6
for(b=0; b<6 ;b++){
if(board[x-i+b][y-i+b] == current_my_color) current_my_count++;
else if(board[x-i+b][y-i+b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=0; b<6 ;b++){
if(board[x-i+b][y-i+b] == EMPTY){
current_my_live_line_count[x-i+b][y-i+b][current_my_count] -= 1;
current_my_live_line_count[x-i+b][y-i+b][current_my_count+1] += 1;
}
}
}
}
// check op live line first
current_op_count = 0;
if( ( x-i-1 < 0 || y-i-1 < 0 || board[x-i-1][y-i-1]!=current_op_color ) && ( x-i+6 >= BOARD_SIZE || y-i+6 >= BOARD_SIZE || board[x-i+6][y-i+6]!=current_op_color) ){
for(b=0; b<6 ;b++){
if(board[x-i+b][y-i+b] == current_op_color) current_op_count++;
else if(board[x-i+b][y-i+b] == current_my_color){
current_op_count = -1;
break;
}
}
if(current_op_count != -1){
for(b=0; b<6 ;b++){
if(board[x-i+b][y-i+b] == EMPTY){
current_op_live_line_count[x-i+b][y-i+b][current_op_count] -= 1;
}
}
}
}
}
//==================================================== if move make exist live line to over 6 -> remove exist live line ====================================================
//left hor x-1,y ~ x-6
current_my_count = 0;
if( (x-6 >= 0) && (x-7 < 0 || board[x-7][y]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x-b][y] == current_my_color) current_my_count++;
else if(board[x-b][y] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x-b][y] == EMPTY){
current_my_live_line_count[x-b][y][current_my_count] -= 1;
}
}
}
}
//right hor x+1,y ~ x+6,y
current_my_count = 0;
if( (x+6 < BOARD_SIZE) && (x+7 >= BOARD_SIZE || board[x+7][y]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x+b][y] == current_my_color) current_my_count++;
else if(board[x+b][y] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x+b][y] == EMPTY){
current_my_live_line_count[x+b][y][current_my_count] -= 1;
}
}
}
}
//upside ver x,y+1 ~ x, y+6
current_my_count = 0;
if( (y+6 < BOARD_SIZE) && (y+7 >= BOARD_SIZE || board[x][y+7]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x][y+b] == current_my_color) current_my_count++;
else if(board[x][y+b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x][y+b] == EMPTY){
current_my_live_line_count[x][y+b][current_my_count] -= 1;
}
}
}
}
//downside ver x,y-1 ~ x, y-6
current_my_count = 0;
if( (y-6 >= 0) && (y-7 < 0 || board[x][y-7]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x][y-b] == current_my_color) current_my_count++;
else if(board[x][y-b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x][y-b] == EMPTY){
current_my_live_line_count[x][y-b][current_my_count] -= 1;
}
}
}
}
//upside top left down right x-1,y+1 ~ x-6,y+6
current_my_count = 0;
if( (x-6 >= 0 && y+6 < BOARD_SIZE) && (x-7 < 0 || y+7 >= BOARD_SIZE || board[x-7][y+7]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x-b][y+b] == current_my_color) current_my_count++;
else if(board[x-b][y+b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x-b][y+b] == EMPTY){
current_my_live_line_count[x-b][y+b][current_my_count] -= 1;
}
}
}
}
//downside top left down right x+1,y-1 ~ x+6,y-6
current_my_count = 0;
if( (x+6 < BOARD_SIZE && y-6 >= 0) && (x+7 >= BOARD_SIZE || y-7 < 0 || board[x+7][y-7]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x+b][y-b] == current_my_color) current_my_count++;
else if(board[x+b][y-b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x+b][y-b] == EMPTY){
current_my_live_line_count[x+b][y-b][current_my_count] -= 1;
}
}
}
}
//upside top right down left x+1,y+1 ~ x+6,y+6
current_my_count = 0;
if( (x+6 < BOARD_SIZE && y+6 < BOARD_SIZE) && (x+7 >= BOARD_SIZE || y+7 >= BOARD_SIZE || board[x+7][y+7]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x+b][y+b] == current_my_color) current_my_count++;
else if(board[x+b][y+b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x+b][y+b] == EMPTY){
current_my_live_line_count[x+b][y+b][current_my_count] -= 1;
}
}
}
}
//downside top right down left x-1,y-1 ~ x-6,y-6
current_my_count = 0;
if( (x-6 >= 0 && y-6 >= 0) && (x-7 < 0 || y-7 < 0 || board[x-7][y-7]!=current_my_color) ){
for(b=1;b<=6;b++){
if(board[x-b][y-b] == current_my_color) current_my_count++;
else if(board[x-b][y-b] == current_op_color){
current_my_count = -1;
break;
}
}
if(current_my_count != -1){
for(b=1;b<=6;b++){
if(board[x-b][y-b] == EMPTY){
current_my_live_line_count[x-b][y-b][current_my_count] -= 1;
}
}
}
}
// set move
board[x][y] = current_my_color;
return;
}
|
C++
|
UTF-8
| 345 | 3.015625 | 3 |
[] |
no_license
|
#ifndef Node_h
#define Node_h
#include <string>
class Node
{
private:
std::string element;
Node *nextNode;
public:
Node();
Node(std::string element);
~Node();
// METODOS ELEMENT
std::string getElement();
void setElement(std::string element);
Node *getNextNode();
void setNextNode(Node *node);
};
#endif
|
C++
|
UTF-8
| 1,287 | 3.296875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int finder(int S[], int i, int N, int n){
if(n>N)
return 0;
if(S[i]==0)
return i;
else return finder(S, S[i], N, n+1);
}
void Union(int S[], int n, int i, int j){
if(S[i]==0)
S[i]=j;
else if(S[j]==0)
S[j]=i;
else {
int x = finder(S, i, n, 0);
if(x==0) cout<<"\nA loop is existing, the given elements are already related.";
else S[x]=j;
}
}
int Check(int S[], int i, int j, int N, int n){
if(n>N)
return 0;
if(S[i]==j)
return -1;
if(S[i]==0)
return i;
return Check(S, S[i], j, N, n+1);
}
int main(){
int S[20];
S[0]=-1;
for(int i=1;i<20;i++)
S[i]=0;
int n, i, j;
char ch;
cout<<"Enter the number of elements in the set: ";
cin>>n;
cout<<"Elements less than "<<n<<" are present in the set\n";
while(1){
cout<<"Enter the two elements: ";
cin>>i;
if(i==-1) break;
cin>>j;
Union(S, n, i, j);
}
cout<<"\nEnter the two elements to be checked: ";
cin>>i>>j;
int p1 = Check(S, i, j, n, 0);
int p2 = Check(S, j, i, n, 0);
if(p1!=-1 && p1!=0){
if(p1==p2)
cout<<"\nThe elements are related!";
else cout<<"\nNO";
}
else if(p1==0 && p2==-1 || p1==-1 && p2==0 || p1==-1 && p2==-1)
cout<<"\nThe elements are related!";
else cout<<"\nNO";
return 0;
}
|
C++
|
WINDOWS-1252
| 960 | 3.484375 | 3 |
[] |
no_license
|
// Name: iѻ
// Date: Apr. 12, 2018
// Last Update: Apr. 12, 2018
// Problem statement: Vector Computation
#include <iostream>
#include "Vector.h"
using namespace std;
int main()
{
float x, y, k;
while (cin >> x >> y) {
Vector mainVector = Vector(x, y);
cin >> x >> y;
Vector addVector = Vector(x, y);
Vector addResult = mainVector + addVector;
cin >> x >> y;
Vector subVector = Vector(x, y);
Vector subResult = mainVector - subVector;
cin >> x >> y;
Vector dotVector = Vector(x, y);
float dotResult = mainVector * dotVector;
cin >> k;
Vector scaleVector = mainVector * k;
cout << "Add Result = ( " << addResult.x << " , " << addResult.y << " )" << endl;
cout << "Subtract Result = ( " << subResult.x << " , " << subResult.y << " )" << endl;
cout << "Dot Result = " << dotResult << endl;
cout << "Scale Result = ( " << scaleVector.x << " , " << scaleVector.y << " )" << endl;
}
system("pause");
return 0;
}
|
Python
|
UTF-8
| 140 | 3.625 | 4 |
[] |
no_license
|
#To reverse a string
def reversed_string(inputstring):
return inputstring[::-1]
output = reversed_string("hello")
print output
|
C#
|
UTF-8
| 26,209 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
// TODO:
// [ ] Exception handling for various actions which could fail (file handles being held etc)
namespace PluginInstaller
{
class Program
{
private const string ExampleEnginePath = "C:/Epic Games/UE_4.22/";
private static string msbuildPath;
public static readonly bool IsLinux;
public static readonly bool IsMacOS;
public static readonly bool IsWindows;
/// <summary>
/// The directory path of PluginInstaller.exe
/// </summary>
public static string AppDirectory;
static Program()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Unix:
case PlatformID.MacOSX:
if (File.Exists("/usr/lib/libc.dylib") && File.Exists("/System/Library/CoreServices/SystemVersion.plist"))
{
// This isn't exactly fool proof but msbuild does similar in NativeMethodsShared.cs
IsMacOS = true;
}
else
{
IsLinux = true;
}
break;
default:
IsWindows = true;
break;
}
}
static void Main(string[] args)
{
AppDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
string enginePath = GetEnginePathFromCurrentFolder();
if (string.IsNullOrEmpty(enginePath) || !Directory.Exists(enginePath))
{
Console.WriteLine("Failed to find the engine folder! Make sure PluginInstaller.exe is under /Engine/Plugins/USharp/Binaries/Managed/PluginInstaller/PluginInstaller.exe");
Console.ReadLine();
return;
}
PrintHelp();
Console.WriteLine();
Console.WriteLine("Targeting engine version '" + new DirectoryInfo(enginePath).Name + "'");
Console.WriteLine();
ProcessArgs(null, args);
while (true)
{
string line = Console.ReadLine();
string[] lineArgs = ParseArgs(line);
if (ProcessArgs(line, lineArgs))
{
break;
}
}
}
private static bool ProcessArgs(string commandLine, string[] args)
{
if (args.Length > 0)
{
switch (args[0].ToLower())
{
case "exit":
case "close":
case "quit":
case "q":
return true;
case "clear":
case "cls":
Console.Clear();
break;
case "build":
CompileCs(args);
CompileCpp(args);
Console.WriteLine("done");
break;
case "buildcs":
CompileCs(args);
Console.WriteLine("done");
break;
case "buildcustomsln":
if(args.Length >= 3 &&
!string.IsNullOrEmpty(args[1]) && File.Exists(args[1]) &&
!string.IsNullOrEmpty(args[2]) && File.Exists(args[2]))
{
BuildCustomSolution(args[1], args[2]);
}
break;
case "buildcpp":
{
Stopwatch cppCompileTime = new Stopwatch();
cppCompileTime.Start();
CompileCpp(args);
Console.WriteLine("done (" + cppCompileTime.Elapsed + ")");
}
break;
case "copyruntime":
if (args.Length >= 2)
{
bool minimal = args.Length >= 3 && args[2].ToLower() == "min";
string configFile = NetRuntimeHelper.GetConfigFile(minimal);
if (File.Exists(configFile))
{
switch (args[1].ToLower())
{
case "all":
NetRuntimeHelper.CopyAll(minimal);
Console.WriteLine("done");
break;
case "mono":
NetRuntimeHelper.CopyMono(minimal);
Console.WriteLine("done");
break;
case "coreclr":
NetRuntimeHelper.CopyCoreCLR(minimal);
Console.WriteLine("done");
break;
}
}
else
{
Console.WriteLine("Couldn't find '" + configFile + "'");
}
}
else
{
Console.WriteLine("Invalid input. Expected one of the following: all, mono, coreclr");
}
break;
case "help":
case "?":
PrintHelp();
break;
}
}
return false;
}
private static void PrintHelp()
{
Console.WriteLine("Available commands:");
Console.WriteLine("- build builds C# and C++ projects");
Console.WriteLine("- buildcs builds C# projects (Loader, AssemblyRewriter, Runtime)");
Console.WriteLine("- buildcpp builds C++ projects");
Console.WriteLine("- copyruntime [all] [mono] [coreclr] copies the given runtime(s) locally");
}
private static string[] ParseArgs(string commandLine)
{
char[] parmChars = commandLine.ToCharArray();
bool inSingleQuote = false;
bool inDoubleQuote = false;
for (var index = 0; index < parmChars.Length; index++)
{
if (parmChars[index] == '"' && !inSingleQuote)
{
inDoubleQuote = !inDoubleQuote;
parmChars[index] = '\n';
}
if (parmChars[index] == '\'' && !inDoubleQuote)
{
inSingleQuote = !inSingleQuote;
parmChars[index] = '\n';
}
if (!inSingleQuote && !inDoubleQuote && parmChars[index] == ' ')
{
parmChars[index] = '\n';
}
}
return (new string(parmChars)).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
private static Dictionary<string, string> GetKeyValues(string[] args)
{
Dictionary<string, string> result = new Dictionary<string, string>();
if (args != null)
{
foreach (string arg in args)
{
int valueIndex = arg.IndexOf('=');
if (valueIndex > 0)
{
string key = arg.Substring(0, valueIndex);
string value = arg.Substring(valueIndex + 1);
result[arg.ToLower()] = value;
}
else
{
result[arg.ToLower()] = null;
}
}
}
return result;
}
private static string GetCurrentDirectory()
{
return AppDirectory;
}
internal static void CopyFiles(DirectoryInfo source, DirectoryInfo target, bool overwrite)
{
CopyFiles(source, target, overwrite, false);
}
internal static void CopyFiles(DirectoryInfo source, DirectoryInfo target, bool overwrite, bool recursive)
{
if (!target.Exists)
{
target.Create();
}
if (recursive)
{
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyFilesRecursive(dir, target.CreateSubdirectory(dir.Name), overwrite);
}
}
foreach (FileInfo file in source.GetFiles())
{
CopyFile(file.FullName, Path.Combine(target.FullName, file.Name), overwrite);
}
}
internal static void CopyFilesRecursive(DirectoryInfo source, DirectoryInfo target, bool overwrite)
{
CopyFiles(source, target, overwrite, true);
}
internal static void CopyFile(string sourceFileName, string destFileName, bool overwrite)
{
if ((overwrite || !File.Exists(destFileName)) && File.Exists(sourceFileName))
{
try
{
File.Copy(sourceFileName, destFileName, overwrite);
}
catch
{
Console.WriteLine("Failed to copy to '{0}'", destFileName);
}
}
}
static string GetEnginePathFromCurrentFolder()
{
// Check upwards for /Epic Games/ENGINE_VERSION/Engine/Plugins/USharp/ and extract the path from there
string[] parentFolders = { "Managed", "Binaries", "USharp", "Plugins", "Engine" };
string currentPath = GetCurrentDirectory();
DirectoryInfo dir = Directory.GetParent(currentPath);
for (int i = 0; i < parentFolders.Length; i++)
{
if (!dir.Exists || !dir.Name.Equals(parentFolders[i], StringComparison.OrdinalIgnoreCase))
{
return null;
}
dir = dir.Parent;
}
// Make sure one of these folders exists along side the Engine folder: FeaturePacks, Samples, Templates
if (dir.Exists && Directory.Exists(Path.Combine(dir.FullName, "Templates")))
{
return dir.FullName;
}
return null;
}
/// <summary>
/// Returns the main USharp plugin directory from the engine path
/// </summary>
private static string GetUSharpPluginDirectory(string enginePath)
{
return Path.Combine(enginePath, "Engine", "Plugins", "USharp");
}
private static void CompileCs(string[] args)
{
string slnDir = Path.Combine(GetCurrentDirectory(), "../../../Managed/UnrealEngine.Runtime");
if (!Directory.Exists(slnDir))
{
Console.WriteLine("Failed to find the UnrealEngine.Runtime directory");
return;
}
string loaderProj = Path.Combine(slnDir, "Loader/Loader.csproj");
string runtimeProj = Path.Combine(slnDir, "UnrealEngine.Runtime/UnrealEngine.Runtime.csproj");
string assemblyRewriterProj = Path.Combine(slnDir, "UnrealEngine.AssemblyRewriter/UnrealEngine.AssemblyRewriter.csproj");
string[] projectPaths = { loaderProj, runtimeProj, assemblyRewriterProj };
string[] shippingBuildProjectPaths = { runtimeProj };
string slnPath = Path.Combine(slnDir, "UnrealEngine.Runtime.sln");
Dictionary<string, string> keyValues = GetKeyValues(args);
bool x86Build = keyValues.ContainsKey("x86");
foreach (string projPath in projectPaths)
{
if (!File.Exists(projPath))
{
Console.WriteLine("Failed to find C# project '{0}'", projPath);
return;
}
}
for (int i = 0; i < 2; i++)
{
bool shippingBuild = i == 1;
string[] paths = shippingBuild ? shippingBuildProjectPaths : projectPaths;
foreach (string projPath in paths)
{
string targetName = Path.GetFileName(projPath);
if (shippingBuild)
{
targetName += " (Shipping)";
}
if (!BuildCs(slnPath, projPath, !shippingBuild, x86Build, null))
{
Console.WriteLine("Failed to build (see build.log) - " + targetName);
return;
}
else
{
Console.WriteLine("Build successful - " + targetName);
}
}
}
}
private static bool BuildCs(string solutionPath, string projectPath, bool debug, bool x86, string customDefines)
{
string buildLogFile = Path.Combine(GetCurrentDirectory(), "build.log");
if (!string.IsNullOrEmpty(solutionPath) && File.Exists(solutionPath))
{
solutionPath = Path.GetFullPath(solutionPath);
}
if (!string.IsNullOrEmpty(projectPath) && File.Exists(projectPath))
{
projectPath = Path.GetFullPath(projectPath);
}
if (string.IsNullOrEmpty(msbuildPath))
{
msbuildPath = NetRuntimeHelper.FindMsBuildPath();
}
if (string.IsNullOrEmpty(msbuildPath))
{
File.AppendAllText(buildLogFile, "Couldn't find MSBuild path" + Environment.NewLine);
return false;
}
string config = debug ? "Debug" : "Release";
string platform = x86 ? "x86" : "\"Any CPU\"";
string fileArgs = "\"" + solutionPath + "\"" + " /p:Configuration=" + config + " /p:Platform=" + platform;
if (!string.IsNullOrEmpty(projectPath))
{
// '.' must be replaced with '_' for /t
string projectName = Path.GetFileNameWithoutExtension(projectPath).Replace(".", "_");
// Skip project references just in case (this means projects should be built in the correct order though)
fileArgs += " /t:" + projectName + " /p:BuildProjectReferences=false";
}
if (!string.IsNullOrEmpty(customDefines))
{
Debug.Assert(!customDefines.Contains(' '));
fileArgs += " /p:DefineConstants=" + customDefines;
}
File.AppendAllText(buildLogFile, "Build: " + msbuildPath + " - " + fileArgs + Environment.NewLine);
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = msbuildPath,
Arguments = fileArgs,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
int timeout = 60000;
bool built = process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout);
File.AppendAllText(buildLogFile, "Build sln '" + solutionPath + "' proj '" + projectPath + "'" + Environment.NewLine);
File.AppendAllText(buildLogFile, string.Empty.PadLeft(100, '-') + Environment.NewLine);
File.AppendAllText(buildLogFile, output.ToString() + Environment.NewLine);
File.AppendAllText(buildLogFile, error.ToString() + Environment.NewLine + Environment.NewLine);
if (!built)
{
Console.WriteLine("Failed to wait for compile.");
}
return built && process.ExitCode == 0;
}
}
}
private static void CompileCpp(string[] args)
{
Dictionary<string, string> keyValues = GetKeyValues(args);
bool shippingBuild = keyValues.ContainsKey("shipping");
bool x86Build = keyValues.ContainsKey("x86");
bool skipCopy = keyValues.ContainsKey("nocopy");
bool skipCleanup = keyValues.ContainsKey("noclean");
string pluginName = "USharp";
string pluginExtension = ".uplugin";
string pluginExtensionTemp = ".uplugin_temp";
string enginePath = GetEnginePathFromCurrentFolder();
string batchFileName = "RunUAT" + (IsWindows ? ".bat" : ".sh");
string batchFilesDir = Path.Combine(enginePath, "Engine/Build/BatchFiles/");
string batchPath = Path.Combine(batchFilesDir, batchFileName);
string pluginDir = Path.Combine(enginePath, "Engine/Plugins/", pluginName);
string pluginPath = Path.Combine(pluginDir, pluginName + pluginExtension);
//string outputDir = Path.Combine(projectBaseDir, "Build");
if (!File.Exists(batchPath))
{
Console.WriteLine("Failed to compile C++ project. Couldn't find RunUAT at '" + batchPath + "'");
return;
}
try
{
if (!File.Exists(pluginPath))
{
// We might have a temp plugin file extension due to a partial previous build
string tempPluginPath = Path.ChangeExtension(pluginPath, pluginExtensionTemp);
if (File.Exists(tempPluginPath))
{
File.Move(tempPluginPath, pluginPath);
}
}
}
catch
{
}
if (!File.Exists(pluginPath))
{
Console.WriteLine("Failed to compile C++ project. Couldn't find the plugin '{0}'", Path.GetFullPath(pluginPath));
return;
}
// Use an appdata folder instead of a local Build folder as we may be building from inside the engine folder
// which doesn't allow compile output to be within a sub folder of /Engine/
string usharpAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "USharp");
if (!Directory.Exists(usharpAppData))
{
Directory.CreateDirectory(usharpAppData);
}
string outputDir = Path.Combine(usharpAppData, "Build");
// In 4.20 if it detects that the plugin already exists our compilation will fail (even if we are compiling in-place!)
// Therefore we need to rename the existing .uplugin file to have a different extension so that UBT doesn't complain.
// NOTE: For reference the build error is "Found 'USharp' plugin in two locations" ... "Plugin names must be unique."
string existingPluginFile = Path.Combine(pluginDir, pluginName + pluginExtension);
string tempExistingPluginFile = null;
if (File.Exists(existingPluginFile))
{
tempExistingPluginFile = Path.ChangeExtension(existingPluginFile, pluginExtensionTemp);
if (File.Exists(tempExistingPluginFile))
{
File.Delete(tempExistingPluginFile);
}
File.Move(existingPluginFile, tempExistingPluginFile);
}
// Since we are compiling from within the engine plugin folder make sure to use temp changed .plugin_temp file
pluginPath = tempExistingPluginFile;
// Create *another* temp directory where we will copy just the C++ source files over. Otherwise the build tool will copy
// all of the content files before it builds (which might be a lot of data)
string tempCopyDir = Path.Combine(usharpAppData, "BuildTemp2");
string tempCopyPluginPath = Path.Combine(tempCopyDir, Path.GetFileName(pluginPath));
if (!Directory.Exists(tempCopyDir))
{
Directory.CreateDirectory(tempCopyDir);
}
CopyFile(pluginPath, tempCopyPluginPath, true);
CopyFilesRecursive(new DirectoryInfo(Path.Combine(pluginDir, "Source")), new DirectoryInfo(Path.Combine(tempCopyDir, "Source")), true);
CopyFilesRecursive(new DirectoryInfo(Path.Combine(pluginDir, "Config")), new DirectoryInfo(Path.Combine(tempCopyDir, "Config")), true);
// The Intermediate directory doesn't seem to improve compile times so don't bother copying it for now (saves around 100MB of data copying 2x)
//CopyFilesRecursive(new DirectoryInfo(Path.Combine(pluginDir, "Intermediate")), new DirectoryInfo(Path.Combine(tempCopyDir, "Intermediate")), true);
try
{
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo()
{
FileName = batchPath,
UseShellExecute = false,
// The -Platform arg is ignored? It instead compiles based on whitelisted/blacklisted? (or for all platforms if no list)
Arguments = string.Format("BuildPlugin -Plugin=\"{0}\" -Package=\"{1}\" -Rocket -Platform=Win64", tempCopyPluginPath, outputDir)
};
process.Start();
process.WaitForExit();
}
if (!skipCopy)
{
// Copy the entire contents of /Binaries/ and /Intermediate/
string[] copyDirs = { "Binaries", "Intermediate" };
foreach (string dir in copyDirs)
{
if (Directory.Exists(Path.Combine(outputDir, dir)))
{
CopyFilesRecursive(new DirectoryInfo(Path.Combine(outputDir, dir)),
new DirectoryInfo(Path.Combine(pluginDir, dir)), true);
}
}
}
}
finally
{
try
{
if (!string.IsNullOrEmpty(tempExistingPluginFile) && File.Exists(tempExistingPluginFile))
{
if (File.Exists(existingPluginFile))
{
File.Delete(existingPluginFile);
}
File.Move(tempExistingPluginFile, existingPluginFile);
}
}
catch
{
}
if (!skipCleanup)
{
try
{
if (Directory.Exists(outputDir))
{
Directory.Delete(outputDir, true);
}
}
catch
{
}
}
try
{
if (Directory.Exists(tempCopyDir))
{
Directory.Delete(tempCopyDir, true);
}
}
catch
{
}
}
}
static bool BuildCustomSolution(string slnPath, string projPath)
{
Console.WriteLine("Attempting to build solution: " + slnPath);
bool buildcs = BuildCs(slnPath, projPath, true, false, null);
if(buildcs)
{
Console.WriteLine("Solution was compiled successfully");
}
else
{
Console.WriteLine("There was an issue with compiling the provided solution: " + slnPath);
}
return buildcs;
}
}
}
|
Python
|
UTF-8
| 1,275 | 3.546875 | 4 |
[] |
no_license
|
#1 My Ans, path template
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary tree.
@param: A: A TreeNode
@param: B: A TreeNode
@return: Return the LCA of the two nodes.
"""
def lowestCommonAncestor3(self, root, A, B):
if not root:
return None
pathA, pathB = [], []
self.build_path(root, A, [], pathA)
self.build_path(root, B, [], pathB)
print([a.val for a in pathA])
print([b.val for b in pathB])
if not pathA or not pathB:
return None
lca = None
for i in range(min(len(pathA), len(pathB))):
if pathA[i] == pathB[i]:
lca = pathA[i]
return lca
def build_path(self, node, target, path, ret):
if node is None:
return
path.append(node)
if node == target:
ret.extend(path)
self.build_path(node.left, target, path, ret)
self.build_path(node.right, target, path, ret)
path.pop()
|
Java
|
UTF-8
| 1,193 | 2.109375 | 2 |
[] |
no_license
|
/********************************************************************************
* MIT Java Wordnet Interface (JWI)
* Copyright (c) 2007-2008 Massachusetts Institute of Technology
*
* This is the non-commercial version of JWI. This version may *not* be used
* for commercial purposes.
*
* This program and the accompanying materials are made available by the MIT
* Technology Licensing Office under the terms of the MIT Java Wordnet Interface
* Non-Commercial License. The MIT Technology Licensing Office can be reached
* at 617-253-6966 for further inquiry.
*******************************************************************************/
package edu.mit.jwi.item;
/**
* Represents a version of Wordnet.
*
* @author Mark A. Finlayson
* @version 2.1.5, Jan 22, 2008
* @since 1.5.0
*/
public interface IVersion {
/**
* @return the major version number, i.e., the '1' in '1.7.2'
*/
public int getMajorVersion();
/**
* @return the minor version number, i.e., the '7' in '1.7.2'
*/
public int getMinorVersion();
/**
* @return the bugfix version number, i.e., the '2' in '1.7.2'
*/
public int getBugfixVersion();
}
|
Swift
|
UTF-8
| 1,580 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
//
// DemoData.swift
// SwiftLintStarter
//
// Created by Daymein Gregorio on 3/11/20.
// Copyright © 2020 Daymein Gregorio. All rights reserved.
//
import Foundation
let p1 = CBPlayer(name: "Ken",
powerLevel: 4,
number: 5)
let p2 = CBPlayer(name: "Ryu",
powerLevel: 4,
number: 3)
let p3 = CBPlayer(name: "Akuma",
powerLevel: 5,
number: 4)
let p4 = CBPlayer(name: "Mario",
powerLevel: 4,
number: 5)
let p5 = CBPlayer(name: "Lugi",
powerLevel: 4,
number: 3)
let p6 = CBPlayer(name: "Peach",
powerLevel: 5,
number: 4)
let p7 = CBPlayer(name: "Cuphead",
powerLevel: 4,
number: 5)
let p8 = CBPlayer(name: "Mugman",
powerLevel: 4,
number: 3)
let p9 = CBPlayer(name: "Ms. Chalice",
powerLevel: 5,
number: 4)
let owls = DGTeam(name: "Owls",
players: [p1, p2, p3],
mascotIconName: "Owls", cheer: .best,
winCount: 3, lossCount: 5)
let piranhas = DGTeam(name: "Piranhas",
players: [p4, p5, p6],
mascotIconName: "Piranhas", cheer: .defense,
winCount: 6, lossCount: 2)
let zombies = DGTeam(name: "Zombies",
players: [p7, p8, p9],
mascotIconName: "Zombies", cheer: .go,
winCount: 0, lossCount: 5)
|
Python
|
UTF-8
| 472 | 3.296875 | 3 |
[] |
no_license
|
arivals = list(map(int,"1 3 5".strip().split(" ")))
departures = list(map(int,"2 6 8".strip().split(" ")))
k = int(input())
arivals = [i + 1 for i in arivals]
departures = [(-1*i) - 1 for i in departures]
# print(arivals,departures)
meets = arivals + departures
print(meets)
meets.sort(key=lambda x:abs(x))
print(meets)
x = 0
ans = 0
for i in meets:
if i>0:
x = x + 1
ans = max(x,ans)
if i<0:
x = x-1
print("No" if k<ans else "Yes")
|
PHP
|
UTF-8
| 917 | 2.6875 | 3 |
[] |
no_license
|
<?php
//This class is used to execute queries on MIS.NEWSEARCH_PAGEVIEW table
class MIS_NEWSEARCH_PAGEVIEW extends TABLE
{
public function __construct($dbname='')
{
parent::__construct($dbname);
}
public function insertRecord($pageNo,$sid)
{
//JSM-881---temp stop
return 1;
if(!$pageNo || !$sid)
throw new jsException("","PAGE NO OR SEARCH ID IS BLANK IN insertRecord() OF MIS_NEWSEARCH_PAGEVIEW.class.php");
try
{
$sql = "INSERT INTO MIS.NEWSEARCH_PAGEVIEW(DATE,SEARCH_ID,PAGE_NO) VALUES (NOW(),:SID,:PAGE)";
$res = $this->db->prepare($sql);
$res->bindValue(":SID", $sid, PDO::PARAM_INT);
$res->bindValue(":PAGE", $pageNo, PDO::PARAM_INT);
$res->execute();
}
catch(PDOException $e)
{
throw new jsException($e);
}
}
}
?>
|
JavaScript
|
UTF-8
| 3,193 | 4.0625 | 4 |
[] |
no_license
|
class Node {
constructor(value) {
this.left = null;
this.right = null;
this.value = value;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
let set = false;
if (this.root === null) {
this.root = newNode;
} else {
let trav = this.root;
while (set === false) {
if (value > trav.value) {
if (trav.right !== null) {
trav = trav.right;
} else {
trav.right = newNode;
set = true;
}
} else {
if (trav.left !== null) {
trav = trav.left;
} else {
trav.left = newNode;
set = true;
}
}
}
}
}
lookup(value) {
let set = false;
let trav = this.root;
if(!this.root) {
return set;
} else {
while (set === false) {
if (trav.value === value) {
return trav;
} else {
if (value > trav.value) {
if (trav.right !== null) {
trav = trav.right;
} else {
return set;
}
} else {
if (trav.left !== null) {
trav = trav.left;
} else {
return set;
}
}
}
}
}
console.log(set);
}
remove(value) {
let trav = this.root;
let head = trav;
while(trav.value !== value) {
if(value > trav.value) {
if(trav.right !== null) {
head = trav;
trav = trav.right;
} else {
return false;
}
} else {
if(trav.left !== null) {
head = trav;
trav = trav.left;
} else {
return false;
}
}
}
//console.log("trav", trav, "head", head);
if(trav.left === null && trav.right === null) {
head.right = null;
} else {
let tLeft;
if(trav.left !== null) {
tLeft = trav.left;
}
if(trav.right !== null) {
let tRight = trav.right;
let tRightLeft = tRight.left;
while(tRightLeft.left !== null) {
tRightLeft = tRightLeft.left;
}
// console.log("head", head);
// console.log("trav", trav);
// console.log("tRight", tRight);
// console.log("tRightLeft", tRightLeft);
// console.log("tLeft", tLeft);
head.right = tRightLeft;
tRightLeft.right = tRight;
tRightLeft.left = tLeft;
} else {
head.right = trav.left;
}
}
return this;
}
}
const tree = new BinarySearchTree();
tree.insert(9)
tree.insert(4)
tree.insert(6)
tree.insert(20)
tree.insert(90)
tree.insert(15)
tree.insert(1)
tree.insert(85)
tree.insert(82)
tree.insert(95)
//JSON.stringify(traverse(tree.root))
//tree.lookup(9);
tree.remove(20);
console.log(tree);
// JSON.stringify(traverse(tree.root))
// 9
// 4 20
//1 6 15 170
function traverse(node) {
const tree = { value: node.value };
tree.left = node.left === null ? null : traverse(node.left);
tree.right = node.right === null ? null : traverse(node.right);
return tree;
}
|
Java
|
UTF-8
| 3,616 | 2.234375 | 2 |
[] |
no_license
|
package com.zt.blog.interceptor;
import com.alibaba.fastjson.JSON;
import com.zt.blog.common.config.SpringContextHolder;
import com.zt.blog.common.constant.Constants;
import com.zt.blog.common.entity.Result;
import com.zt.blog.common.property.AppletProps;
import com.zt.blog.common.util.DateUtil;
import com.zt.blog.common.util.Md5Encrypt;
import com.zt.blog.common.util.ResponseUtils;
import com.zt.blog.model.UserToken;
import com.zt.blog.service.UserTokenService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
* @author ZhouTian
* @Description
* @since 2018/11/6
*/
public class OpenApiSignInterceptor implements HandlerInterceptor {
private String loginUrl;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try {
String uri = request.getRequestURI();
if (uri.startsWith(loginUrl)){//需要登录验证,判断token
String token = request.getParameter("token");
if (StringUtils.isEmpty(token)){
return printJson(response,Constants.Status.TOKEN_NOT_EXISTS);
}
UserTokenService userTokenService = SpringContextHolder.getBean(UserTokenService.class);
UserToken userToken = userTokenService.getByToken(token);
if (null == userToken){
return printJson(response,Constants.Status.TOKEN_NOT_EXISTS);
}
Date expireTime = userToken.getExpireTime();
if (DateUtil.before(expireTime,new Date())){//token过期
return printJson(response,Constants.Status.TOKEN_EXPIRED);
}
}
String sign = request.getParameter("sign");
String timeStamp = request.getParameter("timeStamp");
String appId = request.getParameter("appId");
if (StringUtils.isEmpty(timeStamp)||StringUtils.isEmpty(sign)||StringUtils.isEmpty(appId)){
return printJson(response,Constants.Status.PARAM_EMPTY);
}
Date date = DateUtil.getDate(timeStamp);
Date oneMinAfter = DateUtils.addMinutes(new Date(), 1);
Date oneMinBefore = DateUtils.addMinutes(new Date(), -1);
if (date.before(oneMinBefore)||date.after(oneMinAfter)){//时间搓失效 超过一分钟
return printJson(response,Constants.Status.TIMESTAMP_INVALID);
}
//判断签名是否正确
String signKey=AppletProps.getSignSecret() +"&@!"+timeStamp+"#*("+appId;
String signMd5 = Md5Encrypt.md5(signKey);
if (!signMd5.equalsIgnoreCase(sign)) {
return printJson(response,Constants.Status.SIGN_ERROR);
}
}catch (Exception e){
e.printStackTrace();
}
return true;
}
/**
* 输出状态信息
* @param response
* @param status
* @return
*/
private boolean printJson(HttpServletResponse response, Constants.Status status) {
Result result = new Result(status);
ResponseUtils.renderJson(response, JSON.toJSONString(result));
return false;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
}
|
JavaScript
|
UTF-8
| 1,122 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
/*global Widget */
function ErrorWidget(widget, configName) {
this.widget = widget;
this.configName = configName;
this.dataToBind = {
'value': ''
};
}
ErrorWidget.prototype = new Widget();
ErrorWidget.prototype.constructor = ErrorWidget;
$.extend(ErrorWidget.prototype, {
/**
* Invoked after each response from long polling server
*
* @param response Response from long polling server
*/
handleResponse: function (response) {
this.prepareData(response);
},
/**
* Updates widget's state
*
* @param {Object} response Response object from long polling controller
*/
prepareData: function (response) {
this.dataToBind.value = response.data;
if (parseFloat(response.data) > 0) {
this.$widget.addClass('warning');
} else {
this.$widget.removeClass('warning');
}
this.oldValue = response.data;
this.dataToBind.lastUpdate = response.updateTime;
this.renderTemplate(this.dataToBind);
this.checkThresholds(this.dataToBind.value);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.