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
| 8,902 | 2.859375 | 3 |
[] |
no_license
|
import sys
import datetime as dt
import pandas as pd
import numpy as np
from collections import defaultdict
years = [2008, 2009, 2010, 2011, 2012, 2013]
weatherDFs = []
fireDFs = []
OUTPUT_FILE = "bakedData/fireWeatherData.csv"
for y in years:
weatherDFs.append(pd.read_csv(f"cleanedData/weather{y}.csv"))
fireDFs.append(pd.read_csv(f"cleanedData/fireStats{y}.csv"))
stationDF = pd.read_csv("cleanedData/geocodedStations.csv",
index_col=0,
dtype={'fips': object}) # preserve leading zero
# --- get county for each station ---
# lowercase everything for simpler string comparison
stationDF['county'] = stationDF['county'].apply(str.lower)
# use a dict for fast lookup
stationToFips = stationDF['fips'].to_dict()
fipsToCounty = stationDF[['fips', 'county']].set_index('fips').to_dict()['county']
# some stations only provide min/max temperature, we want average
# fill with the average of min/max, which should be a good approximation
print("filling in average temp where missing")
filledAvgs = 0
for wdf in weatherDFs:
mask = wdf['tavg'].isna()
wdf.loc[mask, 'tavg'] = (wdf['tmax'][mask] + wdf['tmin'][mask]) / 2
filledAvgs += sum(mask)
print(f"filled averages for {filledAvgs} rows")
print("attributing counties to station")
i = 0
droppedRows = 0
for wdf in weatherDFs:
stationCountyList = []
for row in wdf.itertuples():
try:
f = stationToFips[row.station]
except KeyError:
f = np.NaN
stationCountyList.append(f)
wdf['fips'] = stationCountyList
i += 1
sys.stdout.write(f"\r{i}/{len(weatherDFs)} years done")
# drop rows for which we have no fips
oldsize = len(wdf)
wdf.dropna(subset=['fips'], inplace=True)
droppedRows += oldsize - len(wdf)
sys.stdout.write(f"\t{droppedRows} rows dropped for bad location")
sys.stdout.flush()
print() # newline after rewriting progress
# --- gather average temp/precip by county ---
# create a dict mapping dates to dicts mapping
# counties to lists of data points
defaultdictOfList = lambda: defaultdict(list)
dateToTempDataByFips = defaultdict(defaultdictOfList)
dateToPrecipDataByCounty = defaultdict(defaultdictOfList)
print("clustering weather data by county")
i = 0
for wdf in weatherDFs:
for row in wdf.itertuples():
if pd.notna(row.tavg):
dateToTempDataByFips[row.date][row.fips].append(row.tavg)
if pd.notna(row.prcp):
dateToPrecipDataByCounty[row.date][row.fips].append(row.prcp)
i += 1
sys.stdout.write(f"\r{i}/{len(weatherDFs)} years done")
sys.stdout.flush()
print() # newline after rewriting progress
# build a df where for every date we have avg data for each county
dates = []
fips = []
counties = []
avgTemps = []
avgPrecip = []
print("getting avg data by county")
i = 0
for d in dateToTempDataByFips:
for f in dateToTempDataByFips[d]:
dates.append(d)
fips.append(f)
try:
counties.append(fipsToCounty[f])
except KeyError:
counties.append("UNKNOWN")
avgT = int(np.average(dateToTempDataByFips[d][f]))
avgTemps.append(avgT)
countyPrecip = dateToPrecipDataByCounty[d][f]
if countyPrecip:
avgP = np.average(countyPrecip)
else:
avgP = np.NaN
avgPrecip.append(avgP)
i += 1
sys.stdout.write(f"\r{i}/{len(dateToTempDataByFips)} dates done")
sys.stdout.flush()
print() # newline after rewriting progress
# combine our lists of counties, dates, and avgs
# transpose to produce intended shape
countyData = np.array([fips, counties, dates, avgTemps, avgPrecip]).transpose()
fireWeatherDF = pd.DataFrame(data=countyData,
columns=["fips", "county", "date", "tavg", "prcp"])
# force typing of some fields
fireWeatherDF = fireWeatherDF.astype({'tavg': int, 'prcp': float})
dtCols = fireWeatherDF['date'].apply(dt.datetime.fromisoformat)
fireWeatherDF['date'] = dtCols
# it looks like some stations send NaN instead of zero for no precip
fireWeatherDF['prcp'].fillna(0, inplace=True)
# sort by county, use stable sort to preserve date sorting
fireWeatherDF.sort_values(['fips', 'date'], inplace=True)
# --- get a rolling average of the last N days ---
# --- for temp/precip data by county ---
rollAvgTempWindow = 14
rollAvgPrecipWindow = 3
print("getting rolling averages. "
f"Temperature roll window: {rollAvgTempWindow}"
f"Precip roll window: {rollAvgPrecipWindow}")
# the data is sorted by county then date
# so the rolling average carries one county's data
# over to the next for the window of rolling (N).
# The first N days of a rolling avg should be NaN
# anyway so we allow this junk data and then replace
# with NaNs
rollAvgTempDF = fireWeatherDF['tavg'].rolling(rollAvgTempWindow).mean()
# find invalid dates by getting the first N dates
invalidRollDates = list(fireWeatherDF['date'].head(rollAvgTempWindow))
# create a mask that's true for every instance of those dates
rollMask = fireWeatherDF['date'].isin(invalidRollDates)
rollAvgTempDF = rollAvgTempDF.mask(rollMask)
fireWeatherDF['rtavg'] = rollAvgTempDF
rollAvgPrecipDF = fireWeatherDF['prcp'].rolling(rollAvgPrecipWindow).mean()
invalidRollDates = list(fireWeatherDF['date'].head(rollAvgPrecipWindow))
rollMask = fireWeatherDF['date'].isin(invalidRollDates)
rollAvgPrecipDF = rollAvgPrecipDF.mask(rollMask)
recentRain = [p > 0 if pd.notna(p) else np.NaN for p in rollAvgPrecipDF]
fireWeatherDF['rprcp'] = recentRain
# --- drop dates for which there are any temp NaNs ---
oldSize = len(fireWeatherDF)
fireWeatherDF.dropna(subset=['tavg', 'rtavg'], inplace=True)
print(f"dropped {oldSize - len(fireWeatherDF)} rows for NaN temps")
# --- bucket temp data ---
tempBucketSize = 5
precipBucketSize = 0.1
print("bucketing temperature and precip data."
f"temp bucket size: {tempBucketSize} degrees,"
f"precit bucket size: {precipBucketSize} inches"
)
# bucket by subtracting temp % bucketSize, giving the nearest
# int divisible by bucketSize
fireWeatherDF['tavg'] = fireWeatherDF['tavg'].apply(lambda x: x - x % tempBucketSize)
fireWeatherDF['rtavg'] = fireWeatherDF['rtavg'].apply(lambda x: x - x % tempBucketSize)
fireWeatherDF['prcp'] = fireWeatherDF['prcp'].apply(lambda x: x - x % precipBucketSize)
fireWeatherDF.to_csv(OUTPUT_FILE, index=False)
# --- join fire info ---
print("joining fire data with weather date")
# start by converting string dates to datetime objects
# the fire data requires a format argument to parse, but
# the format is not a named argument so it cannot be passed
# directly to DF.apply()
fireStrToDT = lambda x: dt.datetime.strptime(x, '%m/%d/%y')
# add our columns for fireStarted and activeFires
fireWeatherDF['fireStarted'] = np.full(len(fireWeatherDF), fill_value=False)
fireWeatherDF['hasFire'] = np.full(len(fireWeatherDF), fill_value=False)
fireWeatherDF['activeFires'] = np.full(len(fireWeatherDF), fill_value=0)
# track what counties are/aren't in each dataset to ensure consistency
fireCounties = set()
allCounties = set(fireWeatherDF['county'])
for fdf in fireDFs:
dtCols = fdf[['start','contained']].applymap(fireStrToDT)
fdf[['start','contained']] = dtCols
# lowercase everything for easier string comparison
fdf['counties'] = fdf['counties'].apply(str.lower)
# some fires occur in multiple counties, so the field
# lists all counties separated by dashes
fdf['counties'] = fdf['counties'].apply(str.split, sep='-')
for row in fdf.itertuples():
# each row in every fire dataframe represents a fire
fireCounties.update(row.counties)
# again, counties is a list
for c in row.counties:
# note that a fire started in this county on this date
fireStartMask = (fireWeatherDF['county'] == c) \
& (fireWeatherDF['date'] == row.start)
fireWeatherDF.loc[fireStartMask, 'fireStarted'] = True
# get rows where county matches and dates are between
# the fire starting and being contained
activeFireMask = (fireWeatherDF['county'] == c) \
& (fireWeatherDF['date'] >= row.start) \
& (fireWeatherDF['date'] <= row.contained)
newAF = fireWeatherDF.loc[activeFireMask, 'activeFires'].apply(lambda x: x + 1)
fireWeatherDF.loc[activeFireMask, 'activeFires'] = newAF
# we already have a mask for active fires, set hasFire to true there
fireWeatherDF.loc[activeFireMask, 'hasFire'] = True
print("counties in fire data not in station data: ")
print(fireCounties - allCounties)
print("counties in station data with no fires: ")
print(allCounties - fireCounties)
# write out DF
print(fireWeatherDF.describe())
fireWeatherDF.to_csv(OUTPUT_FILE, index=False)
|
JavaScript
|
UTF-8
| 2,067 | 2.546875 | 3 |
[] |
no_license
|
( function() {
"use strict";
/**
* 마우스 드래그 줌아웃 객체.
*
* 마우스로 드래깅하여 해당 영역으로 축소하는 컨트롤 객체.
*
* @constructor
*
* @example
*
* <pre>
* var ugDragZoomOut = new ugmp.control.uGisDragZoomOut( {
* uGisMap : new ugmp.uGisMap({...}),
* useSnap : true,
* useDragPan : true,
* cursorCssName : 'cursor-zoomOut',
* activeChangeListener : function(state_) {
* console.log( state_ );
* }
* } );
* </pre>
*
* @param opt_options {Object}
* @param opt_options.uGisMap {ugmp.uGisMap} {@link ugmp.uGisMap ugmp.uGisMap} 객체.
* @param opt_options.useDragPan {Boolean} 지도 이동 사용 여부. Default is `false`.
* @param opt_options.cursorCssName {String} 마우스 커서 CSS Class Name.
* @param opt_options.activeChangeListener {Function} 컨트롤의 상태 변경 CallBack.
*
* @Extends {ugmp.control.uGisControlDefault}
*/
ugmp.control.uGisDragZoomOut = ( function(opt_options) {
var _self = this;
var _super;
/**
* Initialize
*/
( function() {
var options = opt_options || {};
_super = ugmp.control.uGisControlDefault.call( _self, options );
_self._init();
} )();
// END initialize
return ugmp.util.uGisUtil.objectMerge( _super, {
_this : _self
} );
} );
ugmp.control.uGisDragZoomOut.prototype = Object.create( ugmp.control.uGisControlDefault.prototype );
ugmp.control.uGisDragZoomOut.prototype.constructor = ugmp.control.uGisDragZoomOut;
/**
* 초기화
*
* @override {ugmp.control.uGisControlDefault.prototype._init}
*
* @private
*/
ugmp.control.uGisDragZoomOut.prototype._init = function() {
var _self = this._this || this;
_self.interaction = new ol.interaction.DragZoom( {
condition : ol.events.condition.always,
duration : 0,
out : true
} );
_self.interaction.setActive( false );
ugmp.control.uGisControlDefault.prototype._init.call( this );
};
} )();
|
C++
|
UTF-8
| 641 | 2.921875 | 3 |
[] |
no_license
|
/*乘客类,原理和card类相似,也是主要以存放信息、显示信息为主。特别的是takeon方法用于人车交互*/
#ifndef PERSON_H_
#define PERSON_H_
#include <string>
#include <iostream>
#include "card.h"
using namespace std;
enum sex{male, female};
class Person{
private:
string Name;
sex Gender;
string Job;
string Workplace;
string Number;
int Take_on_times;
public:
Person();
Person(string name, sex gender, string job, string workplace, string number, Card c);
~Person();
void takeon();//上车
void show();
};
#endif
|
PHP
|
UTF-8
| 2,674 | 2.8125 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Faker;
class UsergenController extends Controller
{
public function __construct()
{
# Not in use but here for future enhancement
}
public function getPage(Request $request)
{
//Returns User Generator Template with Get Request
return view('usergen');
}
public function postPage(Request $request)
{
//return $request->email;
// Validate the request data
// Is required, must be numeric, must be between 1 - 500
$this->validate($request, [
'users' => 'required|numeric|min:1|max:500',
'email' => 'in:on',
'password' => 'in:on',
'location' => 'in:on',
'profile' => 'in:on',
'birthdate' => 'in:on',
]);
// Passed validation now time to generate users
$numusers = $request->input('users');
$faker = Faker\Factory::create();
$name = array();
$email = array();
$password = array();
$location = array();
$profile = array();
$birthdate = array();
for ($i = 0; $i < $numusers; $i++) {
$name[] = $faker->name;
if ($request->input('email') == "on") {
$email[] = $faker->email;
}
else
{
unset($email);
}
if ($request->input('password') == "on") {
$password[] = $faker->password(6, 8);
}
else
{
unset($password);
}
if ($request->input('location') == "on") {
$location[] = $faker->address;
}
else
{
unset($location);
}
if ($request->input('profile') == "on") {
$profile[] = $faker->text(100);
}
else
{
unset($profile);
}
if ($request->input('birthdate') == "on") {
$birthdate[] = $faker->date();
}
else
{
unset($birthdate);
}
}
return view('usergen', compact('name', 'email', 'password', 'location', 'profile','birthdate'));
/*
return view('usergen', ['name' => $name,
'email' => $email,
'password' => $password,
'location' => $location,
'profile' => $profile]);*/
}
}
?>
|
PHP
|
UTF-8
| 5,675 | 2.53125 | 3 |
[] |
no_license
|
<?php
namespace Chibi;
use Chibi\Hurdle\ShouldRedirect;
use Chibi\Router\Router;
use Chibi\Exceptions\ControllerNotFound;
use Chibi\Exceptions\ControllersMethodNotFound;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Handler\JsonResponseHandler;
class App
{
/**
* @var App
*/
protected static $instance;
/**
* @var Container
*/
protected $container;
/**
* Construct
*/
public function __construct()
{
$this->runWhoops();
$this->container = new Container(array(
'router' => function(){
$om = AppObjectManager::getInstance();
return $om->resolve(Router::class);
},
'response' => function(){
$om = AppObjectManager::getInstance();
return $om->resolve(Response::class);
},
'request' => function(){
$om = AppObjectManager::getInstance();
return $om->resolve(Request::class);
},
'om' => function () {
return AppObjectManager::getInstance();
}
));
$this->registerApp();
}
/**
* Get the App instance
*
* @return App
*/
public static function getInstance()
{
return static::$instance;
}
/**
* Register the App instance
*/
public function registerApp()
{
static::$instance = $this;
}
/**
* Get container instance
*
* @return Container
*/
public function getContainer()
{
return $this->container;
}
/**
* Run the App
*
* @throws ControllerNotFound
* @throws ControllersMethodNotFound
*/
public function run()
{
$router = $this->container->router;
$request = $this->container->request;
$response = $this->container->response;
$om = $this->getContainer()->om;
/* @var $om Chibi\ObjectManager\ObjectManager */
$router->setPath(isset($_SERVER['PATH_INFO']) ?$_SERVER['PATH_INFO']: '/');
// Get Hurdles that run on every request
$hurdles = $this->getHurdles();
foreach ($hurdles as $hurdle) {
$instance = $om->resolve($hurdle);
if (!$instance->filter($request, $response)) {
if ($instance instanceof ShouldRedirect) {
// do some Magic in here
return ;
}
throw new \Exception("You don't have the rights to enter here", 1);
}
}
// run specific Hurdles
$specificHurdles = $router->getHurdlesByPath();
foreach($specificHurdles as $specific){
$specificInstance = $om->resolve($specific);
if(!$specificInstance->filter($request, $response)){
if($specificInstance instanceof ShouldRedirect){
$specificInstance->redirectTo();
return ;
}
throw new \Exception("You don't have the rights to enter here", 1);
}
}
$res =$router->getResponse();
$response = $res['response'];
$params = $res['parames'];
return $this->respond($this->process($response, $params));
}
/**
* Run Whoops
*/
protected function runWhoops()
{
$run = new \Whoops\Run;
$handler = new PrettyPageHandler;
$handler->setPageTitle("There was a problem.");
$run->pushHandler($handler);
if (\Whoops\Util\Misc::isAjaxRequest()) {
$run->pushHandler(new JsonResponseHandler);
}
$run->register();
}
/**
* Process the Handler
*
* @param $callable
* @param array $parames
* @return mixed
* @throws ControllerNotFound
* @throws ControllersMethodNotFound
*/
public function process($callable, $parames = [])
{
$om = $this->getContainer()->om;
/* @var $om Chibi\ObjectManager\ObjectManager */
$parames_all = $parames;
$om = AppObjectManager::getInstance();
if (is_callable($callable)) {
return call_user_func_array($callable,
$this->getContainer()->resolveMethod('', $callable, $parames_all)
);
}
if (is_string($callable)) {
$array = explode('@', $callable);
$class = $array[0];
if (!class_exists($class)) {
throw new ControllerNotFound("{$class} Controller Not Found");
}
$caller = $om->resolve($class);
$method = $array[1];
if (!method_exists($caller, $method)) {
throw new ControllersMethodNotFound("{$method} Not Found in the {$class} Controller");
}
return call_user_func_array(
[$caller, $method],
$this->getContainer()->resolveMethod($class, $method, $parames_all)
);
}
}
/**
* Echo out the response
*
* @param $response
*/
public function respond($response)
{
if(!$response instanceof Response){
echo $response;
return;
}
$response->applyHeaders();
echo $response->getBody();
}
/**
* Get hurdles
*
* @return type
*/
protected function getHurdles(){
return require('app/Hurdles/register.php');
}
}
|
Java
|
UTF-8
| 5,954 | 2.34375 | 2 |
[] |
no_license
|
package com.nanalog.api.user.service;
import com.nanalog.api.user.model.entity.User;
import com.nanalog.api.user.model.entity.UserDeleteQueue;
import com.nanalog.api.user.model.request.UserCreateRequest;
import com.nanalog.api.user.model.request.UserDeleteRequest;
import com.nanalog.api.user.model.request.UserUpdateRequest;
import com.nanalog.api.user.model.response.UserResponse;
import com.nanalog.api.user.repository.UserDeleteQueueRepository;
import com.nanalog.api.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Created by 1002731 on 2016. 7. 17..
* Email : eenan@sk.com
*/
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserDeleteQueueRepository userDeleteQueueRepository;
@Override
public Integer createUser(UserCreateRequest userCreateRequest) {
String uid = userCreateRequest.getUid();
User user = this.userRepository.findByUid(uid);
if(user != null && user.getUid().equals(uid)){
return -1;
}
String name = userCreateRequest.getName();
String password = userCreateRequest.getPassword();
String currentTime = getCurrentDate();
user = new User();
user.setUid(uid);
user.setName(name);
user.setPassword(password);
user.setRegistrationDate(currentTime);
user.setActive(true);
user.setPermission("USER");
this.userRepository.save(user);
return 1;
}
@Override
public Integer updateUser(UserUpdateRequest userUpdateRequest) {
String uid = userUpdateRequest.getUid();
String name = userUpdateRequest.getName();
String password = userUpdateRequest.getPassword();
User user = this.userRepository.findByUid(uid);
if(user != null && !(user.getPassword().equals(password))){
return -1;
}
else if(user == null){
return 0;
}
user.setUid(uid);
user.setName(name);
user.setPassword(password);
this.userRepository.save(user);
return 1;
}
@Override
public Integer deleteUser(UserDeleteRequest userDeleteRequest) {
String uid = userDeleteRequest.getUid();
String password = userDeleteRequest.getPassword();
User user = this.userRepository.findByUid(uid);
if(user != null && !(user.getPassword().equals(password))){
return -1;
}
else if(user == null){
return 0;
}
else if(user.isActive() == false){
return -2;
}
String deleteDate = getCurrentDate();
UserDeleteQueue userDeleteQueue = new UserDeleteQueue();
userDeleteQueue.setUid(uid);
userDeleteQueue.setDeleteDate(deleteDate);
user.setActive(false);
this.userRepository.save(user);
this.userDeleteQueueRepository.save(userDeleteQueue);
return 1;
}
@Override
public UserResponse readUser(String uid) {
User user = this.userRepository.findByUid(uid);
if(user == null){
return null;
}
UserResponse userResponse = new UserResponse();
userResponse.setUid(uid);
userResponse.setName(user.getName());
userResponse.setPermission(user.getPermission());
userResponse.setActive(user.isActive());
userResponse.setRegistrationDate(user.getRegistrationDate());
return userResponse;
}
@Override
public Integer updateUserActiveState(String uid) {
User user = this.userRepository.findByUid(uid);
if(user == null){
return -1;
}
boolean active = user.isActive();
if(active == true){
user.setActive(false);
String currentTime = getCurrentDate();
UserDeleteQueue userDeleteQueue = new UserDeleteQueue();
userDeleteQueue.setId(user.getId());
userDeleteQueue.setUid(user.getUid());
userDeleteQueue.setDeleteDate(currentTime);
this.userDeleteQueueRepository.save(userDeleteQueue);
}
else{
user.setActive(true);
this.userDeleteQueueRepository.delete(user.getId());
}
this.userRepository.setUserActiveByUid(user.isActive(), uid);
return 1;
}
@Override
public UserDeleteQueue readUserActiveState(String uid) {
User user = this.userRepository.findByUid(uid);
if(user == null){
return null;
}
UserDeleteQueue userDeleteQueue = this.userDeleteQueueRepository.findOne(user.getId());
if(userDeleteQueue == null){
return null;
}
return userDeleteQueue;
}
@Override
public Integer deleteUserDeleteQueue(String uid) {
User user = this.userRepository.findByUid(uid);
if(user == null){
return -1;
}
UserDeleteQueue userDeleteQueue = this.userDeleteQueueRepository.findOne(user.getId());
if(userDeleteQueue == null) {
return -2;
}
this.userDeleteQueueRepository.delete(userDeleteQueue);
return 1;
}
@Override
public User login(String uid, String password){
User user = this.userRepository.findByUid(uid);
if(user == null){
return new User();
}
if(!(user.getPassword().equals(password))){
return new User();
}
return user;
}
private String getCurrentDate(){
return LocalDateTime.now().plusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
}
}
|
Java
|
ISO-8859-1
| 2,250 | 2.921875 | 3 |
[] |
no_license
|
package control;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
import entities.Candidato;
public class RetornaAgendaEntrevistaController {
public void RetornaAgenda(Candidato candidato) throws IOException {
//getNotaEntrevista est retornando a nota do lattes
if(!candidato.getDataEntrevista().contains("semdata")) {
JOptionPane.showMessageDialog(null, "SUA ENTREVISTA FOI AGENDADA!\nData e Horrio:" + candidato.getDataEntrevista());
} else {
JOptionPane.showMessageDialog(null, "A data para sua entrevista ainda no foi definida. Por favor, aguarde. ");
}
}
public void alteraTxtComDadosNovos(Candidato candidato) throws IOException {
String path = System.getProperty("user.dir");
String nome = "CadastrosGerais.txt";
File arq = new File(path, nome);
String conteudo = readTxt(path, nome, candidato);
BufferedReader reader = null;
FileWriter writer = null;
try {
reader = new BufferedReader(new FileReader(arq));
writer = new FileWriter(arq);
writer.write(conteudo);
} catch (IOException e) {
e.printStackTrace();
} finally {
reader.close();
writer.close();
}
}
private String readTxt(String path, String nome, Candidato candidato) throws IOException {
File arq = new File(path, nome);
StringBuffer conteudo = new StringBuffer();
if(arq.exists() && arq.isFile()) {
FileInputStream fluxo = new FileInputStream(arq); //abre o arquivo
InputStreamReader leitor = new InputStreamReader(fluxo); //l e converte o arquivo
BufferedReader buffer = new BufferedReader(leitor); // coloca o arquivo no buffer
String linha = buffer.readLine();
while(linha != null) { // procurando EOF (End of File)
if(linha.contains(candidato.getCpf())) {
linha = linha.replaceAll("N", candidato.getdivulgaNotaFinal());
}
conteudo.append(linha + System.lineSeparator());
linha = buffer.readLine();
}
buffer.close();
leitor.close();
fluxo.close();
} else {
throw new IOException("Arquivo invlido");
}
return conteudo.toString();
}
}
|
C++
|
UTF-8
| 221 | 2.640625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int a[1010];
int main(){
int a1, a2, n;
cin>>a1>>a2>>n;
a[0] = a1;
a[1] = a2;
for(int i=2; i<n; i++){
a[i] = a[i-1] + a[i-1] - a[i-2];
}
cout<<a[n-1];
return 0;
}
|
C++
|
GB18030
| 1,670 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
/*------------------------------------------------------------------------------
* FileName : gsafemem.h
* Author : lbh
* Create Time : 2018-08-26
* Description : ȫڴ
* CopyRight : from gservers_engine @loboho
* ----------------------------------------------------------------------------*/
#ifndef __GBASE__GSAFEMEM_H__
#define __GBASE__GSAFEMEM_H__
#include <unordered_set>
#include "gbase/threads.h"
#ifdef G_WIN_PLATFORM
#define _ALIGNED_ALLOC(align, size) _aligned_malloc(size, align)
#define _ALIGNED_FREE(p) _aligned_free(p)
#else
#include <cstdlib>
#define _ALIGNED_ALLOC(align, size) std::aligned_alloc(align, size)
#define _ALIGNED_FREE(p) std::free(p)
#endif // G_WIN_PLATFORM
namespace GBASE_INTERNAL
{
class GSafeMem
{
G_SINGLETON_SAFE(GSafeMem)
public:
void* MSafeAlloc(size_t size);
void* MSafeAlloc(size_t alignment, size_t size);
void MSafeFree(void* p);
void MSafeFreeAlign(void* p);
bool MCheckValid(void* p);
private:
~GSafeMem();
std::unordered_set<void*> m_mpPCheck;
std::unordered_set<void*> m_mpPCheckAligned;
GSpinLock m_spinLock;
};
#ifndef GBUILD_OPT_MEMSAFE
inline void* GSafeMem::MSafeAlloc(size_t size)
{
return new char[size];
}
inline void* GSafeMem::MSafeAlloc(size_t alignment, size_t size)
{
return _ALIGNED_ALLOC(alignment, size);
}
inline bool GSafeMem::MSafeFree(void* p)
{
delete[] p;
}
inline void* GSafeMem::MSafeFreeAlign(void* p)
{
return _ALIGNED_FREE(p);
}
constexpr inline bool GSafeMem::MCheckValid(void* p)
{
reutrn true;
}
inline GSafeMem::~GSafeMem()
{
}
#endif // !GBUILD_OPT_MEMSAFE
}
#endif // __GBASE__GSAFEMEM_H__
|
Python
|
UTF-8
| 360 | 3.78125 | 4 |
[] |
no_license
|
#22.インデックス付きループ
#インデックスと値を同時に取り出す
test_list=['python','-','izm','.','com']
for idx,val in enumerate(test_list):
print(idx,':',val)
print('-------------------')
#開始値を指定する場合
test_list2=['python','-','izm','.','com']
for idx,val in enumerate(test_list,1):
print(idx,':',val)
|
Java
|
UTF-8
| 841 | 3.578125 | 4 |
[
"MIT"
] |
permissive
|
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
//import edu.princeton.cs.algs4.Stopwatch;
/**
* Created by Katyana on 4/15/2016.
*
* Takes an integer argument k and reads in N strings from StdInput.
* It then prints out exactly k of the strings in uniformly random order.
*
* We're assuming 0<=k<=N. Otherwise it will throw errors.
*
*/
public class Subset {
public static void main(String[] args){
int k = Integer.parseInt(args[0]);
RandomizedQueue rq = new RandomizedQueue();
while(!StdIn.isEmpty()){
String item = StdIn.readString();
rq.enqueue(item);
}
//Stopwatch timer = new Stopwatch();
for(int i=0; i<k; i++){
StdOut.println(rq.dequeue());
}
//StdOut.print(timer.elapsedTime());
}
}
|
Java
|
UTF-8
| 2,104 | 2.234375 | 2 |
[
"MIT"
] |
permissive
|
package com.KND.chequera.model;
import java.sql.Date;
import com.KND.chequera.entity.Chequera;
import com.KND.chequera.entity.Tipo_Movimiento;
public class MovimientosModel {
private int idmovimientos;
private String m_concepto;
private Double m_monto;
private Date mFecha;
private Boolean m_status;
private Tipo_Movimiento tipo_Movimiento;
private Chequera chequera;
public MovimientosModel() {}
public MovimientosModel(int idmovimientos, String m_concepto, Double m_monto, Date mFecha, Boolean m_status,
Tipo_Movimiento tipo_Movimiento, Chequera chequera) {
super();
this.idmovimientos = idmovimientos;
this.m_concepto = m_concepto;
this.m_monto = m_monto;
this.mFecha = mFecha;
this.m_status = m_status;
this.tipo_Movimiento = tipo_Movimiento;
this.chequera = chequera;
}
public int getIdmovimientos() {
return idmovimientos;
}
public void setIdmovimientos(int idmovimientos) {
this.idmovimientos = idmovimientos;
}
public String getM_concepto() {
return m_concepto;
}
public void setM_concepto(String m_concepto) {
this.m_concepto = m_concepto;
}
public Double getM_monto() {
return m_monto;
}
public void setM_monto(Double m_monto) {
this.m_monto = m_monto;
}
public Date getmFecha() {
return mFecha;
}
public void setmFecha(Date mFecha) {
this.mFecha = mFecha;
}
public Boolean getM_status() {
return m_status;
}
public void setM_status(Boolean m_status) {
this.m_status = m_status;
}
public Tipo_Movimiento getTipo_Movimiento() {
return tipo_Movimiento;
}
public void setTipo_Movimiento(Tipo_Movimiento tipo_Movimiento) {
this.tipo_Movimiento = tipo_Movimiento;
}
public Chequera getChequera() {
return chequera;
}
public void setChequera(Chequera chequera) {
this.chequera = chequera;
}
@Override
public String toString() {
return "MovimientosModel [idmovimientos=" + idmovimientos + ", m_concepto=" + m_concepto + ", m_monto="
+ m_monto + ", mFecha=" + mFecha + ", m_status=" + m_status + ", tipo_Movimiento=" + tipo_Movimiento
+ ", chequera=" + chequera + "]";
}
}
|
Java
|
UTF-8
| 765 | 3.546875 | 4 |
[] |
no_license
|
package chapter_4;
/**
* Implement a function to check if a tree is balanced
* For the purposes of this question, a balanced tree is
* defined to be a tree such that no two leaf nodes differ
* in distance from the root by more than one
* @author Andy
*
*/
public class question4_1 {
public static boolean check(Btree root){
if(root == null ||(root.getLeft() == null && root.getRight() == null)){
return true;
}
if(Math.abs( maxDepth(root.getLeft()) - maxDepth(root.getRight())) > 1){
return false;
}
else{
return true;
}
}
private static int maxDepth(Btree root){
//touch the bottom;
if(root == null){
return 0;
}
else{
return Math.max(maxDepth(root.getLeft()), maxDepth(root.getRight())) + 1;
}
}
}
|
Python
|
UTF-8
| 1,759 | 3.078125 | 3 |
[] |
no_license
|
from SciStreams.interfaces.streams import Stream
from SciStreams.interfaces.StreamDoc import StreamDoc
from SciStreams.interfaces.StreamDoc import merge, psdm, psda
def test_stream_map():
'''
Make sure that stream mapping still works with StreamDoc
'''
def addfunc(arg, **kwargs):
return arg + 1
s = Stream()
sout = s.map(psda(addfunc))
# get the number member from StreamDoc
sout = sout.map(lambda x: x['args'][0])
# save to list
L = list()
sout.map(L.append)
s.emit(StreamDoc(args=[1], kwargs=dict(foo="bar"),
attributes=dict(name="john")))
s.emit(StreamDoc(args=[4], kwargs=dict(foo="bar"),
attributes=dict(name="john")))
assert L == [2, 5]
def test_stream_accumulate():
''' This tests that the dispatching on the streamdoc's accumulate routine
is working properly.'''
def myacc(prevstate, newstate):
return prevstate + newstate
s = Stream()
sout = s.accumulate(psdm(myacc))
L = list()
sout.map(L.append)
sout.emit(StreamDoc(args=[1]))
sout.emit(StreamDoc(args=[2]))
sout.emit(StreamDoc(args=[3]))
print(L)
def test_merge():
''' Test the merging option for StreamDoc's.'''
s1 = Stream()
s2 = Stream()
stot = s1.zip(s2).map(merge)
L = list()
stot.map(L.append)
sdoc1 = StreamDoc(args=[1,2],kwargs={'a' : 1, 'c' : 3})
sdoc2 = StreamDoc(args=[3,4],kwargs={'b' : 2, 'c' : 4})
s1.emit(sdoc1)
assert len(L) == 0
s2.emit(sdoc2)
result_kwargs = L[0]['kwargs']
result_args = L[0]['args']
assert result_kwargs['a'] == 1
assert result_kwargs['b'] == 2
assert result_kwargs['c'] == 4
assert result_args == [1,2,3,4]
|
TypeScript
|
UTF-8
| 6,056 | 2.609375 | 3 |
[] |
no_license
|
jest.unmock("eventsource");
import EventSource from "eventsource";
import IntegrationTestEnvironment from "./helpers/integrationTestEnvironment";
interface IEventListener {
cb: (evt: MessageEvent) => void;
type: string;
}
interface ICallbacks {
onmessage?: (evt: MessageEvent, resolve: (...any) => void) => void;
onerror?: (evt: MessageEvent, resolve: (...any) => void) => void;
eventListeners?: IEventListener[];
}
function sse(
port: number,
callbacks: ICallbacks = {},
options: object = {}
): Promise<any> {
return new Promise(resolve => {
const source = new EventSource(`http://localhost:${port}`, options);
if (callbacks.onmessage) {
source.onmessage = evt => {
callbacks.onmessage(evt, resolve);
};
} else if (callbacks.onerror) {
source.onerror = evt => {
callbacks.onerror(evt, resolve);
};
} else {
source.onopen = () => resolve(source);
}
(callbacks.eventListeners || []).forEach(({ type, cb }) =>
source.addEventListener(type, cb)
);
});
}
describe("Proxy - Server Sent Events", () => {
let env;
beforeEach(async () => {
env = new IntegrationTestEnvironment();
await env.setup();
env.proxyTargetApp.use((req, res, next) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive"
});
res.sseSendUntyped = data => {
res.write("data: " + JSON.stringify(data) + "\n\n");
};
res.sseSendTyped = (type, data) => {
res.write("event: " + type + "\n");
res.write("data: " + JSON.stringify(data) + "\n\n");
};
next();
});
});
afterEach(async () => {
await env.teardown();
});
describe("Requests", () => {
let mockMiddleware;
beforeEach(() => {
mockMiddleware = jest.fn();
env.proxyTargetApp.use((req, res) => {
mockMiddleware(req);
res.sseSendUntyped({ done: true });
res.end();
});
});
it("opens a connection", async () => {
const source = await sse(env.port);
source.close();
expect(mockMiddleware).toHaveBeenCalled();
});
it("sends the headers", async () => {
const source = await sse(
env.port,
{},
{ headers: { "my-header": "foo" } }
);
source.close();
const call = mockMiddleware.mock.calls[0][0];
expect(call.headers["my-header"]).toBe("foo");
});
});
describe("Response", () => {
it("forwards data", async () => {
env.proxyTargetApp.use((req, res) => {
res.sseSendUntyped({ count: 1 });
res.sseSendUntyped({ count: 2 });
res.end();
});
const mockOnMessage = jest.fn();
let callCount = 0;
await sse(env.port, {
onmessage: (evt, resolve) => {
callCount++;
mockOnMessage();
if (callCount === 2) {
resolve();
}
}
});
expect(mockOnMessage).toHaveBeenCalledTimes(2);
});
it("forwards data with a similar interval", async () => {
env.proxyTargetApp.use((req, res) => {
res.sseSendUntyped({ count: 1 });
setTimeout(() => {
res.sseSendUntyped({ count: 2 });
res.end();
}, 800);
});
const mockOnMessage = jest.fn();
await sse(env.port, {
onmessage: (evt, resolve) => {
mockOnMessage(evt);
resolve();
}
});
expect(mockOnMessage).toHaveBeenCalledTimes(1);
});
it("forwards data in the same order", async () => {
env.proxyTargetApp.use((req, res) => {
res.sseSendUntyped({ count: 1 });
res.sseSendUntyped({ count: 2 });
res.end();
});
const mockOnMessage = jest.fn();
let callCount = 0;
await sse(env.port, {
onmessage: (evt, resolve) => {
callCount++;
mockOnMessage(JSON.parse(evt.data).count);
if (callCount === 2) {
resolve();
}
}
});
expect(mockOnMessage).toHaveBeenCalledTimes(2);
expect(mockOnMessage.mock.calls[0][0]).toBe(1);
expect(mockOnMessage.mock.calls[1][0]).toBe(2);
});
it("forwards untyped data events", async () => {
env.proxyTargetApp.use((req, res) => {
res.sseSendUntyped({ foo: "my-untyped-message" });
res.end();
});
const mockOnMessage = jest.fn();
const msg = await sse(env.port, {
onmessage: (evt, resolve) => {
resolve(JSON.parse(evt.data));
}
});
expect(msg).toEqual({ foo: "my-untyped-message" });
});
it("forwards typed data events", async () => {
env.proxyTargetApp.use((req, res) => {
res.sseSendTyped("typeA", { count: 1 });
res.sseSendTyped("typeB", { count: 2 });
res.sseSendUntyped({ end: true });
res.end();
});
const mockTypeA = jest.fn();
const mockTypeB = jest.fn();
const mockTypeC = jest.fn();
await sse(env.port, {
onmessage: (evt, resolve) => resolve(),
eventListeners: [
{
type: "typeA",
cb: evt => mockTypeA(evt)
},
{
type: "typeB",
cb: evt => mockTypeB(evt)
},
{
type: "typeC",
cb: evt => mockTypeC(evt)
}
]
});
expect(mockTypeA).toHaveBeenCalledTimes(1);
expect(JSON.parse(mockTypeA.mock.calls[0][0].data).count).toBe(1);
expect(mockTypeB).toHaveBeenCalledTimes(1);
expect(JSON.parse(mockTypeB.mock.calls[0][0].data).count).toBe(2);
expect(mockTypeC).not.toHaveBeenCalled();
});
it("invokes error callback if no event is sent", async () => {
env.proxyTargetApp.use((req, res) => {
res.end();
});
const error = await sse(env.port, {
onerror: (evt, resolve) => resolve(evt)
});
expect(error.type).toBe("error");
});
});
});
|
Markdown
|
UTF-8
| 24 | 2.640625 | 3 |
[] |
no_license
|
# ios-training-travelers
|
Java
|
UTF-8
| 7,180 | 1.90625 | 2 |
[] |
no_license
|
package com.labs.client.generated;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.labs.client.generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _DeleteStudentResponse_QNAME = new QName("http://labs.com/", "deleteStudentResponse");
private final static QName _UpdateStudentResponse_QNAME = new QName("http://labs.com/", "updateStudentResponse");
private final static QName _UpdateStudent_QNAME = new QName("http://labs.com/", "updateStudent");
private final static QName _CreateStudentResponse_QNAME = new QName("http://labs.com/", "createStudentResponse");
private final static QName _GetStudentsByFields_QNAME = new QName("http://labs.com/", "getStudentsByFields");
private final static QName _DeleteStudent_QNAME = new QName("http://labs.com/", "deleteStudent");
private final static QName _CreateStudent_QNAME = new QName("http://labs.com/", "createStudent");
private final static QName _GetStudentsByFieldsResponse_QNAME = new QName("http://labs.com/", "getStudentsByFieldsResponse");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.labs.client.generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link CreateStudentResponse }
*
*/
public CreateStudentResponse createCreateStudentResponse() {
return new CreateStudentResponse();
}
/**
* Create an instance of {@link DeleteStudentResponse }
*
*/
public DeleteStudentResponse createDeleteStudentResponse() {
return new DeleteStudentResponse();
}
/**
* Create an instance of {@link UpdateStudentResponse }
*
*/
public UpdateStudentResponse createUpdateStudentResponse() {
return new UpdateStudentResponse();
}
/**
* Create an instance of {@link UpdateStudent }
*
*/
public UpdateStudent createUpdateStudent() {
return new UpdateStudent();
}
/**
* Create an instance of {@link DeleteStudent }
*
*/
public DeleteStudent createDeleteStudent() {
return new DeleteStudent();
}
/**
* Create an instance of {@link CreateStudent }
*
*/
public CreateStudent createCreateStudent() {
return new CreateStudent();
}
/**
* Create an instance of {@link GetStudentsByFieldsResponse }
*
*/
public GetStudentsByFieldsResponse createGetStudentsByFieldsResponse() {
return new GetStudentsByFieldsResponse();
}
/**
* Create an instance of {@link GetStudentsByFields }
*
*/
public GetStudentsByFields createGetStudentsByFields() {
return new GetStudentsByFields();
}
/**
* Create an instance of {@link Student }
*
*/
public Student createStudent() {
return new Student();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DeleteStudentResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "deleteStudentResponse")
public JAXBElement<DeleteStudentResponse> createDeleteStudentResponse(DeleteStudentResponse value) {
return new JAXBElement<DeleteStudentResponse>(_DeleteStudentResponse_QNAME, DeleteStudentResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link UpdateStudentResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "updateStudentResponse")
public JAXBElement<UpdateStudentResponse> createUpdateStudentResponse(UpdateStudentResponse value) {
return new JAXBElement<UpdateStudentResponse>(_UpdateStudentResponse_QNAME, UpdateStudentResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link UpdateStudent }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "updateStudent")
public JAXBElement<UpdateStudent> createUpdateStudent(UpdateStudent value) {
return new JAXBElement<UpdateStudent>(_UpdateStudent_QNAME, UpdateStudent.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link CreateStudentResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "createStudentResponse")
public JAXBElement<CreateStudentResponse> createCreateStudentResponse(CreateStudentResponse value) {
return new JAXBElement<CreateStudentResponse>(_CreateStudentResponse_QNAME, CreateStudentResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetStudentsByFields }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "getStudentsByFields")
public JAXBElement<GetStudentsByFields> createGetStudentsByFields(GetStudentsByFields value) {
return new JAXBElement<GetStudentsByFields>(_GetStudentsByFields_QNAME, GetStudentsByFields.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DeleteStudent }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "deleteStudent")
public JAXBElement<DeleteStudent> createDeleteStudent(DeleteStudent value) {
return new JAXBElement<DeleteStudent>(_DeleteStudent_QNAME, DeleteStudent.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link CreateStudent }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "createStudent")
public JAXBElement<CreateStudent> createCreateStudent(CreateStudent value) {
return new JAXBElement<CreateStudent>(_CreateStudent_QNAME, CreateStudent.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetStudentsByFieldsResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://labs.com/", name = "getStudentsByFieldsResponse")
public JAXBElement<GetStudentsByFieldsResponse> createGetStudentsByFieldsResponse(GetStudentsByFieldsResponse value) {
return new JAXBElement<GetStudentsByFieldsResponse>(_GetStudentsByFieldsResponse_QNAME, GetStudentsByFieldsResponse.class, null, value);
}
}
|
PHP
|
UTF-8
| 1,450 | 2.71875 | 3 |
[] |
no_license
|
<?php
use CleanPhp\Invoicer\Domain\Entity\Invoice;
use CleanPhp\Invoicer\Domain\Entity\Order;
use CleanPhp\Invoicer\Domain\Factory\InvoiceFactory;
describe( "InvoiceFactory", function () {
describe( "->createFromOrder()", function () {
it( "should return an order object", function () {
$order = new Order();
$factory = new InvoiceFactory();
$invoice = $factory->createFromOrder( $order );
expect( $invoice )->to->be->instanceof( Invoice::class );
} );
it( 'should set the total of the invoice', function () {
$order = new Order();
$order->setTotal( 500 );
$factory = new InvoiceFactory();
$invoice = $factory->createFromOrder( $order );
expect( $invoice->getTotal() )->to->equal( 500 );
} );
it( 'should associate the Order to the Invoice', function () {
$order = new Order();
$factory = new InvoiceFactory();
$invoice = $factory->createFromOrder( $order );
expect( $invoice->getOrder() )->to->equal( $order );
} );
it( 'should set the date of the Invoice', function () {
$order = new Order();
$factory = new InvoiceFactory();
$invoice = $factory->createFromOrder( $order );
expect( $invoice->getInvoiceDate() )->to->loosely->equal( new \DateTime() );
} );
} );
} );
|
Java
|
UTF-8
| 1,044 | 3.34375 | 3 |
[] |
no_license
|
/***
* Runtime: 2 ms 99.87%
* Memory Usage: 40 MB
*/
public class Q6_ZigZag {
public String convert(String s, int numRows) {
if(numRows == 1) {
return s;
}
StringBuilder sb = new StringBuilder();
int iteration = numRows * 2 - 2;
int counter = 0;
while(counter < s.length()) {
sb.append(s.charAt(counter));
counter += iteration;
}
for(int i = 1; i < numRows - 1; i++) {
counter = 0;
while(i + counter < s.length()) {
sb.append(s.charAt(i + counter));
if(i + counter + (numRows - i - 1) * 2 >= s.length()) {
break;
}
sb.append(s.charAt(i + counter + (numRows - i - 1) * 2));
counter += iteration;
}
}
counter = numRows - 1;
while(counter < s.length()) {
sb.append(s.charAt(counter));
counter += iteration;
}
return sb.toString();
}
}
|
Java
|
UTF-8
| 272 | 2.390625 | 2 |
[] |
no_license
|
package replit;
public class html {
public static void main(String[] args) {
String html= "the whole time was raining";
do{
System.out.println(html.charAt(0));
html=html.substring(5);
}while (!html.isEmpty());
}
}
|
Java
|
UTF-8
| 581 | 1.585938 | 2 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import util.MysqlConnection;
import util.ReadProperties;
import util.ReadRTxt;
public class test {
public static void main(String arg[]) {
ReadRTxt.toArrayByRandomAccessFile();
}
}
|
Java
|
UTF-8
| 367 | 2.109375 | 2 |
[] |
no_license
|
package com.oops.interfacess;
public class TestAnnn {
public static void main(String[] args) {
FuncInter funcInter=new FuncInter() {
@Override
public void testAdd() {
System.out.println("testing");
}
};
funcInter.testAdd();
funcInter.check();
FuncInter.dTest();
}
}
|
Java
|
UTF-8
| 1,004 | 2.59375 | 3 |
[] |
no_license
|
package edu.northeastern.ccs.im;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import edu.northeastern.ccs.im.dao.Group;
import edu.northeastern.ccs.im.dao.User;
/**
* This class tests the functionality of Group class
* @author farha
*
*/
public class GroupTest {
private Group group;
private List<User>users;
@BeforeEach
public void Before(){
users = new ArrayList<>();
User user = new User("farha","1232");
users.add(user);
group = new Group("MSD",users);
}
@Test
public void testGetGroupName() {
assertEquals("MSD",group.getGroupName());
}
@Test
public void testGetUsers() {
int i = 0;
for(User user: users) {
assertEquals(user.getUsername(),group.getUsers().get(i).getUsername());
i++;
}
}
}
|
Markdown
|
UTF-8
| 33,961 | 2.609375 | 3 |
[] |
no_license
|
# ゴール
Kubernetes環境をローカルで構築し、アプリケーションのデプロイ方法の一種である「ローリングアップデート」と「Blue/Greenデプロイ」を簡単な例で体験する。
(参考) [アプリケーションのデプロイとテストの戦略](https://cloud.google.com/solutions/application-deployment-and-testing-strategies?hl=ja)
# 目次
- [ゴール](#ゴール)
- [目次](#目次)
- [kubernetes環境構築](#kubernetes環境構築)
- [kubernetesのインストール](#kubernetesのインストール)
- [**必ず** PROXY設定を初期化](#必ず-proxy設定を初期化)
- [Kubernetes有効化](#kubernetes有効化)
- [完了状態](#完了状態)
- [Kubernetes Dashboardインストール](#kubernetes-dashboardインストール)
- [インストール](#インストール)
- [確認](#確認)
- [Dashboard管理ユーザー登録とroleのバインド](#dashboard管理ユーザー登録とroleのバインド)
- [Ingress-nginxインストール](#ingress-nginxインストール)
- [インストール](#インストール-1)
- [確認](#確認-1)
- [イメージファイルのビルド](#イメージファイルのビルド)
- [Dashboard画面を起動](#dashboard画面を起動)
- [DashboardにログインするためのTOKENを取得](#dashboardにログインするためのtokenを取得)
- [dashboardにアクセスするためのPROXYを起動する](#dashboardにアクセスするためのproxyを起動する)
- [dashboard起動](#dashboard起動)
- [kubernetesの概念](#kubernetesの概念)
- [kubernetesクラスタとNode](#kubernetesクラスタとnode)
- [kubernetesクラスタとNode 概念図](#kubernetesクラスタとnode概念図)
- [Master Nodeを構成する管理コンポーネント](#master-nodeを構成する管理コンポーネント)
- [Dashbord画面で確認](#dashbord画面で確認)
- [Namespace](#namespace)
- [Pod](#pod)
- [Pod単体](#pod単体)
- [PodのNodeへの配置](#podのnodeへの配置)
- [Podをデプロイ~動作確認~削除まで](#podをデプロイ動作確認削除まで)
- [デプロイ](#デプロイ)
- [デバッグ用Podのデプロイ](#デバッグ用podのデプロイ)
- [Pod仮想IPについて](#pod仮想ipについて)
- [SWTESTの情報](#swtestの情報)
- [DebugコンテナからSWTESTの動作確認](#debugコンテナからswtestの動作確認)
- [curlコマンドで確認](#curlコマンドで確認)
- [Podの削除](#podの削除)
- [ReplicaSet](#replicaset)
- [マニフェストファイルの確認](#マニフェストファイルの確認)
- [ReplicaSet生成](#replicaset生成)
- [ReplicaSet削除](#replicaset削除)
- [Deployment](#deployment)
- [Deployment/ReplicaSet/Pod関連図](#deploymentreplicasetpod関連図)
- [世代管理付のデプロイ](#世代管理付のデプロイ)
- [コマンドラインからデプロイする](#コマンドラインからデプロイする)
- [リビジョンの確認](#リビジョンの確認)
- [ローリングアップデートとロールバック](#ローリングアップデートとロールバック)
- [ローリングアップデート](#ローリングアップデート)
- [マニフェストファイル](#マニフェストファイル)
- [アップデートの実施](#アップデートの実施)
- [履歴の確認](#履歴の確認)
- [ロールバックの実施](#ロールバックの実施)
- [切り替え中の状態](#切り替え中の状態)
- [履歴の確認](#履歴の確認-1)
- [最後に削除する](#最後に削除する)
- [Service(blue/green)作成](#servicebluegreen作成)
- [blue/greenデプロイメント](#bluegreenデプロイメント)
- [blue/greenサービス](#bluegreenサービス)
- [デプロイ](#デプロイ-1)
- [状態確認](#状態確認)
- [debugコンテナからアクセスし動作確認](#debugコンテナからアクセスし動作確認)
- [IngressによるBlue/Greenデプロイ](#ingressによるbluegreenデプロイ)
- [IngressによるBlue/Greenデプロイイメージ](#ingressによるbluegreenデプロイイメージ)
- [Ingress-nginxの状況確認](#ingress-nginxの状況確認)
- [Ingress追加](#ingress追加)
- [動作確認](#動作確認)
- [現行バージョンへのアクセス](#現行バージョンへのアクセス)
- [次期バージョンへのアクセス](#次期バージョンへのアクセス)
- [Blue -> Green への切り替え](#blue---green-への切り替え)
- [path切り替え](#path切り替え)
- [新バージョンへのアクセス](#新バージョンへのアクセス)
- [旧バージョンへのアクセス](#旧バージョンへのアクセス)
- [最後に実習環境の削除方法(できればKubernetes環境は破棄願います)](#最後に実習環境の削除方法できればkubernetes環境は破棄願います)
- [Kubernetesリソース削除](#kubernetesリソース削除)
- [ingress-nginx, dashboard削除](#ingress-nginx-dashboard削除)
- [Docker Dashboardで無効化](#docker-dashboardで無効化)
- [不要データの削除](#不要データの削除)
---
# kubernetes環境構築
## kubernetesのインストール
DockerDesktopからKubernetesを有効化します。
> **[ 重要 ]**
>
> 社内LAN、VPN環境ではうまく有効化できないので、DockerDesktopのPROXY設定は必ず空にすること。<br/>
> Kubernetes有効化はiphoneのテザリング環境下、または、自宅のインターネット環境下で実施します。
>
> Kubernetes関連イメージのダウンロード部分で止まり、進退窮まり初期状態にリセットせざるを得なくなります。
>
### **必ず** PROXY設定を初期化

SettingsのResourcesでPROXIESは空白にして「Apply&Restart」ボタンを押す
---
### Kubernetes有効化
- Enable Kubernetesにチェックを入れる
- Show system containers(advanced)にチェックを入れる → インストール進捗が分かりやすい
- 「Apply&Reset」ボタンを押す

### 完了状態
コンテナが全てグリーンになり、画面左下のKubernetesがグリーンになりrunnningと表示されれば有効化完了です。

---
## Kubernetes Dashboardインストール
Kubernetesの状況把握や管理のためのダッシュボードソフトをインストールします。
### インストール
パワーシェルを起動し、作業フォルダにて次のコマンドを投入する。
```cmd
> kubectl apply -f recommended.yaml
```
### 確認
ひきつづきパワーシェルにて起動を確認
```cmd
> kubectl get svc -n kubernetes-dashboard
-------------------------------------------------------------------------------
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
dashboard-metrics-scraper ClusterIP 10.111.105.244 <none> 8000/TCP 9h
kubernetes-dashboard ClusterIP 10.108.122.103 <none> 443/TCP 9h
-------------------------------------------------------------------------------
```
### Dashboard管理ユーザー登録とroleのバインド
パワーシェルで次のコマンドを投入する。
```cmd
> kubectl apply -f create_account.yaml
> kubectl apply -f role_binding.yaml
```
---
## Ingress-nginxインストール
2日目に必要なIngress-nginxをあらかじめインストールします。
### インストール
パワーシェルを起動し、作業フォルダにて次のコマンドを投入する。
```cmd
> kubectl apply -f mandatory.yaml
-------------------------------------------------------------------------------
namespace/ingress-nginx created
deployment.apps/default-http-backend created
service/default-http-backend created
configmap/nginx-configuration created
configmap/tcp-services created
configmap/udp-services created
serviceaccount/nginx-ingress-serviceaccount created
clusterrole.rbac.authorization.k8s.io/nginx-ingress-clusterrole created
role.rbac.authorization.k8s.io/nginx-ingress-role created
rolebinding.rbac.authorization.k8s.io/nginx-ingress-role-nisa-binding created
clusterrolebinding.rbac.authorization.k8s.io/nginx-ingress-clusterrole-nisa-binding created
deployment.apps/nginx-ingress-controller created
-------------------------------------------------------------------------------
> kubectl apply -f cloud-generic.yaml
-------------------------------------------------------------------------------
service/ingress-nginx created
-------------------------------------------------------------------------------
```
### 確認
ひきつづきパワーシェルにて起動を確認
```cmd
> kubectl get svc -n ingress-nginx
-------------------------------------------------------------------------------
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
default-http-backend ClusterIP 10.105.175.142 <none> 80/TCP 2m27s
ingress-nginx LoadBalancer 10.105.219.79 localhost 9000:31923/TCP,443:31166/TCP 101s
-------------------------------------------------------------------------------
```
---
## イメージファイルのビルド
予め今回使用するイメージファイルをビルド・PULLしておきます。
パワーシェルにて下記バッチを起動
```cmd
> .\build_image.bat
-------------------------------------------------------------------------------
:
:
REPOSITORY TAG IMAGE ID CREATED SIZE
swtest/nginx latest 8d71d4b00e5f 28 hours ago 170MB
REPOSITORY TAG IMAGE ID CREATED SIZE
swtest/api v2 51e06a4c2b89 5 hours ago 121MB
swtest/api latest 6380831691ba 28 hours ago 121MB
REPOSITORY TAG IMAGE ID CREATED SIZE
swtest/debug latest 421bf1f5871d About a minute ago 8.67MB
-------------------------------------------------------------------------------
```
<br/>
---
## Dashboard画面を起動
### DashboardにログインするためのTOKENを取得
**[ 重要 ]** 次のコマンドは必ずパワーシェルで実行すること。
```cmd
> kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | sls admin-user | ForEach-Object { $_ -Split '\s+' } | Select -First 1)
-------------------------------------------------------------------------------
Name: admin-user-token-8db5m
Namespace: kubernetes-dashboard
Labels: <none>
Annotations: kubernetes.io/service-account.name: admin-user
kubernetes.io/service-account.uid: 7b982cb1-97a4-4c83-ae58-c0514d77d656
Type: kubernetes.io/service-account-token
Data
====
ca.crt: 1025 bytes
namespace: 20 bytes
token: eyJhbGciOiJSUzI1NiIsImtpZCI6IlA1SDBab2ozYlZ4cDY4Ry1lMXE4WGc5SW5PcmgxYl9fYUVFY3NyZlpCTVUifQ.........
-------------------------------------------------------------------------------
```
### dashboardにアクセスするためのPROXYを起動する
```
>kubectl proxy
-------------------------------------------------------------------------------
Starting to serve on 127.0.0.1:8001
-------------------------------------------------------------------------------
```
### dashboard起動
下記URLをブラウザで開く
```
http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/
```

- トークンを選択する
- パワーシェル画面に表示されているTOKENをコピーし、WEB画面のトークン部分にペーストする
- 「サインイン」ボタンをクリックする

---
# kubernetesの概念
kubernetesクラスタで実行されるアプリケーションは様々なリソースと協調して動作することで成立している。(コンテナ・オーケストレーションと呼ばれる)
以下にkubernetesのリソース一覧をまとめる。*付は今回実習で体験する。
|リソース名|用途|
|---------|---|
|Node* |Kubernetesクラスタで実行するコンテナを配置するためのサーバー|
|Namespace* |Kuberneteクラスタ内で作る仮想的なクラスタ |
|Pod* |コンテナの集合体の単位。コンテナを実行する方法を定義する |
|ReplicaSet* |同じ仕様のPodを複数生成・管理する |
|Deployment* |ReplicaSetの世代を管理する |
|Service* |Podの集合にアクセスするための経路を定義する|
|Ingress* |ServiceをKubernetesの外部に公開する |
|ConfigMap |設定情報を定義し、Podに供給する|
|PersistentVolume |Podが利用するストレージのサイズや種別を定義する |
|PersistentVolumeClaim |PersisitentVolumeを動的に確保する |
|StorageClass |PersistentVolumeが確保するストレージの種類を定義する |
|StatefulSet |同じ仕様で一意性のあるPosを複数生成・管理する |
|Job |常駐目的ではない複数のPodを作成し、正常終了することを保証する |
|CronJob |cron記法でスケジューリングして実行されるJob |
|Secret |認証情報等の機密データを定義する |
|Role |Namespace内で操作可能なKubernetesリソースのルールを定義する |
|RoleBinding |RoleとKubernetesリソースを利用するユーザーを紐付ける |
|ClusterRole |Cluster全体で操作可能なKubernetesリソースのルールを定義する |
|ClusterRoleBinding |ClusterRoleとKubernetesリソースを利用するユーザーを紐付ける |
|ServiceAccont |PodにKubernetesリソースを操作させる際に利用するユーザー |
<br/>
## kubernetesクラスタとNode
- KubernetesクラスタはKubernetesの様々なリソースを管理する集合体のこと。
- その中で最も大きい概念がNode(ホストのこと)となる。
- Kubernetesクラスタには全体を管理する役割のMaster Nodeが少なくとも一つは必要。
## kubernetesクラスタとNode 概念図

<br/>
### Master Nodeを構成する管理コンポーネント
|コンポーネント名|役割|
|---------------|----|
|kube-apiserver |KubernetesのAPIを公開するコンポーネント。kubectlからのリソース操作を受け付ける|
|etcd |高可用性を備えた分散キーバリューストア。Kubernetesのバッキングストアとして利用される|
|kube-scheduler |Nodeを監視し、コンテナを配置する最適なNodeを選択する|
|kube-controller-manager|リソースを制御するコントローラを実行|
<br/>
### Dashbord画面で確認
- ネームスペース:kube-system を選択
- 概要をクリック

---
## Namespace
NamespaceとはKubernetesクラスタ内に入れ子となる仮想的なクラスタ

---
## Pod
コンテナの集合体の単位で少なくともひとつのコンテナを持つ
Dockerコンテナ単体、あるいはDockerコンテナの集合体
### Pod単体

<br/>
### PodのNodeへの配置

※ひとつのPod内のコンテナが別々のノードに配置されることはない
<br/>
---
### Podをデプロイ~動作確認~削除まで
マニフェストファイル: ```swtest-pod.yaml```
```yaml
apiVersion: v1
kind: Pod # リソース種類を表す(Pod,ReplicaSet,Deployment...)
metadata:
name: swtest
spec:
containers: # Podなので配下にコンテナの仕様を記載する
- name: nginx
image: swtest/nginx:latest # 使用するイメージ
imagePullPolicy: Never # 必ずローカルを使用
env:
- name: BACKEND_HOST # 環境変数設定
value: localhost:8080 # バックエンドのlocalhost:8080へフォワードする
ports:
- containerPort: 80 # コンテナポートとしてExposeする番号を指定
- name: api
image: swtest/api:latest # 使用するイメージ
imagePullPolicy: Never # 必ずローカルを使用
ports:
- containerPort: 8080 # コンテナポートとしてExposeする番号を指定
```
### デプロイ
Dashboard画面からデプロイします

1. 画面右上「+」マークをクリック
2. 「ファイルから作成」を選択
3. 「…」をクリックし```swtest-pod.yaml```を選択
4. 「アップロード」ボタンをクリック
下図のようになれば正常にデプロイできています。
<br/>

### デバッグ用Podのデプロイ
```debug-pod.yaml```を同様にデプロイする
---
### Pod仮想IPについて

### SWTESTの情報

### DebugコンテナからSWTESTの動作確認

### curlコマンドで確認

<br/>
### Podの削除
Dashboardを使ってswtestのPodを削除します。
メニューの「ワークロード」>「ポッド」を選択します。


---
## ReplicaSet
同一仕様のPodの複製数を管理・制御する
PodのマニフェストファイルからはひとつのPodしか生成出来ない。
これを複数同時に生成可能なのが「ReplicaSet」。
<br/>
### マニフェストファイルの確認
マニフェストファイル: ```swtest-replicaset.yaml```
```yaml
apiVersion: apps/v1
kind: ReplicaSet # 属性が「ReplicaSet」となる
metadata:
name: swtest
labels:
app: swtest
spec:
replicas: 3 # 作成するPodの数を指定
selector:
matchLabels:
app: swtest
template: # template以下はPodのそれと同様
metadata:
labels:
app: swtest
spec:
containers:
- name: nginx
image: swtest/nginx:latest
imagePullPolicy: Never
env:
- name: BACKEND_HOST
value: localhost:8080
ports:
- containerPort: 80
- name: api
image: swtest/api:latest
imagePullPolicy: Never
ports:
- containerPort: 8080
```
### ReplicaSet生成
Dashboardからマニフェストファイルを選択し、ReplicaSetを生成します。

<br/>

<br/>

<br/>

<br/>

<br/>
<br/>
### ReplicaSet削除
Dashboardのレプリカセットのメニューから、先ほど生成したレプリカセットを削除する。

<br/>
<br/>
---
## Deployment
- **Deployment** とは、ReplicaSetの上位リソース。
- Deploymentはアプリケーションデプロイの基本単位となるリソース。
- ReplicaSetを管理・操作することができる。
- Deploymentは世代管理機能を持っておりデプロイのロールバックが可能。
- 実運用ではReplicaSetを直接用いる事は少なく、ほとんどがDeploymentのマニフェストファイルで運用している。
### Deployment/ReplicaSet/Pod関連図

<br/>
### 世代管理付のデプロイ
マニフェストファイル: ```swtest-deployment.yaml```
```yaml
apiVersion: apps/v1
kind: Deployment # ReplicaSetと異なるのはkindだけ
metadata:
name: swtest
labels:
app: swtest
spec:
replicas: 3
selector:
matchLabels:
app: swtest
template:
metadata:
labels:
app: swtest
spec:
containers:
- name: nginx
image: swtest/nginx:latest
imagePullPolicy: Never
env:
- name: BACKEND_HOST
value: localhost:8080
ports:
- containerPort: 80
- name: api
image: swtest/api:latest
imagePullPolicy: Never
ports:
- containerPort: 8080
```
### コマンドラインからデプロイする
作業フォルダより、下記コマンドを投入し、アプリケーションをデプロイする。
```cmd
> kubectl apply -f swtest-deployment.yaml --record
deployment.apps/swtest created
```

### リビジョンの確認
```cmd
> kubectl rollout history deployment swtest
deployment.apps/swtest
REVISION CHANGE-CAUSE
1 kubectl.exe apply --filename=swtest-deployment.yaml --record=true
```
---
# ローリングアップデートとロールバック
## ローリングアップデート
アプリのダウンタイムをゼロで、新しいバージョンに順次切り替えることをローリングアップデートという。
今回swtest/apiのバージョンがv2に変更になった場合を想定したローリングアップデートを行う。

## マニフェストファイル
新バージョンのマニフェストファイル: ```swtest-deployment-v2.yaml```
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: swtest
labels:
app: swtest
spec:
replicas: 3
selector:
matchLabels:
app: swtest
template:
metadata:
labels:
app: swtest
spec:
containers:
- name: nginx
image: swtest/nginx:latest
imagePullPolicy: Never
env:
- name: BACKEND_HOST
value: localhost:8080
ports:
- containerPort: 80
- name: api
image: swtest/api:v2 # apiアプリバージョンがlatestからv2になった
imagePullPolicy: Never
ports:
- containerPort: 8080
```
## アップデートの実施
作業フォルダで下記コマンドを投入する。
```cmd
> kubectl apply -f swtest-deployment-v2.yaml --record
deployment.apps/swtest configured
```
## 履歴の確認
```cmd
> kubectl rollout history deployment swtest
deployment.apps/swtest
REVISION CHANGE-CAUSE
1 kubectl.exe apply --filename=swtest-deployment.yaml --record=true
2 kubectl.exe apply --filename=swtest-deployment-v2.yaml --record=true
```

## ロールバックの実施
新バージョンに何らかの問題があった場合、旧バージョンへロールバックします。
作業フォルダで下記コマンドを投入する。
```cmd
> kubectl rollout undo deployment swtest
deployment.apps/swtest rolled back
```
### 切り替え中の状態

## 履歴の確認
```cmd
> kubectl rollout history deployment swtest
deployment.apps/swtest
REVISION CHANGE-CAUSE
2 kubectl.exe apply --filename=swtest-deployment-v2.yaml --record=true
3 kubectl.exe apply --filename=swtest-deployment.yaml --record=true
```

## 最後に削除する
```cmd
> kubectl delete -f swtest-deployment.yaml
deployment.apps "swtest" deleted
```
---
# Service(blue/green)作成
- **Service** とはPodの集合体(ReplicaSet)に対して経路やサービスディスカバリを提供
- Serviceのターゲットはラベルセレクタにより決定される
<br/>

<br/>
Blue/Greenデプロイメントを実現するため、下記2つのサービス-ReplicaSetを作成します。
1. Blueサービス → Blueデプロイメント (swtest/api:latest)
2. Greenサービス → Greenデプロイメント (swtest/api:v2)
## blue/greenデプロイメント
マニフェストファイル: ```swtest-deployment-blue.yaml```
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: swtest-blue
labels:
app: swtest
release: blue # releaseというラベルでblue/greenを切り替える
spec:
replicas: 3
selector:
matchLabels:
app: swtest
release: blue
template:
metadata:
labels:
app: swtest
release: blue
spec:
containers:
- name: nginx
image: swtest/nginx:latest
imagePullPolicy: Never
env:
- name: BACKEND_HOST
value: localhost:8080
ports:
- containerPort: 80
- name: api
image: swtest/api:latest
imagePullPolicy: Never
ports:
- containerPort: 8080
```
マニフェストファイル: ```swtest-deployment-green.yaml```
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: swtest-green
labels:
app: swtest
release: green
spec:
replicas: 3
selector:
matchLabels:
app: swtest
release: green
template:
metadata:
labels:
app: swtest
release: green
spec:
containers:
- name: nginx
image: swtest/nginx:latest
imagePullPolicy: Never
env:
- name: BACKEND_HOST
value: localhost:8080
ports:
- containerPort: 80
- name: api
image: swtest/api:v2 # 新バージョンのAPI
imagePullPolicy: Never
ports:
- containerPort: 8080
```
## blue/greenサービス
マニフェストファイル: ```swtest-servvice.yaml```
```yaml
apiVersion: v1
kind: Service
metadata:
name: swtest-blue
spec:
selector:
app: swtest
release: blue # release=blueのReplicaSetはswtest-blueサービス
ports:
- name: http # httpの80番ポートをswtestに振り当てる
port: 80
---
apiVersion: v1
kind: Service
metadata:
name: swtest-green
spec:
selector:
app: swtest
release: green # release=greenのReplicaSetはswtest-greenサービス
ports:
- name: http # httpの80番ポートをswtestに振り当てる
port: 80
```
## デプロイ
作業フォルダで下記コマンドを投入する。
```cmd
> kubectl apply -f swtest-deployment-blue.yaml --record
> kubectl apply -f swtest-deployment-green.yaml --record
> kubectl apply -f swtest-service.yaml
```
<br/>
## 状態確認

<br/>
## debugコンテナからアクセスし動作確認

---
# IngressによるBlue/Greenデプロイ
## IngressによるBlue/Greenデプロイイメージ

<br/>
## Ingress-nginxの状況確認
メニューのネームスペースから ```ingress-nginx``` を選択し、メニューの「概要」をクリックすると下記画面表示となる。
<br/>

<br/>
画面中の「外部エンドポイント」のURLリンクをクリックすると、下記画面が新たに開けば正常に動作している。


---
## Ingress追加
マニフェストファイル: ```swtest-ingress.yaml```
```yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: swtest
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: swtest.api.local
http:
paths:
- path: / # 現行バージョンは/でアクセス
backend:
serviceName: swtest-blue
servicePort: 80
- path: /staging # 新バージョンは/stagingでアクセス
backend:
serviceName: swtest-green
servicePort: 80
```
作業フォルダで下記コマンドを投入する
```cmd
> kubectl apply -f swtest-ingress.yaml
ingress.networking.k8s.io/swtest configured
```
<br/>
下図のようにイングレスが追加される

<br/>
## 動作確認
### 現行バージョンへのアクセス
Postmanで動作確認を行います
- URL: http://localhost:9000/
- Headers: Host -> swtest.api.local
- 「Send」ボタンクリック
現行バージョンの応答が返る

### 次期バージョンへのアクセス
- URL: http://localhost:9000/staging/
- Headers: Host -> swtest.api.local
- 「Send」ボタンクリック
次期バージョンの応答が返る

---
# Blue -> Green への切り替え
## path切り替え
マニフェストファイルの「path」を入れ替えることによりGreenをリリースする

<br/>
オンラインからpathを書き換えると即時にBlueからGreenにアプリケーションが切り替わる

<br/>
### 新バージョンへのアクセス
Postmanで動作確認を行います
- URL: http://localhost:9000/
- Headers: Host -> swtest.api.local
- 「Send」ボタンクリック
新バージョンの応答が返る

<br/>
### 旧バージョンへのアクセス
- URL: http://localhost:9000/staging/
- Headers: Host -> swtest.api.local
- 「Send」ボタンクリック
旧バージョンの応答が返る

<br/>
---
# 最後に実習環境の削除方法(できればKubernetes環境は破棄願います)
次回予定の、 **```Apache Kafka```** はDocker環境で実施します。Kubernetes環境が残っていると、動作が重くなります。<br/>
出来れば次回実習までにKubernetes環境を破棄願います。
PROXYのプロセスをCtrl+Cで終了させた後、構築の逆順でリソースを削除します。
## Kubernetesリソース削除
1. Ingress: kubectl delete -f swtest-ingress.yaml
2. Service: kubectl delete -f swtest-service.yaml
3. Deployment: kubectl delete -f swtest-deployment-green.yaml
4. Deployment: kubectl delete -f swtest-deployment-blue.yaml
## ingress-nginx, dashboard削除
1. ingress-nginx: kubectl delete -f cloud-generic.yaml
2. ingress-nginx: kubectl delete -f mandatory.yaml
3. admin-user: kubectl delete -f role_binding.yaml
4. admin-user: kubectl delete -f create_account.yaml
5. dashboard: kubectl delete -f recommended.yaml
## Docker Dashboardで無効化
1. Docker DashboardのSettingでKubernetesの有効化ボタンを元に戻す
2. 「Apply&Restart」ボタンを押す
## 不要データの削除
1. Docker DashboardのTroubleshootボタンを押す
2. 「Clean / Purge data」ボタンを押す
3. 削除対象のチェックを全て付ける
4. 「Delete」ボタンを押す

<br/>

|
Ruby
|
UTF-8
| 2,244 | 3.140625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song
extend Concerns::Findable
attr_accessor :name
attr_reader :artist, :genre
@@all = []
def initialize(name, artist = nil, genre = nil)
@name = name
self.artist=(artist) unless artist == nil
self.genre=(genre) unless genre == nil
end
def self.all
@@all
@@all.dup.freeze
end
def save
@@all << self
self
end
def self.destroy_all
@@all.clear
end
def self.create(name)
self.new(name).save
end
def artist=(name)
@artist = name unless @artist != nil
name.add_song(self) unless name.songs.include?(self)
end
def genre=(genre)
@genre = genre
genre.songs << self unless genre.songs.include?(self)
end
def self.new_from_filename(filename)
file_artist, file_song, file_genre = filename.split(" - ")
file_genre = file_genre.gsub(".mp3", "")
song = self.find_or_create_by_name(file_song)
artist = Artist.find_or_create_by_name(file_artist)
genre = Genre.find_or_create_by_name(file_genre)
song.artist = artist
song.genre = genre
song
end
def self.create_from_filename(filename)
self.new_from_filename(filename)
end
def self.find_by_name(name)
@@all.each do |song|
if song.name == name
return song
end
end
false
end
def self.find_or_create_by_name(name)
if self.find_by_name(name)
self.find_by_name(name)
else
self.create(name)
end
end
def self.get_song_by_name(artist_name)
song_list = []
i = 0
@@all.collect do |instance|
if instance.artist.name == artist_name
song_list[i] = "#{instance.name} - #{instance.genre.name}"
i += 1
end
end
song_list
end
def self.get_song_by_genre(genre_name)
genre_list = []
song_name = []
ordered_list = []
i = 0
x = 0
@@all.collect do |instance|
if instance.genre.name == genre_name
genre_list[i] = "#{instance.artist.name} - #{instance.name}"
song_name[i] = instance.name
i += 1
end
end
song_name.each do |name|
genre_list.each do |list|
if list.include? "#{name}"
ordered_list[x] = list
x += 1
end
end
end
ordered_list
end
end
|
Python
|
UTF-8
| 3,809 | 3.09375 | 3 |
[] |
no_license
|
import unittest
import math
from openmm import Vec3
from openmm.unit import *
from openmm.app.internal.unitcell import computePeriodicBoxVectors
from openmm.app.internal.unitcell import computeLengthsAndAngles
from openmm.app.internal.unitcell import reducePeriodicBoxVectors
def strip_units(x):
if is_quantity(x): return x.value_in_unit_system(md_unit_system)
return x
class TestUnitCell(unittest.TestCase):
""" Test the unitcell.py module """
def testReducePBCVectors(self):
""" Checks that reducePeriodicBoxVectors properly reduces vectors """
a = Vec3(4.24388485, 0.0, 0.0)
b = Vec3(-1.4146281691908937, 4.001173048368583, 0.0)
c = Vec3(-1.4146281691908937, -2.0005862820516203, 3.4651176446201674)
vecs = reducePeriodicBoxVectors((a, b, c)*nanometers)
vecs2 = computePeriodicBoxVectors(4.24388485, 4.24388485, 4.24388485,
109.4712190*degrees, 109.4712190*degrees, 109.4712190*degrees)
# Check that the vectors are the same
a1, a2, a3 = vecs
b1, b2, b3 = vecs2
for x, y in zip(a1, b1):
self.assertAlmostEqual(strip_units(x), strip_units(y))
for x, y in zip(a2, b2):
self.assertAlmostEqual(strip_units(x), strip_units(y))
for x, y in zip(a3, b3):
self.assertAlmostEqual(strip_units(x), strip_units(y))
def testComputePBCVectors(self):
""" Tests computing periodic box vectors """
deg90 = 90 * degrees
vecs = computePeriodicBoxVectors(1, 2, 3, deg90, deg90, deg90)
a, b, c = vecs
self.assertAlmostEqual(a[0]/nanometers, 1)
self.assertAlmostEqual(a[1]/nanometers, 0)
self.assertAlmostEqual(a[2]/nanometers, 0)
self.assertAlmostEqual(b[0]/nanometers, 0)
self.assertAlmostEqual(b[1]/nanometers, 2)
self.assertAlmostEqual(b[2]/nanometers, 0)
self.assertAlmostEqual(c[0]/nanometers, 0)
self.assertAlmostEqual(c[1]/nanometers, 0)
self.assertAlmostEqual(c[2]/nanometers, 3)
# Make sure round-trip works
la, lb, lc, al, be, ga = computeLengthsAndAngles(vecs)
self.assertAlmostEqual(la, 1)
self.assertAlmostEqual(lb, 2)
self.assertAlmostEqual(lc, 3)
self.assertAlmostEqual(al, math.pi / 2)
self.assertAlmostEqual(be, math.pi / 2)
self.assertAlmostEqual(ga, math.pi / 2)
# Now test a truncated octahedron. Can't do a simple round-trip though,
# due to the reduced form. So test the *second* round-trip, which should
# yield the same measurements
vecs = computePeriodicBoxVectors(4.24388485, 4.24388485, 4.24388485,
109.4712190*degrees, 109.4712190*degrees, 109.4712190*degrees)
la, lb, lc, al, be, ga = computeLengthsAndAngles(vecs)
vecs2 = computePeriodicBoxVectors(la, lb, lc, al, be, ga)
la2, lb2, lc2, al2, be2, ga2 = computeLengthsAndAngles(vecs2)
# Now make sure that the round-trip worked
self.assertAlmostEqual(strip_units(la), strip_units(la2))
self.assertAlmostEqual(strip_units(lb), strip_units(lb2))
self.assertAlmostEqual(strip_units(lc), strip_units(lc2))
self.assertAlmostEqual(strip_units(al), strip_units(al2))
self.assertAlmostEqual(strip_units(be), strip_units(be2))
self.assertAlmostEqual(strip_units(ga), strip_units(ga2))
# Check that the vectors are the same
a1, a2, a3 = vecs
b1, b2, b3 = vecs2
for x, y in zip(a1, b1):
self.assertAlmostEqual(strip_units(x), strip_units(y))
for x, y in zip(a2, b2):
self.assertAlmostEqual(strip_units(x), strip_units(y))
for x, y in zip(a3, b3):
self.assertAlmostEqual(strip_units(x), strip_units(y))
|
C#
|
UTF-8
| 9,646 | 2.796875 | 3 |
[] |
no_license
|
using UnityEngine;
static public class ColliderExtensions
{
#region Volume
static public float ComputeVolume(this Collider that)
{
if(that is BoxCollider)
return (that as BoxCollider).ComputeVolume();
else if(that is SphereCollider)
return (that as SphereCollider).ComputeVolume();
else if(that is MeshCollider)
return (that as MeshCollider).ComputeVolume();
else if(that is CapsuleCollider)
return (that as CapsuleCollider).ComputeVolume();
else
throw new System.NotImplementedException();
}
static public float ComputeVolume(this BoxCollider that)
{
Vector3 size = that.size;
Vector3 scale = that.transform.lossyScale;
return size.x * scale.x * size.y * scale.y * size.z * scale.z;
}
static public float ComputeVolume(this SphereCollider that)
{
float r = that.radius;
Vector3 scale = that.transform.lossyScale;
return (4.0f / 3.0f) * Mathf.PI * r * r * r * scale.x * scale.y * scale.z;
}
static public float ComputeVolume(this MeshCollider that)
{
float volume = 0;
var mesh = that.sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
int numTriangles = triangles.Length;
Vector3 center = that.transform.InverseTransformPoint(that.bounds.center);
for(int i = 0; i < numTriangles;)
{
Vector3 p1 = vertices[triangles[i++]] - center;
Vector3 p2 = vertices[triangles[i++]] - center;
Vector3 p3 = vertices[triangles[i++]] - center;
volume += SignedVolumeOfTriangle(p1, p2, p3);
}
Vector3 scale = that.transform.lossyScale;
return Mathf.Abs(volume) * scale.x * scale.y * scale.z;
}
static public float ComputeVolume(this CapsuleCollider that)
{
float r = that.radius;
float sphere = (4.0f / 3.0f) * Mathf.PI * r * r * r;
float cylinder = Mathf.PI * r * r * that.height;
Vector3 scale = that.transform.lossyScale;
return (cylinder + sphere) * scale.x * scale.y * scale.z;
}
static public float SignedVolumeOfTriangle(Vector3 p1, Vector3 p2, Vector3 p3)
{
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (1.0f / 6.0f) * (-v321 + v231 + v312 - v132 - v213 + v123);
}
#endregion
#region Area
static public float ComputeArea(this Collider that)
{
if(that is MeshCollider)
return (that as MeshCollider).ComputeArea();
else if(that is BoxCollider)
return (that as BoxCollider).ComputeArea();
else if(that is SphereCollider)
return (that as SphereCollider).ComputeArea();
else if(that is CapsuleCollider)
return (that as CapsuleCollider).ComputeArea();
else
throw new System.NotImplementedException();
}
static public float ComputeArea(this MeshCollider that)
{
float area = 0;
var mesh = that.sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
int numTriangles = triangles.Length;
Vector3 scale = that.transform.lossyScale;
for(int i = 0; i < numTriangles;)
{
Vector3 origin = vertices[triangles[i++]];
Vector3 a = vertices[triangles[i++]] - origin;
Vector3 b = vertices[triangles[i++]] - origin;
a.Scale(scale);
b.Scale(scale);
area += Vector3.Cross(a, b).magnitude;
}
return area * 0.5f;
}
static public float ComputeArea(this BoxCollider that)
{
Vector3 size = that.size;
size.Scale(that.transform.lossyScale);
return 2.0f * (size.x * size.y + size.y * size.z + size.x * size.z);
}
static public float ComputeArea(this SphereCollider that)
{
float s = that.transform.lossyScale.magnitude;
float r = that.radius * s;
return 4.0f * Mathf.PI * r * r;
}
static public float ComputeArea(this CapsuleCollider that)
{
Vector3 scale = that.transform.lossyScale;
float r = that.radius * scale.magnitude;
float height = that.height;
switch(that.direction)
{
case 0: height *= scale.x; break;
case 1: height *= scale.y; break;
case 2: height *= scale.z; break;
default: throw new System.NotImplementedException();
}
return 2.0f * Mathf.PI * r * (2.0f * r + height);
}
#endregion
#region Random
/// <summary>
/// Returns random local point in a collider.
/// </summary>
/// <param name="that"></param>
/// <returns></returns>
static public Vector3 RandomPoint(this Collider that)
{
if(that is MeshCollider)
return (that as MeshCollider).RandomPoint();
else if(that is BoxCollider)
return (that as BoxCollider).RandomPoint();
else if(that is CapsuleCollider)
return (that as CapsuleCollider).RandomPoint();
else if(that is SphereCollider)
return (that as SphereCollider).RandomPoint();
else
throw new System.NotImplementedException();
}
static private double RandomDouble()
{
return Random.value + (Random.value - 0.5) * 0.00008;
}
static public Vector3 RandomPoint(this MeshCollider that)
{
var bounds = that.sharedMesh.bounds;
Vector3 min = bounds.min;
Vector3 max = bounds.max;
Vector3 range = (max - min);
Vector3 p = new Vector3();
for(int i = 0; i < 40; ++i)
{
p.x = min.x + Random.value * range.x;
p.y = min.y + Random.value * range.y;
p.z = min.z + Random.value * range.z;
if(that.IsPointInside(that.transform.TransformPoint(p)))
break;
}
return p;
}
static public Vector3 RandomPoint(this BoxCollider that)
{
Vector3 center = that.center;
Vector3 halfSize = that.size * 0.5f;
float x = center.x + Random.Range(-halfSize.x, halfSize.x);
float y = center.y + Random.Range(-halfSize.y, halfSize.y);
float z = center.z + Random.Range(-halfSize.z, halfSize.z);
return new Vector3(x, y, z);
}
static public Vector3 RandomPoint(this CapsuleCollider that)
{
float r = that.radius;
float cylinderHeight = that.height;
float cylinderVolume = Mathf.PI * r * r * cylinderHeight;
float spheresVolume = (4.0f / 3.0f) * Mathf.PI * r * r * r;
float f = Random.Range(0.0f, cylinderVolume + spheresVolume);
Vector3 p;
if(f < cylinderVolume)
{
p = RandomPointInCircle(r);
p.z = p.y;
p.y = Random.Range(-cylinderHeight * 0.5f, cylinderHeight * 0.5f);
}
else
{
p = RandomPointInSphere(r);
if(p.y < 0.0f)
p.y -= cylinderHeight * 0.5f;
else
p.y += cylinderHeight * 0.5f;
}
if(that.direction == 0)
{
float t = p.y;
p.y = p.x;
p.x = t;
}
else if(that.direction == 2)
{
float t = p.y;
p.y = p.z;
p.z = t;
}
return p;
}
static public Vector3 RandomPoint(this SphereCollider that)
{
return RandomPointInSphere(that.radius);
}
static public Vector3 RandomPointInSphere(float radius)
{
float rvals = Random.Range(-1.0f, 1.0f);
float elevation = Mathf.Asin(rvals);
float azimuth = 2 * Mathf.PI * Random.Range(0.0f, 1.0f);
float radii = 3 * Mathf.Pow(Random.Range(0.0f, 1.0f), 0.33333333f);
float se = Mathf.Sin(elevation);
return new Vector3(
radii * se * Mathf.Cos(azimuth),
radii * se * Mathf.Sin(azimuth),
radii * Mathf.Cos(elevation)
);
}
static public Vector2 RandomPointInCircle(float radius)
{
float t = 2 * Mathf.PI * Random.Range(0.0f, 1.0f);
float u = Random.Range(0.0f, 1.0f) + Random.Range(0.0f, 1.0f);
float r = (u > 1 ? 2 - u : u) * radius;
return new Vector2(r * Mathf.Cos(t), r * Mathf.Sin(t));
}
#endregion
static public void GetLocalMinMax(Collider collider, out Vector3 min, out Vector3 max)
{
if(collider is MeshCollider)
{
var bounds = (collider as MeshCollider).sharedMesh.bounds;
min = bounds.min;
max = bounds.max;
}
else if(collider is BoxCollider)
{
var box = collider as BoxCollider;
min = box.center - box.size * 0.5f;
max = box.center + box.size * 0.5f;
}
else if(collider is SphereCollider)
{
var sphere = collider as SphereCollider;
Vector3 center = sphere.center;
float halfRadius = sphere.radius * 0.5f;
min = new Vector3(center.x - halfRadius, center.y - halfRadius, center.z - halfRadius);
max = new Vector3(center.x + halfRadius, center.y + halfRadius, center.z + halfRadius);
}
else if(collider is CapsuleCollider)
{
var capsule = collider as CapsuleCollider;
Vector3 center = capsule.center;
float halfRadius = capsule.radius * 0.5f;
float halfHeight = capsule.height * 0.5f + halfRadius;
switch(capsule.direction)
{
case 0:
{
min = new Vector3(center.x - halfHeight, center.y - halfRadius, center.z - halfRadius);
max = new Vector3(center.x + halfHeight, center.y + halfRadius, center.z + halfRadius);
break;
}
case 1:
{
min = new Vector3(center.x - halfRadius, center.y - halfHeight, center.z - halfRadius);
max = new Vector3(center.x + halfRadius, center.y + halfHeight, center.z + halfRadius);
break;
}
case 2:
{
min = new Vector3(center.x - halfRadius, center.y - halfRadius, center.z - halfHeight);
max = new Vector3(center.x + halfRadius, center.y + halfRadius, center.z + halfHeight);
break;
}
default:
throw new System.NotImplementedException();
}
}
else
throw new System.NotImplementedException();
//Vector3 s = collider.transform.localScale;
//if(s.x < 0) s.x = -s.x;
//if(s.y < 0) s.y = -s.y;
//if(s.z < 0) s.z = -s.z;
//min.Scale(s);
//max.Scale(s);
}
static public bool IsPointInside(this Collider convex, Vector3 point)
{
var bounds = convex.bounds;
if(!bounds.Contains(point))
return false;
Vector3 dir = bounds.center - point;
float magnitude = dir.magnitude;
if(magnitude < 0.00001f)
return true;
RaycastHit hitInfo;
return !convex.Raycast(new Ray(point, dir), out hitInfo, magnitude);
}
}
|
JavaScript
|
UTF-8
| 1,702 | 2.859375 | 3 |
[] |
no_license
|
import React from 'react';
import PokemonSelector from '../components/pokemonSelector';
import PokemonDetail from '../components/pokemonDetails';
class PokemonContainer extends React.Component {
constructor() {
super();
this.state = {
pokemons: [],
selectedPokemon: '',
pokemonDetails: ''
};
this.handlePokemonSelected = this.handlePokemonSelected.bind(this);
}
componentDidMount() {
const url = 'https://pokeapi.co/api/v2/pokemon?limit=151';
fetch(url)
.then(res => res.json())
.then(pokemons => this.setState({pokemons: pokemons.results}))
.catch(err => console.log(err));
}
fetchPokemonDetail(name) {
// if(!selectedPokemon) {
// return null;
// }
const url = 'https://pokeapi.co/api/v2/pokemon/' + name;
fetch(url)
.then(res => res.json())
.then(pokemon => this.setState({pokemonDetails: pokemon}))
.catch(err => console.log(err));
}
handlePokemonSelected(name) {
this.setState({selectedPokemon: name});
this.fetchPokemonDetail(name);
}
render() {
const selectedPokemon = this.state.pokemons.find((pokemon) => {
return pokemon.name === this.state.selectedPokemon;
});
return (
<div>
<h2>Pokemon Container</h2>
<PokemonSelector pokemons={this.state.pokemons} handlePokemonSelected={this.handlePokemonSelected}/>
<PokemonDetail pokemon={selectedPokemon} pokemonDetails={this.state.pokemonDetails}/>
</div>
)
}
}
export default PokemonContainer;
|
Java
|
UTF-8
| 704 | 2.203125 | 2 |
[] |
no_license
|
package com.spring.core;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.model.Triangle;
public class AOPMain {
public static void main(String[] args) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
// ApplicationContext cntxt = new ClassPathXmlApplicationContext("spring.xml");
ctx.registerShutdownHook();
ShapeService shapeService = (ShapeService) ctx.getBean("shapeService", ShapeService.class);
Triangle trn = (Triangle) ctx.getBean("triangle", Triangle.class);
// shapeService.getCircle().getName();
trn.getName();
}
}
|
Java
|
UTF-8
| 2,226 | 4.1875 | 4 |
[] |
no_license
|
package lessons.week3.pratice.queue.pratice1;
import java.util.Stack;
/**
* @version 1.0 剑指 Offer 09. 用两个栈实现队列
* @Description: 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,
* 分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead操作返回 -1 )
*
* 示例 1:
* 输入:
* ["CQueue","appendTail","deleteHead","deleteHead"]
* [[],[3],[],[]]
* 输出:[null,null,3,-1]
*
* 示例 2:
* 输入:
* ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
* [[],[],[5],[2],[],[]]
* 输出:[null,-1,null,null,5,2]
*
* 提示:
* 1 <= values <= 10000
* 最多会对appendTail、deleteHead 进行10000次调用
*
* @author: bingyu 我使用的是解法一
* @date: 2022/4/7
*/
public class CQueue2 {
//TODO: 解法二:入队-用两个栈倒腾; 出队-直接出栈(好像没办法这样做,只能取的时候进行挪移)
/**
* 一个栈A,一个临时栈B,第一个数据先入栈A,当后面有数据进入时将栈A的数据都移动到临时栈,然后在将新数据存入栈A中;再把临时栈的数据全部移动到
* 栈A,这样最先进去的数据就到栈A的栈顶了!
*/
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> temp = new Stack<Integer>();
public CQueue2() {
}
public void appendTail(int value) {
while (!stack.empty()) {
temp.push(stack.pop()); //将栈的数据全部移动到临时栈
}
stack.push(value); //新数据放入栈底
while (!temp.empty()) {
stack.push(temp.pop()); //再把临时栈的数据全部移动回栈中,这样的话最先进栈的就到栈顶了,后面就可以直接出
}
}
public int deleteHead() {
if (stack.empty()) return -1;
return stack.pop();
}
public static void main(String[] args) {
CQueue2 queue2 = new CQueue2();
queue2.appendTail(1);
queue2.appendTail(2);
queue2.appendTail(3);
System.out.println(queue2.deleteHead());
}
}
|
Java
|
UTF-8
| 1,031 | 2.015625 | 2 |
[] |
no_license
|
package com.duheng.gmall.pms.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/*************************
Author: 杜衡
Date: 2020/1/21
Describe:
*************************/
@Configuration
public class PmsDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
//spring的ResourceUtils来获取资源
//File file = ResourceUtils.getFile("classpath:sharding-jdbc.yml");
//return MasterSlaveDataSourceFactory.createDataSource(file);
return new DruidDataSource();
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
|
Java
|
UTF-8
| 718 | 3.359375 | 3 |
[] |
no_license
|
import java.util.UUID;
/**
* superclass of Triangle and Rectangle
* having a abstract method
*/
public abstract class Shape implements Comparable {
UUID id;
/**
* Get the ID of the property
*
* @return the UUID of the property
*/
public UUID getId() {
return id;
}
/**
* Set the ID of the property
*
* @param id the UUID of the property
*/
public void setId(UUID id) {
this.id = id;
}
public abstract double perimeter();
/**
* Array sorted by uuid
* @param o other object
* @return int
*/
@Override
public int compareTo(Object o) {
return this.id.compareTo(((Shape) o).id);
}
}
|
Shell
|
UTF-8
| 4,002 | 3.109375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#!/bin/bash
export IPT="iptables"
# Внешний интерфейс
export WAN={{ nat_router_wan_interface }}
# Локальная сеть
export LAN1={{ nat_router_lan_interface }}
export LAN1_IP_RANGE={{ nat_router_lan_ip_range }}
# Очищаем правила
$IPT -F
$IPT -F -t nat
$IPT -F -t mangle
$IPT -X
$IPT -t nat -X
$IPT -t mangle -X
# Запрещаем все, что не разрешено
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP
# Разрешаем localhost и локалку
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A INPUT -i $LAN1 -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT
$IPT -A OUTPUT -o $LAN1 -j ACCEPT
# Рзрешаем пинги
$IPT -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
$IPT -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
$IPT -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
$IPT -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
# Разрешаем исходящие подключения сервера
$IPT -A OUTPUT -o $WAN -j ACCEPT
#$IPT -A INPUT -i $WAN -j ACCEPT
# разрешаем установленные подключения
$IPT -A INPUT -p all -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A OUTPUT -p all -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A FORWARD -p all -m state --state ESTABLISHED,RELATED -j ACCEPT
# Отбрасываем неопознанные пакеты
$IPT -A INPUT -m state --state INVALID -j DROP
$IPT -A FORWARD -m state --state INVALID -j DROP
# Отбрасываем нулевые пакеты
$IPT -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
# Закрываемся от syn-flood атак
$IPT -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
$IPT -A OUTPUT -p tcp ! --syn -m state --state NEW -j DROP
# Блокируем доступ с указанных адресов
#$IPT -A INPUT -s 84.122.21.197 -j REJECT
# Пробрасываем порт в локалку
{% for port_forwards in nat_router_port_forwards %}
$IPT -t nat -A PREROUTING -p {{ port_forwards.protocol }} --dport {{ port_forwards.port }} -i {{ nat_router_wan_interface }} -j DNAT --to {{ port_forwards.destination }}:{{ port_forwards.port }}
$IPT -A FORWARD -i {{ nat_router_wan_interface }} -d {{ port_forwards.destination }} -p {{ port_forwards.protocol }} -m {{ port_forwards.protocol }} --dport {{ port_forwards.port }} -j ACCEPT
{% endfor %}
# Разрешаем доступ из локалки наружу
$IPT -A FORWARD -i $LAN1 -o $WAN -j ACCEPT
# Закрываем доступ снаружи в локалку
$IPT -A FORWARD -i $WAN -o $LAN1 -j REJECT
# Включаем NAT
$IPT -t nat -A POSTROUTING -o $WAN -s $LAN1_IP_RANGE -j MASQUERADE
# открываем доступ к SSH
$IPT -A INPUT -i $WAN -p tcp --dport 22 -j ACCEPT
# Открываем доступ к почтовому серверу
#$IPT -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
#$IPT -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT
#$IPT -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT
#$IPT -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT
#$IPT -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT
#$IPT -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT
#Открываем доступ к web серверу
#$IPT -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
#$IPT -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
#Открываем доступ к DNS серверу
#$IPT -A INPUT -i $WAN -p udp --dport 53 -j ACCEPT
# Включаем логирование
#$IPT -N block_in
#$IPT -N block_out
#$IPT -N block_fw
#$IPT -A INPUT -j block_in
#$IPT -A OUTPUT -j block_out
#$IPT -A FORWARD -j block_fw
#$IPT -A block_in -j LOG --log-level info --log-prefix "--IN--BLOCK"
#$IPT -A block_in -j DROP
#$IPT -A block_out -j LOG --log-level info --log-prefix "--OUT--BLOCK"
#$IPT -A block_out -j DROP
#$IPT -A block_fw -j LOG --log-level info --log-prefix "--FW--BLOCK"
#$IPT -A block_fw -j DROP
# Сохраняем правила
/sbin/iptables-save > /etc/sysconfig/iptables
|
Python
|
UTF-8
| 3,213 | 2.671875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
"""Chainer example: train a multi-layer perceptron on MNIST
This is a minimal example to write a feed-forward net. It requires scikit-learn
to load MNIST dataset.
"""
import argparse
import numpy as np
import six
import chainer
from chainer import computational_graph as c
from chainer import cuda
import chainer.functions as F
from chainer import optimizers
from autoencoder import Autoencoder
from sigmoid_cross_entropy_float import sigmoid_cross_entropy_float
import data
import pickle
parser = argparse.ArgumentParser(description='Chainer example: MNIST')
parser.add_argument('--gpu', '-g', default=-1, type=int,
help='GPU ID (negative value indicates CPU)')
args = parser.parse_args()
if args.gpu >= 0:
cuda.check_cuda_available()
xp = cuda.cupy if args.gpu >= 0 else np
batchsize = 100
n_epoch = 25
n_units = 500
# Prepare dataset
print('load MNIST dataset')
mnist = data.load_mnist_data()
mnist['data'] = mnist['data'].astype(np.float32)
mnist['data'] /= 255
mnist['target'] = mnist['target'].astype(np.int32)
N = 60000
x_train, x_test = np.split(mnist['data'], [N])
y_train, y_test = np.split(mnist['target'], [N])
N_test = y_test.size
# Prepare multi-layer perceptron model
model = chainer.FunctionSet(ae1=Autoencoder(784, n_units))
if args.gpu >= 0:
cuda.get_device(args.gpu).use()
model.to_gpu()
def forward(x_data, t_data, train=True):
x = chainer.Variable(x_data)
t = chainer.Variable(t_data)
y = model.ae1(x)
loss = sigmoid_cross_entropy_float(y, t)
return loss
def ZeroMask(data, ratio=0.90):
return data * (xp.random.random_sample(data.shape) > ratio)
def SP(data, ratio=0.50):
n = int(data.size*ratio)
perm = np.random.permutation(data.size)[:n]
ret = cuda.to_cpu(data).flatten()
ret[perm] = (np.random.rand(n) > 0.5)
ret = ret.reshape(data.shape)
return xp.asarray(ret)
def GN(data, var=0.75):
noise = xp.random.normal(scale=var, size=data.shape, dtype=xp.float32)
return data+noise
# Setup optimizer
optimizer = optimizers.Adam()
optimizer.setup(model)
# Learning loop
for epoch in six.moves.range(1, n_epoch + 1):
print('epoch', epoch)
# training
perm = np.random.permutation(N)
sum_accuracy = 0
sum_loss = 0
for i in six.moves.range(0, N, batchsize):
x_batch = xp.asarray(x_train[perm[i:i + batchsize]])
noised = GN(x_batch)
optimizer.zero_grads()
loss = forward(noised, x_batch)
loss.backward()
optimizer.update()
sum_loss += float(loss.data) * batchsize
print('train mean loss={}'.format(
sum_loss / N))
# evaluation
sum_accuracy = 0
sum_loss = 0
for i in six.moves.range(0, N_test, batchsize):
x_batch = xp.asarray(x_test[i:i + batchsize])
noised = GN(x_batch)
loss = forward(noised, x_batch, train=False)
sum_loss += float(loss.data) * batchsize
print('test mean loss={}'.format(
sum_loss / N_test))
print 'serialize ...'
ae1 = model.ae1
model_data = {'w': cuda.to_cpu(ae1.W), 'b1':cuda.to_cpu(ae1.b1), 'b2':cuda.to_cpu(ae1.b2)}
f = open("ae1.pickle", "w")
pickle.dump(model_data, f)
f.close()
|
Python
|
UTF-8
| 6,508 | 2.84375 | 3 |
[] |
no_license
|
# Modelo de detección de SPAM usando la base de datos CSDMC2010_SPAM
import os
import gensim
from pyspark import SparkContext
sc = SparkContext()
sc.setCheckpointDir('/user/cloudera/checkpoiting')
rejectedChars = ['<>\'\"?+=\r\n']
# Carga de los datos
mailFiles = sc.wholeTextFiles('/user/cloudera/lab-spark-2/TRAINING').map(lambda x: (os.path.basename(x[0]), x[1]
.replace('\n','')\
.replace('<','')\
.replace('>','')\
.replace('[','')\
.replace(']','')))
labelFiles = sc.textFile('/user/cloudera/lab-spark-2/SPAMTrain.label')
# Separación del set de entrenamiento en conjuntos de entrenamiento y validación
labelList = labelFiles.map(lambda x: x.split()).map(lambda x: (x[1], float(x[0])) )
labelList_train = labelList.filter(lambda x: x[0] < 'TRAIN_03500')
labelList_val = labelList.filter(lambda x: x[0] >= 'TRAIN_03500')
# Creo un RDD con elementos de (label, texto), limpando el texto de caracteres "extraños".
labeledMails = labelList_train.join(mailFiles).map(lambda x: x[1])
cleanLabeledMails = labeledMails.map(lambda x: (x[0], ''.join([w for w in x[1] if w not in rejectedChars])) )
# Transformo los datos "raw" desde texto a listas de palabras lematizadas
cleanLabeledMailsStemmed = cleanLabeledMails.map(lambda x: (x[0], gensim.utils.lemmatize(x[1])) )
# Se crea el vocabulario que después de usará para extraer los descriptores tipo Bag of Words
vocab_raw = cleanLabeledMailsStemmed.flatMap(lambda x: x[1]).map(lambda w: (w,1)).reduceByKey(lambda a,b: a+b)
vocab_filtered = vocab_raw.filter(lambda x: x[1]>10)
# Genero un hashing desde la palabra de vocabulario hacia el índice del vector Bag of Words
vocab = {}
for idx,w in enumerate(vocab_filtered.collect()):
vocab[w[0]] = idx
num_w = len(vocab)
# Función para generar los datos de entrenamiento en formato LabeledPoint
from pyspark.mllib.feature import LabeledPoint, Vectors
def create_sparse_bow(word_list, vocab, N):
words = []
indices = []
counts = []
for w in word_list:
if w in vocab:
if w in words:
idx = words.index(w)
counts[idx] += 1.0
else:
words.append(w)
indices.append(vocab[w])
counts.append(1.0)
# sort lists
idx = [i for i,data in sorted(enumerate(indices), key=lambda x: x[1])]
return Vectors.sparse(N, [indices[i] for i in idx], [counts[i] for i in idx])
# Creación de los datos de entrenamiento en formato (label, vector de BoW)
trainingData = cleanLabeledMailsStemmed.map( lambda x: LabeledPoint(x[0], create_sparse_bow(x[1], vocab, num_w) ) ).filter(lambda x: x.features.numNonzeros() > 1)
# Entrenamiento del modelo
from pyspark.mllib.classification import NaiveBayes, NaiveBayesModel
model = NaiveBayes.train(trainingData)
# Aplicación del modelo a datos de entrenamiento
predTrain = trainingData.map(lambda x: (x.label, model.predict(x.features))).collect()
# Matriz de confusión en entrenamiento
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def plotConfusionMatrix(conf_arr, alphabet, title='', path='confusion-matrix.png'):
conf_arr = np.array(conf_arr)
norm_conf = []
for i in conf_arr:
a = 0
tmp_arr = []
a = sum(i, 0)
for j in i:
tmp_arr.append(float(j)/float(a))
norm_conf.append(tmp_arr)
fig = plt.figure()
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
res = ax.imshow(np.array(norm_conf), cmap=plt.cm.jet,
interpolation='nearest')
width, height = conf_arr.shape
for x in xrange(width):
for y in xrange(height):
ax.annotate(str(conf_arr[x][y]), xy=(y, x),
horizontalalignment='center',
verticalalignment='center')
plt.title(title)
plt.xticks(range(width), alphabet[:width])
plt.yticks(range(height), alphabet[:height])
plt.savefig(path)
confMatrixTrain = [[0,0],[0,0]]
for r,p in predTrain:
real = int(r)
pred = int(p)
confMatrixTrain[real][pred] += 1
# Guardamos la matriz de confusión en una imagen train-confusion-matrix.png
plotConfusionMatrix(confMatrixTrain, ['SPAM', 'NOT SPAM'], "Matriz de confusion en entrenamiento", "train-confusion-matrix.png")
accuracy_train = sum(1 for p in predTrain if p[0] == p[1])/float(len(predTrain))
print "Accuracy en entrenamiento", accuracy_train
# Aplicación del modelo a datos de validación
labeledMailsVal = labelList_val.join(mailFiles).map(lambda x: x[1])
cleanLabeledMailsVal = labeledMailsVal.map(lambda x: (x[0], ''.join([w for w in x[1] if w not in rejectedChars])) )
cleanLabeledMailsStemmedVal = cleanLabeledMailsVal.map(lambda x: (x[0], gensim.utils.lemmatize(x[1])) )
validationData = cleanLabeledMailsStemmedVal.map( lambda x: LabeledPoint(x[0], create_sparse_bow(x[1], vocab, num_w) ) ).filter(lambda x: x.features.numNonzeros() > 1)
predVal = validationData.map(lambda x: (x.label, model.predict(x.features))).collect()
accuracy_val = sum(1 for p in predVal if p[0] == p[1])/float(len(predVal))
confMatrixVal = [[0,0],[0,0]]
for r,p in predVal:
real = int(r)
pred = int(p)
confMatrixVal[real][pred] += 1
# Guardamos la matriz de confusión en una imagen val-confusion-matrix.png
plotConfusionMatrix(confMatrixVal, ['SPAM', 'NOT SPAM'], "Matriz de confusion en validacion", "val-confusion-matrix.png")
print "Accuracy en validación ", accuracy_val
# Revision de set de test
mailFilesTest = sc.wholeTextFiles('/user/cloudera/lab-spark-2/TESTING')\
.map(lambda x: (x[0], x[1]\
.replace('\n','')\
.replace('<','')\
.replace('>','')\
.replace('[','')\
.replace(']','')) )
cleanMailsTest = mailFilesTest.map(lambda x: (x[0], ''.join([w for w in x[1] if w not in rejectedChars])))
cleanMailsStemmedTest = cleanMailsTest.map(lambda x: (x[0], gensim.utils.lemmatize(x[1])) )
testData = cleanMailsStemmedTest.map( lambda x: (x[0], create_sparse_bow(x[1], vocab, num_w) )) .filter(lambda x: x[1].numNonzeros() > 1)
predTest = testData.map(lambda x: (x[0], model.predict(x[1])) ).map(lambda x: (x[0], 'SPAM' if x[1] == 0.0 else 'NOT SPAM'))
print predTest.sample(False, 0.1).take(20)
|
Java
|
UTF-8
| 8,716 | 3.578125 | 4 |
[] |
no_license
|
import java.util.Random;
import java.util.Scanner;
/*работает на поле любого размера с любим выигрышным числом*/
public class homeWork3 {
private static char[][] field;
private static int fieldSizeX = 9;
private static int fieldSizeY = 6;
private static int winNumber = 3; //выигрышное число
private static int xStep;
private static int yStep;
private static final Scanner SCANNER = new Scanner(System.in);
private static final Random RANDOM = new Random();
private static final char DOT_HUMAN = 'X';
private static final char DOT_AI = 'O';
private static final char DOT_EMPTY = '.';
private static void initField() {
field = new char[fieldSizeY][fieldSizeX];
for (int i = 0; i < fieldSizeY; i++) {
for (int j = 0; j < fieldSizeX; j++) {
field[i][j] = DOT_EMPTY;
}
}
}
private static void showField() {
for (int i = 0; i < fieldSizeY; i++) {
// System.out.println("-------------");
System.out.print('|');
for (int j = 0; j < fieldSizeX; j++) {
System.out.print(field[i][j] + "|");
;
}
System.out.println("");
}
System.out.println("----------------------");
}
private static void humanTurn() {
int x, y;
do {
System.out.print("Enter coord X and Y : ");
x = SCANNER.nextInt() - 1;
y = SCANNER.nextInt() - 1;
} while (!isValidCell(x, y) || !isEmptyCell(x, y));
field[y][x] = DOT_HUMAN;
}
private static boolean isValidCell(int x, int y) {
return x >= 0 && x < fieldSizeX && y >= 0 && y < fieldSizeY;
}
private static boolean isEmptyCell(int x, int y) {
return field[y][x] == DOT_EMPTY;
}
private static boolean isDraw() {
for (int i = 0; i < fieldSizeY; i++) {
for (int j = 0; j < fieldSizeX; j++) {
if (field[i][j] == DOT_EMPTY) return false;
}
}
return true;
}
public static void main(String[] args) {
// System.out.print("Enter size X and Y and windNumber:");//можно вводить ручками
// fieldSizeX=SCANNER.nextInt();
// fieldSizeY=SCANNER.nextInt();
// winNumber=SCANNER.nextInt();
initField();
showField();
while (true) {
humanTurn();
showField();
if (checkWin3(DOT_HUMAN, winNumber)) {
System.out.println("Human win!");
break;
}
if (isDraw()) {
System.out.println("Draw!");
break;
}
aiTurn();
System.out.println("step AI ------");
showField();
if (checkWin3(DOT_AI, winNumber)) {
System.out.println("Computer win!");
break;
}
if (isDraw()) {
System.out.println("Draw!");
break;
}
}
}
//проверка на выигрыш
private static boolean checkWin3(char c, int size) {
for (int i = 0; i < fieldSizeY; i++) {
for (int j = 0; j < fieldSizeX; j++) {
if (chDown(c, i, j, size) || chRight(c, i, j, size) || chFDiag(c, i, j, size) || chSDiag(c, i, j, size))
return true;
}
}
return false;
}
// проверка от исх точки на size значений вниз
/*если координаты удовлетворяют проверке, не выходя за границы, то проверяем по соотв направлению.
* в счетчик закидываем кол-во клеточек с заданным символом.
* если символ не совпадает- запоминаем коорд
* в случае кода колво симовлов совпадает с колвом клеток- выиграли,
* в случае если не хватате одного символа- проверяем его на пустую клетку и если тру- запоминаем глобальными
* приходится проверять каждую сторону по отдельности, поскольку сразу передаем координаты
* если делаю один цикл прохода от точки в ширину по всем направлениям сразу, то выигрыш определитьь можно,
* а каким образом вытащить координаты пустой клетки- не догадываюсь((
* */
private static boolean chDown(char c, int x, int y, int size) {
if (x <= fieldSizeY - size) {//проверка на выход за пределы
int numbchek = 0;//сколько символов
int t_x = x, t_y = y;//временные переменные для координат
for (int i = 0; i < size; i++) {
if (field[x + i][y] == c) {
numbchek++;
} else {//
t_x = x + i;
t_y = y;
}
}
if (numbchek == size) return true;
else if ((numbchek == size - 1) && isEmptyCell(t_y, t_x)) {// если не хватает одного хода и его можно сделать
xStep = t_x;
yStep = t_y;
}
}
return false;
}
//проверка от исх точки на size значений вправо
private static boolean chRight(char c, int x, int y, int size) {
if (y <= fieldSizeX - size) {
int numbchek = 0;
int t_x = x, t_y = y;
for (int i = 0; i < size; i++) {
if (field[x][y + i] == c) {
numbchek++;
} else {
t_x = x;
t_y = y + i;
}
}
if (numbchek == size) return true;
else if ((numbchek == size - 1) && isEmptyCell(t_y, t_x)) {
xStep = t_x;
yStep = t_y;
}
}
return false;
}
//проверка от исх точки на size значений по диагонали вправо-вниз
private static boolean chFDiag(char c, int x, int y, int size) {
if ((x <= fieldSizeY - size) && (y <= fieldSizeX - size)) {
int numbchek = 0;
int t_x = x, t_y = y;
for (int i = 0; i < size; i++) {
if (field[x + i][y + i] == c) {
numbchek++;
} else {
t_x = x + i;
t_y = y + i;
}
}
if (numbchek == size) return true;
else if ((numbchek == size - 1) && isEmptyCell(t_y, t_x)) {
xStep = t_x;
yStep = t_y;
}
}
return false;
}
//проверка от исх точки на size значений по диагонали вправо-вверх
private static boolean chSDiag(char c, int x, int y, int size) {
if ((x >= size - 1) && (y <= fieldSizeX - size)) {
int numbchek = 0;
int t_x = x, t_y = y;
for (int i = 0; i < size; i++) {
if (field[x - i][y + i] == c) {
numbchek++;
} else {
t_x = x - i;
t_y = y + i;
}
}
if (numbchek == size) return true;
else if ((numbchek == size - 1) && isEmptyCell(t_y, t_x)) {
xStep = t_x;
yStep = t_y;
}
}
return false;
}
private static void aiTurn() {
int x, y;
if (!checkWin3(DOT_AI, winNumber)) //ищем таким образом выигрышные координаты
field[xStep][yStep] = DOT_AI;
else {
if (!checkWin3(DOT_HUMAN, winNumber)) //ищем координаты помехи
field[xStep][yStep] = DOT_AI;
else {
do {
x = RANDOM.nextInt(fieldSizeX);
y = RANDOM.nextInt(fieldSizeY);
} while (!isEmptyCell(x, y));
field[y][x] = DOT_AI;
}
}
}
}
|
Shell
|
UTF-8
| 605 | 3.15625 | 3 |
[] |
no_license
|
# Build container
echo "Building docker container"
docker build -t todo-frontend .
# Update local registry
echo "Tagging container for update to registry"
docker tag todo-frontend 192.168.1.41:25129/todo-frontend:latest
echo "Pushing container to registry"
docker push 192.168.1.41:25129/todo-frontend:latest
if [ -z $1 ]
then
echo "Provide a version #"
else
# Update local registry
echo "Tagging container for update to registry"
docker tag todo-frontend 192.168.1.41:25129/todo-frontend:$1
echo "Pushing container to registry"
docker push 192.168.1.41:25129/todo-frontend:$1
fi
|
C++
|
UTF-8
| 387 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
int max (int a, int b)
{
std::cout<<"int function"<< std::endl;
if(a>b)
return a;
else
return b;
}
short max (short a, short b)
{
std::cout<<"short function"<< std::endl;
if(a>b)
return a;
else
return b;
}
int main(int argc, char const *argv[]) {
short a = 1, b = 29, result;
result = max(a,b);
std::cout<<result<<std::endl;
}
|
C
|
UTF-8
| 2,488 | 2.71875 | 3 |
[] |
no_license
|
/******************************************************************************
* @File: main.c
* @Author: Milandr, L.
* @Project: #15.1_CAN_[Simple_Exchange]
* @Version: 1.0.1
* @Compiler: ARM Compiler V5.06 (build 750)
* @Microcontroller: К1986ВЕ92QI
* @Device: Отладочная плата «МилКиТЭС»
* @Date: 07.05.2020
* @Purpose: Основной модуль
* @Description:
* В данном проекте реализована работа CAN в режиме самотестирования. Передача
* кадра производится по нажатию кнопки. Принятый кадр отображается на дисплей.
******************************************************************************/
// Подключение заголовка
#include "main.h"
// Основная функция
int main(void)
{
// Общая инициализация
CPU_Init(); // Система тактирования
TICK_Init(); // Системный таймер
BTN_Init(); // Кнопки
LCD_Init(); // ЖК-дисплей
// Инициализация CAN
CAN_Init();
// Инициализация переменных
frame_t rx_frame = {0};
frame_t tx_frame = {0};
// Формирование кадра
tx_frame.id = 123;
tx_frame.datal = 256;
tx_frame.datah = 0;
// Отображение пустого кадра
CAN_PrintFrame(rx_frame);
// Основной цикл (пустой)
while (true) {
// Блок работы с передатчиком
if (Wait(&mark[0], 100) == true) {
// Обработка кнопки MID
if (BTN_Handler(BTN_M) == true) {
// Передача кадра
CAN_SendFrame(tx_frame, TX_BUF);
// Изменение данных кадра
tx_frame.datal <<= 1;
}
}
// Блок работы с приёмником
if (Wait(&mark[1], 5) == true) {
// Если флаг приёма кадра установлен...
if (flg_frm_rcvd == true) {
// Сброс флага приёма кадра
flg_frm_rcvd = false;
// Извлечение кадра из буфера
rx_frame = CAN_ExtractFrame(RX_BUF);
// Отображение содержания кадра
CAN_PrintFrame(rx_frame);
}
}
}
}
|
Markdown
|
UTF-8
| 8,438 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
---
lang: zh
title: "控制器(Controllers)"
keywords: LoopBack 4.0, LoopBack 4
sidebar: zh_lb4_sidebar
permalink: /doc/zh/lb4/Controllers.html
layout: translation
---
## 总览
控制器(`Controller`)是一个用于实现应用 API 定义的操作的类。它实现一个应用的业务逻辑, 它实现了一个应用的业务逻辑,并作为“HTTP / REST API”和“域 / 数据库模型”之间的桥梁。
添加修饰符到`Controller`类及其成员,可以映射应用的 API 操作到对应的 Controller(控制器)操作。
控制器(`Controller`)仅对“已处理的输入”和“后端服务/数据库”的抽象进行操作。
本页面仅涵盖用于 REST API 的控制器(`Controller`)。
## 操作(Operations)
在[路由(Routes)](Routes.md)示例的操作(Operation)中,`greet()`操作被定义为一个普通的 JavaScript 函数。The
```ts
// 普通函数Operation
function greet(name: string) {
return `hello ${name}`;
}
// 控制器方法Operation
class MyController {
greet(name: string) {
return `hello ${name}`;
}
}
```
## 路由到控制器(Controller)
下面的示例是一个基本的 API 规范。这是一个[操作对象(Operation Object)](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operationObject).
```ts
const spec = {
parameters: [{ name: "name", schema: { type: "string" }, in: "query" }],
responses: {
"200": {
description: "greeting text",
content: {
"application/json": {
schema: { type: "string" }
}
}
}
}
};
```
定义路由(`Routes`)到控制器(Controller)方法,有数种方式。
第一个示例是普通地定义路由到控制器方法:
```ts
// ... 在你的application构造函数中
this.route("get", "/greet", spec, MyController, "greet");
```
修饰符允许你使用路由元数据描述你的控制器方法,然后 LoopBack 可以替你调用`app.route()`函数。
```ts
import { get } from "@loopback/rest";
class MyController {
@get("/greet", spec)
greet(name: string) {
return `hello ${name}`;
}
}
// ... 在你的application构造函数中
this.controller(MyController);
```
## 指明控制器(Controller)的 API
大型的 LoopBack 应用中,你可以使用 OpenAPI 规范来组织你的路由。
`@api`修饰符会取得一个类型为`ControllerSpec`,包含`basePath`字符串和[Paths Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#paths-object)的规范。
注意,这*不是*一个完整的[OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oasObject)规范。
```ts
// ... 在你的application构造函数中
this.api({
openapi: "3.0.0",
info: {
title: "Hello World App",
version: "1.0.0"
},
paths: {
"/greet": {
get: {
"x-operation-name": "greet",
"x-controller-name": "MyController",
parameters: [{ name: "name", schema: { type: "string" }, in: "query" }],
responses: {
"200": {
description: "greeting text",
content: {
"application/json": {
schema: { type: "string" }
}
}
}
}
}
}
}
});
this.controller(MyController);
```
`@api`修饰符允许你使用一个规范来描述你的 Controller(控制器),然后 LoopBack 可以替你调用`app.api()` 函数。
```ts
@api({
openapi: "3.0.0",
info: {
title: "Hello World App",
version: "1.0.0"
},
paths: {
"/greet": {
get: {
"x-operation-name": "greet",
"x-controller-name": "MyController",
parameters: [{ name: "name", schema: { type: "string" }, in: "query" }],
responses: {
"200": {
description: "greeting text",
content: {
"application/json": {
schema: { type: "string" }
}
}
}
}
}
}
}
})
class MyController {
greet(name: string) {
return `hello ${name}`;
}
}
app.controller(MyController);
```
## 编写控制器(Controller)方法
下面是一个控制器(Controller)的示例,使用了数种内置的助手(修饰符)。
这些助手给了 LoopBack 关于控制器(Controller)方法的提示。
```ts
import { HelloRepository } from "../repositories";
import { HelloMessage } from "../models";
import { get, param } from "@loopback/rest";
import { repository } from "@loopback/repository";
export class HelloController {
constructor(
@repository(HelloRepository) protected repository: HelloRepository
) {}
// 返回我们的对象的列表
@get("/messages")
async list(@param.query.number("limit") limit = 10): Promise<HelloMessage[]> {
if (limit > 100) limit = 100; // 我们的逻辑
return this.repository.find({ limit }); // 来自我们的存储库的CRUD方法
}
}
```
- `HelloRepository`扩展自`Repository`(存储库),这是 LoopBack 的一个数据库抽象。
查阅[存储库(Repositories)](./Repositories.md) 获得更多信息。
- `HelloMessage` 返回一个随意的对象的`list`列表。
- `@get('/messages')`为 OpenAPI 规范自动创建[Paths Item Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#path-item-object),同时也处理请求路由。
- `@param.query.number`指明了此规范的路由接受一个参数,此参数通过 Query(查询)传递,并且为一个数字。
## 在控制器(Controller)中处理错误
为了控制器(Controller)方法抛出异常,需要用到`HttpErrors`类。`HttpErrors`导出自
[http-errors](https://www.npmjs.com/package/http-errors),包含在`@loopback/rest` 包中。
Listed below are some of the most common error codes. The full list of supported
codes is found
[here](https://github.com/jshttp/http-errors#list-of-all-constructors).
| Status Code(状态码) | 错误 | 描述 |
| --------------------- | ------------------- | -------------- |
| 400 | BadRequest | 错误请求 |
| 401 | Unauthorized | 未授权 |
| 403 | Forbidden | 被禁止 |
| 404 | NotFound | 未找到 |
| 500 | InternalServerError | 内部服务器错误 |
| 502 | BadGateway | 错误网关 |
| 503 | ServiceUnavailable | 服务不可用 |
| 504 | GatewayTimeout | 网关超时 |
下列示例展示了上述示例带有`HttpErrors`的改版,并附加了一个测试,以验证错误能够被确实地抛出。
{% include code-caption.html content="src/__tests__/integration/controllers/hello.controller.integration.ts" %}
```ts
import { HelloController } from "../../../controllers";
import { HelloRepository } from "../../../repositories";
import { testdb } from "../../fixtures/datasources/testdb.datasource";
import { expect } from "@loopback/testlab";
import { HttpErrors } from "@loopback/rest";
const HttpError = HttpErrors.HttpError;
describe("Hello Controller", () => {
it("returns 422 Unprocessable Entity for non-positive limit", () => {
const repo = new HelloRepository(testdb);
const controller = new HelloController(repo);
return expect(controller.list(0.4)).to.be.rejectedWith(HttpError, {
message: "limit is non-positive",
statusCode: 422
});
});
});
```
{% include code-caption.html content="src/controllers/hello.controller.ts" %}
```ts
import { HelloRepository } from "../repositories";
import { HelloMessage } from "../models";
import { get, param, HttpErrors } from "@loopback/rest";
import { repository } from "@loopback/repository";
export class HelloController {
constructor(@repository(HelloRepository) protected repo: HelloRepository) {}
// returns a list of our objects
@get("/messages")
async list(@param.query.number("limit") limit = 10): Promise<HelloMessage[]> {
// throw an error when the parameter is not a non-positive integer
if (!Number.isInteger(limit) || limit < 1) {
throw new HttpErrors.UnprocessableEntity("limit is non-positive");
} else if (limit > 100) {
limit = 100;
}
return this.repo.find({ limit });
}
}
```
|
Markdown
|
UTF-8
| 1,827 | 3.96875 | 4 |
[
"MIT"
] |
permissive
|
# 80. Median
**Description**
Given a unsorted array with integers, find the `median` of it.
A median is the middle number of the array after it is sorted.
If there are even numbers in the array, return the `N/2-th` number after sorted.
> The size of array is not exceed `10000`
**Example**
Example 1:
```
Input: [4, 5, 1, 2, 3]
Output: 3
Explanation:
After sorting, [1,2,3,4,5], the middle number is 3
```
Example 2:
```
Input: [7, 9, 4, 5]
Output: 5
Explanation:
After sorting,[4,5,7,9], the second(4/2) number is 5
```
**Challenge**
`O(n)` time.
**Quick Sort**
考点:
区间第 `k` 大元素的查找
题解:
Quick Select 算法, 基于快排的分治思想, 递归实现, 从而复杂度接近 `O(n)`
```python
class Solution:
"""
@param nums: A list of integers
@return: An integer denotes the middle number of the array
"""
def median(self, nums):
# write your code here
if not nums or len(nums) == 0:
return
return self.sortQuick(nums, 0, len(nums) - 1, (len(nums) + 1) // 2)
def sortQuick(self, nums, start, end, k):
if start == end:
return nums[start]
left, right = start, end
pivot = nums[left + (right - left) // 2]
while left <= right:
while left <= right and nums[left] < pivot:
left += 1
while left <= right and nums[right] > pivot:
right -= 1
if left <= right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
if start + k - 1 <= right:
return self.sortQuick(nums, start, right, k)
if start + k - 1 >= left:
return self.sortQuick(nums, left, end, k - (left - start))
return nums[right + 1]
```
|
TypeScript
|
UTF-8
| 2,096 | 2.53125 | 3 |
[] |
no_license
|
import { Component, OnInit } from '@angular/core';
import { UserCommonService } from '../user-common.service';
import * as $ from "jquery";
/**
* @desc 修改用户个人密码
* @author lilong
* @date 2018-12-29
*/
@Component({
selector: 'app-user-repass',
templateUrl: './user-repass.component.html',
styleUrls: ['./user-repass.component.css']
})
export class UserRepassComponent implements OnInit {
/**
* 定义接收数据变量
*/
userRepass: any; // 会员信息数据
constructor(
private userCommon: UserCommonService // 引入UserCommonService服务
) { }
ngOnInit() {
this.userInfo(); // 初始化用户信息
}
/**
* 显示会员信息
*/
userInfo() {
// 访问userInfoService请求方法
this.userCommon.userInfoService()
.subscribe((response: any) => {
if (response.code === 200 || response.ok) { // 判断是否正确取得数据
this.userRepass = response; // 获取的数据赋值给定义变量userRepass
console.log(response);
} else { // 没有正确取到值
alert(response.message); // 从后台报错误信息
return false; // 不跳转页面
}
})
}
/**
* 修改密码
* @param oldPassword 旧密码
* @param newpassword 新密码
* @param sureNewPassWord 确认密码
*/
repass(oldPassword, newpassword, sureNewPassWord) {
// 赋值成json数据
const data = {
'oldPassword': oldPassword,
'newPassword': newpassword,
'sureNewPassword': sureNewPassWord
};
// 访问userRepassService请求方法
this.userCommon.userRepassService(data)
.subscribe((response: any) => {
if (response.code === 200 || response.ok) { // 判断是否正确取得数据
alert('修改成功');
} else { // 没有正确取到值
alert(response.message); // 从后台报错误信息
return false; // 不跳转页面
}
})
}
/**
* 重置事件
*/
reset() {
// 密码
$('input[type="password"]').prop('value', '');
}
}
|
Java
|
UTF-8
| 2,787 | 2.6875 | 3 |
[] |
no_license
|
package com.frca.passmgr.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.HashMap;
import java.util.Map;
public class DbVariables
{
// Database fields
private SQLiteDatabase database;
private SqlLiteHelper dbHelper;
private Map<String, String> values;
public DbVariables(Context context)
{
dbHelper = new SqlLiteHelper(context);
values = new HashMap<String, String>();
}
public void open() throws SQLException
{
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public String getVariable(String key)
{
// if loaded to locale map return its content
if (values.containsKey(key))
return (String)values.get(key);
// otherwise load from DB
Cursor cur = database.query(SqlLiteHelper.TABLE_VARIABLES, new String[] {SqlLiteHelper.VARIABLES_VALUE}, SqlLiteHelper.VARIABLES_KEY + " = \"" + key + "\"", null, null, null, null);
if (!cur.moveToFirst() || cur.getString(0) == null ||cur.getString(0).equals(""))
return null;
String value = cur.getString(0);
values.put(key, value);
return value;
}
public int getIntVariable(String key)
{
String strVar = getVariable(key);
try
{
return Integer.parseInt(strVar);
}
catch (Exception e)
{
System.err.println(e.getMessage());
return 0;
}
}
public float getFloatVariable(String key)
{
String strVar = getVariable(key);
try
{
return Float.parseFloat(strVar);
}
catch (Exception e)
{
System.err.println(e.getMessage());
return 0;
}
}
public void setVariable(String key, String value)
{
// save in locale map
values.put(key, value);
// save in DB
ContentValues data = new ContentValues();
data.put(SqlLiteHelper.VARIABLES_KEY, key);
data.put(SqlLiteHelper.VARIABLES_VALUE, value);
database.replace(SqlLiteHelper.TABLE_VARIABLES, null, data);
}
public void setVariable(String key, int value)
{
setVariable(key, Integer.toString(value));
}
public void setVariable(String key, float value)
{
setVariable(key, Float.toString(value));
}
public void deleteVariable(String key)
{
values.remove(key);
database.delete(SqlLiteHelper.TABLE_VARIABLES, SqlLiteHelper.VARIABLES_KEY + " = \"" + key + "\"", null);
}
}
|
TypeScript
|
UTF-8
| 331 | 2.59375 | 3 |
[] |
no_license
|
export default class Communicator {
private ws: WebSocket;
constructor(destination: string, port: number) {
this.ws = new WebSocket(`ws://${destination}:${port}`)
}
send(data: any) {
this.ws.send(JSON.stringify(data))
}
onRecieve(lambda: any) {
this.ws.onmessage = lambda
}
}
|
Python
|
UTF-8
| 5,551 | 2.984375 | 3 |
[] |
no_license
|
class BaseStream:
"""
The parent class for all Streams.
Describes attributes about Stream such as size, resolution, and type
"""
def __init__(self, original_size=None, resolution=None, series_type=None):
"""
:param original_size: The number of data points in the stream
:type original_size: int
:param resolution: Level of detail (sampling) for the stream.
May be of types: [low, medium, high]
:type resolution: string
:param series_type: Base series used in case stream was downsampled.
May be of type: [distance, time]
:type series_type: string
"""
pass
self.original_size = original_size
self.resolution = resolution
self.series_type = series_type
def __repr__(self):
# There is no reasonable way to represent the data
return f"{self.__class__.__name__}(original_size={self.original_size}, resolution='{self.resolution}', series_type='{self.series_type}')"
class StreamSet:
pass
class AltitudeStream(BaseStream):
"""
An array of data that shows the altitude at each recorded point
"""
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class CadenceStream(BaseStream):
"""
An array of data that shows the pedal cadence at each recorded point
"""
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class DistanceStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class HeartrateStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class LatLngStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class MovingStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class PowerStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class SmoothGradeStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class SmoothVelocityStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class TemperatureStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
class TimeStream(BaseStream):
def __init__(self, data=None, *args, **kwargs):
"""
Look to BaseStream docs for other parameters
:param data: The data recorded at each point
:type data: list
"""
super().__init__(*args, **kwargs)
self.data = data
def __repr__(self):
return super().__repr__()
|
Java
|
UTF-8
| 1,270 | 2.234375 | 2 |
[] |
no_license
|
package com.quiz.resources;
import com.quiz.model.WordList;
import com.quiz.model.beans.RestDataMessage;
import com.quiz.model.beans.RestMessage;
import com.quiz.service.WordListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ashitosh on 10/05/18.
*/
@RestController
@RequestMapping("/api/lists")
public class ListResource {
@Autowired
WordListService wordListServiceImpl;
@RequestMapping
public RestMessage<List<WordList>> getWordLists(){
List<WordList> list = new ArrayList<>();
for(WordList wordList : wordListServiceImpl.getWordLists()){
list.add(wordList);
}
return new RestDataMessage<>(list);
}
@RequestMapping(method = RequestMethod.POST)
public RestMessage<WordList> saveWordList(@RequestBody WordList wordList){
WordList response = wordListServiceImpl.saveWordList(wordList);
return new RestDataMessage<>(response);
}
}
|
Java
|
UTF-8
| 637 | 1.851563 | 2 |
[] |
no_license
|
package cloud.servicefeign.feign;
import cloud.servicefeign.HelloWorldServiceFailure;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Author :zhouxiwang
* @Description:
* @Date: 12:54 2019/4/1
* @Modified by:
*/
@FeignClient(value = "CONFIG-CLIENT" , fallback = HelloWorldServiceFailure.class)
public interface HelloWorldService {
@RequestMapping(value = "/",method = RequestMethod.GET)
String home();
}
|
Ruby
|
UTF-8
| 128 | 3.09375 | 3 |
[] |
no_license
|
arr = [ 1, 2, 3, "Hello", true, [], 0.5, 4 ]
arr.each do |num|
if num.is_a?(Integer)
p num ** 2
else
next
end
end
|
Python
|
UTF-8
| 2,536 | 3.171875 | 3 |
[] |
no_license
|
import math
from collections import deque
'''
다시 풀어보기
'''
def solution(board):
def bfs(start):
# table[y][x] = 해당 위치에 도달하는 최솟값.
table = [[math.inf for _ in range(len(board))] for _ in range(len(board))]
# 진행 방향. 위 - 0, 왼쪽 - 1, 아래 = 2, 오른쪽 = 3
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
queue = deque([start])
# 처음 위치의 비용 = 0
table[0][0] = 0
while queue:
# y좌표, x좌표, 비용, 진행방향
y, x, cost, head = queue.popleft()
for idx, (dy, dx) in enumerate(dirs):
ny, nx = y + dy, x + dx
# 진행방향과 다음 방향이 일치하면 + 100, 다르면 전환비용 500 + 진행비용 100 = 600
n_cost = cost + 600 if idx != head else cost + 100
# board[y][x] == 0 : 진행방향에 벽이 없음. table[ny][nx] > n_cost : 다음 좌표의 최솟값보다 진행방향 비용이 작을 경우
if 0 <= ny < len(board) and 0 <= nx < len(board) and board[ny][nx] == 0 and table[ny][nx] > n_cost:
# table 좌표 업데이트.
table[ny][nx] = n_cost
queue.append((ny, nx, n_cost, idx))
return table[-1][-1]
return min(bfs((0, 0, 0, 2)), bfs((0, 0, 0, 3)))
# dx = [-1, 1, 0, 0]
# dy = [0, 0, -1, 1]
# brd = []
# n = 0
# min_cost = 1e9
# visited = []
#
#
# def dfs(px, py, x, y, cost):
# global min_cost
# if visited[x][y] == -1:
# visited[x][y] = cost
# elif visited[x][y] < cost:
# return visited[x][y]
#
# mn = visited[x][y]
# if x == n - 1 and y == n - 1:
# print("NUM")
# print(cost)
# min_cost = min(min_cost, cost)
# return min_cost
#
# for k in range(4):
# nx, ny = x + dx[k], y + dy[k]
# curr_cost = 100
# if nx < 0 or ny < 0 or nx >= n or ny >= n:
# continue
# if abs(px - nx) == 1 and abs(py - ny) == 1:
# curr_cost += 500
# print(curr_cost)
# mn = min(mn, dfs(x, y, nx, ny, cost + curr_cost))
# visited[x][y] = mn
# return mn
#
#
# def solution(board):
# global brd, n, visited
# answer = 0
# brd = board
# n = len(board)
# visited = [[-1] * n for _ in range(n)]
# dfs(0, 0, 0, 0, 0)
#
# return answer
#
#
# board = [[0, 0, 1, 0], [0, 0, 0, 0], [0, 1, 0, 1], [1, 0, 0, 0]]
# solution(board)
# print(min_cost)
|
Markdown
|
UTF-8
| 2,213 | 2.59375 | 3 |
[] |
no_license
|
---
layout: listing
title: Department of History, University of Chicago - Postdoc Fellowship in Digital History
link:
country: United States
subrEmail: jts@uchicago.edu
organization: Department of History, University of Chicago
date: 2008-02-15
closingDate:
jobTitle: Postdoc Fellowship in Digital History
published: false
postdate:
location:
name:
latitude:
longitude:
institution:
organization:
position:
---
# {{ page.title }}
## Description
<p>
Postdoc Fellowship in Digital History. The Department of History at the University of Chicago seeks applications and nominations for a two-year residential Mellon Postdoctoral Fellowship in digital history, beginning fall 2008 . The successful candidate will be expected to research how the proliferation of digital possibilities is changing the culture of historical inquiry and pedagogy. Areas of interest may include, for example, the provision of databases and search techniques (as in Google-type scanning projects), the use of digital media to convey aspects of cultural knowledge beyond the capability of the printed page, or the implications of global networking for the circulation and credibility of historiographical claims among new audiences. But the specific theme is open, and these are only three among a very wide range of possibilities. The appointment will be at the rank of instructor. The fellow will combine research, writing, and half-time teaching, with the opportunity to teach two one-quarter courses per year (one undergraduate and one graduate) about the possibilities and implications of new media for historical knowledge. Open to applicants who will have received the PhD within five academic years previous to the year of the award; persons holding tenure-track appointments are ineligible to apply. Applications include a c.v., a chapter length piece of writing and three letters of recommendation. Applications will be read as soon as they arrive. No electronic applications will be accepted. Please address all materials to: Mellon Postdoctoral Fellowship Search Committee, Dept of History, University of Chicago, 1126 East 59th Street, Chicago, IL 60637-1580. The University of Chicago is an AA/EOE
</p>
|
Python
|
UTF-8
| 569 | 2.859375 | 3 |
[] |
no_license
|
from functools import reduce
def solve():
N = int(input())
A = list(map(int,input().split()))
diffs_perm = []
dfs(list(),N,diffs_perm)
cnt = 0
for p in diffs_perm:
B = A[:]
for i in range(N):
B[i] += p[i]
if reduce(lambda a,b:a*b, B) % 2 == 0:
cnt += 1
print(cnt)
def dfs(diffs,N,res):
if len(diffs) == N:
res.append(diffs)
return
dfs(diffs[:]+[1],N,res)
dfs(diffs[:]+[0],N,res)
dfs(diffs[:]+[-1],N,res)
if __name__ == '__main__':
solve()
|
Java
|
UTF-8
| 3,267 | 2.125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.bytedance.boost_multidex;
import android.os.Looper;
import android.os.MessageQueue;
import android.util.Log;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by Xiaolin(xiaolin.gan@bytedance.com) on 2019/3/3.
*/
public class Monitor {
private static final boolean enableLog = true;
private static Monitor sMonitor;
private ScheduledExecutorService mExecutor = Executors.newScheduledThreadPool(1);
private String mProcessName;
static void init(Monitor monitor) {
sMonitor = monitor != null ? monitor : new Monitor();
}
static Monitor get() {
return sMonitor;
}
private ScheduledExecutorService getExecutor() {
return mExecutor;
}
String getProcessName() {
return mProcessName;
}
public Monitor setExecutor(ScheduledExecutorService executor) {
mExecutor = executor;
return this;
}
public Monitor setProcessName(String processName) {
mProcessName = processName;
return this;
}
protected void loadLibrary(String libName) {
System.loadLibrary(libName);
}
protected void logError(String msg) {
if (!enableLog) {
return;
}
Log.println(Log.ERROR, Constants.TAG, msg);
}
protected void logWarning(String msg) {
if (!enableLog) {
return;
}
Log.w(Constants.TAG, msg);
}
protected void logInfo(String msg) {
if (!enableLog) {
return;
}
// Log.println(Log.INFO, Constants.TAG, msg);
Log.i(Constants.TAG, msg);
}
protected void logDebug(String msg) {
if (!enableLog) {
return;
}
// Log.println(Log.DEBUG, Constants.TAG, msg);
Log.d(Constants.TAG, msg);
}
protected void logError(String msg, Throwable tr) {
if (!enableLog) {
return;
}
Log.e(Constants.TAG, msg, tr);
}
protected void logWarning(String msg, Throwable tr) {
if (!enableLog) {
return;
}
Log.w(Constants.TAG, msg, tr);
}
protected boolean isEnableNativeCheckSum() {
return true;
}
protected void logErrorAfterInstall(String msg, Throwable tr) {
Log.e(Constants.TAG, msg, tr);
}
protected void reportAfterInstall(long cost, long freeSpace, long reducedSpace, String dexHolderInfo) {
Log.println(Log.INFO, Constants.TAG, "Cost time: " + cost + ", free space: " + freeSpace
+ ", reduced space: " + reducedSpace + ", holder: " + dexHolderInfo);
}
protected void doBeforeHandleOpt() {
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void doAfterInstall(final Runnable optRunnable) {
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
getExecutor().schedule(optRunnable, 5_000, TimeUnit.MILLISECONDS);
return false;
}
});
}
}
|
Java
|
UTF-8
| 8,367 | 1.9375 | 2 |
[] |
no_license
|
package YouTube.MailNotify;
import DiscordBot.Settings.Settings;
import DiscordBot.Settings.YouTubeSubscribeItem;
import com.sun.mail.imap.IMAPFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sx.blah.discord.handle.obj.IGuild;
import javax.mail.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Subscriber {
private static final Logger log = LoggerFactory.getLogger(Subscriber.class);
private static List<SubscribItem> subscribItems = new ArrayList<>();
private MessageIncomingListener listener;
private static final String regexp = "(?i)\\b(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\\.?)(?::\\d{2,5})?(?:[/?#]\\S*)?\\b";
private static final Pattern pattern = Pattern.compile(regexp);
private Folder inbox;
private Store store;
private KeepAliveRunnable runnable;
public Subscriber()
{
Properties properties = System.getProperties();
properties.put("mail.debug" , "false" );
properties.put("mail.store.protocol" , "imaps" );
properties.put("mail.imap.ssl.enable" , "true" );
properties.put("mail.imap.port" , Settings.body.IMAP_Port);
//properties.put("mail.imaps.usesocketchannels", "true");
Authenticator auth = new EmailAuthenticator(Settings.body.IMAP_AUTH_EMAIL,
Settings.body.IMAP_AUTH_PWD);
Session session = Session.getInstance(properties, auth);
session.setDebug(false);
listener = new MessageIncomingListener();
try {
store = session.getStore();
log.info("store and folder connect");
storeConnect();
Thread t = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
log.info("start idle");
((IMAPFolder) inbox).idle();
} catch (StoreClosedException e){
log.info("store reconnect");
storeConnect();
} catch (FolderClosedException e) {
log.info("folder reconnect");
folderConnect();
} catch (MessagingException e) {
log.error("MessagingException",e);
} catch (IllegalStateException e){
log.error("IllegalStateException",e);
storeConnect();
} catch (Exception e) {
log.error("Exception",e);
}
}
log.info("thread IdleDoing stopped");
}, "IdleDoing");
t.start();
}
catch (MessagingException e) {
log.error("MessagingException",e);
}
}
private void folderConnect()
{
try {
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
inbox.addMessageCountListener(listener);
if (runnable != null){
runnable.setFolder((IMAPFolder) inbox);
} else {
runnable = new KeepAliveRunnable((IMAPFolder) inbox);
Thread t1 = new Thread(runnable, "NoopPolling");
t1.start();
}
} catch (Exception ex) {
log.error("Exception", ex);
}
}
private void storeConnect()
{
try {
store.connect(Settings.body.IMAP_Server, Settings.body.IMAP_AUTH_EMAIL, Settings.body.IMAP_AUTH_PWD);
if (inbox != null && inbox.isOpen())
inbox.close();
folderConnect();
} catch (Exception ex) {
log.error("Exception",ex);
}
}
private static class KeepAliveRunnable implements Runnable {
private static final long KEEP_ALIVE_FREQ = 300000; // 5 minutes
private IMAPFolder folder;
KeepAliveRunnable(IMAPFolder folder) {
this.folder = folder;
}
void setFolder(IMAPFolder folder){
this.folder = folder;
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(KEEP_ALIVE_FREQ);
// Perform a NOOP just to keep alive the connection
log.info("Performing a NOOP to keep alive the connection");
folder.doCommand(p -> {
p.simpleCommand("NOOP", null);
return null;
});
} catch (InterruptedException e) {
// Ignore, just aborting the thread...
} catch (MessagingException e) {
// Shouldn't really happen...
log.warn("Unexpected exception while keeping alive the IDLE connection", e);
}
}
log.info("thread NoopPolling stopped");
}
}
static void parseNewMessage(String message)
{
Matcher matcher = pattern.matcher(message);
while (matcher.find())
{
//http://www.youtube.com/watch?v=teXOCKK88-4&feature=em-uploademail
log.info("link - " + message.substring(matcher.start(),matcher.end()));
Map<String,String> param = queryToMap(message.substring(matcher.start(),matcher.end()));
if(!param.containsKey("feature") || !param.containsKey("v"))
continue;
if(!param.get("feature").equals("em-lbcastemail") && !param.get("feature").equals("em-uploademail"))
continue;
try {
YouTubeVideo video = YouTubeAPI.getVideoByID(param.get("v"));
for(SubscribItem item : subscribItems) {
if(!item.isYtChannelContains(video.snippet.channelId))
continue;
if (param.get("feature").equals("em-lbcastemail")) {
log.info("live channel " + video.snippet.channelTitle);
item.getChannel().sendMessage("@everyone, " + video.snippet.channelTitle + " начал стримить!",MessageBuilder.chanIsLive(video));
} else {
log.info("new video on channel " + video.snippet.channelTitle);
item.getChannel().sendMessage("@everyone, новое видео на канале " + video.snippet.channelTitle,MessageBuilder.newVideoOnChan(video));
}
}
} catch (Exception e)
{
log.error("error with parsing ",e);
}
}
}
public void addGuild(IGuild guild)
{
for(SubscribItem subscribItem: subscribItems)
{
if(subscribItem.getGuild().equals(guild))
{
return;
}
}
for(YouTubeSubscribeItem settingsItem: Settings.body.youTubeSubscribeItemList)
{
if(settingsItem.guild == guild.getLongID() && guild.getChannelByID(settingsItem.channel) != null)
{
SubscribItem item = new SubscribItem(guild,guild.getChannelByID(settingsItem.channel), settingsItem.ytChans);
subscribItems.add(item);
log.info("YT Subscribe settings for guild " + guild.getName() + " has been added");
}
}
}
private static Map<String, String> queryToMap(String query){
Map<String, String> result = new HashMap<>();
query = query.substring(1 + query.indexOf("?"));
for (String param : query.split("&")) {
String pair[] = param.split("=");
if (pair.length>1) {
result.put(pair[0], pair[1]);
}else{
result.put(pair[0], "");
}
}
return result;
}
}
|
Java
|
UTF-8
| 434 | 3.203125 | 3 |
[] |
no_license
|
public class MathObjectExamples
{
public static void main(String[] args)
{
Integer y = new Integer(2);
Double d = new Double(-101.1);
double z = 25;
System.out.println(y.MAX_VALUE);
System.out.println(y);
System.out.println(Math.abs(d));
System.out.println(Math.pow(y, 3));
System.out.println(Math.sqrt(z));
// System.out.println(Math.random());
//How do we make random useful?
}
}
|
Swift
|
UTF-8
| 5,833 | 3.484375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
import RegexBuilder
public struct Predicate<Value> {
private let predicate: (Value) -> Bool
public init(_ predicate: @escaping (Value) -> Bool) {
self.predicate = predicate
}
public func callAsFunction(_ value: Value) -> Bool {
predicate(value)
}
}
extension Predicate {
public init(_ predicate: @escaping (Value) throws -> Bool) {
self.init { value in
do {
return try predicate(value)
} catch {
return false
}
}
}
}
// MARK: - Modifying Predicates
public func && <T>(lhs: Predicate<T>, rhs: Predicate<T>) -> Predicate<T> {
Predicate { value in lhs(value) && rhs(value) }
}
public func || <T>(lhs: Predicate<T>, rhs: Predicate<T>) -> Predicate<T> {
Predicate { value in lhs(value) || rhs(value) }
}
public prefix func ! <T>(predicate: Predicate<T>) -> Predicate<T> {
Predicate { value in !predicate(value) }
}
extension Sequence {
public func joined<T>(
operator: (Predicate<T>, Predicate<T>) -> Predicate<T>
) -> Predicate<T> where Element == Predicate<T> {
reduce(`operator`) ?? .true
}
}
// MARK: - Creating Predicates
extension Predicate {
/// A predicate that is always true.
public static var `true`: Predicate { Predicate { _ in true } }
/// A predicate that is always false.
public static var `false`: Predicate { Predicate { _ in false } }
}
extension Predicate where Value == Int {
/// Returns a predicate that checks that a value is greater than the given
/// value.
///
/// - Parameter value: The value to be greater than.
/// - Returns: A predicate used to check an `Int`.
public static func isGreaterThan(_ value: Int) -> Predicate {
Predicate { $0 > value }
}
/// Returns a predicate that checks that a value is less than the given
/// value.
///
/// - Parameter value: The value to be less than.
/// - Returns: A predicate used to check an `Int`.
public static func isLessThan(_ value: Int) -> Predicate {
Predicate { $0 < value }
}
}
extension Predicate where Value == String {
public static func hasPrefix(_ prefix: String) -> Predicate {
Predicate { $0.hasPrefix(prefix) }
}
public static func matches(
_ pattern: RegularExpression.Pattern
) -> Predicate {
guard let regex = try? RegularExpression(pattern: pattern) else {
return Predicate { _ in false }
}
return Predicate(regex.matches)
}
}
extension Predicate where Value == String {
public static func hasPrefix<Output>(_ regex: Regex<Output>) -> Predicate {
Predicate { try regex.prefixMatch(in: $0) != nil }
}
public static func hasPrefix(
@RegexComponentBuilder _ builder: () -> some RegexComponent
) -> Predicate {
.hasPrefix(Regex(builder))
}
public static func wholeMatch<Output>(_ regex: Regex<Output>) -> Predicate {
Predicate { try regex.wholeMatch(in: $0) != nil }
}
public static func wholeMatch(
@RegexComponentBuilder _ builder: () -> some RegexComponent
) -> Predicate {
.wholeMatch(Regex(builder))
}
}
extension Predicate where Value: Collection {
/// Returns a predicate that accepts a collection which checks that the
/// count is of the given length.
///
/// - Parameter count: The count to check.
/// - Returns: A predicate used to check a `Collection`.
public static func count(is count: Int) -> Self {
Predicate { $0.count == count }
}
}
extension Predicate { // Set Predicates
/// Returns a predicate that checks whether a set is a subset of the given
/// set.
/// - Parameter set: The set to check against.
/// - Returns: A predicate used to check a `Set<Element>`.
public static func isSubset<Element>(
of set: Set<Element>
) -> Self where Value == Set<Element> {
Predicate { $0.isSubset(of: set) }
}
/// Returns a predicate that checks whether a set is a superset of the given
/// set.
///
/// - Parameter set: The set to check against.
/// - Returns: A predicate used to check a `Set<Element>`.
public static func isSuperset<Element>(
of set: Set<Element>
) -> Self where Value == Set<Element> {
Predicate { $0.isSuperset(of: set) }
}
}
extension Predicate {
public static func isWithin<Range: RangeExpression>(
_ range: Range
) -> Predicate where Range.Bound == Value {
Predicate(range.contains)
}
}
extension Predicate where Value: Equatable {
public static func `is`(_ value: Value) -> Predicate {
Predicate { $0 == value }
}
public static func contained<Sequence>(in values: Sequence) -> Predicate where Sequence: Swift.Sequence, Sequence.Element == Value {
Predicate(values.contains)
}
}
// MARK: - Using Predicates
public func ~= <T>(predicate: Predicate<T>, value: T) -> Bool {
predicate(value)
}
extension Sequence {
public func allSatisfy(_ predicate: Predicate<Element>) -> Bool {
allSatisfy { predicate($0) }
}
public func count(where predicate: Predicate<Element>) -> Int {
count(where: { predicate($0) })
}
public func drop(while predicate: Predicate<Element>) -> DropWhileSequence<Self> {
drop(while: { predicate($0) })
}
public func filter(_ isIncluded: Predicate<Element>) -> [Element] {
filter { isIncluded($0) }
}
public func first(where predicate: Predicate<Element>) -> Element? {
first(where: { predicate($0) })
}
}
extension Collection {
public subscript(predicate: Predicate<Self.Element>) -> Element {
get throws { try first(where: predicate).unwrapped }
}
}
|
Markdown
|
UTF-8
| 9,264 | 3.046875 | 3 |
[] |
no_license
|
#Google Java Style
[参考文献](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html)
##源文件
文件名为它所包含的大小写敏感的顶级类名,后缀为.java,采用UTF-8编码。
- 空格:除了行结束符,空格字符只用0x20代表,这意味着:
1. 所有字符串中的空格符需要转义。
2. 制表符不用于缩进。
- 对特殊字符,采用转义字符(如\b, \t, \n, \f, \r, \", \' and \\),而不是相应的八进制(\012)或Unicode(\u000a)编码。
- 对非ASCII字符,是采用Unicode字符还是Unicode转义字符(适当的注释非常有用),取决于代码的可读性能否更好。
Example | Discussion
----|------
String unitAbbrev = "μs";|非常好: 非常清晰不需要注释
String unitAbbrev = "\u03bcs"; // "μs"|允许,但没必要这么做
String unitAbbrev = "\u03bcs"; // Greek letter mu, "s"|允许,但很奇怪且易错
String unitAbbrev = "\u03bcs";|差,读者不知道什么意思
return '\ufeff' + content; // byte order mark|好,为不可打印的字符使用转义,必要的注释
##源文件结构
- 组成顺序:(块间空一行)
- 许可或版权信息(如果有的话)
- 包名
- 同一语句不能换行
- import语句
- 不能使用通配符或静态导入
- 同一语句不能换行
- **分组规则:**
- 所有静态导入作为单独一组
- com.google导入
- 第三方导入,相同顶级包名的作为一组,按ASCII顺序排序,例如android, com, junit, org, sun
- java导入
- javax导入
- 组与组之间不空行
- 顶级类名
- 类声明
- 顶级类用单独一个文件保存
- 类成员的声明顺序对可读性有很大影响,在这里并没有一个唯一正确的方法,不同类的成员声明顺序可不同,但必须存在一定逻辑。例如新增加的方法未必要添加到类尾部,这会导致按照新增时间顺序声明的逻辑,而这种逻辑并没有意义。
- 多个构造函数或覆盖方法应该写在一起
##格式化
- 大括号
- 在if, else, for, do, while语句后必须加括号,即使括号中为空或只包含一条语句
- 遵循K & R风格
- {前不换行
- {后换行
- }前换行
- }后换行,但else或逗号后不换行
- 除了`if/else-if/else或try/catch/finally`等多区块语句,如果{}中为空则直接闭合,例如void doNothing() {}
Example:
return new MyClass() {
@Override public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
}
}
};
- 块缩进
- 新块开始都有两个空格的缩进。块结束时恢复到之前缩进等级。同一块内的代码和注释的缩进等级相同。
- 每句语句后面一个换行
- 列宽为160,超过的行将自动换行,除了以下情况:
- URL或JSNI方法等无法遵循该原则的行;
- package包名或import语句;
- 注释中的命令行将被拷贝到shell中执行的语句
- 换行规则
- 方法或构造函数与后面的(在一起,不换行
- 逗号,与前面的内容一起,不换行
- 如果换行,下一行比上一行缩进4空格
- 如果多个连续换行,行间缩进递增4空格。只有在每行都描述同一系列的元素时,才不递增缩进。
- 变量声明
- enum类型:如果不包含方法,则像声明数组一样声明enum。例如private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
- 每个变量声明一次,而不是一起声明,如int a, b
- 全局变量在类开始时声明。局部变量需要时才声明,而且尽快初始化。
- 数组初始化方式如下:
example:
new int[] { new int[] {
0, 1, 2, 3 0,
} 1,
2,
new int[] { 3,
0, 1, }
2, 3
} new int[]
{0, 1, 2, 3}
- 方括号在类型后面,而不是变量后面。例如String[] args, 而不是 String args[]
- switch
example:
switch (input) { //switch中的内容缩进2格
case 1:
case 2: //case中的内容缩进2格
prepareOneOrTwo();
// fall through //语句以break,continue,return或throw结束
case 3: //或者通过注释说明继续执行下一分支的原因
handleOneTwoOrThree();
break;
default: //switch中必须包含default分支,即使没有内容
handleLargeNumber(input); //最后分支的后面不需要注释
}
##命名
- 变量使用ASCII字符或数字,有效的命名必须符合\w+正则表达式。不使用像name_, mName, s_name, kName的前缀或后缀。
- 包名全部小写
- 类名采用`CamelCase`写法,由名词或名词短语组成;接口名由形容词或形容词短语组成;注释没有统一规则。测试类以测试类名开头,以Test结尾,例如`HashTest或HashIntegrationTest`.
- 方法名采用`lowerCamelCase`,由动词或动词短语组成。JUnit测试中方法名会采用下划线以区分不同逻辑,典型例子为`test<MethodUnderTest>_<state>`, 例如`testPop_emptyStack`,测试方法名没有统一规则。
- 常量成员变量名采用`CONSTANT_CASE`,全部大写,以下划线分割。常量是static final字段,但不是所有static final字段都是常量,
Example:
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};
- 非常量成员变量名采用`lowerCamelCase`
- 参数名词采用`lowerCamelCase`,避免单个字符
- 局部变量采用`lowerCamelCase`,可尽量简短,避免单个字符,除非循环变量或临时变量。即使为final可不可变的,局部变量也不认为是常量,不要加final static修饰。
- 泛型可采用两种方式命名:
- 单一大写字母,后面可跟一数字(例如E,T,X,T2)
- 类名后跟一大写T(例如RequestT,FooBarT)
- Camel case
- 第一步:将短语转成ASCII字符,去掉多余符号,例如Müller's algorithm转为Muellers algorithm
- 第二步:将结果按空格拆分成单词,例如AdWords变为ad words,但iOS不是在此列。
- 第三步:将每个单词的第一个字母大写,或除了第一个单词的其他单词的第一个字母大写
- 第四步:将得到的单词连接起来
Example:
Prose form|Correct|Incorrect
----|-----|-----
"XML HTTP request"| XmlHttpRequest| XMLHTTPRequest
"new customer ID"| newCustomerId| newCustomerID
"inner stopwatch"| innerStopwatch| innerStopWatch
"supports IPv6 on iOS?" | supportsIpv6OnIos| supportsIPv6OnIOS
"YouTube importer"| YouTubeImporter,YoutubeImporter*
##编程
- @Override不可忽略
- 总是捕获异常catch exception
确实没有必要在catch中执行操作时,需要写注释说明原因
try {
int i = Integer.parseInt(response);
return handleNumericResponse(i);
} catch (NumberFormatException ok) {
// it's not numeric; that's fine, just continue
}
return handleTextResponse(response);
catch中命名为expected时,不需要写注释
try {
emptyStack.pop();
fail();
} catch (NoSuchElementException expected) {
}
- 静态成员
通过类名访问,而不是通过引用
Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad
- Finalizers不要使用,很少需要覆盖Object.finalize方法,如果你有一定要这样做的理由,请先读并认真理解`Effective Java Item 7, "Avoid Finalizers," `,然后别这么做
##Javadoc
注释格式一般如下:
/**
* Multiple lines of Javadoc text are written here,
* wrapped normally...
*/
public int method(String p1) { ... }
简短格式如下:
/** An especially short bit of Javadoc. */
- 每个类或方法前有一段简短说明,由名词或动词组成,并未非完整句子。该说明非常重要,常作为搜索关键字。 Tip:Javadoc格式易写成`/** @return the customer ID */`,应该为`/** Returns the customer ID. */`。
- 注释的参数顺序为@param,@return,@throws,@deprecated,其值不能为空。一行无法写下时,换行起点为@后空四格。
- 公共类和公共或保护方法前加注释,除了以下情况
- 对简单方法例如getFoo,或单元测试方法前,方法名就能充分说明方法含义时。但对getCanonicalName方法,读者不知道cannonical name什么意思时,需要加注释
- 重载方法时不需要注释
- 包外部不可见的类或方法仍需要注释,当需要注释说明类或方法的目的或行为时,都需要注释。
|
C#
|
UTF-8
| 1,341 | 2.671875 | 3 |
[] |
no_license
|
using Microsoft.Xna.Framework.Graphics;
using MonoGameFrogger.Controllers;
using MonoGameFrogger.FSM;
using MonoGameFrogger.Models;
using MonoGameFrogger.Views;
namespace MonoGameFrogger.States
{
class GameOverState : BaseState
{
private SpriteBatch _spriteBatch;
private GameOverView _view;
private GameOverController _controller;
private GameOverModel _model;
public GameOverState(StateMachine stateMachine)
: base(stateMachine)
{
_spriteBatch = new SpriteBatch(StateMachine.Game.GraphicsDevice);
_view = new GameOverView(StateMachine.Game.Content, _spriteBatch);
_model = new GameOverModel();
_controller = new GameOverController(_model);
}
public override void Draw()
{
_spriteBatch.Begin();
_view.Draw();
_spriteBatch.End();
}
public override void Enter(params object[] args)
{
_model.PlayAgain = false;
}
public override void Exit()
{
}
public override void Update(float deltaTime)
{
_controller.Update(deltaTime);
if (_model.PlayAgain)
{
StateMachine.Change("game");
}
}
}
}
|
Java
|
UTF-8
| 502 | 1.84375 | 2 |
[] |
no_license
|
package com.zcpure.foreign.trade;
/**
* @author ethan
* @create_time 2018/10/23 16:29
*/
public class RequestThroughInfoContext {
private static ThreadLocal<RequestThroughInfo> threadInfo = new ThreadLocal<>();
public static String KEY_INFO_IN_HTTP_HEADER = "X-AUTO-FP-INFO";
public static RequestThroughInfo getInfo() {
return threadInfo.get();
}
public static void setInfo(RequestThroughInfo info) {
threadInfo.set(info);
}
public static void remove() {
threadInfo.remove();
}
}
|
Java
|
UTF-8
| 2,109 | 2.25 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.estiasi.restaurant.controller;
import com.estiasi.restaurant.model.Restaurant;
import com.estiasi.restaurant.service.RestaurantService;
import com.estiasi.restaurant.vo.RestaurantVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@Validated
@RestController
@RequestMapping("/v1/restaurants")
public class RestaurantController {
private final RestaurantService restaurantService;
@Autowired
public RestaurantController(RestaurantService restaurantService) {
this.restaurantService = restaurantService;
}
@GetMapping
public Restaurant findById(@RequestParam("id") Integer id) throws Exception {
return restaurantService.get(id);
}
@GetMapping("/name")
public List<Restaurant> findByName(@RequestParam("name") String name) throws Exception {
return restaurantService.get(name);
}
@GetMapping("/all")
public Iterable<Restaurant> getAll() throws Exception {
return restaurantService.getAll();
}
@PostMapping
public Restaurant createRestaurant(@RequestBody @Valid RestaurantVO restaurantVO) throws Exception {
Restaurant restaurant = new Restaurant();
BeanUtils.copyProperties(restaurantVO, restaurant);
return restaurantService.add(restaurant);
}
@PutMapping
public Restaurant updateRestaurant(@RequestBody @Valid RestaurantVO restaurantVO) throws Exception {
Restaurant restaurant = new Restaurant();
BeanUtils.copyProperties(restaurantVO, restaurant);
return restaurantService.update(restaurant);
}
@DeleteMapping
public ResponseEntity<Void> deleteRestaurant(@RequestParam("id") Integer id) throws Exception {
restaurantService.remove(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
JavaScript
|
UTF-8
| 560 | 2.828125 | 3 |
[] |
no_license
|
import { Coords } from "../world/Coords.js";
import { Grid } from "../world/Grid.js";
export class GridElement {
constructor(coords, grid) {
if(!(grid instanceof Grid)) throw new Error(`${grid} is not of type Grid`);
this.grid = grid;
this.setCoordinates(coords);
}
setCoordinates(coords) {
if(!(coords instanceof Coords)) {
Coords.notInstanceOfCoords(coords);
} else {
this.coords = coords;
}
this.grid.insertElement(this);
}
move(xDelta, yDelta) {
}
}
|
Java
|
UTF-8
| 337 | 2.140625 | 2 |
[] |
no_license
|
package com.nahidstudio.cashmafia.Models;
public class DailyChecking {
private String date;
public DailyChecking() {
}
public DailyChecking(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
|
Java
|
UTF-8
| 1,860 | 1.726563 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
*
* Copyright (c) 2013-2021, Alibaba Group Holding Limited;
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.aliyun.polardbx.binlog.cdc.topology;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.util.List;
/**
*
*/
@Data
@AllArgsConstructor
@Builder
public class LogicMetaTopology {
private List<LogicDbTopology> logicDbMetas;
public void add(LogicDbTopology logicDbMeta) {
logicDbMetas.add(logicDbMeta);
}
@Data
public static class LogicDbTopology {
private String schema;
private String charset;
private List<PhyDbTopology> phySchemas;
private List<LogicTableMetaTopology> logicTableMetas;
}
@Data
public static class LogicTableMetaTopology {
private String tableName;
private String tableCollation;
private int tableType;
private String createSql;
private List<PhyTableTopology> phySchemas;
}
@Data
public static class PhyDbTopology {
private String storageInstId;
private String group;
private String schema;
}
@Data
public static class PhyTableTopology extends PhyDbTopology {
private List<String> phyTables;
}
public List<LogicDbTopology> getLogicDbMetas() {
return logicDbMetas;
}
}
|
Python
|
UTF-8
| 961 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
import os
from PIL import Image
im=Image.open("nb.png","r")
pix=im.load()
column,line=im.size
big_array=[[] for b in range(line)]
for i in range(line):
for j in range(column):
value=pix[j,i]
if value[:3]==(0,255,0):
big_array[i].append("grass")
elif value[:3]==(150,75,0):
big_array[i].append("tree")
elif value[:3]==(0,0,255):
big_array[i].append("water")
elif value[:3]==(0,0,0):
big_array[i].append("wall")
else:
print("Error at "+str(i)+" "+str(j))
im.close()
name_file=str(input("Give the name of the file you want to create: "))
pawns=str(input("Give the configuration of up to 9 pawns: "))
fil = open(name_file+".txt","w")
fil.write("COLUMN="+str(column)+",LINE="+str(line)+"\n")
fil.write(pawns+",\n")
for i in range(line):
for j in range(column):
fil.write(big_array[i][j]+",")
fil.write("\n")
print("Done.")
fil.close()
|
Java
|
UTF-8
| 735 | 2.40625 | 2 |
[
"BSD-2-Clause"
] |
permissive
|
package com.weisong.common.vodo;
abstract public class WithVocoLevel {
final protected VoDoUtil voDoUtil;
final protected int vocoLevel;
abstract public void doExecute() throws Exception;
public WithVocoLevel(VoDoUtil voDoUtil, int vocoLevel) throws Exception {
this.voDoUtil = voDoUtil;
this.vocoLevel = vocoLevel;
execute();
}
private void execute() throws Exception {
VoDoUtil.Settings settings = voDoUtil.getPerThreadSettings();
int oldValue = settings.getVocoLevel();
try {
settings.setVocoLevel(vocoLevel);
doExecute();
}
finally {
settings.setVocoLevel(oldValue);
}
}
}
|
Markdown
|
UTF-8
| 13,493 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Selections
A selection, or a selection folder, allows a [user](#users) to select and
organize artworks found on the API.
There is no limit to the number of selections created for a particular user,
and there is no limit to the number of artworks that a selection may contain.
<aside class="notice">Note that a selection references a particular version of
an artwork, and that an artwork stored in a selection folder does not get
updated automatically.</aside>
## List selections
### HTTP Request
`GET http://api.dev.rmn.af83.com/v1/selections`
### Query Parameters
Parameter | Default | Description
----------------- | ------- | ------------
user_id | | Which user's selections should we show?
page | 1 | Results page offset
per_page | 10 | Number of results per page
tags | | Comma separated list of tags
works[include] | | Include works in results?
works[q] | | Search for works
works[lang] | fr | Return works facets for this language (fr, en, de)
works[sort] | | Sort works
works[per_page] | 1 | Number of works per page
works[page] | 10 | Works page offset
works[facet_per] | 1 | Number of works facets per page
works[facet_page] | 10 | Works facets page offset
works[facets][collections] | | Filter works on a collection facet
works[facets][locations] | | Filter works on a location facet
works[facets][authors] | | Filter works on an author facet
works[facets][periods] | | Filter works on a period facet
works[facets][techniques] | | Filter works on a technique facet
works[facets][styles] | | Filter works on a style facet
works[facets][schools] | | Filter works on a school facet
works[facets][geographies] | | Filter works on a geography facet
images[include] | | Include images in results?
images[q] | | Search for images
images[lang] | fr | Return images facets for this language (fr, en, de)
images[sort] | | Sort images
images[per_page] | 1 | Number of images per page
images[page] | 10 | Works page offset
images[facet_per] | 1 | Number of images facets per page
images[facet_page] | 10 | Works facets page offset
images[facets][collections] | | Filter images on a collection facet
images[facets][locations] | | Filter images on a location facet
images[facets][authors] | | Filter images on an author facet
images[facets][periods] | | Filter images on a period facet
images[facets][techniques] | | Filter images on a technique facet
images[facets][styles] | | Filter images on a style facet
images[facets][schools] | | Filter images on a school facet
images[facets][geographies] | | Filter images on a geography facet
### HTTP Response
On success, the server replies with a `200` HTTP status code and returns a
list of selections in JSON.
```shell
curl -H'ApiKey: demo' 'http://api.dev.rmn.af83.com/v1/selections'
```
> On success, the above command should yield a JSON array, structured as
> follows:
<pre class="live_requests" data-path="/v1/selections">
</pre>
> If you pass the `include[works]=true` (and/or `include[images]=true`)
parameter, you should get a JSON array with the following structure
(the `works` and `images` keys are added):
<pre class="live_requests"
data-path="/v1/selections?works[include]=true&images[include]=true">
</pre>
## Create a selection
### HTTP Request
`POST http://api.dev.rmn.af83.com/v1/selections`
### Parameters
Parameter | Default | Description
--------- | ------- | ------------
name | | Selection's name (mandatory)
description | | Selection's description
user_id | | Selection's owner (mandatory)
work_ids | | Array of work IDs to associate
image_ids | | Array of image IDs to associate
### HTTP Response
Upon successful creation, the server replies with a `201` HTTP status code and
returns the newly created selection in JSON format. Any other status code
indicate a failure to create the selection.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections' -XPOST -d'name=example&user_id=1'
```
> On success, the above command should yield a JSON object, structured as
> follows:
```json
{
"id": 1,
"name": "example",
"description": "Example",
"user_id": 1,
"default": true,
"updated_at": "2014-09-01T00:00:00.42Z",
"created_at": "2014-09-01T00:00:00.42Z",
"tags": "Foo,Bar"
}
```
## Update a selection
### HTTP Request
`PUT http://api.dev.rmn.af83.com/v1/selections/:id`
### Parameters
Parameter | Default | Description
--------- | ------- | ------------
id | | Selection ID (mandatory)
name | | Selection's name
description | | Selection's description
user_id | | Selection's owner (mandatory)
work_ids | | Array of work IDs to associate
image_ids | | Array of image IDs to associate
### HTTP Response
Upon successful update, the server replies with a `200` HTTP status code and
returns the updated selection in JSON format. Any other status code indicate a
failure to update the selection.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections/:id' -XPUT -d'name=example&user_id=1'
```
> On success, the above command should yield a JSON object, structured as
> follows:
```json
{
"id": 1,
"name": "example",
"description": "Example",
"user_id": 1,
"default": true,
"updated_at": "2014-09-01T00:00:00.42Z",
"created_at": "2014-09-01T00:00:00.42Z",
"tags": "Foo,Bar"
}
```
## Destroy a selection
### HTTP Request
`DELETE http://api.dev.rmn.af83.com/v1/selections/:id`
### HTTP Response
The server *should* reply with a `200` HTTP status code, when the selection is
successfully destroyed.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections/1' -XDELETE
```
> On success, the above command results in a `200` HTTP code and returns the
> JSON representation of the destroyed selection folder. For example:
```json
{
"id": 1,
"name": "example",
"description": "Example",
"user_id": 1,
"default": true,
"updated_at": "2014-09-01T00:00:00.42Z",
"created_at": "2014-09-01T00:00:00.42Z",
"tags": "Foo,Bar"
}
```
## Get a selection
> The above command returns JSON structured like this:
<pre class="live_requests" data-path="_selection_by_id_">
</pre>
### HTTP Request
`GET http://api.dev.rmn.af83.com/v1/selections/:id`
### Query Parameters
Parameter | Default | Description
--------------------------- | ------- | ------------
id | | Selection ID (mandatory)
works[include] | | Include works in results?
works[q] | | Search for works
works[lang] | fr | Return works facets for this language (fr, en, de)
works[sort] | | Sort works
works[per_page] | 1 | Number of works per page
works[page] | 10 | Works page offset
works[facet_per] | 1 | Number of works facets per page
works[facet_page] | 10 | Works facets page offset
works[facets][collections] | | Filter works on a collection facet
works[facets][locations] | | Filter works on a location facet
works[facets][authors] | | Filter works on an author facet
works[facets][periods] | | Filter works on a period facet
works[facets][techniques] | | Filter works on a technique facet
works[facets][styles] | | Filter works on a style facet
works[facets][schools] | | Filter works on a school facet
works[facets][geographies] | | Filter works on a geography facet
images[include] | | Include images in results?
images[q] | | Search for images
images[lang] | fr | Return images facets for this language (fr, en, de)
images[sort] | | Sort images
images[per_page] | 1 | Number of images per page
images[page] | 10 | Works page offset
images[facet_per] | 1 | Number of images facets per page
images[facet_page] | 10 | Works facets page offset
images[facets][collections] | | Filter images on a collection facet
images[facets][locations] | | Filter images on a location facet
images[facets][authors] | | Filter images on an author facet
images[facets][periods] | | Filter images on a period facet
images[facets][techniques] | | Filter images on a technique facet
images[facets][styles] | | Filter images on a style facet
images[facets][schools] | | Filter images on a school facet
images[facets][geographies] | | Filter images on a geography facet
### HTTP Response
The server *should* reply with a `200` HTTP status code.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections/1' -XGET
```
> On success, the above command results in a `200` HTTP code and returns the
> JSON representation of this selection folder. For example:
<pre class="live_requests"
data-path="/v1/selections/1?works[include]=true&images[include]=true">
</pre>
## Add a work or an image to a selection
### HTTP Request
`POST http://api.dev.rmn.af83.com/v1/selections/:id/:document_type`
### Parameters
Parameter | Default | Description
------------- | ------- | ------------
id | | Selection ID (mandatory)
document_type | | Type of document to add, `images` or `works` (mandatory)
document_id | | Document's ID on the API (mandatory)
position | | unsigned integer to choose the entry's position (mandatory)
### HTTP Response
Upon successful creation, the server replies with a `201` HTTP status code and
returns a JSON object with the selected work ID and its version number.
Any other status code indicate a failure to create the selection.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections/1/works' \
-XPOST -d'work_id=42&position=1'
```
> On success, the above command results in a `201` HTTP status code and
> should yield a JSON object, structured as follows:
```json
{
"id": 1,
"selection_id": 1,
"document_id": 42,
"document_type": "Work",
"version_id": 1,
"position": 1
}
```
## Add a work or an image to the user default selection
### HTTP Request
`POST http://api.dev.rmn.af83.com/v1/selections/:user_id/default/:document_type`
### Parameters
Parameter | Default | Description
------------- | ------- | ------------
user_id | | User ID (mandatory)
document_type | | Type of document to add, `images` or `works` (mandatory)
document_id | | Document's ID on the API (mandatory)
position | | unsigned integer to choose the entry's position (mandatory)
### HTTP Response
Upon successful creation, the server replies with a `201` HTTP status code and
returns a JSON object with the selected work ID and its version number.
Any other status code indicate a failure to create the selection.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections/42/default/works' \
-XPOST -d'work_id=42&position=1'
```
> On success, the above command results in a `201` HTTP status code and
> should yield a JSON object, structured as follows:
```json
{
"id": 1,
"selection_id": 1,
"document_id": 42,
"document_type": "Work",
"version_id": 1,
"position": 1
}
```
## Remove a work or an image from a selection
### HTTP Request
`DELETE http://api.dev.rmn.af83.com/v1/selections/:selection_id/:document_type/:id`
### Parameters
Parameter | Default | Description
------------- | ------- | ------------
document_type | | Type of document to add, `images` or `works` (mandatory)
document_id | | Document's ID on the API (mandatory)
### HTTP Response
The server *should* reply with a `200` HTTP status code, when the work is
successfully removed from the selection.
If you try to delete from a selection folder that does not exist, or a work
that is not part of the selection, then the server replies with a `404` HTTP
error code.
```shell
curl -H'ApiKey: demo' \
'http://api.dev.rmn.af83.com/v1/selections/1/works/42' -XDELETE
```
> On success, the above command results in a `200` HTTP code and returns the
> JSON representation of the destroyed entry. For example:
```json
{
"id": 1,
"selection_id": 1,
"document_id": 42,
"document_type": "Work",
"version_id": 1,
"position": 1
}
```
|
TypeScript
|
UTF-8
| 3,526 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
import { KeyValueObject } from "./utilities";
export declare type FormErrors<Values> = {
[K in keyof Values]?: Values[K] extends object ? FormErrors<Values[K]> : string;
};
export declare type FormTouched<Values> = {
[K in keyof Values]?: Values[K] extends object ? FormTouched<Values[K]> : boolean;
};
export interface IRcFormlyFormProps<T = any> {
errors: FormErrors<T>;
touched: FormTouched<T>;
submitCount: number;
values: T;
}
export interface IRcFormlyProps<TModel = any> {
changeFieldConfig(fieldKey: string, changeFieldConfigFunction: (existingFieldConfig: IFormlyFieldConfig) => IFormlyFieldConfig): void;
changeFieldConfigs(changeFieldConfigsFunction: (existingFieldConfigs: IFormlyFieldConfig[]) => IFormlyFieldConfig[]): void;
handleSubmit?(e: React.FormEvent<any>): void;
replaceValues: (values: any) => void;
resetForm(): void;
resetForm(values: TModel): void;
resetForm(resetFormValuesFunction: (existingValues: TModel) => TModel): void;
setFieldValue(field: string, value: any): void;
setFieldError(field: string, message: string): void;
setFieldTouched(field: string, isTouched?: boolean): void;
setValues(changeValuesFunc: (values: any) => any): void;
submit(): void;
formProps: IRcFormlyFormProps<TModel>;
}
export type IFormlyTemplateOptions<T extends {} = {}> = T & {
onChange?(newValue: any, oldValue: any, formlyProps: IRcFormlyProps, ...additionalData: any[]): void;
onPress?(): void;
type?: string;
label?: string;
placeholder?: string;
disabled?: boolean;
rows?: number;
cols?: number;
description?: string;
hidden?: boolean;
max?: number;
min?: number;
minLength?: number;
maxLength?: number;
pattern?: string | RegExp;
required?: boolean;
attributes?: {
[key: string]: string | number;
};
[additionalProperties: string]: any;
}
export interface IFormlyFieldConfig<TTemplateOptions = {}>{
/**
* The model that stores all the data, where the model[key] is the value of the field
*/
readonly model?: any;
/**
* The key that relates to the model. This will link the field value to the model
*/
key?: string;
/**
* This allows you to specify the `id` of your field. Note, the `id` is generated if not set.
*/
id?: string;
/**
* If you wish, you can specify a specific `name` for your field.
* This is useful if you're posting the form to a server using techniques of yester-year.
*/
name?: string;
/**
* This is reserved for the templates. Any template-specific options go in here.
* Look at your specific template implementation to know the options required for this.
*/
templateOptions?: IFormlyTemplateOptions<TTemplateOptions>;
style?: KeyValueObject;
wrappers?: string[];
/**
* Whether to hide the field. Defaults to false. If you wish this to be conditional use `hideExpression`
*/
hide?: boolean;
/**
* A field group is a way to group fields together, making advanced layout very simple.
* It can also be used to group fields that are associated with the same model.
* (useful if it's different than the model for the rest of the fields).
*/
fieldGroup?: IFormlyFieldConfig[];
fieldArray?: IFormlyFieldConfig;
/**
* This should be a formly-field type added either by you or a plugin. More information over at Creating Formly Fields.
*/
type?: string;
}
|
Python
|
UTF-8
| 604 | 3.765625 | 4 |
[] |
no_license
|
'''
Can Python handle everything?
Now that you know something more about combining different sources of information, have a look at the four Python
expressions below. Which one of these will throw an error? You can always copy and paste this code in the IPython
Shell to find out!
Instructions
50 XP
Possible Answers
"I can add integers, like " + str(5) + " to strings."
"I said " + ("Hey " * 2) + "Hey!"
"The correct answer to this multiple choice exercise is answer number " + 2
True + False
Answer : "The correct answer to this multiple choice exercise is answer number " + 2
'''
|
Shell
|
UTF-8
| 1,205 | 3.109375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# ----------------------------------------------------------------------------
#
# Package : ua-parser-js
# Version : master
# Source repo : https://github.com/faisalman/ua-parser-js
# Tested on : UBI 8
# Script License: Apache-2.0 License
# Maintainer : Vaibhav Nazare <vaibhav_nazare@persistent.com>
#
# Disclaimer: This script has been tested in root mode on given
# ========== platform using the mentioned version of the package.
# It may not work as expected with newer versions of the
# package and/or distribution. In such case, please
# contact "Maintainer" of this script.
#
# ----------------------------------------------------------------------------
#!/bin/bash
REPO=https://github.com/faisalman/ua-parser-js.git
PACKAGE_VERSION=master
#Install Required Files
yum -y update
yum install -y git wget
wget "https://nodejs.org/dist/v12.22.4/node-v12.22.4-linux-ppc64le.tar.gz"
tar -xzf node-v12.22.4-linux-ppc64le.tar.gz
export PATH=$CWD/node-v12.22.4-linux-ppc64le/bin:$PATH
#Cloning repo
git clone $REPO
cd ua-parser-js/
git checkout $PACKAGE_VERSION
npm install
npm i --package-lock-only
npm audit fix --force
npm run test
|
Markdown
|
UTF-8
| 604 | 3.09375 | 3 |
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
---
author: Nathan Carter (ncarter@bentley.edu)
---
This solution uses fake example data.
When using this code, replace our fake data with your real data.
```R
# Here is the fake data you should replace with your real data.
xs <- c( 393, 453, 553, 679, 729, 748, 817 )
ys <- c( 24, 25, 27, 36, 55, 68, 84 )
# If you need the model coefficients stored in variables for later use, do:
model <- lm( ys ~ xs )
beta0 = model$coefficients[1]
beta1 = model$coefficients[2]
# If you just need to see the coefficients, do this alone:
lm( ys ~ xs )
```
The linear model in this example is approximately $y=0.133x-37.32$.
|
PHP
|
UTF-8
| 3,422 | 2.640625 | 3 |
[] |
no_license
|
<?php
include("db_connect.php");
if(isset($_POST['submit'])){
if (!empty($patientid) || !empty($name) || !empty($icnumber) || !empty($phonenumber) || !empty($address) || !empty($gender) || !empty($races) || !empty($birthdate))
{
$patientid = $_POST['patientid'];
$name = $_POST['name'];
$icnumber = $_POST['ic_number'];
$phonenumber = $_POST['phone_number'];
$address = $_POST['address'];
$gender = $_POST['gender'];
$races = $_POST['races'];
$birthdate = $_POST['birthdate'];
$sql = "INSERT INTO `patient_information`(`PatientID`, `Name`, `IC_Num`, `Phone_Num`, `Address`, `Gender`, `Races`, `Birth_Date`)
VALUES ([$patientid],[$name],[$icnumber],[$phonenumber],[$address],[$gender],[$races],[$birthdate]) ";
$qry = mysqli_query($connect, $sql);
if($qry){
echo "inserted successfully";
}
}else{
echo "all fields must be filled";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Patient Information Form</title>
<link rel="stylesheet" type="text/css" href="CSS(baru)/patientinformation.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="menu-bar">
<ul>
<li><a href= "homepage.html"><i class="fa fa-home"></i>Home</a></li>
<li><a href= "healthinfo.html">Health Info</a></li>
<li class="active"><a href= "nurse.html">Nurse</a>
<div class="sub-menu-1">
<ul>
<li ><a href="patientinformation.html">Manage Patient Information</a></li>
<li ><a href="patientmedicine.html">Manage Patient Medicine</a></li>
<li><a href="#">View Health Information</a></li>
</ul>
</div>
</li>
<li><a href= "homepage">Logout</a></li>
</ul>
</div>
<br>
<br>
<br>
<div class="patientinformation">
<h2>Patient Information Form</h2>
<form method="POST" id="patientinformation" autocomplete="off" action="/HRCS/PHP/patientinformation.php">
<label> PatientID :</label><br>
<input type="string" name="patientID" id="name" placeholder=""><br><br>
<label> Name :</label><br>
<input type="string" name="name" id="name" placeholder=""><br><br>
<label> IC Number :</label><br>
<input type="string" name="ic_number" id="name" placeholder=""><br><br>
<label>Phone Number :</label><br>
<input type="string" name="phone_number" id="num" placeholder=""><br><br>
<label> Address :</label><br>
<textarea name ="Address" rows="5" cols="55"></textarea><br><br>
<label> Gender :</label><br>
<input type="radio" name="position" value="Male" checked>Male<br>
<input type="radio" name="position" value="Female">Female<br><br>
<label> Races :</label><br>
<select name="races">
<option value="Malay">Malay</option>
<option value="chinese">Chinese</option>
<option value="indian">Indian</option>
<option value="other">Other</option>
</select><br><br>
<label> BirthDate :</label><br>
<input type="date" name="birthdate" id="name" placeholder="Enter BirthDate"><br><br>
<input type="reset" name="reset" value="Reset" id="sub">
<input type="submit" name="submit" value="Save" id="sub">
</form>
</div>
</body>
</html>
|
Rust
|
UTF-8
| 3,363 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
use crate::conversion::{BorrowFromGValue, FromGValue};
use crate::structure::{Edge, Path, Property, Vertex, VertexProperty};
use crate::GremlinResult;
use chrono;
use std::collections::{HashMap, VecDeque};
pub type Map = HashMap<String, GValue>;
pub type List = Vec<GValue>;
pub type Set = Vec<GValue>;
pub type Date = chrono::DateTime<chrono::offset::Utc>;
/// Represent possible values coming from the [Gremlin Server](http://tinkerpop.apache.org/docs/3.4.0/dev/io/)
#[allow(clippy::large_enum_variant)]
#[derive(Debug, PartialEq, Clone)]
pub enum GValue {
Vertex(Vertex),
Edge(Edge),
VertexProperty(VertexProperty),
Property(Property),
Uuid(uuid::Uuid),
Int32(i32),
Int64(i64),
Float(f32),
Double(f64),
Date(Date),
List(List),
Set(Set),
Map(Map),
String(String),
Path(Path),
}
impl GValue {
pub fn take<T>(self) -> GremlinResult<T>
where
T: FromGValue,
{
T::from_gvalue(self)
}
pub fn get<'a, T>(&'a self) -> GremlinResult<&'a T>
where
T: BorrowFromGValue,
{
T::from_gvalue(self)
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum GID {
String(String),
Int32(i32),
Int64(i64),
}
impl From<&'static str> for GID {
fn from(val: &str) -> Self {
GID::String(String::from(val))
}
}
impl From<i32> for GID {
fn from(val: i32) -> Self {
GID::Int32(val)
}
}
impl From<i64> for GID {
fn from(val: i64) -> Self {
GID::Int64(val)
}
}
impl From<Date> for GValue {
fn from(val: Date) -> Self {
GValue::Date(val)
}
}
impl From<String> for GValue {
fn from(val: String) -> Self {
GValue::String(val)
}
}
impl From<i32> for GValue {
fn from(val: i32) -> Self {
GValue::Int32(val)
}
}
impl From<i64> for GValue {
fn from(val: i64) -> Self {
GValue::Int64(val)
}
}
impl From<f32> for GValue {
fn from(val: f32) -> Self {
GValue::Float(val)
}
}
impl From<f64> for GValue {
fn from(val: f64) -> Self {
GValue::Double(val)
}
}
impl<'a> From<&'a str> for GValue {
fn from(val: &'a str) -> Self {
GValue::String(String::from(val))
}
}
impl From<Vertex> for GValue {
fn from(val: Vertex) -> Self {
GValue::Vertex(val)
}
}
impl From<Path> for GValue {
fn from(val: Path) -> Self {
GValue::Path(val)
}
}
impl From<Edge> for GValue {
fn from(val: Edge) -> Self {
GValue::Edge(val)
}
}
impl From<VertexProperty> for GValue {
fn from(val: VertexProperty) -> Self {
GValue::VertexProperty(val)
}
}
impl From<Property> for GValue {
fn from(val: Property) -> Self {
GValue::Property(val)
}
}
impl From<HashMap<String, GValue>> for GValue {
fn from(val: HashMap<String, GValue>) -> Self {
GValue::Map(val)
}
}
impl From<Vec<GValue>> for GValue {
fn from(val: Vec<GValue>) -> Self {
GValue::List(val)
}
}
impl From<GValue> for Vec<GValue> {
fn from(val: GValue) -> Self {
vec![val]
}
}
impl From<GValue> for VecDeque<GValue> {
fn from(val: GValue) -> Self {
match val {
GValue::List(l) => VecDeque::from(l),
GValue::Set(l) => VecDeque::from(l),
_ => VecDeque::from(vec![val]),
}
}
}
|
Python
|
UTF-8
| 9,237 | 2.5625 | 3 |
[] |
no_license
|
import sys,os
from optparse import OptionParser
from subprocess import call,check_output
usage=''' Compute and compare ratio with combine and C-P intervals.
* python compare.py
* python compare.py -n 3000 -d 5000 --muD='4500,5500' --rmin=0.55 --rmax=0.75
'''
parser=OptionParser(usage=usage)
parser.add_option("-n","--numerator",help="Numerator [%default]",type='int',default=3)
parser.add_option("-d","--denominator",help="Denominator [%default]",type='int',default=5)
parser.add_option("","--format",help="Format string for numbers [%default]",type='string',default="%.2f")
parser.add_option("","--muD",help="Range for muD: [-xx,+yy] [%default]",type='string',default="")
parser.add_option("","--rmin",help="min boundary for rMin [%default]",type='string',default="0")
parser.add_option("","--rmax",help="min boundary for rMax [%default]",type='string',default="4")
opts,args=parser.parse_args()
opts.poi="r"
def mycall(cmd):
status = call(cmd,shell=True)
if status != 0:
print "<*> ERROR: unable to execute '"+cmd+"'"
raise IOError
import ROOT
ROOT.gStyle.SetOptStat(0)
ROOT.gStyle.SetOptTitle(0)
## UTILITIES FUNCTIONS
def findQuantile(pts,cl):
#gr is a list of r,nll
# start by walking along the variable and check if crosses a CL point
if cl<=0:
min=pts[0][0]
mincl=pts[0][1]
for pt in pts:
if pt[1]<mincl:
mincl=pt[1]
min = pt[0]
return min,min
crossbound = [ pt[1]<=cl for pt in pts ]
rcrossbound = crossbound[:]
rcrossbound.reverse()
minci = 0
maxci = len(crossbound)-1
min = pts[0][0]
max = pts[maxci][0]
for c_i,c in enumerate(crossbound):
if c :
minci=c_i
break
for c_i,c in enumerate(rcrossbound):
if c :
maxci=len(rcrossbound)-c_i-1
break
if minci>0:
y0,x0 = pts[minci-1][0],pts[minci-1][1]
y1,x1 = pts[minci][0],pts[minci][1]
min = y0+((cl-x0)*y1 - (cl-x0)*y0)/(x1-x0)
if maxci<len(crossbound)-1:
y0,x0 = pts[maxci][0],pts[maxci][1]
y1,x1 = pts[maxci+1][0],pts[maxci+1][1]
max = y0+((cl-x0)*y1 - (cl-x0)*y0)/(x1-x0)
return min,max
def smoothNLL_v2(gr,res,w=0.3):
print "-> Smooth v2"
minVal = min([re[0] for re in res])
maxVal = max([re[0] for re in res])
gr2=ROOT.TGraph()
myfunc = ROOT.TF1("myfunc","pol2",-100,100)
for p in range(100):
x = minVal+p*((maxVal-minVal)/100.)
fitmin = x-w
fitmax = x+w
myfunc.SetRange(fitmin,fitmax)
gr.Fit("myfunc","RQN")
gr.Fit("myfunc","RQNM")
y = myfunc.Eval(x)
if y<5:
gr2.SetPoint(gr2.GetN(),x,y)
return gr2
def smoothNLL_v3(gr,res,w=0.3,delta=0.05):
print "-> Smooth v3 <-"
gr2 = smoothNLL_v2(gr,res,w)
gr3 = ROOT.TGraph()
for x,y in res:
y2 = gr2.Eval(x)
if abs(y-y2) < delta:
gr3.SetPoint(gr3.GetN(), x,y )
gr4 = smoothNLL_v2(gr3,res,w)
return gr4
def cleanSpikes1D(rfix):
# cindex is where deltaNLL = 0 (pre anything)
MAXDER = 1.0
for i,r in enumerate(rfix):
if abs(r[1]) <0.001: cindex = i
lhs = rfix[0:cindex]; lhs.reverse()
rhs= rfix[cindex:-1]
keeplhs = []
keeprhs = []
for i,lr in enumerate(lhs):
if i==0:
prev = lr[1]
idiff = 1
if abs(lr[1]-prev) > MAXDER :
idiff+=1
continue
keeplhs.append(lr)
prev = lr[1]
idiff=1
keeplhs.reverse()
for i,rr in enumerate(rhs):
if i==0:
prev = rr[1]
idiff = 1
if abs(rr[1]-prev) > MAXDER :
idiff+=1
continue
keeprhs.append(rr)
prev = rr[1]
idiff=1
rfix = keeplhs+keeprhs
rkeep = []
#now try to remove small jagged spikes
for i,r in enumerate(rfix):
if i==0 or i==len(rfix)-1:
rkeep.append(r)
continue
tres = [rfix[i-1][1],r[1],rfix[i+1][1]]
mean = float(sum(tres))/3.
mdiff = abs(max(tres)-min(tres))
if abs(tres[1] - mean) > 0.6*mdiff :continue
rkeep.append(r)
return rkeep
### PARSE DATACARD AND RUN COMBINE
mycall("cp datacard2.txt datacard_tmp.txt")
mycall("sed -i'' 's/$NUM/%d/g' datacard_tmp.txt"%(opts.numerator))
mycall("sed -i'' 's/$DEN/%d/g' datacard_tmp.txt"%(opts.denominator))
mycall("text2workspace.py --X-allow-no-background -o tmp.root datacard_tmp.txt")
extra=""
if opts.muD !="":
#extra += "--setPhysicsModelParameterRanges muD="+opts.muD
extra += "--setParameterRanges muD="+opts.muD
mycall("combine -M MultiDimFit --algo=grid --points=1000 --rMin=%s --rMax=%s %s tmp.root"%(opts.rmin,opts.rmax,extra))
fIn=ROOT.TFile.Open("higgsCombineTest.MultiDimFit.mH120.root")
tree = fIn.Get('limit')
res=[]
for i in range(tree.GetEntries()):
tree.GetEntry(i)
xv = getattr(tree,opts.poi)
if tree.deltaNLL<0 : print "Warning, found -ve deltaNLL = ", tree.deltaNLL, " at ", xv
if 2*tree.deltaNLL < 100:
res.append([xv,2*tree.deltaNLL])
res.sort()
obs=ROOT.TGraph()
for re, nll in res:
if nll>=0. and nll<5:
obs.SetPoint(obs.GetN(),re,nll)
m,m1 = findQuantile(res,0);
l,h = findQuantile(res,1); ## 1sigma
l2,h2 = findQuantile(res,4); ## 2sigma
xmin = m
eplus = h-m
eminus = m-l
c=ROOT.TCanvas('c','c',800,800)
c.SetBottomMargin(0.15)
c.SetLeftMargin(0.15)
c.SetTopMargin(0.05)
c.SetRightMargin(0.05)
dummy= ROOT.TH1D("dummy","dummy",100,0,10)
dummy.GetXaxis().SetTitle("Ratio")
dummy.GetYaxis().SetTitle("-2 * #Delta logL")
dummy.GetXaxis().SetTitleOffset(1.3)
dummy.GetYaxis().SetTitleOffset(1.5)
dummy.Draw("AXIS")
dummy.Draw("AXIS X+ Y+ SAME")
dummy.GetYaxis().SetRangeUser(0,5)
dummy.GetXaxis().SetRangeUser(float(opts.rmin),float(opts.rmax))
w=0.2
y=1 ## all centered at 1
oneSigma_LR = ROOT . TPave (l,y-w,h,y+w)
twoSigma_LR = ROOT . TPave (l2,y-w,h2,y+w)
oneSigma_LR.SetFillColor(ROOT.kYellow)
oneSigma_LR.SetLineColor(ROOT.kYellow)
twoSigma_LR.SetFillColor(ROOT.kGreen)
twoSigma_LR.SetLineColor(ROOT.kGreen)
oneSigma_LR.SetBorderSize(0)
twoSigma_LR.SetBorderSize(0)
twoSigma_LR.Draw()
oneSigma_LR.Draw()
bf = ROOT.TGraph()
bf.SetPoint(0,m,y)
bf.SetMarkerStyle(28)
bf.SetMarkerSize(1.5)
bf.SetMarkerColor(ROOT.kBlack)
bf.Draw("P SAME")
obs.Draw("L SAME")
## DERIVE C-P intervals
t = opts.numerator
s = opts.denominator + opts.numerator
CL1=1.-2.*ROOT.RooStats.SignificanceToPValue(1)
CL2=1.-2.*ROOT.RooStats.SignificanceToPValue(2)
cp1 = ROOT.TEfficiency.ClopperPearson(s,t, CL1,True)
h_CP = cp1/(1.-cp1)
cp1 = ROOT.TEfficiency.ClopperPearson(s,t, CL1,False)
l_CP = cp1/(1.-cp1)
cp2 = ROOT.TEfficiency.ClopperPearson(s,t, CL2,True)
h2_CP = cp2/(1.-cp2)
cp2 = ROOT.TEfficiency.ClopperPearson(s,t, CL2,False)
l2_CP = cp2/(1.-cp2)
##
midp1 = ROOT.TEfficiency.MidPInterval(s,t, CL1,True)
h_MIDP = midp1/(1.-midp1)
midp1 = ROOT.TEfficiency.MidPInterval(s,t, CL1,False)
l_MIDP = midp1/(1.-midp1)
midp2 = ROOT.TEfficiency.MidPInterval(s,t, CL2,True)
h2_MIDP = midp2/(1.-midp2)
midp2 = ROOT.TEfficiency.MidPInterval(s,t, CL2,False)
l2_MIDP = midp2/(1.-midp2)
nominal = float(opts.numerator)/float(opts.denominator)
print "BestFit (Likelihood): %4.4f [%4.4g, %4.4g]" % ( xmin, l,h )
print "BestFit (CP): %4.4f [%4.4g, %4.4g]" % ( nominal, l_CP,h_CP )
print "BestFit (MIDP): %4.4f [%4.4g, %4.4g]" % ( nominal, l_MIDP, h_MIDP )
ROOT.gStyle.SetEndErrorSize(5)
##
y=1
cp = ROOT.TGraphAsymmErrors()
cp.SetPoint(0,nominal,y)
cp.SetPointError(0,nominal-l_CP,h_CP-nominal, 0,0)
cp.SetPoint(1,nominal,y)
cp.SetPointError(1,nominal-l2_CP,h2_CP-nominal, 0,0)
cp.SetMarkerStyle(20)
cp.SetMarkerColor(ROOT.kBlack)
cp.SetLineWidth(4)
cp.Draw("PE SAME")
y=1.07
midp = ROOT.TGraphAsymmErrors()
midp.SetPoint(0,nominal,y)
midp.SetPointError(0,nominal-l_MIDP,h_MIDP-nominal, 0,0)
midp.SetPoint(1,nominal,y)
midp.SetPointError(1,nominal-l2_MIDP,h2_MIDP-nominal, 0,0)
midp.SetMarkerStyle(4)
midp.SetMarkerColor(ROOT.kRed)
midp.SetLineColor(ROOT.kRed)
midp.SetLineWidth(2)
midp.Draw("PE SAME")
y=0.93
err = nominal * ROOT.TMath.Sqrt( 1./opts.numerator + 1./opts.denominator)
std = ROOT.TGraphAsymmErrors()
std.SetPoint(0,nominal,y)
std.SetPointError(0,err,err, 0,0)
std.SetPoint(1,nominal,y)
std.SetPointError(1,2*err,2*err, 0,0)
std.SetMarkerStyle(0)
std.SetMarkerColor(ROOT.kBlue+2)
std.SetLineColor(ROOT.kBlue+2)
std.SetLineWidth(2)
std.Draw("PE SAME")
leg = ROOT.TLegend(.23,.66,.54,.91)
leg.AddEntry(obs,"LR","L")
leg.AddEntry(oneSigma_LR,"1#sigma LR","F")
leg.AddEntry(twoSigma_LR,"1#sigma LR","F")
leg.AddEntry(cp,"C-P","PL")
leg.AddEntry(midp,"MidP","PL")
leg.AddEntry(std,"std error","PL")
leg.SetFillStyle(0)
leg.SetBorderSize(0)
leg.Draw()
txt= ROOT.TLatex()
txt.SetNDC()
txt.SetTextFont(42)
txt.SetTextSize(0.035)
txt.SetTextAlign(11)
xtxt = 0.55
ytxt = 0.5
wtxt = 0.04
if opts.format != "":
txt.DrawLatex(xtxt,ytxt+0*wtxt,"#bf{Ratio of %d/%d:}"%(opts.numerator,opts.denominator))
txt.DrawLatex(xtxt,ytxt-1*wtxt,("LR: ["+opts.format+","+opts.format+"] ["+opts.format+","+opts.format+"]")%(l,h,l2,h2))
txt.DrawLatex(xtxt,ytxt-2*wtxt,("CP: ["+opts.format+","+opts.format+"] ["+opts.format+","+opts.format+"]")%(l_CP,h_CP,l2_CP,h2_CP))
txt.DrawLatex(xtxt,ytxt-3*wtxt,("MP: ["+opts.format+","+opts.format+"] ["+opts.format+","+opts.format+"]")%(l_MIDP,h_MIDP,l2_MIDP,h2_MIDP))
txt.DrawLatex(xtxt,ytxt-4*wtxt,("STD: ["+opts.format+","+opts.format+"] ["+opts.format+","+opts.format+"]")%(nominal-err,nominal+err,nominal-2*err,nominal+2*err))
c.Update()
raw_input("ok?")
|
JavaScript
|
UTF-8
| 402 | 2.734375 | 3 |
[] |
no_license
|
var fs = require('fs')
module.exports = function(directory, extension, callback) {
var filteredList = new Array
fs.readdir(directory, function(err, list) {
if (err) {
return callback(err)
}
for(var i = 0; i < list.length; i++) {
if(list[i].indexOf('.' + extension) > 0) {
filteredList.push(list[i])
}
}
return callback(null, filteredList)
})
}
|
Markdown
|
UTF-8
| 1,483 | 2.71875 | 3 |
[] |
no_license
|
# Efeito Magnus
Código para a matéria de Física Básica I (7600105) do curso de Ciências de Computação da USP São Carlos.
O objetivo do código é dado uma velocidade, thetha e phi de chute, verificar se através do Efeito Magnus o jogador conseguiu acertar o gol. Além disso, plotar o chute.
Observação: A acurâcia dos resultados e aplicação da fórmula do Efeito Magnus não é 100%.
#### Para executar o código
```
gcc chute.c -o chute -lm
./chute
```
#### Alguns exemplos de entradas:
##### Acerta o chute
Velocidade: 36.1m/s Theta: 45º Phi: 30º
##### Não acerta o chute
Velocidade: 36.1 m/s Theta: 30º Phi: 30º
#### Em seguida, acessar o gnuplot
```
gnuplot
```
#### Executar no gnuplot
```
reset
set xrange[-300:10]
set xlabel 'x'
set yrange[-200:200]
set ylabel 'y'
set zrange[0:50]
set zlabel 'z'
set ticslevel 0
set mxtics 20
set mytics 20
set ticscale 1.0, 0.01
set grid x y mx my lt 1 lc "#77dd77" lw 2
splot 'chute.dat' using 1:2:3 with lines lc "red", 'baliza1.dat' with lines lc "black", 'baliza2.dat' with lines lc "black", 'baliza3.dat' with lines lc "black"
```
##### Explicação:
`reset`: Limpa as configurações atuais
`set <EIXO>range[<INFERIOR>:<SUPERIOR>]`: Coloca um limite em `<EIXO>` de `<INFERIOR>` até `<SUPERIOR>`
`set <EIXO>label '<TEXTO>'`: Coloca um label com o texto `<TEXTO>` no `<EIXO>` para descrever o eixo
...
`lc <COR>`: Atribui `<COR>` coloração (nome da cor, hexadecimal ou rgb)
|
C#
|
UTF-8
| 1,153 | 2.84375 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Underwater.VRHome
{
/// <summary>
/// Manages all the items protected by the FailSafe script.
/// </summary>
public class FallSafeManager : MonoBehaviour
{
/// <summary>
/// Height under which the items shouldn't fall.
/// </summary>
private float _minY = 0.05f;
/// <summary>
/// Array containing every protected item.
/// </summary>
[SerializeField]
private FallSafe[] _protectedObjects;
// Start is called before the first frame update
void Start()
{
_protectedObjects = GameObject.FindObjectsOfType<FallSafe>();
}
// Update is called once per frame
void Update()
{
foreach (FallSafe protectedObject in _protectedObjects)
{
if (protectedObject.gameObject.transform.position.y <= _minY)
{
protectedObject.gameObject.transform.position = protectedObject.initialPosition;
}
}
}
}
}
|
Python
|
UTF-8
| 6,740 | 2.71875 | 3 |
[] |
no_license
|
from flask import render_template, flash, redirect, url_for
from app import app, db
from app.forms import LoginForm, BasriForm, BasriForm2, RandommealForm, BasriDiceForm, BasriSuggestionsForm
from app.models import Suggestion
import lib.BasriFunctions as h
import config as c
import numpy as np
import base64
from io import BytesIO
from matplotlib.figure import Figure
import pandas as pd
@app.route('/')
@app.route('/index')
def index():
'''
user = {'username': 'Miguel'}
posts = [
{
'author': {'username': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'username': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
=======index.html======
{% block content %}
<h1>Hi, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
{% endblock %}
=======return as!!!======
return render_template('index.html', title='Home', user=user, posts=posts)
'''
return render_template('index.html', title='Home')
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for user {}, remember_me={}'.format(
form.username.data, form.remember_me.data))
return redirect(url_for('index'))
return render_template('login.html', title='Sign In', form=form)
@app.route('/basri', methods=['GET', 'POST'])
def basri():
form = BasriForm()
if form.validate_on_submit():
flash('Var1 for user {}, Var2 for user {}, remember_me={}'.format(
form.var1.data, form.var2.data, form.remember_me.data))
return redirect(url_for('index'))
return render_template('getdata.html', title='Basri', form=form)
@app.route('/basri2', methods=['GET', 'POST'])
def basri2():
form = BasriForm2()
if form.validate_on_submit():
multiplied_value = h.BasriNumbers(form.var1.data,form.var2.data).MultiplyThem()
flash('Var1 for user: {}, |Var2 for user: {}, |multiplication {}, |SECRET_KEY: {}, |USERNAME:{}'.format(
form.var1.data, form.var2.data, multiplied_value, c.Config.SECRET_KEY,c.Config.USERNAME))
return redirect(url_for('index'))
return render_template('getdata2.html', title='Basri', form=form)
@app.route('/suggestions', methods=['GET', 'POST'])
def suggestions():
user = {'username': 'Basri'}
posts = [
{
'body': 'Gets your suggestions. List previous suggestions'
},
{
'body': 'To demonstate basic database operations.'
},
{
'body': 'SQLAlchemy, AWS RDS (MySQL)'
}
]
form = BasriSuggestionsForm()
if form.validate_on_submit():
flash('Others have provided the following so far...')
suggestions_retreived_from_db = Suggestion.query.all()
for s in suggestions_retreived_from_db:
flash(s)
flash('Your suggestions: {}'.format(form.Suggestions.data))
suggestion = Suggestion(body=form.Suggestions.data)
db.session.add(suggestion)
db.session.commit()
return render_template('index_Suggestions.html', title='Home', user=user, posts=posts)
return render_template('suggestions.html', title='Basri Suggestions', form=form)
@app.route('/dice', methods=['GET', 'POST'])
def dice():
user = {'username': 'Basri'}
posts = [
{
'body': 'An imaginary and random dice is thrown. :)'
},
{
'body': 'Next move is assessed according to the table you entered in the previous form.'
},
{
'body': 'Process is repeated until the total value reaches to 100'
},
{
'body': 'Maximum 2000 dice throws allowed!'
}
]
form = BasriDiceForm()
if form.validate_on_submit():
flash('Dice1: {},|Dice2: {},|Dice3: {},|Dice4: {},|Dice5: {},|Dice6: {}'.format(
form.dice1.data,form.dice2.data,form.dice3.data,form.dice4.data,form.dice5.data,form.dice6.data))
url_to_pass = h.BasriDiceAPICall(form.dice1.data,
form.dice2.data,
form.dice3.data,
form.dice4.data,
form.dice5.data,
form.dice6.data
).CreateFigure()
return render_template('index_dice.html', title='Home', user=user, posts=posts, name = 'new_plot_from_the_real_code', url=url_to_pass)
return render_template('dice.html', title='Basri Dice', form=form)
@app.route('/randommeal', methods=['GET', 'POST'])
def randommeal():
user = {'username': 'Basri'}
posts = [
{
'body': 'A random meal is brought to you from:'
},
{
'body': 'a site who provides such service through an API call'
},
{
'body': 'The instruction received is passed to AWS Translate service so that you also receive it in the lanaguage you asked for!'
},
{
'body': 'Example for amalgamation of services in the new world :)'
}
]
form = RandommealForm()
if form.validate_on_submit():
url = 'https://www.themealdb.com/api/json/v1/1/random.php'
received_data = h.BasriAPICall(url).GetJSONData()
flash('Name of meal: {}'.format(received_data['meals'][0]['strMeal']))
flash('Image of meal: {}'.format(received_data['meals'][0]['strMealThumb']))
flash('Source of meal: {}'.format(received_data['meals'][0]['strSource']))
flash('YouTube Link of meal: {}'.format(received_data['meals'][0]['strYoutube']))
flash('Ingredients:')
reduced_df = h.BasriAPICallReduceDF(received_data).ReduceDF()
var=0
while var < len(reduced_df):
for key,value in reduced_df[var].items():
flash('{},{}'.format(key, value))
var=var+1
flash('Instructions: {}'.format(received_data['meals'][0]['strInstructions']))
temp = h.BasriAPITranslate(received_data['meals'][0]['strInstructions'],str(form.language.data)).Translate()
flash('Instructions in {}: {}'.format(form.language.data,temp))
#return redirect(url_for('index'))
return render_template('index_Randommeal.html', title='Home', user=user, posts=posts, name = 'dnm name')
return render_template('InitiateRandommeal.html', title='Random Meal', form=form)
|
Java
|
UTF-8
| 9,554 | 1.765625 | 2 |
[] |
no_license
|
package com.ipmph.v.fragment;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ipmph.v.LoginActivity;
import com.ipmph.v.R;
import com.ipmph.v.callback.MyInterface.NetRequestIterface;
import com.ipmph.v.callback.NetRequest;
import com.ipmph.v.object.LoginResultObject;
import com.ipmph.v.object.UserInfoObject;
import com.ipmph.v.setting.activity.AlbumPromptActivity;
import com.ipmph.v.setting.activity.CacheActivity;
import com.ipmph.v.setting.activity.MessageActivity;
import com.ipmph.v.setting.activity.SettingActivity;
import com.ipmph.v.setting.activity.UserInfoActivity;
import com.ipmph.v.setting.activity.VideoCollectActivity;
import com.ipmph.v.setting.activity.WatchRecordActivity;
import com.ipmph.v.tool.CommonUrl;
import com.ipmph.v.tool.CommonUtil;
import com.ipmph.v.tool.HttpUtils;
public class MyFragment extends Fragment implements NetRequestIterface,
OnClickListener {
public static int gaolei = 0, zhaoyue = 0;
private RelativeLayout play_record_layout, setting_layout, person_layout,
cache_layout, album_prompt_layout, video_collect_layout,
message_layout;
private boolean isLogin = false;
private static NetRequest netRequest;
private static ImageView user_photo;
public static final int LOGIN = 1;
public static final int LOGOUT = 2;
private static TextView click_login;
private Bitmap photoBitmap;
public static boolean changePhoto = false;
public static Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.arg1) {
case LOGIN:
String sessionId = LoginResultObject.getInstance().sessionId;
getUserInfo(sessionId);
break;
case LOGOUT:
user_photo.setImageResource(R.drawable.default_photo);
click_login.setText("点击登录\n登录后您可以享受更多特权");
break;
}
}
};
public static void changeGaoLei(int arg) {
gaolei = arg;
}
public void onResume() {
super.onResume();
Log.d("gaolei", "MyFragment-----------onResume---------");
}
public void onPause() {
super.onPause();
Log.d("gaolei", "MyFragment-----------onPause---------");
}
public void onStop(){
super.onStop();
Log.d("gaolei", "MyFragment-----------onStop--");
}
public void onDestroy(){
super.onDestroy();
Log.d("gaolei", "MyFragment-----------onDestroy--");
}
public void onStart() {
super.onStart();
Log.d("gaolei", "MyFragment-----------onStart---------");
// if (changePhoto) {
String sessionId = LoginResultObject.getInstance().sessionId;
getUserInfo(sessionId);
// changePhoto=false;
// }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = LayoutInflater.from(getActivity()).inflate(
R.layout.my_fragment, null);
initView(view);
return view;
}
private void initView(View view) {
netRequest = new NetRequest(this, getActivity());
play_record_layout = (RelativeLayout) view
.findViewById(R.id.play_record_layout);
setting_layout = (RelativeLayout) view
.findViewById(R.id.setting_layout);
person_layout = (RelativeLayout) view.findViewById(R.id.person_layout);
cache_layout = (RelativeLayout) view.findViewById(R.id.cache_layout);
album_prompt_layout = (RelativeLayout) view
.findViewById(R.id.album_prompt_layout);
video_collect_layout = (RelativeLayout) view
.findViewById(R.id.video_collect_layout);
message_layout = (RelativeLayout) view
.findViewById(R.id.message_layout);
user_photo = (ImageView) view.findViewById(R.id.user_photo);
click_login = (TextView) view.findViewById(R.id.click_login);
play_record_layout.setOnClickListener(this);
setting_layout.setOnClickListener(this);
person_layout.setOnClickListener(this);
cache_layout.setOnClickListener(this);
album_prompt_layout.setOnClickListener(this);
video_collect_layout.setOnClickListener(this);
message_layout.setOnClickListener(this);
String sessionId = LoginResultObject.getInstance().sessionId;
Log.d("gaolei", "sessionId-------MyFragment---------" + sessionId);
if (sessionId == null) {
click_login.setText(getString(R.string.click_login));
return;
}
getUserInfo(sessionId);
}
private static void getUserInfo(String sessionId) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("jeesite.session.id", sessionId);
if (netRequest != null) {
netRequest.httpRequest(map, CommonUrl.getUserInfo);
netRequest.httpRequest(map, CommonUrl.getHomeUser);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent;
String sessionId = LoginResultObject.getInstance().sessionId;
switch (v.getId()) {
case R.id.person_layout:
Log.d("gaolei", "sessionId-------MyFragment---------"
+ LoginResultObject.getInstance().sessionId);
if (LoginResultObject.getInstance().sessionId == null) {
intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
} else {
intent = new Intent(getActivity(), UserInfoActivity.class);
// intent = new Intent(getActivity(),
// UploadPhotoActivity.class);
startActivity(intent);
}
break;
case R.id.play_record_layout:
if (sessionId == null) {
Toast.makeText(getActivity(), getString(R.string.please_login),
Toast.LENGTH_LONG).show();
intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return;
}
intent = new Intent(getActivity(), WatchRecordActivity.class);
startActivity(intent);
break;
case R.id.cache_layout:
intent = new Intent(getActivity(), CacheActivity.class);
intent.putExtra("mVideoPath", "");
startActivity(intent);
break;
case R.id.album_prompt_layout:
if (sessionId == null) {
Toast.makeText(getActivity(), getString(R.string.please_login),
Toast.LENGTH_LONG).show();
intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return;
}
intent = new Intent(getActivity(), AlbumPromptActivity.class);
startActivity(intent);
break;
case R.id.video_collect_layout:
if (sessionId == null) {
Toast.makeText(getActivity(), getString(R.string.please_login),
Toast.LENGTH_LONG).show();
intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return;
}
intent = new Intent(getActivity(), VideoCollectActivity.class);
startActivity(intent);
break;
case R.id.message_layout:
if (sessionId == null) {
Toast.makeText(getActivity(), getString(R.string.please_login),
Toast.LENGTH_LONG).show();
intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return;
}
intent = new Intent(getActivity(), MessageActivity.class);
startActivity(intent);
break;
case R.id.setting_layout:
intent = new Intent(getActivity(), SettingActivity.class);
startActivity(intent);
break;
}
}
@Override
public void changeView(String result, String requestUrl) {
// TODO Auto-generated method stub
if (requestUrl.equals(CommonUrl.getUserInfo)) {
try {
JSONObject object = new JSONObject(result);
String userImg = object.getString("userImg");
// UserInfoObject.getInstance().userImg = userImg;
// CommonUtil.getUtilInstance().displayRoundCornerImage(CommonUrl.baseUrl
// +userImg,
// user_photo, 120);
new DownloadImageTask().execute(CommonUrl.baseUrl + userImg);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (requestUrl.equals(CommonUrl.getHomeUser)) {
try {
JSONObject objct = new JSONObject(result);
// .getString("homeUser");
JSONObject object2 = objct.getJSONObject("homeUser");
String createDate = object2.getString("createDate");
String username = object2.getString("loginName");
UserInfoObject.getInstance().username = username;
UserInfoObject.getInstance().createDate = createDate;
click_login.setText(username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void exception(IOException e, String requestUrl) {
// TODO Auto-generated method stub
}
class DownloadImageTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("[downloadImageTask->]doInBackground "
+ params[0]);
photoBitmap = HttpUtils.getNetWorkBitmap(params[0]);
return "";
}
// 下载完成回调
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
user_photo.setImageBitmap(photoBitmap);
System.out.println("result = " + result);
super.onPostExecute(result);
}
// 更新进度回调
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
}
|
C++
|
UTF-8
| 8,297 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
/*------------------------------------------------------------------------------
LIDARLite Arduino Library
v4LED/v4LED_fast
This example shows how to take multiple distance measurements with a
LIDAR-Lite v4 LED with a high rep rate using the optional GPIO pins
or the I2C port to trigger measurements.
*** NOTE ***
The LIDAR-Lite v4 LED is strictly a 3.3V system. The Arduino Due is a
3.3V system and is recommended for use with the LIDAR-Lite v4 LED.
Care MUST be taken if connecting to a 5V system such as the Arduino Uno.
See comment block in the setup() function for details on I2C connections.
It is recommended to use a voltage level-shifter if connecting the GPIO
pins to any 5V system I/O.
Connections:
LIDAR-Lite 5 VDC (pin 1) to Arduino 5V
LIDAR-Lite Ground (pin 2) to Arduino GND
LIDAR-Lite I2C SDA (pin 3) to Arduino SDA
LIDAR-Lite I2C SCL (pin 4) to Arduino SCL
Optional connections to utilize GPIO triggering:
LIDAR-Lite GPIOA (pin 5) to Arduino Digital 2
LIDAR-Lite GPIOB (pin 6) to Arduino Digital 3 (AMCD: changed to 16 to avoid conflict)
(Capacitor recommended to mitigate inrush current when device is enabled)
680uF capacitor (+) to Arduino 5V
680uF capacitor (-) to Arduino GND
See the Operation Manual for wiring diagrams and more information
------------------------------------------------------------------------------*/
#include <stdint.h>
#include <Wire.h>
#include "LIDARLite_v4LED.h"
LIDARLite_v4LED myLidarLite;
#define FAST_I2C
#define MonitorPin 16
#define TriggerPin 2
//---------------------------------------------------------------------
void setup()
//---------------------------------------------------------------------
{
// Initialize Arduino serial port (for display of ASCII output to PC)
Serial.begin(115200);
// Initialize Arduino I2C (for communication to LidarLite)
Wire.begin();
#ifdef FAST_I2C
#if ARDUINO >= 157
Wire.setClock(400000UL); // Set I2C frequency to 400kHz (for Arduino Due)
#else
TWBR = ((F_CPU / 400000UL) - 16) / 2; // Set I2C frequency to 400kHz
#endif
#endif
// ----------------------------------------------------------------------
// The LIDAR-Lite v4 LED is strictly a 3.3V system. The Arduino Due is a
// 3.3V system and is recommended for use with the LIDAR-Lite v4 LED.
// Care MUST be taken if connecting to a 5V system such as the Arduino Uno.
//
// I2C is a two wire communications bus that requires a pull-up resistor
// on each signal. In the Arduino microcontrollers the Wire.begin()
// function (called above) turns on pull-up resistors that pull the I2C
// signals up to the system voltage rail. The Arduino Uno is a 5V system
// and using the Uno's internal pull-ups risks damage to the LLv4.
//
// The two digitalWrite() functions (below) turn off the micro's internal
// pull-up resistors. This protects the LLv4 from damage via overvoltage
// but requires external pullups to 3.3V for the I2C signals.
//
// External pull-ups are NOT present on the Arduino Uno and must be added
// manually to the I2C signals. 3.3V is available on pin 2 of the 6pin
// "POWER" connector and can be used for this purpose. See the Uno
// schematic for details:
// https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
//
// External 1.5k ohm pull-ups to 3.3V are already present on the
// Arduino Due. If using the Due no further action is required
// ----------------------------------------------------------------------
digitalWrite(SCL, LOW);
digitalWrite(SDA, LOW);
// ----------------------------------------------------------------------
// Optional GPIO pin assignments for measurement triggering & monitoring
// ----------------------------------------------------------------------
pinMode(MonitorPin, INPUT);
pinMode(TriggerPin, OUTPUT);
digitalWrite(TriggerPin, LOW);
// ----------------------------------------------------------------------
// Optionally configure the LidarLite parameters to lend itself to
// various modes of operation by altering 'configure' input integer.
// See LIDARLite_v4LED.cpp for details.
// ----------------------------------------------------------------------
myLidarLite.configure(0);
// ----------------------------------------------------------------------
// ** One method of increasing the measurement speed of the
// LIDAR-Lite v4 LED is to adjust the number of acquisitions taken
// per measurement from the default of 20. For max speed we
// set this value to 0x00 in this example.
// ** Note that when reducing the number of acquisitions taken per
// measurement from the default, repeatability of measurements is
// reduced.
// ----------------------------------------------------------------------
uint8_t dataByte = 0x00;
myLidarLite.write(0xEB, &dataByte, 1, 0x62); // Turn off high accuracy mode
}
//---------------------------------------------------------------------
void loop()
//---------------------------------------------------------------------
{
// Using GPIO triggering can increase the rep rate.
// Remove comments from the line below to use I2C triggering.
// #define USE_I2C_TRIGGERING
uint16_t distance;
uint8_t newDistance;
#ifdef USE_I2C_TRIGGERING
newDistance = distanceContinuous(&distance);
#else
newDistance = distanceContinuousGpio(&distance);
#endif
if (newDistance)
{
if(distance < 65000){ // AMCD: added to stop sending max-distance values
Serial.println(distance); // print measurement to serial terminal
}
}
}
//---------------------------------------------------------------------
// Read Continuous Distance Measurements
//
// The most recent distance measurement can always be read from
// device registers. Polling for the BUSY flag in the STATUS
// register can alert the user that the distance measurement is new
// and that the next measurement can be initiated. If the device is
// BUSY this function does nothing and returns 0. If the device is
// NOT BUSY this function triggers the next measurement, reads the
// distance data from the previous measurement, and returns 1.
//---------------------------------------------------------------------
uint8_t distanceContinuous(uint16_t * distance)
{
uint8_t newDistance = 0;
// Check on busyFlag to indicate if device is idle
// (meaning = it finished the previously triggered measurement)
if (myLidarLite.getBusyFlag() == 0)
{
// Trigger the next range measurement
myLidarLite.takeRange();
// Read new distance data from device registers
*distance = myLidarLite.readDistance();
// Report to calling function that we have new data
newDistance = 1;
}
return newDistance;
}
//---------------------------------------------------------------------
// Read Continuous Distance Measurements using Trigger / Monitor Pins
//
// The most recent distance measurement can always be read from
// device registers. Polling for the BUSY flag using the Monitor Pin
// can alert the user that the distance measurement is new
// and that the next measurement can be initiated. If the device is
// BUSY this function does nothing and returns 0. If the device is
// NOT BUSY this function triggers the next measurement, reads the
// distance data from the previous measurement, and returns 1.
//---------------------------------------------------------------------
uint8_t distanceContinuousGpio(uint16_t * distance)
{
uint8_t newDistance = 0;
// Check on busyFlag to indicate if device is idle
// (meaning = it finished the previously triggered measurement)
if (myLidarLite.getBusyFlagGpio(MonitorPin) == 0)
{
// Trigger the next range measurement
myLidarLite.takeRangeGpio(TriggerPin, MonitorPin);
// Read new distance data from device registers
*distance = myLidarLite.readDistance();
// Report to calling function that we have new data
newDistance = 1;
}
return newDistance;
}
|
Java
|
UTF-8
| 1,063 | 2.1875 | 2 |
[] |
no_license
|
/**
*
*/
package com.meikai.listener;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.meikai.util.PropertiesUtil;
/**
* 设值全局变量
* @author meikai
* @version 2017年10月23日 下午2:15:19
*/
public class PropertiesListenter implements ServletContextListener {
/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
/**
* 将properties文件存入map中
*/
Map<String, String> pros =PropertiesUtil.getMap("kenhome-common.properties");
ServletContext sct=sce.getServletContext();
sct.setAttribute("pros", pros);
}
}
|
Markdown
|
UTF-8
| 1,162 | 2.875 | 3 |
[] |
no_license
|
Summary
=======
In the end, this internship made me discover the world of research by working on a
thesis project. This project, melange, taught me the basics of model engineering,
an IT field I barely knew. Shoutout to Thomas Degueule for having spend a lot of time
explaining me what a language is and how melange is working.
Moreover, it has been a technical challenge; I had to learn a new lanaguage syntax, xtend, and a
new environnement, Eclipse RCP. What stays in my mind is that xtend is a sexy way of doing Java
and it helps focusing on modeling and design because of its powerful yet simple syntax.
(Lambdas expressions are a great example)
On the contrary, the Eclipse Rich Client Platform is really heavy and not accessible.
The main problem is the lack of documentation about its behaviour, especially when
you want to customize thing generated by xtext/emf. This have slowed down the developpement
because each time I wanted to work on a new feature, I had to do some archeology and try to
understand how things work.
To sum up in a few words, the internship has been very enriching intellectually and taught me
the basics of model-driven engineering.
|
Java
|
UHC
| 12,969 | 2.1875 | 2 |
[] |
no_license
|
package sample;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import annotation.Autowired;
import annotation.Controller;
import annotation.RequestMapping;
import annotation.RequestMethod;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import org.snu.ids.ha.ma.Eojeol;
import org.snu.ids.ha.ma.MExpression;
import org.snu.ids.ha.ma.MorphemeAnalyzer;
import org.snu.ids.ha.ma.Sentence;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
@Autowired
TestAutoWired test;
MorphemeAnalyzer ma;
public HomeController() {
// TODO Auto-generated constructor stub
ma = new MorphemeAnalyzer();
// create logger, null then System.out is set as a default logger
}
ConcurrentHashMap<String, UserSession> userSessionMap = new ConcurrentHashMap<>();
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
}
@RequestMapping(value = "/keyboard", method = RequestMethod.GET)
public String keyboard() {
String response = makeDefaultButtonJson().toString();
return response;
}
@RequestMapping(value = "/message", method = RequestMethod.POST)
public String message(String body) {
JSONObject json;
String user_key = null;
String content = null;
try {
json = new JSONObject(body);
user_key = json.getString("user_key");
content = json.getString("content");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (userSessionMap.get(user_key) != null && userSessionMap.get(user_key).is_making) {
insertIntoFile(userSessionMap.get(user_key), content);
userSessionMap.get(user_key).is_making = false;
return makeMessageWithButton3("Է Ͽϴ. ش н Էϱ ؼ Ͽ ϰ, ش ۾ ɸ ֽϴ. Ͽ ٽ ϸ ۵ Դϴ.");
}
if (content.contains("˻")) {
} else if (content.startsWith(":")) {
if (content.equals(":˷ش.")) {
if (userSessionMap.get(user_key) == null) {
return makeMessageWithText(" ʽϴ.");
}
userSessionMap.get(user_key).is_making = true;
return makeMessageWithText("νÿ ϴ ˷, ٸ "
+ " ϴ ˷ , ּ.");
} else if (content.equals(":˷ ʴ´.")) {
return makeMessageWithText("Ǹ ..");
} else if (content.equals(":")) {
return makeMessageWithText("ϴ Էϼ,");
} else if (content.equals(":ٸ")) {
if (userSessionMap.get(user_key) == null) {
return makeMessageWithText(" ʽϴ.");
}
userSessionMap.get(user_key).is_topic_creating = true;
return makeMessageWithText(" ʴ ̾.");
} else if (content.equals(":")) {
getMessageToBot(":build Dorothy reset");
return makeMessageWithText(" н ݿǾϴ.");
}
} else {
content = changeContent(content);
}
System.out.println(content);
String response = getMessageToBot(content);
if (response.equals("ʰ ھ. ˷ٷ?")) {
if (userSessionMap.get(user_key) == null) {
UserSession userSession = new UserSession();
userSession.topic = "brabe";
userSession.topic_count = "0";
userSession.last_content = content;
userSessionMap.put(user_key, userSession);
} else {
userSessionMap.get(user_key).last_content = content;
}
return makeMessageWithButton(response);
} else {
try {
String botMessage[] = response.split("/-");
UserSession userSession = new UserSession();
userSession.topic = botMessage[0];
userSession.topic_count = botMessage[1];
userSession.last_content = content;
userSessionMap.put(user_key, userSession);
response = botMessage[2];
} catch (Exception e) {
e.printStackTrace();
}
}
return makeMessageWithText(response);
}
private void insertIntoFile(UserSession userSession, String message) {
try {
String str;
File file = new File("C:\\Users\\wg\\Documents\\SoftBotProject\\Dorothy\\"+userSession.topic+".top");
RandomAccessFile rf= new RandomAccessFile(file, "rw");
try {
String botMessage[] = userSession.last_content.split(" ");
str = botMessage[0] + " ";
} catch (Exception e) {
str = userSession.last_content;
}
insert("C:\\Users\\wg\\Documents\\SoftBotProject\\Dorothy\\"+userSession.topic+".top", 29, new String(str.getBytes("UTF-8"), "8859_1"));
rf.seek(rf.length());
str = "\r\nu:"+(Integer.parseInt(userSession.topic_count) + 1)+" ( << ";
rf.writeBytes(new String(str.getBytes("UTF-8"), "8859_1"));
str = userSession.last_content + " ";
rf.writeBytes(new String(str.getBytes("UTF-8"), "8859_1"));
str = ">> ) ";
rf.writeBytes(new String(str.getBytes("UTF-8"), "8859_1"));
str = userSession.topic + "/-" + (Integer.parseInt(userSession.topic_count) + 1) + "/-" + message;
rf.writeBytes(new String(str.getBytes("UTF-8"), "8859_1"));
rf.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void insert(String filename, long offset, String content) {
try {
File tmpFile = new File(filename + "~");
RandomAccessFile r = new RandomAccessFile(new File(filename), "rw");
RandomAccessFile rtemp = new RandomAccessFile(tmpFile, "rw");
long fileSize = r.length();
FileChannel sourceChannel = r.getChannel();
FileChannel targetChannel = rtemp.getChannel();
sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
sourceChannel.truncate(offset);
r.seek(offset);
r.writeBytes(content);
long newOffset = r.getFilePointer();
targetChannel.position(0L);
sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
sourceChannel.close();
targetChannel.close();
tmpFile.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String changeContent(String content) {
List ret;
List stl = null;
StringBuffer changeContent = new StringBuffer();
try {
ret = ma.analyze(content);
// refine spacing
ret = ma.postProcess(ret);
// leave the best analyzed result
ret = ma.leaveJustBest(ret);
// divide result to setences
stl = ma.divideToSentences(ret);
Sentence st;
Eojeol eojeol;
// print the result
for (int i = 0; i < stl.size(); i++) {
st = (Sentence) stl.get(i);
for (int j = 0; j < st.size(); j++) {
eojeol = st.get(j);
for (int k = 0; k < eojeol.size(); k++) {
if (eojeol.get(k).getTag().startsWith("NN")) {
changeContent.append(eojeol.get(k).getString() + " ");
} else if (eojeol.get(k).getTag().startsWith("V")) {
changeContent.append(eojeol.get(k).getString() + " ");
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (changeContent.toString().isEmpty()) {
try {
ret = ma.analyze(content);
// refine spacing
ret = ma.postProcess(ret);
// leave the best analyzed result
ret = ma.leaveJustBest(ret);
// divide result to setences
stl = ma.divideToSentences(ret);
Sentence st;
Eojeol eojeol;
// print the result
for (int i = 0; i < stl.size(); i++) {
st = (Sentence) stl.get(i);
for (int j = 0; j < st.size(); j++) {
eojeol = st.get(j);
for (int k = 0; k < eojeol.size(); k++) {
changeContent.append(eojeol.get(k).getString() + " ");
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return changeContent.toString();
}
private String getMessageToBot(String message) {
String response = "";
try {
String urlParameters = "message=" + message + "&send=&user=wongu2";
// Send data
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = "http://127.0.0.1/ui_TESTBOT.php";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response = response + line;
}
rd.close();
} catch (Exception e) {
}
return response;
}
private String makeMessageWithText(String message) {
JSONObject json = new JSONObject();
JSONObject innerJson = new JSONObject();
try {
innerJson.put("text", message);
json.put("message", innerJson);
json.put("keyboard", makeDefaultTextJson());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json.toString();
}
private JSONObject makeDefaultButtonJson() {
JSONObject json = new JSONObject();
try {
json.put("type", "buttons");
JSONArray jarr = new JSONArray();
jarr.put("ϱ");
json.put("buttons", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private JSONObject makeDefaultTextJson() {
JSONObject json = new JSONObject();
try {
json.put("type", "text");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private JSONObject makeCustomButtonJson() {
JSONObject json = new JSONObject();
try {
json.put("type", "buttons");
JSONArray jarr = new JSONArray();
jarr.put(":˷ش.");
jarr.put(":˷ ʴ´.");
json.put("buttons", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private String makeMessageWithButton(String message) {
JSONObject json = new JSONObject();
JSONObject innerJson = new JSONObject();
try {
innerJson.put("text", message);
json.put("message", innerJson);
json.put("keyboard", makeCustomButtonJson());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json.toString();
}
//--------------------------------------------------------------------------
private JSONObject makeCustomButton2Json() {
JSONObject json = new JSONObject();
try {
json.put("type", "buttons");
JSONArray jarr = new JSONArray();
jarr.put(":");
jarr.put(":ٸ");
json.put("buttons", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private String makeMessageWithButtonSubject(String message) {
JSONObject json = new JSONObject();
JSONObject innerJson = new JSONObject();
try {
innerJson.put("text", message);
json.put("message", innerJson);
json.put("keyboard", makeCustomButton2Json());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json.toString();
}
//---------------------------------------------------------------------
private JSONObject makeCustomButton3Json() {
JSONObject json = new JSONObject();
try {
json.put("type", "buttons");
JSONArray jarr = new JSONArray();
jarr.put(":");
json.put("buttons", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private String makeMessageWithButton3(String message) {
JSONObject json = new JSONObject();
JSONObject innerJson = new JSONObject();
try {
innerJson.put("text", message);
json.put("message", innerJson);
json.put("keyboard", makeCustomButton3Json());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json.toString();
}
}
|
PHP
|
UTF-8
| 1,167 | 2.625 | 3 |
[] |
no_license
|
<?php
function save_php_file($file,$arr,$content) {
$f = fopen($file,"w");
fwrite($f,'<?php'."\n");
foreach ($content as $k => $v) {
fwrite($f,"\t".'$'.$k.' = ');
if ($v == 'string')
fwrite($f,"'".addcslashes($arr[$k],"'")."'");
elseif ($v == 'bool')
fwrite($f,$arr[$k]?'true':'false');
else
fwrite($f,$arr[$k]);
fwrite($f,";\n");
}
fwrite($f,'?>');
fclose($f);
}
function save_globals($arr) {
$including='cmsglobals.inc';
include('_data/__abstraction.php');
$def = get_defined_vars();
include('_data/__info_data.php');
$my_arr = array();
foreach ($data_content[$including] as $k => $v) {
$my_arr[$k] = (isset($arr[$k]))?$arr[$k]:$def[$k];
}
save_php_file(server_dir.'/_data/cmsglobals.inc.php',$my_arr,$data_content[$including]);
}
function save_globals_mob($arr) {
$including='mobglobals.inc';
include('mobile/_data/__abstraction.php');
$def = get_defined_vars();
include('_data/__info_data.php');
$my_arr = array();
foreach ($data_content[$including] as $k => $v) {
$my_arr[$k] = (isset($arr[$k]))?$arr[$k]:$def[$k];
}
save_php_file(server_dir.'/mobile/_data/mobglobals.inc.php',$my_arr,$data_content[$including]);
}
?>
|
JavaScript
|
UTF-8
| 366 | 3.8125 | 4 |
[] |
no_license
|
function weekendOrWorkingDay(arg) {
let days = {'Monday': 1, 'Tuesday' : 1, 'Wednesday' : 1, 'Thursday' : 1, 'Friday' : 1, 'Saturday':2 ,'Sunday':2}
if (days[arg] === 1) {
console.log('Working day');
} else if( days[arg] === 2){
console.log('Weekend');
} else{
console.log('Error');
}
}
// weekendOrWorkingDay('Monday')
// weekendOrWorkingDay('April')
|
C++
|
UTF-8
| 1,754 | 2.96875 | 3 |
[] |
no_license
|
// Module: BallBase.cpp
// Author: Miguel Antonio Logarta
// Date: February 28, 2020
// Purpose: Implementation file for base class BallBase
// Responsible for drawing balls
#include "CIS023_S2020_HW11 Miguel Antonio Logarta.h"
void BallBase::Initialize(HWND hWnd)
{
// Make GDI graphic a random size of 20 to 50 px
dSize = GetRandom(20, 50);
// Get client window dimensions
RECT rClient;
GetClientRect(hWnd, &rClient); // Window
// Start at the center of the window
// Half of the client window - half of the size of the ball
rDim.left = (rClient.right / 2) - (dSize / 2.0);
rDim.top = (rClient.bottom / 2) - (dSize / 2.0);
rDim.right = rDim.left + dSize;
rDim.bottom = rDim.top + dSize;
// Set a random color
r = GetRandom(0, 255);
g = GetRandom(0, 255);
b = GetRandom(0, 255);
// Set the x and y speed of the object to a random value between 1 and 20
pSpeed.x = GetRandom(1, 20);
pSpeed.y = GetRandom(1, 20);
}
void BallBase::Draw(HDC hdc)
{
HBRUSH brush = CreateSolidBrush(RGB(r, g, b));
HBRUSH oldBrush;
oldBrush = (HBRUSH)SelectObject(hdc, brush);
// Draw the object
Ellipse(hdc, rDim.left, rDim.top, rDim.right, rDim.bottom);
SelectObject(hdc, oldBrush);
DeleteObject(brush);
}
int BallBase::GetRandom(int iMin, int iMax)
{
random_device rd; // Non-deterministic generator
mt19937 gen(rd()); // To seed mersenne twister
uniform_int_distribution<> dist(iMin, iMax); // Distribute results inside center rect
return dist(gen);
}
RECT BallBase::GetInvalidRect()
{
rReturn = rDim; // Start with current size
// Expand to account for movement
rReturn.left -= dSize;
rReturn.top -= dSize;
rReturn.right += dSize;
rReturn.bottom += dSize;
return rReturn; // Return new (larger) rectangle
}
|
Java
|
UTF-8
| 1,026 | 2.40625 | 2 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
package com.dianping.phoenix.agent;
import java.io.File;
import org.apache.log4j.Logger;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
public class StandaloneServer {
private final static Logger logger = Logger.getLogger(StandaloneServer.class);
public static void main(String[] args) throws Exception {
if (args.length != 3) {
logger.error("usage: port contextPath warRoot");
return;
}
int port = Integer.parseInt(args[0]);
String contextPath = args[1];
File warRoot = new File(args[2]);
logger.info(String.format("starting jetty@%d, contextPath %s, warRoot %s", port, contextPath,
warRoot.getAbsoluteFile()));
Server server = new Server(port);
WebAppContext context = new WebAppContext();
System.out.println(warRoot.getAbsolutePath());
context.setContextPath(contextPath);
context.setDescriptor(new File(warRoot, "WEB-INF/web.xml").getPath());
context.setResourceBase(warRoot.getPath());
server.setHandler(context);
server.start();
}
}
|
Python
|
UTF-8
| 1,894 | 2.890625 | 3 |
[] |
no_license
|
from types import TracebackType
from typing import IO, AnyStr, Iterable, Iterator, Optional, Type
import pyte
class PyteStreamWrapper(IO):
"""
A simple wrapper around pyte's stream to be usable from blessed's terminal.
"""
FILE_NO = 999999
def __init__(self, stream: pyte.streams.Stream):
self._stream = stream
def close(self) -> None:
raise NotImplementedError
def fileno(self) -> int:
return self.FILE_NO
def flush(self) -> None:
pass
def isatty(self) -> bool:
return True
def read(self, n: int = ...) -> AnyStr:
raise NotImplementedError
def readable(self) -> bool:
raise NotImplementedError
def readline(self, limit: int = ...) -> AnyStr:
raise NotImplementedError
def readlines(self, hint: int = ...) -> list[AnyStr]:
raise NotImplementedError
def seek(self, offset: int, whence: int = ...) -> int:
raise NotImplementedError
def seekable(self) -> bool:
raise NotImplementedError
def tell(self) -> int:
raise NotImplementedError
def truncate(self, size: Optional[int] = ...) -> int:
raise NotImplementedError
def writable(self) -> bool:
raise NotImplementedError
def write(self, s: AnyStr) -> int:
self._stream.feed(s)
return len(s)
def writelines(self, lines: Iterable[AnyStr]) -> None:
raise NotImplementedError
def __next__(self) -> AnyStr:
raise NotImplementedError
def __iter__(self) -> Iterator[AnyStr]:
raise NotImplementedError
def __enter__(self) -> IO[AnyStr]:
raise NotImplementedError
def __exit__(
self,
t: Optional[Type[BaseException]],
value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> Optional[bool]:
raise NotImplementedError
|
Java
|
UTF-8
| 26,084 | 1.757813 | 2 |
[] |
no_license
|
package com.eostek.sciflyui.thememanager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import scifly.dm.EosDownloadListener;
import scifly.dm.EosDownloadManager;
import scifly.dm.EosDownloadTask;
import scifly.thememanager.IThemeChangeListener;
import android.app.AlertDialog;
import android.app.DownloadManager.Request;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.FileUtils;
import android.os.RemoteException;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnHoverListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.eostek.sciflyui.thememanager.download.IDownloadProgressListener;
import com.eostek.sciflyui.thememanager.download.IUpgradeStateListener;
import com.eostek.sciflyui.thememanager.task.ThemeModel;
import com.eostek.sciflyui.thememanager.ui.TransparentDialog;
import com.eostek.sciflyui.thememanager.util.Constant;
import com.eostek.sciflyui.thememanager.util.ThemeManagerUtils;
/**
* @author Admin
*/
public class ThemeListener {
/**
* TAG.
*/
protected static final String TAG = "ThemeListener";
private ThemeDisplayAct mActivity = null;
private ThemeHolder mHolder = null;
private static boolean isDownloading = false;
private int mSelectedPosition = 0;
/**
* mWarning AlertDialog.
*/
protected AlertDialog mWarning = null;
private TransparentDialog mChangeThemeWaittingDialog;
private Context mContext;
private EosDownloadManager mManager;
private EosDownloadTask mTask;
private int mPercent;
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public EosDownloadManager getmManager() {
return mManager;
}
public void setmManager(EosDownloadManager mManager) {
this.mManager = mManager;
}
public EosDownloadTask getmTask() {
return mTask;
}
public void setmTask(EosDownloadTask mTask) {
this.mTask = mTask;
}
public int getmPercent() {
return mPercent;
}
public void setmPercent(int mPercent) {
this.mPercent = mPercent;
}
/**
* set selected the position.
*
* @param selectedPosition selected the position.
*/
public final void setSelectedPosition(int selectedPosition) {
this.mSelectedPosition = selectedPosition;
}
/**
* constructor.
*
* @param activity context.
* @param holder views.
*/
public ThemeListener(ThemeDisplayAct activity, ThemeHolder holder) {
this.mActivity = activity;
this.mHolder = holder;
}
private ProgressBar mCurrentProgressBar;
/**
* monitor delete event.
*/
protected OnClickListener deleteThemeListener = new OnClickListener() {
public void onClick(View arg0) {
boolean isDeleteSuccessed = ThemeManagerUtils.deleteTheme(mActivity, mSelectedPosition);
if (isDeleteSuccessed) {
Log.i(TAG, "deleting successed");
mActivity.mHandler.sendEmptyMessage(ThemeDisplayAct.UPGRADE_GRIDVIEW);
mActivity.mSelected = mSelectedPosition;
}
mActivity.mDeleteThemeDialog.dismiss();
}
};
/**
* monitor cancel delete theme event.
*/
protected OnClickListener deleteThemeCancelListener = new OnClickListener() {
public void onClick(View arg0) {
mActivity.mDeleteThemeDialog.dismiss();
}
};
/**
* monitor download progress.
*/
protected class ThemeDownloadProgressListener implements IDownloadProgressListener {
int mPosition = 0;
/**
* @param position position
*/
public ThemeDownloadProgressListener(int position) {
super();
this.mPosition = position;
}
@Override
public void onDownloadSizeChange(int taskId, final int i) {
// mThemes.get(current).progress = i;
if (i == Constant.RESOURCE_TOTAL_SIZE) {
Log.i(TAG, "download finished");
mActivity.mThemes.get(mPosition).downloadIsCompleted = true;
mActivity.mThemes.get(mPosition).mType = ThemeModel.TYPE.LOCAL;
}
// shielded by youpeng.wan
// mHandler.sendEmptyMessage(1);
if (mCurrentProgressBar != null) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mCurrentProgressBar.setProgress(i);
}
});
}
}
}
/**
* update state.
*/
protected class ThemeUpgradeStateListener implements IUpgradeStateListener {
private int mPosition = 0;
/**
* @param position position
*/
public ThemeUpgradeStateListener(int position) {
super();
this.mPosition = position;
}
@Override
public void onResume(int taskId, String string) {
Log.i(TAG, "onResume");
}
@Override
public void onPreparedSuccess(int taskId, String string) {
isDownloading = true;
Log.i(TAG, "onPreparedSuccess");
}
@Override
public void onPreparedFailed(int taskId, String string) {
Log.i(TAG, "onPreparedFailed");
isDownloading = false;
}
@Override
public void onPause(int taskId, String string) {
Log.i(TAG, "onPause");
}
@Override
public void onInstalledSuccess(int taskId, String string) {
Log.i(TAG, "onInstalledSuccess");
}
@Override
public void onInstalledFailed(int taskId, String string) {
Log.i(TAG, "onInstalledFailed");
}
@Override
public void onDownloadedSuccess(int taskId, String localUrl) {
isDownloading = false;
// ThemeManager.getInstance().changeTheme(localUrl, listener);
mActivity.mThemes.get(mPosition).mType = ThemeModel.TYPE.LOCAL;
mActivity.setSelected(mPosition);
mActivity.mHandler.sendEmptyMessage(ThemeDisplayAct.UPGRADE_GRIDVIEW);
setItemHoverListener();
}
@Override
public void onDownloadFailed(int taskId, String string) {
isDownloading = false;
mActivity.mThemes.get(mPosition).isError = true;
}
@Override
public void onCleanSuccess(int taskId, String string) {
}
@Override
public void onCleanFailed(int taskId, String string) {
}
}
private IThemeChangeListener mIThemeChangeListener = new IThemeChangeListener.Stub() {
@Override
public void onSucceed() throws RemoteException {
Log.i(TAG, "Theme changed succeed.");
}
@Override
public void onStatus(String arg0) throws RemoteException {
}
@Override
public void onFailed(String arg0) throws RemoteException {
Log.i(TAG, "Theme changed failed.");
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mWarning = new AlertDialog.Builder(mActivity).setMessage(R.string.warning)
.setPositiveButton(R.string.confirm, null).show();
}
});
}
};
/**
* monitor gridView event.
*/
public void setListeners() {
mHolder.getGirdview().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "id = " + position);
final ThemeModel selectedModel = mActivity.mThemes.get(position);
if (selectedModel != null) {
if (selectedModel.mType == ThemeModel.TYPE.LOCAL || selectedModel.mType == ThemeModel.TYPE.DEFAULT) {
mActivity.setSelected(position);
if (!selectedModel.equals(mActivity.mCurrentThemeModel)) {
// mHolder.changeWallpaperWatting.setVisibility(View.VISIBLE);
mChangeThemeWaittingDialog = new TransparentDialog(mActivity);
mChangeThemeWaittingDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
// switch theme
// ThemeManager.getInstance().changeTheme(selectedModel.mLocalUrl,
// mIThemeChangeListener);
try {
Log.d(TAG, "selectedModel.mLocalUrl=" + selectedModel.mLocalUrl);
upZipFile(selectedModel.mLocalUrl, "/data/eostek/");
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
changeWallpaper(selectedModel);
mActivity.runOnUiThread(new Runnable() {
public void run() {
mActivity.changeBackgound();
Toast.makeText(mActivity, R.string.change_success, Toast.LENGTH_LONG)
.show();
mChangeThemeWaittingDialog.dismiss();
}
});
}
private static final int BUFF_SIZE = 1024 * 1024; // 1M
// Byte
public void deleteAllFiles(File file, boolean delParent) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else {
File[] files = file.listFiles();
for (File f : files) {
if (file.isFile()) {
file.delete();
} else {
deleteAllFiles(f, true);
}
}
if (delParent) {
file.delete();
}
}
}
}
public void upZipFile(String source, String destPath) throws ZipException, IOException {
// delete folder and files.
File file = new File(destPath);
try {
deleteAllFiles(file, false);
} catch (Exception e) {
e.printStackTrace();
}
// dest path is same as the zip file
File destDir = new File(destPath);
if (!destDir.exists()) {
destDir.mkdirs();
// change access right of folder.
FileUtils.setPermissions(source, 0777, -1, -1);
}
ZipFile zf = new ZipFile(source);
for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String str = destPath + File.separator + entry.getName();
if (entry.isDirectory()) {
File desFile = new File(str);
if (!desFile.exists()) {
desFile.mkdirs();
// change access right of
// folder.
FileUtils.setPermissions(str, 0777, -1, -1);
}
} else {
// unzip file.
InputStream in = zf.getInputStream(entry);
File desFile = new File(str);
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
FileUtils.setPermissions(fileParentDir.getAbsolutePath(), 0777, -1,
-1);
}
desFile.createNewFile();
// change access right of file.
FileUtils.setPermissions(str, 0777, -1, -1);
}
OutputStream out = new FileOutputStream(desFile);
byte buffer[] = new byte[BUFF_SIZE];
int realLength;
while ((realLength = in.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
out.flush();
in.close();
out.close();
in = null;
out = null;
}
}
zf.close();
}
}).start();
ImageView mCurrent = null;
if (mActivity.mCurrentView != null) {
mCurrent = (ImageView) mActivity.mCurrentView.findViewById(R.id.selected);
}
final ImageView mSelected = (ImageView) view.findViewById(R.id.selected);
final ImageView current = mCurrent;
mActivity.mCurrentThemeModel = selectedModel;
mActivity.mCurrentView = view;
/**
* refresh selected icon in current view and
* selected view
*/
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mSelected.setVisibility(View.VISIBLE);
if (current != null) {
current.setVisibility(View.GONE);
}
}
});
}
} else if (selectedModel.mType == ThemeModel.TYPE.ONLINE) {
Log.i(TAG, "isDownloading " + isDownloading);
if (isDownloading) {
Toast.makeText(mActivity, R.string.downloading_tip, Toast.LENGTH_LONG).show();
return;
}
isDownloading = true;
if (selectedModel.mDownloadUrl == null || "".equals(selectedModel.mDownloadUrl)) {
isDownloading = false;
Toast.makeText(mActivity, R.string.no_downloadurl_tip, Toast.LENGTH_LONG).show();
return;
}
mActivity.setSelected(position);
mCurrentProgressBar = (ProgressBar) view.findViewById(R.id.progress);
mCurrentProgressBar.setVisibility(View.VISIBLE);
final TextView downloadInfo = (TextView) view.findViewById(R.id.item_textview);
ImageView download = (ImageView) view.findViewById(R.id.download);
// 1.download theme.
downloadInfo.setText(R.string.downloading);
Request request = new Request(Uri.parse(selectedModel.mDownloadUrl));
// Log.i("test", selectedModel.mLocalUrl);
// Log.i("test", selectedModel.mDownloadUrl);
request.setDestinationInExternalPublicDir(Constant.PREFIX, "/" + selectedModel.mTitle + "_"
+ selectedModel.mThemeVersion + ".zip");
// 打印u盘路径
File file = Environment.getExternalStoragePublicDirectory(Constant.PREFIX);
Log.d(TAG, "download path=" + file.getAbsolutePath());
EosDownloadListener listener = new EosDownloadListener() {
@Override
public void onDownloadStatusChanged(int status) {
// TODO Auto-generated method stub
Log.i("test", "onDownloadStatusChanged: " + status);
if (status == 4) {
// Toast.makeText(getmContext(),
// R.string.info,
// Toast.LENGTH_SHORT).show();
isDownloading = false;
Log.i("test", "-------------> 4");
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(mActivity, R.string.download_fail_tip, Toast.LENGTH_SHORT)
.show();
downloadInfo.setText(R.string.info);
mManager.removeTask(mTask.getTaskId());
mCurrentProgressBar.setProgressDrawable(mActivity.getResources()
.getDrawable(R.drawable.progress_pause));
}
});
}
}
@Override
public void onDownloadSize(long size) {
// TODO Auto-generated method stub
Log.i("test", "onDownloadSize: " + size);
}
@Override
public void onDownloadComplete(final int percent) {
// TODO Auto-generated method stub
Log.i("test", "onDownloadComplete: " + percent);
mPercent = percent;
mActivity.runOnUiThread(new Runnable() {
public void run() {
mCurrentProgressBar.setProgress(percent);
if (percent == 100) {
isDownloading = false;
downloadInfo.setText(selectedModel.mTitle);
mCurrentProgressBar.setProgress(0);
selectedModel.mType = ThemeModel.TYPE.LOCAL;
}
}
});
}
};
mTask = new EosDownloadTask(request, listener);
mManager = new EosDownloadManager(mContext);
long num = mManager.addTask(mTask);
download.setVisibility(View.GONE);
Log.i("test", "" + num);
}
}
}
private synchronized void changeWallpaper(ThemeModel selectedModel) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(mActivity);
Bitmap bitmap = ThemeManagerUtils.getWallpaperFromZip(selectedModel.mLocalUrl);
try {
if (bitmap != null) {
Log.i(TAG, "set wallpaper");
wallpaperManager.setBitmap(bitmap);
mActivity.mHandler.sendEmptyMessage(ThemeDisplayAct.RESTART_SCIFLY_VIDEO);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
mHolder.getGirdview().setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// mActivity.setSelected(arg2);
Log.i(TAG, "" + arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
Bitmap getImageFromAssetsFile(String fileName) {
Bitmap image = null;
AssetManager am = mActivity.getResources().getAssets();
try {
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
/**
* setItemHoverListener.
*/
public void setItemHoverListener() {
Log.i(TAG, "mHolder.getGirdview().getCount() " + mHolder.getGirdview().getCount());
final ViewTreeObserver observer = mHolder.getGirdview().getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (!observer.isAlive()) {
ViewTreeObserver observer = mHolder.getGirdview().getViewTreeObserver();
observer.removeOnGlobalLayoutListener(this);
} else {
observer.removeOnGlobalLayoutListener(this);
}
for (int i = 0; i < mHolder.getGirdview().getCount(); i++) {
View child = mHolder.getGirdview().getChildAt(i);
Log.i(TAG, "child== null?" + (child == null));
if (child != null) {
Log.i(TAG, "child i" + i);
child.setOnHoverListener(new ThemeHoverListener());
}
}
}
});
mHolder.getMainLayout().setOnHoverListener(new ThemeHoverListener());
mHolder.getGirdview().setOnHoverListener(new ThemeHoverListener());
}
/**
* @author admin
*/
public class ThemeHoverListener implements OnHoverListener {
@Override
public boolean onHover(View view, MotionEvent motionEvent) {
mActivity.setHoveredView(view);
return true;
}
}
/**
* get Change Theme Waitting Dialog.
*
* @return TransparentDialog
*/
public TransparentDialog getChangeThemeWaittingDialog() {
return mChangeThemeWaittingDialog;
}
}
|
Java
|
UTF-8
| 14,578 | 2.25 | 2 |
[
"MIT"
] |
permissive
|
/*
***************************************************************************
* Mica - the Java(tm) Graphics Framework *
***************************************************************************
* NOTICE: Permission to use, copy, and modify this software and its *
* documentation is hereby granted provided that this notice appears in *
* all copies. *
* *
* Permission to distribute un-modified copies of this software and its *
* documentation is hereby granted provided that no fee is charged and *
* that this notice appears in all copies. *
* *
* SOFTWARE FARM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE *
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT *
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR *
* A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOFTWARE FARM SHALL NOT BE *
* LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR *
* CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, MODIFICATION OR *
* DISTRIBUTION OF THIS SOFTWARE OR ITS DERIVATIVES. *
* *
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND *
* DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, *
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS. *
* *
***************************************************************************
* Copyright (c) 1997-2004 Software Farm, Inc. All Rights Reserved. *
***************************************************************************
*/
package com.swfm.mica;
import com.swfm.mica.util.FastVector;
import java.util.Hashtable;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;
/**
* Constructs a renderer which generates a background
* gradient image effect when assigned to one or more
* parts using their setBackgroundRenderer() method.
*
* @version %I% %G%
* @author Michael L. Davis
* @release 1.4.1
* @module %M%
* @language Java (JDK 1.4)
*/
public class MiGradientRenderer extends MiDeviceRenderer implements MiiTypes, MiiAttributeTypes
{
private int DEFAULT_WIDTH = 128;
private int DEFAULT_HEIGHT = 128;
private int transparency = (255 << 24);
private int lightSourceLocation = Mi_UPPER_LEFT_LOCATION;
private Color baseColor = MiColorManager.veryDarkWhite;
private Color upperLeftColor = MiColorManager.darkWhite;
private Color upperRightColor = MiColorManager.veryDarkWhite;
private Color lowerLeftColor = MiColorManager.veryDarkWhite;
private Color lowerRightColor = MiColorManager.gray;
private int baseImageWidth = DEFAULT_WIDTH;
private int baseImageHeight = DEFAULT_HEIGHT;
private int[] pixels;
private Image image;
private double darkerBrighterFactor = 0.7;
private Hashtable imageCache = new Hashtable();
//private boolean ignoreAssignedToPartsBGColor;
private boolean gradientBaseColorEqualsPartBGColor = true;
/**------------------------------------------------------
* Constructs a renderer which generates a background
* gradient image effect when assigned to one or more
* parts using their setBackgroundRenderer() method.
* @see MiPart#setBackgroundRenderer
* @see setGradientBaseColorEqualsPartBGColor
*------------------------------------------------------*/
public MiGradientRenderer()
{
}
public void setBaseSize(int width, int height)
{
baseImageWidth = width;
baseImageHeight = height;
}
public int getBaseWidth()
{
return(baseImageWidth);
}
public int getBaseHeight()
{
return(baseImageHeight);
}
/**------------------------------------------------------
* Sets the base color of this renderer. This is used in
* conjunction with light direction to generate a gradient.
* TRANSPARENT_COLOR as a background, then this renderer does
* nothing for that part.
* @param c the color.
* @see #setGradientBaseColorEqualsPartBGColor
* @see #getGradientBaseColorEqualsPartBGColor
* @see #getBaseColor
*------------------------------------------------------*/
public void setBaseColor(Color c)
{
baseColor = c;
reCalcCornerColors();
}
/**------------------------------------------------------
* Gets the base color of this renderer. This is used in
* conjunction with light direction to generate a gradient.
* TRANSPARENT_COLOR as a background, then this renderer does
* nothing for that part.
* @return the color.
* @see #setGradientBaseColorEqualsPartBGColor
* @see #getGradientBaseColorEqualsPartBGColor
* @see #setBaseColor
*------------------------------------------------------*/
public Color getBaseColor()
{
return(baseColor);
}
/**------------------------------------------------------
* Sets whether this renderer looks at the background
* color of each part that is being renderered or whether
* this uses the assigned base color. This is true by default.
* In any case, if a part that is being rendered has
* TRANSPARENT_COLOR as a background, then this renderer does
* nothing for that part.
* @param flag true if the background color of the
* part being rendered determine the base color.
* @see #getGradientBaseColorEqualsPartBGColor
* @see #setBaseColor
* @see #getBaseColor
*------------------------------------------------------*/
public void setGradientBaseColorEqualsPartBGColor(boolean flag)
{
gradientBaseColorEqualsPartBGColor = flag;
}
/**------------------------------------------------------
* Gets whether this renderer looks at the background
* color of each part that is being renderered or whether
* this uses the assigned base color. This is true by default.
* In any case, if a part that is being rendered has
* TRANSPARENT_COLOR as a background, then this renderer does
* nothing for that part.
* @return true if the background color of the
* part being rendered determine the base color.
* @see #setGradientBaseColorEqualsPartBGColor
* @see #setBaseColor
* @see #getBaseColor
*------------------------------------------------------*/
public boolean getGradientBaseColorEqualsPartBGColor()
{
return(gradientBaseColorEqualsPartBGColor);
}
/****
public void setIgnoreAssignedToPartsBackgroundColor(boolean flag)
{
ignoreAssignedToPartsBGColor = flag;
}
public boolean getIgnoreAssignedToPartsBackgroundColor()
{
return(ignoreAssignedToPartsBGColor);
}
****/
public void setLightSourceLocation(int location)
{
lightSourceLocation = location;
reCalcCornerColors();
}
public int getLightSourceLocation()
{
return(lightSourceLocation);
}
protected void reCalcCornerColors()
{
if (baseColor == MiiTypes.Mi_TRANSPARENT_COLOR)
return;
// Black does not get "darker or lighter" in JDK 1.0.2
if (baseColor.equals(MiColorManager.black))
baseColor = MiColorManager.darkGray;
Color c = baseColor;
Color brighter = brighter(c);
Color darker = darker(c);
switch (lightSourceLocation)
{
case Mi_CENTER_LOCATION :
break;
case Mi_LEFT_LOCATION :
upperLeftColor = brighter;
upperRightColor = darker;
lowerLeftColor = brighter;
lowerRightColor = darker;
break;
case Mi_RIGHT_LOCATION :
upperLeftColor = darker;
upperRightColor = brighter;
lowerLeftColor = darker;
lowerRightColor = brighter;
break;
case Mi_BOTTOM_LOCATION :
upperLeftColor = darker;
upperRightColor = darker;
lowerLeftColor = brighter;
lowerRightColor = brighter;
break;
case Mi_TOP_LOCATION :
upperLeftColor = brighter;
upperRightColor = brighter;
lowerLeftColor = darker;
lowerRightColor = darker;
break;
case Mi_LOWER_LEFT_LOCATION :
upperLeftColor = c;
upperRightColor = darker;
lowerLeftColor = brighter;
lowerRightColor = c;
break;
case Mi_LOWER_RIGHT_LOCATION :
upperLeftColor = darker;
upperRightColor = c;
lowerLeftColor = c;
lowerRightColor = brighter;
break;
case Mi_UPPER_LEFT_LOCATION :
upperLeftColor = brighter;
upperRightColor = c;
lowerLeftColor = c;
lowerRightColor = darker;
break;
case Mi_UPPER_RIGHT_LOCATION :
upperLeftColor = c;
upperRightColor = brighter;
lowerLeftColor = darker;
lowerRightColor = c;
break;
case Mi_SURROUND_LOCATION :
break;
}
}
/**
* @param factor (default value = 0.7) to use to calc darker and brighter colors from base color
**/
public void setDarkerBrighterFactor(double factor)
{
if (factor < 0.1)
{
factor = 0.1;
}
else if (factor > 0.9)
{
factor = 0.9;
}
darkerBrighterFactor = factor;
reCalcCornerColors();
}
public double getDarkerBrighterFactor()
{
return(darkerBrighterFactor);
}
public Color brighter(Color c)
{
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
if (red < 10)
{
red = 10;
}
if (green < 10)
{
green = 10;
}
if (blue < 10)
{
blue = 10;
}
return(new Color(
Math.min((int )(red/darkerBrighterFactor), 255),
Math.min((int )(green/darkerBrighterFactor), 255),
Math.min((int )(blue/darkerBrighterFactor), 255)));
}
public Color darker(Color c)
{
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
return(new Color(
(int )(red * darkerBrighterFactor),
(int )(green * darkerBrighterFactor),
(int )(blue * darkerBrighterFactor)));
}
public void setUpperLeftColor(Color c)
{
upperLeftColor = c;
}
public Color getUpperLeftColor()
{
return(upperLeftColor);
}
public void setUpperRightColor(Color c)
{
upperRightColor = c;
}
public Color getUpperRightColor()
{
return(upperRightColor);
}
public void setLowerLeftColor(Color c)
{
lowerLeftColor = c;
}
public Color getLowerLeftColor()
{
return(lowerLeftColor);
}
public void setLowerRightColor(Color c)
{
lowerRightColor = c;
}
public Color getLowerRightColor()
{
return(lowerRightColor);
}
public void setTransparency(double t)
{
transparency = ((int )(t * 255)) << 24;
}
public double getTransparency()
{
return(((double )(transparency >> 24))/255);
}
public boolean drawRect(Graphics g, MiAttributes atts,
int dxmin, int dymin, int dwidth, int dheight)
{
if (atts.objectAttributes[Mi_BACKGROUND_IMAGE] != null)
{
return(true);
}
//if (!ignoreAssignedToPartsBGColor)
{
Color bgColor = (Color )atts.objectAttributes[Mi_BACKGROUND_COLOR];
if (bgColor == MiiTypes.Mi_TRANSPARENT_COLOR)
return(true);
if ((bgColor != baseColor) && (gradientBaseColorEqualsPartBGColor))
{
image = (Image )imageCache.get(bgColor);
if (image == null)
setBaseColor(bgColor);
else
baseColor = bgColor;
}
}
if (baseColor == MiiTypes.Mi_TRANSPARENT_COLOR)
return(true);
if (image == null)
{
pixels = createPixelBuffer(baseImageWidth, baseImageHeight);
image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(baseImageWidth, baseImageHeight,
ColorModel.getRGBdefault(),
pixels, 0, baseImageWidth));
imageCache.put(baseColor, image);
}
g.drawImage(image, dxmin, dymin, dwidth, dheight, null);
return(false);
}
public Image createImage(int width, int height)
{
int[] pixels = createPixelBuffer(baseImageWidth, baseImageHeight);
Image image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(baseImageWidth, baseImageHeight,
ColorModel.getRGBdefault(),
pixels, 0, baseImageWidth));
return(image);
}
protected int[] createPixelBuffer(int width, int height)
{
int[] pixelBuffer = new int[width * height];
int leftSideRedColorHeight = lowerLeftColor.getRed() - upperLeftColor.getRed();
int rightSideRedColorHeight = lowerRightColor.getRed() - upperRightColor.getRed();
int leftSideGreenColorHeight = lowerLeftColor.getGreen() - upperLeftColor.getGreen();
int rightSideGreenColorHeight = lowerRightColor.getGreen() - upperRightColor.getGreen();
int leftSideBlueColorHeight = lowerLeftColor.getBlue() - upperLeftColor.getBlue();
int rightSideBlueColorHeight = lowerRightColor.getBlue() - upperRightColor.getBlue();
int upperLeftRedColor = upperLeftColor.getRed();
int upperLeftGreenColor = upperLeftColor.getGreen();
int upperLeftBlueColor = upperLeftColor.getBlue();
int upperRightRedColor = upperRightColor.getRed();
int upperRightGreenColor = upperRightColor.getGreen();
int upperRightBlueColor = upperRightColor.getBlue();
int index = 0;
for (int y = 0; y < height; ++y)
{
double scaleY = ((double )y)/height;
int leftRedColor = (int )(scaleY * leftSideRedColorHeight) + upperLeftRedColor;
int leftGreenColor = (int )(scaleY * leftSideGreenColorHeight) + upperLeftGreenColor;
int leftBlueColor = (int )(scaleY * leftSideBlueColorHeight) + upperLeftBlueColor;
int rightRedColor = (int )(scaleY * rightSideRedColorHeight) + upperRightRedColor;
int rightGreenColor = (int )(scaleY * rightSideGreenColorHeight) + upperRightGreenColor;
int rightBlueColor = (int )(scaleY * rightSideBlueColorHeight) + upperRightBlueColor;
int rowRedColorWidth = rightRedColor - leftRedColor;
int rowGreenColorWidth = rightGreenColor - leftGreenColor;
int rowBlueColorWidth = rightBlueColor - leftBlueColor;
for (int x = 0; x < width; ++x)
{
double scale = ((double )x)/width;
pixelBuffer[index++] =
(((((int )(scale * rowRedColorWidth) + leftRedColor) << 16)
+ (((int )(scale * rowGreenColorWidth) + leftGreenColor) << 8)
+ ((int )(scale * rowBlueColorWidth) + leftBlueColor)) &0x00ffffff)
+ transparency;
}
}
return(pixelBuffer);
}
}
|
C++
|
UTF-8
| 559 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
#ifndef MOUNTAIN
#define MOUNTAIN
#include "Entity/Tiles/Static/StaticTile.h"
using namespace sf;
class Mountain : public StaticTile
{
private:
Vector2i type;
//Get the correct type of a given mountain
static Parts* getParts(const Vector2i& gridPos);
protected:
public:
Mountain(Vector2f pos, Vector2i type);
virtual ~Mountain();
virtual void draw(RenderTarget* window) const;
virtual void update(const float& dt, const float& multiplier);
//Static defintions
inline static Parts* const ROCK = Mountain::getParts(Vector2i(0, 0));
};
#endif
|
Python
|
UTF-8
| 1,296 | 3.171875 | 3 |
[] |
no_license
|
from functools import reduce
def rev(arr, mov, pos):
"""
(0 1 2) 3 4, mov = 3, pos = 0 -> (2 1 0) 3 4
2 1) 0 (3 4, mov = 3, pos = 3 -> 4 3) 0 (1 2
"""
r = list(arr)
for i in range(mov):
r[(pos + i) % len(arr)] = arr[(pos + mov - i - 1) % len(arr)]
return r
def tie(lenghts, n=256):
skipsize = 0
pos = 0
arr = list(range(n))
for _ in range(64):
for mov in lenghts:
arr = rev(arr, mov, pos)
pos += mov + skipsize
skipsize += 1
r = [ reduce(lambda s, x: s ^ x, arr[i*16:(i+1)*16]) for i in range(256//16)]
assert len(r) == 16
r = map(lambda x : '{:02x}'.format(x), r)
return ''.join(r)
def tie_binary(r):
ascii = [ord(str(s)) for s in r]
print('run for', r)
res = tie(ascii + [17, 31, 73, 47, 23])
print('x',res)
assert len(res) == len('a2582a3a0e66e6e86e3812dcb672a272')
return res
assert tie_binary('') == 'a2582a3a0e66e6e86e3812dcb672a272'
assert tie_binary('AoC 2017') == '33efeb34ea91902bb2f59c9920caa6cd'
assert tie_binary('1,2,3') == '3efbe78a8d82f29979031a4aa0b16a9d'
assert tie_binary('1,2,4') == '63960835bcdc130f0b66d7ff4f6a5a8e'
input = ','.join(map(str,[197,97,204,108,1,29,5,71,0,50,2,255,248,78,254,63]))
print('x', tie_binary(input))
|
C++
|
UTF-8
| 1,180 | 3.421875 | 3 |
[] |
no_license
|
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <iterator>
#include <ranges>
void printMap(const std::map <int, std::string, std::less<int>> &);
int main(){
std::map <int, std::string, std::less<int>> mapCont{{10, "Chris"}, {11, "Melod"}, {-2, "mcMac"}, {-2, "mcNuts"}};
auto p{ mapCont.insert(std::pair{10, "Dimebag"} ) };
printMap(mapCont);
std::cout << std::endl << std::endl << std::endl << "Element " << (p.second ? "has been inserted" : "already exists") << "\nThat element is " \
<< (*p.first).first << " " << (*p.first).second << std::endl;
mapCont[10] = "AttaGob3";
mapCont[20] = "WaakyeBase";
printMap(mapCont);
auto pis = mapCont.find(10);
if(pis == mapCont.end())
std::cout << std::endl << "Element not found " << std::endl;
else
std::cout << "Element found is " << (*pis).first << " " <<pis->second << " " << std::endl;
}
void printMap(const std::map <int, std::string, std::less<int>> & someMap){
for(auto item : someMap){
std::cout << item.first << " " << item.second;
std::cout << std::endl;
}
}
|
C++
|
UTF-8
| 1,065 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
// DP. O(N^2) time, O(N) space.
class Solution {
public:
int f[502];
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
int n = stations.size();
if (n == 0) {
if (startFuel >= target)
return 0;
else
return -1;
}
if (startFuel < stations[0][0])
return -1;
memset(f, -1, sizeof(f));
f[0] = startFuel - stations[0][0];
f[1] = f[0] + stations[0][1];
for (int i = 1; i < n; ++i)
{
int diff = stations[i][0] - stations[i-1][0];
for (int j = i+1; j >= 0; --j)
{
if (f[j] >= diff)
f[j] -= diff;
else
f[j] = -1;
if (j > 0 && f[j-1] >= diff)
f[j] = max(f[j], f[j-1] - diff + stations[i][1]);
}
}
int lastDiff = target - stations[n-1][0];
for (int i = 0; i <= n; ++i)
if (f[i] >= lastDiff)
return i;
return -1;
}
};
|
Python
|
UTF-8
| 1,006 | 3.703125 | 4 |
[] |
no_license
|
import random
possible = ["rock", "paper", "scissors"]
score = 0
computerScore = 0
while score < 11 and computerScore < 10:
integer = random.randint(0,2)
computer = possible[integer]
humanPlayer = input("Pick rock, paper, or scissors: ")
if humanPlayer not in possible:
print("Invalid entry")
elif humanPlayer == computer:
print("You tied.")
elif humanPlayer != computer:
if humanPlayer == "rock" and computer == "scissors":
score += 1
print("You win. Computer chose " + computer + ". Your score: " + str(score))
elif humanPlayer == "paper" and computer == "rock":
score += 1
print("You win. Computer chose " + computer + ". Your score: " + str(score))
elif humanPlayer == "scissors" and computer == "paper":
score += 1
print("You win. Computer chose " + computer + ". Your score: " + str(score))
else:
computerScore += 1
print("Computer choose " + computer + ". Computer wins. Computer's score: " + str(computerScore))
|
TypeScript
|
UTF-8
| 993 | 2.984375 | 3 |
[] |
no_license
|
namespace net.user1.orbiter.snapshot
{
/**
* The BannedListSnapshot class is used to load the server's current list of banned client
* addresses. The list of banned addresses retrieved by BannedListSnapshot is a one-time
* snapshot of the state of the server, and is not kept up to date after it is loaded.
* To update a BannedListSnapshot object to match latest the state of the server, pass that
* object to `updateSnapshot()` method.
*/
export class BannedListSnapshot extends Snapshot
{
private bannedList?:string[];
constructor(target?:net.user1.events.EventDispatcher)
{
super(target);
this.method = UPC.GET_BANNED_LIST_SNAPSHOT;
}
/**
* Returns an array of the banned addresses on the server.
* @return {string[] | null}
*/
getBannedList():string[]|null
{
return this.bannedList?.slice() ?? null;
}
/**
* @internal
* @param {string[]} value
*/
setBannedList(value:string[]):void
{
this.bannedList = value;
}
}
}
|
C++
|
UTF-8
| 1,003 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
#include "memory.hpp"
#include <memory>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(unique_ptr_construction_destruction) {
auto lambda = [](int* pointer) {
BOOST_CHECK_EQUAL(pointer, static_cast<int*>(0x0));
};
UniquePtr<int, decltype(lambda)> nullSmartPointer(nullptr, lambda);
BOOST_CHECK_EQUAL(nullSmartPointer.get(), static_cast<int*>(0x0));
BOOST_CHECK_EQUAL(nullSmartPointer.getDeleter(), lambda);
int* a = new int{42};
UniquePtr<int, std::default_delete<int>> notNullSmartPointer(a);
BOOST_CHECK_EQUAL(notNullSmartPointer.get(), a);
}
BOOST_AUTO_TEST_CASE(make_unique_ptr) {
auto smartPtr = makeUniquePtr<int>(42);
static_assert(
std::is_same<decltype(smartPtr), UniquePtr<int, std::default_delete<int>>>::value,
"makeUniquePtr<T> did not return an object of type UniquePtr<T, std::default_delete<T>>");
BOOST_CHECK_NE(smartPtr.get(), static_cast<int*>(0x0));
}
|
Java
|
UTF-8
| 161 | 1.710938 | 2 |
[] |
no_license
|
package com.garbagebinserver.allocator;
public interface SolutionModel {
public double computeCost();
public SolutionModel generateNeighboringSolution();
}
|
PHP
|
UTF-8
| 1,132 | 2.578125 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* 会费信息
* User: huiyong.yu
* Date: 2018/5/21
* Time: 15:06
*/
class DuesConfigModel{
private $filepath = 'dues_config';
private $fields = 'id, name, days, price, create_time, update_time, status ';
public function ModelInfoById($id){
$dataval = array();
$where = " AND id = {$id}";
$row = $GLOBALS['DB']->getSelect(ECHO_AQL_SWITCH, 1, $this->filepath, $this->fields, $where);
if(empty($row)){
return $dataval;
}
return $row;
}
public function ModelList(){
$dataval = array();
$where = "AND status = 1 ";
$list = $GLOBALS['DB']->getSelect(ECHO_AQL_SWITCH, 0, $this->filepath, $this->fields, $where);
if (empty($list)) {
return $dataval;
}
foreach ($list as $key => $val) {
$dataval[$key]['id'] = intval($val['id']);
$dataval[$key]['name'] = $val['name'];
$dataval[$key]['days'] = intval($val['days']);
$dataval[$key]['price'] = doubleval($val['price']);
}
return $dataval;
}
}
|
JavaScript
|
UTF-8
| 303 | 2.96875 | 3 |
[] |
no_license
|
function solve(arr1,arr2){
for(let i=0;i<arr1.length;i++){
for(let j=0;j<arr2.length;j++)
{
if(arr1[i]===arr2[j]){
console.log(arr1[i])
}
}
}
}
solve(['S', 'o', 'f', 't', 'U', 'n', 'i', ' '],
['s', 'o', 'c', 'i', 'a', 'l']
)
|
C
|
UTF-8
| 572 | 3.25 | 3 |
[] |
no_license
|
/* Los calcetines de Ian Malcolm */
#include <stdio.h>
int main() {
char caracter;
int numN, numG;
while(1) {
numN = 0, numG = 0;
scanf("%c", &caracter);
if(caracter == '.') break;
if(caracter == 'N' || caracter == 'G') {
while(1) {
if(caracter == 'N') {
numN++;
} else if(caracter == 'G') {
numG++;
} else if(caracter == '.') break;
scanf("%c", &caracter);
}
(numN % 2) ? (numG % 2) ? printf("PAREJA MIXTA\n") : printf("NEGRO SOLITARIO\n") : (numG % 2) ? printf("GRIS SOLITARIO\n") : printf("EMPAREJADOS\n");
}
}
return 0;
}
|
JavaScript
|
UTF-8
| 40,275 | 2.5625 | 3 |
[] |
no_license
|
"use strict";
// 二分查找
function binarySearch(vlss, vl) {
var low = 0;
var high = vlss.length - 1;
while (low <= high) {
var mid = (low + high) >> 1;
if (vlss[mid][0] < vl) {
low = mid + 1;
} else if (vlss[mid][0] > vl) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
var MATE_VALUE = 10000; // 最高分值
var BAN_VALUE = MATE_VALUE - 100; // 长将判负的分值
var WIN_VALUE = MATE_VALUE - 200; // 赢棋分值 高于此分值都是分值
var DRAW_VALUE = 20; // 和棋时返回的分数 取负值
var NULL_SAFE_MARGIN = 400; // 空步裁剪有效的最小优势
var NULL_OKAY_MARGIN = 200; // 可以进行空步裁剪的最小优势
var ADVANCED_VALUE = 3; // 先行权分值
// 棋子编号
var PIECE_KING = 0; // 将
var PIECE_ADVISOR = 1; // 士
var PIECE_BISHOP = 2; // 像
var PIECE_KNIGHT = 3; // 马
var PIECE_ROOK = 4; // 车
var PIECE_CANNON = 5; // 炮
var PIECE_PAWN = 6; // 卒
// 棋盘范围
var RANK_TOP = 3;
var RANK_BOTTOM = 12;
var FILE_LEFT = 3;
var FILE_RIGHT = 11;
var ADD_PIECE = false;
var DEL_PIECE = true;
// 辅助数组 用于判断棋子是否在棋盘上
var IN_BOARD_ = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
// 辅助数组 用于判断是否在九宫
var IN_FORT_ = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
// 辅助数组 用于校验将(帅) 士 像 的走法 是否合法
var LEGAL_SPAN = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
];
// 辅助数组 用于校验马的走法是否合理 如果合理 返回对应的方向 否则返回 0
var KNIGHT_PIN_ = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,-16, 0,-16, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 16, 0, 16, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
];
var KING_DELTA = [-16, -1, 1, 16];
var ADVISOR_DELTA = [-17, -15, 15, 17];
var KNIGHT_DELTA = [[-33, -31], [-18, 14], [-14, 18], [31, 33]];
var KNIGHT_CHECK_DELTA = [[-33, -18], [-31, -14], [14, 31], [18, 33]];
var MVV_VALUE = [50, 10, 10, 30, 40, 30, 20, 0]; // MVV/LVA每种子的价值
// 棋子位置价值数组
var PIECE_VALUE = [
[ // 帅 (与兵合并)
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0,
0, 0, 0, 19, 24, 34, 42, 44, 42, 34, 24, 19, 0, 0, 0, 0,
0, 0, 0, 19, 24, 32, 37, 37, 37, 32, 24, 19, 0, 0, 0, 0,
0, 0, 0, 19, 23, 27, 29, 30, 29, 27, 23, 19, 0, 0, 0, 0,
0, 0, 0, 14, 18, 20, 27, 29, 27, 20, 18, 14, 0, 0, 0, 0,
0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0,
0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 11, 15, 11, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
], [ // 士
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 20, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 18, 0, 0, 20, 23, 20, 0, 0, 18, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 20, 20, 0, 20, 20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
], [ // 相
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 20, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 18, 0, 0, 20, 23, 20, 0, 0, 18, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 20, 20, 0, 20, 20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
], [ // 马
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 90, 90, 90, 96, 90, 96, 90, 90, 90, 0, 0, 0, 0,
0, 0, 0, 90, 96,103, 97, 94, 97,103, 96, 90, 0, 0, 0, 0,
0, 0, 0, 92, 98, 99,103, 99,103, 99, 98, 92, 0, 0, 0, 0,
0, 0, 0, 93,108,100,107,100,107,100,108, 93, 0, 0, 0, 0,
0, 0, 0, 90,100, 99,103,104,103, 99,100, 90, 0, 0, 0, 0,
0, 0, 0, 90, 98,101,102,103,102,101, 98, 90, 0, 0, 0, 0,
0, 0, 0, 92, 94, 98, 95, 98, 95, 98, 94, 92, 0, 0, 0, 0,
0, 0, 0, 93, 92, 94, 95, 92, 95, 94, 92, 93, 0, 0, 0, 0,
0, 0, 0, 85, 90, 92, 93, 78, 93, 92, 90, 85, 0, 0, 0, 0,
0, 0, 0, 88, 85, 90, 88, 90, 88, 90, 85, 88, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
], [ // 车
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,206,208,207,213,214,213,207,208,206, 0, 0, 0, 0,
0, 0, 0,206,212,209,216,233,216,209,212,206, 0, 0, 0, 0,
0, 0, 0,206,208,207,214,216,214,207,208,206, 0, 0, 0, 0,
0, 0, 0,206,213,213,216,216,216,213,213,206, 0, 0, 0, 0,
0, 0, 0,208,211,211,214,215,214,211,211,208, 0, 0, 0, 0,
0, 0, 0,208,212,212,214,215,214,212,212,208, 0, 0, 0, 0,
0, 0, 0,204,209,204,212,214,212,204,209,204, 0, 0, 0, 0,
0, 0, 0,198,208,204,212,212,212,204,208,198, 0, 0, 0, 0,
0, 0, 0,200,208,206,212,200,212,206,208,200, 0, 0, 0, 0,
0, 0, 0,194,206,204,212,200,212,204,206,194, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
], [ // 炮
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,100,100, 96, 91, 90, 91, 96,100,100, 0, 0, 0, 0,
0, 0, 0, 98, 98, 96, 92, 89, 92, 96, 98, 98, 0, 0, 0, 0,
0, 0, 0, 97, 97, 96, 91, 92, 91, 96, 97, 97, 0, 0, 0, 0,
0, 0, 0, 96, 99, 99, 98,100, 98, 99, 99, 96, 0, 0, 0, 0,
0, 0, 0, 96, 96, 96, 96,100, 96, 96, 96, 96, 0, 0, 0, 0,
0, 0, 0, 95, 96, 99, 96,100, 96, 99, 96, 95, 0, 0, 0, 0,
0, 0, 0, 96, 96, 96, 96, 96, 96, 96, 96, 96, 0, 0, 0, 0,
0, 0, 0, 97, 96,100, 99,101, 99,100, 96, 97, 0, 0, 0, 0,
0, 0, 0, 96, 97, 98, 98, 98, 98, 98, 97, 96, 0, 0, 0, 0,
0, 0, 0, 96, 96, 97, 99, 99, 99, 97, 96, 96, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
], [ // 兵(与帅何必)
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0,
0, 0, 0, 19, 24, 34, 42, 44, 42, 34, 24, 19, 0, 0, 0, 0,
0, 0, 0, 19, 24, 32, 37, 37, 37, 32, 24, 19, 0, 0, 0, 0,
0, 0, 0, 19, 23, 27, 29, 30, 29, 27, 23, 19, 0, 0, 0, 0,
0, 0, 0, 14, 18, 20, 27, 29, 27, 20, 18, 14, 0, 0, 0, 0,
0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0,
0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 11, 15, 11, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
];
// 判断某位置是否在棋盘
function IN_BOARD(sq) {
return IN_BOARD_[sq] != 0;
}
// 判断某位置是否在九宫格
function IN_FORT(sq) {
return IN_FORT_[sq] != 0;
}
// 根据一维矩阵 获取二维矩阵行数
function RANK_Y(sq) {
return sq >> 4;
}
// 根据一维矩阵 获取二维矩阵列数
function FILE_X(sq) {
return sq & 15;
}
// 将二维矩阵转换为一维矩阵
function COORD_XY(x, y) {
return x + (y << 4);
}
function SQUARE_FLIP(sq) {
return 254 - sq;
}
function FILE_FLIP(x) {
return 14 - x;
}
function CHR(n) {
return String.fromCharCode(n);
}
function ASC(c) {
return c.charCodeAt(0);
}
function CHAR_TO_PIECE(c) {
switch (c) {
case "K":
return PIECE_KING;
case "A":
return PIECE_ADVISOR;
case "B":
return PIECE_BISHOP;
case "N":
return PIECE_KNIGHT;
case "R":
return PIECE_ROOK;
case "C":
return PIECE_CANNON;
case "P":
return PIECE_PAWN;
default:
return -1;
}
}
// 获得红黑标记 红子是8 黑子是16
function SIDE_TAG(sd) {
return 8 + (sd << 3);
}
// 获得对方红黑标记
function OPP_SIDE_TAG(sd) {
return 16 - (sd << 3);
}
// 获取走法的起点
function SRC(mv) {
return mv & 255;
}
// 获取走法的终点
function DST(mv) {
return mv >> 8;
}
// 将一个走法的起点和终点 转化为一个整型数字
function MOVE(sqSrc, sqDst) {
return sqSrc + (sqDst << 8);
}
function MIRROR_MOVE(mv) {
return MOVE(MIRROR_SQUARE(SRC(mv)), MIRROR_SQUARE(DST(mv)));
}
// 求MVV/LVAֵ值
function MVV_LVA(pc, lva) {
return MVV_VALUE[pc & 7] - lva;
}
function MIRROR_SQUARE(sq) {
return COORD_XY(FILE_FLIP(FILE_X(sq)), RANK_Y(sq));
}
// sp是棋子位置 sd是走棋方 红方0 黑方1 返回兵 向前走一步的位置
function SQUARE_FORWARD(sq, sd) {
return sq - 16 + (sd << 5);
}
// 校验将(帅)的走法
function KING_SPAN(sqSrc, sqDst) {
return LEGAL_SPAN[sqDst - sqSrc + 256] == 1;
}
// 校验士的走法
function ADVISOR_SPAN(sqSrc, sqDst) {
return LEGAL_SPAN[sqDst - sqSrc + 256] == 2;
}
// 校验像的走法
function BISHOP_SPAN(sqSrc, sqDst) {
return LEGAL_SPAN[sqDst - sqSrc + 256] == 3;
}
// 像眼的位置
function BISHOP_PIN(sqSrc, sqDst) {
return (sqSrc + sqDst) >> 1;
}
// 如果马的走法合法 则返回相应马脚的位置
function KNIGHT_PIN(sqSrc, sqDst) {
return sqSrc + KNIGHT_PIN_[sqDst - sqSrc + 256];
}
// sp是棋子的位置 sd是走棋方(红方0 黑方1) 如果该位置为过河 则返回true 否则返回false
function HOME_HALF(sq, sd) {
return (sq & 0x80) != (sd << 7);
}
// sp是棋子的位置 sd是走棋方(红方0 黑方1) 如果该位置已过河 则返回true 否则返回false
function AWAY_HALF(sq, sd) {
return (sq & 0x80) == (sd << 7);
}
// 如果起点sqSrc到终点sqDst没有过河 则返回true 否则返回false
function SAME_HALF(sqSrc, sqDst) {
return ((sqSrc ^ sqDst) & 0x80) == 0;
}
// 如果sqSrc和sqDst在同一行则返回true 否则返回false
function SAME_RANK(sqSrc, sqDst) {
return ((sqSrc ^ sqDst) & 0xf0) == 0;
}
// 如果sqSrc和sqDst 在同一列返回true 否则返回false
function SAME_FILE(sqSrc, sqDst) {
return ((sqSrc ^ sqDst) & 0x0f) == 0;
}
function RC4(key) {
this.x = this.y = 0;
this.state = [];
for (var i = 0; i < 256; i ++) {
this.state.push(i);
}
var j = 0;
for (var i = 0; i < 256; i ++) {
j = (j + this.state[i] + key[i % key.length]) & 0xff;
this.swap(i, j);
}
}
RC4.prototype.swap = function(i, j) {
var t = this.state[i];
this.state[i] = this.state[j];
this.state[j] = t;
}
RC4.prototype.nextByte = function() {
this.x = (this.x + 1) & 0xff;
this.y = (this.y + this.state[this.x]) & 0xff;
this.swap(this.x, this.y);
var t = (this.state[this.x] + this.state[this.y]) & 0xff;
return this.state[t];
}
// 生成32位随机数
RC4.prototype.nextLong = function() {
var n0 = this.nextByte();
var n1 = this.nextByte();
var n2 = this.nextByte();
var n3 = this.nextByte();
return n0 + (n1 << 8) + (n2 << 16) + ((n3 << 24) & 0xffffffff);
}
var PreGen_zobristKeyPlayer, PreGen_zobristLockPlayer;
var PreGen_zobristKeyTable = [], PreGen_zobristLockTable = [];
var rc4 = new RC4([0]);
PreGen_zobristKeyPlayer = rc4.nextLong();
rc4.nextLong();
PreGen_zobristLockPlayer = rc4.nextLong();
for (var i = 0; i < 14; i ++) {
var keys = [];
var locks = [];
for (var j = 0; j < 256; j ++) {
keys.push(rc4.nextLong());
rc4.nextLong();
locks.push(rc4.nextLong());
}
PreGen_zobristKeyTable.push(keys);
PreGen_zobristLockTable.push(locks);
}
function Position() {
}
// 初始化棋局数组
Position.prototype.clearBoard = function() {
this.sdPlayer = 0; // 该谁走棋 0-红方 1-黑方
this.squares = []; // 这个就是一维棋局数组
for (var sq = 0; sq < 256; sq ++) {
this.squares.push(0);
}
this.zobristKey = this.zobristLock = 0;
this.vlWhite = this.vlBlack = 0;
}
Position.prototype.setIrrev = function() {
this.mvList = [0]; // 存在每步走法的数组
this.pcList = [0]; // 存放每步被吃的棋子 如果没有棋子背吃 存放的是0
this.keyList = [0]; // 存放zobristKeyУ校验码
this.chkList = [this.checked()]; // 是否被将军
this.distance = 0; // 搜索的深度
}
// 将FEN串转为一维数组
Position.prototype.fromFen = function(fen) {
this.clearBoard();
var y = RANK_TOP;
var x = FILE_LEFT;
var index = 0;
if (index == fen.length) {
this.setIrrev();
return;
}
var c = fen.charAt(index);
while (c != " ") {
if (c == "/") {
x = FILE_LEFT;
y ++;
if (y > RANK_BOTTOM) {
break;
}
} else if (c >= "1" && c <= "9") {
x += (ASC(c) - ASC("0"));
} else if (c >= "A" && c <= "Z") {
if (x <= FILE_RIGHT) {
var pt = CHAR_TO_PIECE(c);
if (pt >= 0) {
this.addPiece(COORD_XY(x, y), pt + 8);
}
x ++;
}
} else if (c >= "a" && c <= "z") {
if (x <= FILE_RIGHT) {
var pt = CHAR_TO_PIECE(CHR(ASC(c) + ASC("A") - ASC("a")));
if (pt >= 0) {
this.addPiece(COORD_XY(x, y), pt + 16);
}
x ++;
}
}
index ++;
if (index == fen.length) {
this.setIrrev();
return;
}
c = fen.charAt(index);
}
index ++;
if (index == fen.length) {
this.setIrrev();
return;
}
this.setIrrev();
}
// 生成棋局的所有走法 vls不为null时 生成吃子走法
Position.prototype.generateMoves = function(vls) {
var mvs = [];
var pcSelfSide = SIDE_TAG(this.sdPlayer);
var pcOppSide = OPP_SIDE_TAG(this.sdPlayer);
for (var sqSrc = 0; sqSrc < 256; sqSrc ++) {
var pcSrc = this.squares[sqSrc];
if ((pcSrc & pcSelfSide) == 0) {
continue;
}
switch (pcSrc - pcSelfSide) {
case PIECE_KING:
for (var i = 0; i < 4; i ++) {
var sqDst = sqSrc + KING_DELTA[i];
if (!IN_FORT(sqDst)) {
continue;
}
var pcDst = this.squares[sqDst];
if (vls == null) {
if ((pcDst & pcSelfSide) == 0) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else if ((pcDst & pcOppSide) != 0) { // 目标位置存在对方棋子 这是要生成吃子的走法
mvs.push(MOVE(sqSrc, sqDst)); // 存储吃子的走法
vls.push(MVV_LVA(pcDst, 5)); // 该吃子走法的分值 MVV/LVA启发
}
}
break;
case PIECE_ADVISOR:
for (var i = 0; i < 4; i ++) {
var sqDst = sqSrc + ADVISOR_DELTA[i];
if (!IN_FORT(sqDst)) {
continue;
}
var pcDst = this.squares[sqDst];
if (vls == null) {
if ((pcDst & pcSelfSide) == 0) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
vls.push(MVV_LVA(pcDst, 1));
}
}
break;
case PIECE_BISHOP:
for (var i = 0; i < 4; i ++) { // 像的4个方向
var sqDst = sqSrc + ADVISOR_DELTA[i];
if (!(IN_BOARD(sqDst) && HOME_HALF(sqDst, this.sdPlayer) &&
this.squares[sqDst] == 0)) { // 像眼有棋子
continue;
}
sqDst += ADVISOR_DELTA[i];
var pcDst = this.squares[sqDst];
if (vls == null) {
if ((pcDst & pcSelfSide) == 0) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
vls.push(MVV_LVA(pcDst, 1));
}
}
break;
case PIECE_KNIGHT:
for (var i = 0; i < 4; i ++) {
var sqDst = sqSrc + KING_DELTA[i];
if (this.squares[sqDst] > 0) {
continue;
}
for (var j = 0; j < 2; j ++) {
sqDst = sqSrc + KNIGHT_DELTA[i][j];
if (!IN_BOARD(sqDst)) {
continue;
}
var pcDst = this.squares[sqDst];
if (vls == null) {
if ((pcDst & pcSelfSide) == 0) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
vls.push(MVV_LVA(pcDst, 1));
}
}
}
break;
case PIECE_ROOK:
for (var i = 0; i < 4; i ++) {
var delta = KING_DELTA[i];
var sqDst = sqSrc + delta;
while (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (pcDst == 0) {
if (vls == null) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else {
if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
if (vls != null) {
vls.push(MVV_LVA(pcDst, 4));
}
}
break;
}
sqDst += delta;
}
}
break;
case PIECE_CANNON:
for (var i = 0; i < 4; i ++) {
var delta = KING_DELTA[i];
var sqDst = sqSrc + delta;
while (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (pcDst == 0) {
if (vls == null) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else {
break;
}
sqDst += delta;
}
sqDst += delta;
while (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (pcDst > 0) {
if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
if (vls != null) {
vls.push(MVV_LVA(pcDst, 4));
}
}
break;
}
sqDst += delta;
}
}
break;
case PIECE_PAWN:
var sqDst = SQUARE_FORWARD(sqSrc, this.sdPlayer);
if (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (vls == null) {
if ((pcDst & pcSelfSide) == 0) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
vls.push(MVV_LVA(pcDst, 2));
}
}
if (AWAY_HALF(sqSrc, this.sdPlayer)) {
for (var delta = -1; delta <= 1; delta += 2) {
sqDst = sqSrc + delta;
if (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (vls == null) {
if ((pcDst & pcSelfSide) == 0) {
mvs.push(MOVE(sqSrc, sqDst));
}
} else if ((pcDst & pcOppSide) != 0) {
mvs.push(MOVE(sqSrc, sqDst));
vls.push(MVV_LVA(pcDst, 2));
}
}
}
}
break;
}
}
return mvs;
}
// 判断步骤是否合法 是则返回true 否则返回false
Position.prototype.legalMove = function(mv) {
var sqSrc = SRC(mv); // 获取走法的起点位置
var pcSrc = this.squares[sqSrc]; // 获取起点位置的棋子
var pcSelfSide = SIDE_TAG(this.sdPlayer); // 红黑标记 红子是8 黑子是16
if ((pcSrc & pcSelfSide) == 0) {
// 起点位置的棋子 不是本方棋子 是对方棋子 或者根本没有棋子
return false;
}
var sqDst = DST(mv); // 获取走法的终点位置
var pcDst = this.squares[sqDst]; // 获取终点位置的棋子
if ((pcDst & pcSelfSide) != 0) {
// 终点位置有棋子 而且是本方棋子
return false;
}
switch (pcSrc - pcSelfSide) {
case PIECE_KING: // 起点棋子是将(帅) 校验走法
return IN_FORT(sqDst) && KING_SPAN(sqSrc, sqDst);
case PIECE_ADVISOR: // 起点棋子是士 校验走法
return IN_FORT(sqDst) && ADVISOR_SPAN(sqSrc, sqDst);
case PIECE_BISHOP: // 起点棋子是像 校验走法
return SAME_HALF(sqSrc, sqDst) && BISHOP_SPAN(sqSrc, sqDst) &&
this.squares[BISHOP_PIN(sqSrc, sqDst)] == 0;
case PIECE_KNIGHT: // 起点棋子是马 校验走法
var sqPin = KNIGHT_PIN(sqSrc, sqDst);
return sqPin != sqSrc && this.squares[sqPin] == 0;
case PIECE_ROOK: // 起点棋子是车 校验走法
case PIECE_CANNON: // 起点棋子是炮 校验走法
var delta; // 标识沿哪个方向走棋
if (SAME_RANK(sqSrc, sqDst)) {
// 起点和终点位于同一行 再根据起点和终点的大小关系 判断具体沿哪个方向走棋
delta = (sqDst < sqSrc ? -1 : 1);
} else if (SAME_FILE(sqSrc, sqDst)) {
// 起点后终点位于同一列 再根据起点和终点的大小关系 判断具体是沿哪个方向走棋
delta = (sqDst < sqSrc ? -16 : 16);
} else {
// 起点和终点不在同一行 也不在同一列 走法是非法的
return false;
}
var sqPin = sqSrc + delta; // 沿着方向delta 走一步棋
while (sqPin != sqDst && this.squares[sqPin] == 0) {
// 沿方向delta 一步步向前走 直到遇到棋子 或者sqPin走到了终点的位置
sqPin += delta;
}
if (sqPin == sqDst) {
// 如果终点没有棋子 不管是车还是炮 这步棋都是合法的 如果是车 不管终点有没有棋子(对方的棋子) 这步棋都是合法
return pcDst == 0 || pcSrc - pcSelfSide == PIECE_ROOK;
}
// 此时已经翻山 终点必须有棋子 并且行棋的是炮 否则这步棋不合法
if (pcDst == 0 || pcSrc - pcSelfSide != PIECE_CANNON) {
return false;
}
sqPin += delta;
while (sqPin != sqDst && this.squares[sqPin] == 0) {
sqPin += delta;
}
return sqPin == sqDst;
case PIECE_PAWN:
// 兵已过河 并且是左右两个方向走的
if (AWAY_HALF(sqDst, this.sdPlayer) && (sqDst == sqSrc - 1 || sqDst == sqSrc + 1)) {
return true;
}
// 判断兵是不是 在向前走
return sqDst == SQUARE_FORWARD(sqSrc, this.sdPlayer);
default:
return false;
}
}
/**
* 判断将(帅) 是否被对方攻击
* @return boolean true-被攻击 false-没有被攻击
*/
Position.prototype.checked = function() {
var pcSelfSide = SIDE_TAG(this.sdPlayer); // 己方红黑标记
var pcOppSide = OPP_SIDE_TAG(this.sdPlayer); // 对方红黑标记
for (var sqSrc = 0; sqSrc < 256; sqSrc ++) {
// 遍历棋局数组 直到遇见己方的将(帅)
if (this.squares[sqSrc] != pcSelfSide + PIECE_KING) {
continue;
}
// 判断对方进兵 是否会攻击到己方老将
if (this.squares[SQUARE_FORWARD(sqSrc, this.sdPlayer)] == pcOppSide + PIECE_PAWN) {
return true;
}
// 判断对方平兵 (前提是并已过河) 是否会攻击到己方老将
for (var delta = -1; delta <= 1; delta += 2) {
if (this.squares[sqSrc + delta] == pcOppSide + PIECE_PAWN) {
return true;
}
}
// 判断对方的马是否会攻击到己方老将
for (var i = 0; i < 4; i ++) {
if (this.squares[sqSrc + ADVISOR_DELTA[i]] != 0) { // 马蹄有子 不用害怕
continue;
}
for (var j = 0; j < 2; j ++) {
var pcDst = this.squares[sqSrc + KNIGHT_CHECK_DELTA[i][j]];
if (pcDst == pcOppSide + PIECE_KNIGHT) {
return true;
}
}
}
// 判断对方的车炮是否攻击到己方老将 以及将帅是否对脸
for (var i = 0; i < 4; i ++) {
var delta = KING_DELTA[i];
var sqDst = sqSrc + delta;
while (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (pcDst > 0) {
if (pcDst == pcOppSide + PIECE_ROOK || pcDst == pcOppSide + PIECE_KING) { // 对方车能攻击己方老将 或者将帅对脸
return true;
}
break;
}
sqDst += delta;
}
sqDst += delta;
while (IN_BOARD(sqDst)) {
var pcDst = this.squares[sqDst];
if (pcDst > 0) {
if (pcDst == pcOppSide + PIECE_CANNON) {
return true;
}
break;
}
sqDst += delta;
}
}
return false;
}
return false;
}
// 无棋可走的话 返回true 否则返回false
Position.prototype.isMate = function() {
var mvs = this.generateMoves(null);
for (var i = 0; i < mvs.length; i ++) {
if (this.makeMove(mvs[i])) {
this.undoMakeMove();
return false;
}
}
return true;
}
// 结合搜索深度的输棋分值
Position.prototype.mateValue = function() {
return this.distance - MATE_VALUE;
}
// 结合搜索深度的长将判负分值
Position.prototype.banValue = function() {
return this.distance - BAN_VALUE;
}
// 和棋分值
Position.prototype.drawValue = function() {
return (this.distance & 1) == 0 ? -DRAW_VALUE : DRAW_VALUE;
}
// 某步走过的棋是否被将军
Position.prototype.inCheck = function() {
return this.chkList[this.chkList.length - 1];
}
// 某步走过的棋 是否是吃子走法
Position.prototype.captured = function() {
return this.pcList[this.pcList.length - 1] > 0;
}
// 出现重复局面时 返回分值
Position.prototype.repValue = function(vlRep) {
var vlReturn = ((vlRep & 2) == 0 ? 0 : this.banValue()) +
((vlRep & 4) == 0 ? 0 : -this.banValue());
return vlReturn == 0 ? this.drawValue() : vlReturn;
}
// 判断是否出现重复局面
Position.prototype.repStatus = function(recur_) {
var recur = recur_;
var selfSide = false;
var perpCheck = true;
var oppPerpCheck = true;
var index = this.mvList.length - 1;
while (this.mvList[index] > 0 && this.pcList[index] == 0) {
if (selfSide) {
perpCheck = perpCheck && this.chkList[index];
if (this.keyList[index] == this.zobristKey) { // 这是出现循环局面
recur --;
if (recur == 0) {
return 1 + (perpCheck ? 2 : 0) + (oppPerpCheck ? 4 : 0);
}
}
} else {
oppPerpCheck = oppPerpCheck && this.chkList[index];
}
selfSide = !selfSide;
index --;
}
return 0;
}
// 切换走棋方
Position.prototype.changeSide = function() {
this.sdPlayer = 1 - this.sdPlayer;
this.zobristKey ^= PreGen_zobristKeyPlayer;
this.zobristLock ^= PreGen_zobristLockPlayer;
}
// 走一步棋
Position.prototype.makeMove = function(mv) {
var zobristKey = this.zobristKey;
this.movePiece(mv);
// 检查走棋方是否被将军 如果是 说明这是在送死 撤销走棋并返回false
if (this.checked()) {
this.undoMovePiece(mv);
return false;
}
this.keyList.push(zobristKey); // 存储局面zobristKey的校验码
this.changeSide(); // 切换走棋方
this.chkList.push(this.checked()); //̬ 存储走完棋后 对方是否处于被将军的状态
this.distance ++; // 搜索深度+1
return true;
}
// 取消上一步的走棋
Position.prototype.undoMakeMove = function() {
this.distance --; // 搜索深度减1
this.chkList.pop();
this.changeSide(); // 切换走棋方
this.keyList.pop();
this.undoMovePiece(); // 取消上一步的走棋
}
// 空步搜索
Position.prototype.nullMove = function() {
this.mvList.push(0);
this.pcList.push(0);
this.keyList.push(this.zobristKey);
this.changeSide();
this.chkList.push(false);
this.distance ++;
}
// 撤销上一步的空步搜索
Position.prototype.undoNullMove = function() {
this.distance --;
this.chkList.pop();
this.changeSide();
this.keyList.pop();
this.pcList.pop();
this.mvList.pop();
}
// 根据走法移动棋子 删除终点位置的棋子 将起点位置的棋子放置在终点位置
Position.prototype.movePiece = function(mv) {
var sqSrc = SRC(mv);
var sqDst = DST(mv);
var pc = this.squares[sqDst];
this.pcList.push(pc);
if (pc > 0) {
// 如果终点有棋子 则要删除该棋子
this.addPiece(sqDst, pc, DEL_PIECE);
}
pc = this.squares[sqSrc];
this.addPiece(sqSrc, pc, DEL_PIECE); // 删除起点棋子
this.addPiece(sqDst, pc, ADD_PIECE); // 将原来起点的棋子添加到终点
this.mvList.push(mv);
}
// 取消上一步对棋子的移动
Position.prototype.undoMovePiece = function() {
var mv = this.mvList.pop();
var sqSrc = SRC(mv);
var sqDst = DST(mv);
var pc = this.squares[sqDst];
this.addPiece(sqDst, pc, DEL_PIECE); // 删除终点棋子
this.addPiece(sqSrc, pc, ADD_PIECE); // 将终点位置的棋子添加到起点
pc = this.pcList.pop();
if (pc > 0) {
// 这步棋放生了吃子 需要把吃掉的棋子放回终点位置
this.addPiece(sqDst, pc, ADD_PIECE);
}
}
// 如果bDel为false 则将棋子pc添加进棋局中的sp位置 如果bDel为true 则删除sp位置的棋子
Position.prototype.addPiece = function(sq, pc, bDel) {
var pcAdjust;
// 添加或者删除棋子
this.squares[sq] = bDel ? 0 : pc;
// 更新红黑双方子粒分值
if (pc < 16) {
pcAdjust = pc - 8;
this.vlWhite += bDel ? -PIECE_VALUE[pcAdjust][sq] :
PIECE_VALUE[pcAdjust][sq];
} else {
pcAdjust = pc - 16;
this.vlBlack += bDel ? -PIECE_VALUE[pcAdjust][SQUARE_FLIP(sq)] :
PIECE_VALUE[pcAdjust][SQUARE_FLIP(sq)];
pcAdjust += 7;
}
// 更新局面的zobristKey校验码和zobristLock校验码
this.zobristKey ^= PreGen_zobristKeyTable[pcAdjust][sq];
this.zobristLock ^= PreGen_zobristLockTable[pcAdjust][sq];
}
// 局面评估函数 返回当前走棋的优势
Position.prototype.evaluate = function() {
var vl = (this.sdPlayer == 0 ? this.vlWhite - this.vlBlack :
this.vlBlack - this.vlWhite) + ADVANCED_VALUE;
return vl == this.drawValue() ? vl - 1 : vl; // 这里是评估出来的分值 要跟和棋的分值区分开
}
// 当前局面的优势是否足以进行空步搜索
Position.prototype.nullOkay = function() {
return (this.sdPlayer == 0 ? this.vlWhite : this.vlBlack) > NULL_OKAY_MARGIN;
}
// 空步搜索得到的分值是否有效
Position.prototype.nullSafe = function() {
return (this.sdPlayer == 0 ? this.vlWhite : this.vlBlack) > NULL_SAFE_MARGIN;
}
Position.prototype.mirror = function() {
var pos = new Position();
pos.clearBoard();
for (var sq = 0; sq < 256; sq ++) {
var pc = this.squares[sq];
if (pc > 0) {
pos.addPiece(MIRROR_SQUARE(sq), pc);
}
}
if (this.sdPlayer == 1) {
pos.changeSide();
}
return pos;
}
// 获取开局库中的走法
Position.prototype.bookMove = function() {
if (typeof BOOK_DAT != "object" || BOOK_DAT.length == 0) {
return 0;
}
var mirror = false;
var lock = this.zobristLock >>> 1; // Convert into Unsigned
var index = binarySearch(BOOK_DAT, lock);
if (index < 0) {
mirror = true;
lock = this.mirror().zobristLock >>> 1; // Convert into Unsigned
index = binarySearch(BOOK_DAT, lock);
}
if (index < 0) {
return 0;
}
index --;
while (index >= 0 && BOOK_DAT[index][0] == lock) {
index --;
}
var mvs = [], vls = [];
var value = 0;
index ++;
while (index < BOOK_DAT.length && BOOK_DAT[index][0] == lock) {
var mv = BOOK_DAT[index][1];
mv = (mirror ? MIRROR_MOVE(mv) : mv);
if (this.legalMove(mv)) {
mvs.push(mv);
var vl = BOOK_DAT[index][2];
vls.push(vl);
value += vl;
}
index ++;
}
if (value == 0) {
return 0;
}
//一个局面会对应多种走法 这里是为了增加走棋的随机性 不过每步棋的比重是不一样的
value = Math.floor(Math.random() * value);
for (index = 0; index < mvs.length; index ++) {
value -= vls[index];
if (value < 0) {
break;
}
}
return mvs[index];
}
// 获取历史表的指标
Position.prototype.historyIndex = function(mv) {
return ((this.squares[SRC(mv)] - 8) << 8) + DST(mv);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.