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 |
|---|---|---|---|---|---|---|---|
Shell | UTF-8 | 6,214 | 3.65625 | 4 | [] | no_license | #! /bin/bash
#db配置参数
db_name="iwg_asset_db"
db_pwd="zte"
db_port=3306
db_path="./data/db"
db_image="mariadb"
#web配置参数
web_name="iwg_asset_web"
web_port=5000
web_logs_path="./data/logs"
web_data_path="./data/records"
web_image="iwg_asset"
shell_dir=$(realpath "$(dirname "$0")")
cd "${shell_dir}"
#########################################################
help(){
echo "IWG Asset Management"
echo ""
echo "Options:"
echo " -build Build IWG Asset Version"
echo " -start Start IWG Asset"
echo " -stop Stop IWG Asset"
echo " -install Install IWG Asset"
echo " Before installation, please ensure that the docker(verson 1.9 or later) has already been installed"
echo " -uninstall Uninstall IWG Asset. This dangerous operation may cause data loss"
echo " -upgrade Upgrade IWG Asset"
}
#########################################################
get_container_addr(){
local container_name=$1
echo $(docker inspect ${container_name}|grep -i ipaddress|tail -n1|awk '{print $2}'|egrep -o '([0-9A-Za-z:.]+)')
}
start_db(){
docker ps -a|grep -i ${db_name}|grep -i exited|awk '{print $1}'|xargs -n1 docker rm -f 2>/dev/null
db_info=$(docker ps |grep ${db_name})
if [ -n "$db_info" ]; then
return 0
fi
mkdir -p "${db_path}" 2>/dev/null
db_path=$(realpath "${db_path}")
docker run --name ${db_name} \
-d \
-p ${db_port}:3306 \
-v ${db_path}:/var/lib/mysql \
-v /etc/localtime:/etc/localtime:ro \
-e MYSQL_ROOT_PASSWORD=${db_pwd} \
-e LANG=en_US.UTF-8 \
${db_image}
if [ $? -ne 0 ]; then
return 255
fi
}
start_web(){
docker ps -a|grep -i ${web_name}|grep -i exited|awk '{print $1}'|xargs -n1 docker rm -f 2>/dev/null
web_info=$(docker ps |grep ${web_name})
if [ -n "$web_info" ]; then
echo $web_info
return 0
fi
mkdir -p "${web_logs_path}" 2>/dev/null
mkdir -p "${web_data_path}" 2>/dev/null
web_logs_path=$(realpath "${web_logs_path}")
web_data_path=$(realpath "${web_data_path}")
docker run --name ${web_name} \
-d \
-p ${web_port}:5000 \
-v ${web_logs_path}:/home/iwg_asset/logs \
-v ${web_data_path}:/home/iwg_asset/data \
-v /etc/localtime:/etc/localtime:ro \
-e DEBUG=False \
-e HTTP_TYPE=https \
-e DB_HOST=$(get_container_addr ${db_name}) \
-e DB_PASSWORD=${db_pwd} \
-e DB_PORT=3306 \
-e LANG=en_US.UTF-8 \
${web_image}
if [ $? -ne 0 ]; then
return 255
fi
}
stop_db(){
docker stop ${db_name} 2>/dev/null
docker rm -f ${db_name} 2>/dev/null
docker ps -a|grep -i ${db_name}|grep -i exited|awk '{print $1}'|xargs -n1 docker rm -f 2>/dev/null
}
stop_web(){
docker stop ${web_name} 2>/dev/null
docker rm -f ${web_name} 2>/dev/null
docker ps -a|grep -i ${web_name}|grep -i exited|awk '{print $1}'|xargs -n1 docker rm -f 2>/dev/null
}
build(){
echo "build image ..."
./build/make_image.sh
echo "build version ..."
mkdir -p ./version/iwg_asset 2>/dev/null
cp ./iwg_asset.sh ./readme.txt ./build/images/mariadb.tar ./build/images/iwg_asset.tar ./version/iwg_asset
pushd ./version >/dev/null
version_file="iwg_asset.tar.gz"
rm -rf ${version_file}
tar -zcvf ./${version_file} iwg_asset
rm -rf iwg_asset
popd >/dev/null
echo "version dir: ${shell_dir}/version/${version_file}"
}
install(){
#检查docker
docker --version
if [ $? -ne 0 ]; then
echo "can't find docker in the machine"
return 255
fi
#停止服务
stop_web
stop_db
#导入依赖的镜像文件
docker load -i ./mariadb.tar
docker load -i ./iwg_asset.tar
#初始化数据库
start_db
start_web
echo "Ready to initialize SQL script ..."
#导入脚本
for i in $(seq 1 20); do
sleep 3
result=$(echo "SHOW DATABASES;" | docker exec -i ${db_name} mysql -p${db_pwd} | grep information_schema)
if [ -z "${result}" ]; then
continue
fi
#从web容器中拷贝sql脚本并执行
docker cp ${web_name}:/home/iwg_asset/app/sql ./.sql
cat ./.sql/schema.sql ./.sql/initialize.sql | docker exec -i ${db_name} mysql --default-character-set=utf8 -p${db_pwd}
rm -rf ./.sql
break
done
stop_web
stop_db
}
uninstall(){
stop_web
stop_db
rm -rf data
docker rmi -f mariadb iwg_asset
}
upgrade(){
stop_web
#删除旧的web镜像,导入新的web镜像
docker rmi -f ${web_image}; docker load -i ./iwg_asset.tar
#启动IWG
start_db
start_web
echo "Ready to upgrade SQL script ..."
#导入更新脚本
for i in $(seq 1 5); do
sleep 3
result=$(echo "SHOW DATABASES;" | docker exec -i ${db_name} mysql -p${db_pwd} | grep information_schema)
if [ -z "${result}" ]; then
continue
fi
#从web容器中拷贝sql升级脚本并执行
docker cp ${web_name}:/home/iwg_asset/app/sql ./.sql
upgrade_file="./.sql/upgrade.sql"
if [ -f "${upgrade_file}" ]; then
cat ${upgrade_file} | docker exec -i ${db_name} mysql --default-character-set=utf8 -p${db_pwd}
fi
rm -rf ./.sql
break
done
}
while [ $# -ne 0 ]
do
case "$1" in
"-build")
shift
build
exit 0
;;
"-start")
shift
start_db
start_web
exit 0
;;
"-stop")
shift
stop_web
stop_db
exit 0
;;
"-install")
shift
install
exit 0
;;
"-uninstall")
shift
uninstall
exit 0
;;
"-upgrade")
shift
upgrade
exit 0
;;
"--help")
help
exit 0
;;
*)
shift
;;
esac
done
help
|
JavaScript | UTF-8 | 5,451 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | import * as Config from "./config.js";
const yyyymmdd = (date) => {
if (!date) date = new Date();
const yyyy = date.getFullYear().toString();
const mm = (date.getMonth() + 1).toString(); // getMonth() is zero-based
const dd = date.getDate().toString();
return (
yyyy + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + (dd[1] ? dd : "0" + dd[0])
);
};
const htmlDecode = (input) => {
const doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
};
const getParameterByName = (name, url) => {
if (!url) url = window.location.href;
name = name.replace(/[[\]]/g, "\\$&");
const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
const results = regex.exec(url);
if (!results) return null;
if (!results[2]) return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
const makeTimestampHumanReadable = (timestamp) => {
return (new Date(timestamp)).toString();
};
const getNewNoteObject = () => {
const note = {
changes: [],
creationTime: null,
editorData: Config.newEditorDataObject,
id: null,
isUnsaved: true,
linkedNotes: [],
updateTime: null,
position: {
x: null,
y: null,
},
};
Object.seal(note);
return note;
};
const setNoteTitleByLinkTitleIfUnset = (note, defaultNoteTitle) => {
// if the note has no title yet, take the title of the link metadata
const firstLinkBlock = note.editorData.blocks.find(
(block) => block.type === "linkTool",
);
if (
(note.editorData?.blocks?.[0]?.data?.text
=== defaultNoteTitle)
&& firstLinkBlock
&& typeof firstLinkBlock.data.meta.title === "string"
&& firstLinkBlock.data.meta.title.length > 0
) {
note.editorData.blocks[0].data.text
= firstLinkBlock.data.meta.title;
}
};
/*
@function binaryArrayFind:
This function performs a binary search in an array of objects that is
sorted by a specific key in the objects.
@param sortedArray:
An array of objects that is sorted by a specific key in the objects.
@param sortKeyKey:
They key of the object whose corresponding value is the sort key for
that object.
@param sortKeyKey:
The sort key we want to find.
*/
const binaryArrayFind = function(sortedArray, sortKeyKey, sortKeyToFind) {
let start = 0;
let end = sortedArray.length - 1;
while (start <= end) {
// Find the mid index
const mid = Math.floor((start + end) / 2);
// If element is present at mid, return it
if (sortedArray[mid][sortKeyKey] === sortKeyToFind) {
return sortedArray[mid];
// Else look in left or right half accordingly
} else if (sortedArray[mid][sortKeyKey] < sortKeyToFind) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return null;
};
/*
@function binaryArrayIncludes:
This function performs a binary search in the manner of Array.includes()
in an array of values that has been sorted with Array.sort().
@param sortedArray:
An array of values that is sorted with Array.sort()
@param valueToLookFor:
The value we want to find.
*/
const binaryArrayIncludes = function(sortedArray, valueToLookFor) {
let start = 0;
let end = sortedArray.length - 1;
while (start <= end) {
// Find the mid index
const mid = Math.floor((start + end) / 2);
// If element is present at mid, we have it
if (sortedArray[mid] === valueToLookFor) {
return true;
// Else look in left or right half accordingly
} else if (sortedArray[mid] < valueToLookFor) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return false;
};
function humanFileSize(bytes, si = false, dp = 1) {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + " B";
}
const units = si
? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
: ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
let u = -1;
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (
Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1
);
return bytes.toFixed(dp) + " " + units[u];
}
const shortenText = (text, maxLength) => {
if (text.length > maxLength) {
return text.trim().substr(0, maxLength) + "…";
} else {
return text;
}
};
const streamToBlob = async (stream, mimeType) => {
const response = new Response(
stream,
{
headers: { "Content-Type": mimeType },
},
);
const blob = await response.blob();
return blob;
};
const getUrlForFileId = async (fileId, databaseProvider) => {
let url;
if (databaseProvider.constructor.type === "LOCAL") {
const { readable, mimeType }
= await databaseProvider.getReadableFileStream(
fileId,
);
const blob = await streamToBlob(readable, mimeType);
url = URL.createObjectURL(blob);
} else {
url = Config.API_URL + "file/" + fileId;
}
return url;
};
const getWindowDimensions = () => {
const docEl = document.documentElement;
const width = window.innerWidth || docEl.clientWidth;
const height = window.innerHeight || docEl.clientHeight;
return { width, height };
};
export {
yyyymmdd,
htmlDecode,
getParameterByName,
makeTimestampHumanReadable,
getNewNoteObject,
setNoteTitleByLinkTitleIfUnset,
binaryArrayFind,
binaryArrayIncludes,
humanFileSize,
shortenText,
streamToBlob,
getUrlForFileId,
getWindowDimensions,
};
|
PHP | UTF-8 | 1,655 | 2.546875 | 3 | [] | no_license | <?php
namespace Dontdrinkandroot\GitkiBundle\Tests\Acceptance\Command;
use Dontdrinkandroot\GitkiBundle\Command\SearchCommand;
use Dontdrinkandroot\GitkiBundle\Tests\Acceptance\KernelTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @author Philip Washington Sorst <philip@sorst.net>
*/
class SearchCommandTest extends KernelTestCase
{
public function testSearchEmpty()
{
$application = new Application(static::$kernel);
$application->add(new SearchCommand());
$command = $application->find('gitki:search');
$command->setApplication($application);
$commandTester = new CommandTester($command);
$commandTester->execute(
[
'command' => $command->getName(),
'searchstring' => 'bla'
]
);
$this->assertEquals('No results found', trim($commandTester->getDisplay()));
}
public function testSearchSuccess()
{
$application = new Application(static::$kernel);
$application->add(new SearchCommand());
$command = $application->find('gitki:search');
$command->setApplication($application);
$commandTester = new CommandTester($command);
$commandTester->execute(
[
'command' => $command->getName(),
'searchstring' => 'muliple lines'
]
);
$this->assertRegExp('#TOC Example#', $commandTester->getDisplay());
}
/**
* {@inheritdoc}
*/
protected function getEnvironment(): string
{
return 'elasticsearch';
}
}
|
C | UHC | 493 | 4.34375 | 4 | [] | no_license | #include <stdio.h>
int main()
{
int total2 = 0, total3 = 0; // 2 3
for (int i = 1; i <= 500; i++) // 1 500 ݺ
{
if (i % 2 == 0) // i 2 0̸ 2 ̹Ƿ տ ش.
total2 += i;
if (i % 3 == 0) //
total3 += i;
}
printf(": %d \n", total2 - total3); // 2 հ 3
return 0;
} |
Java | UTF-8 | 1,509 | 2.453125 | 2 | [] | no_license | /**
* (c) planet-ix ltd 2005
*/
package com.ixcode.bugsim;
import static com.ixcode.framework.io.IO.tryToClose;
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
import static java.lang.Thread.currentThread;
/**
* Description : ${CLASS_DESCRIPTION}
*/
public class BugsimVersion {
public static String getVersion() {
Properties properties = loadPropertiesFromClasspath("application/application.properties");
return new StringBuilder()
.append(properties.getProperty("application.version"))
.append(" dist(").append(properties.getProperty("application.distnumber")).append(")")
.append(" rev(").append(properties.getProperty("application.revision")).append(")")
.toString();
}
private static Properties loadPropertiesFromClasspath(String propertiesFilename) {
Properties properties = new Properties();
InputStream in = currentThread().getContextClassLoader().getResourceAsStream(propertiesFilename);
if (in == null) {
throw new RuntimeException(String.format("No properties file '%s'", propertiesFilename));
}
try {
properties.load(in);
} catch (IOException e) {
throw new RuntimeException("Could not load version from properties file 'application.application.version' on the classpath.");
} finally {
tryToClose(in);
}
return properties;
}
}
|
C++ | UTF-8 | 842 | 2.625 | 3 | [
"MIT"
] | permissive | #include "common/types.h"
#include "utils/file.h"
#include "utils/utils.h"
#define DEBUG_LEVEL 5
#include "common/debug.h"
static const std::string snafuDigits = "=-012";
static int64_t snafu2Dec(const std::string &snafu) {
int64_t ret = 0;
for (auto c : snafu) {
ret = 5 * ret + snafuDigits.find(c) - 2;
}
return ret;
}
static std::string dec2snafu(int64_t dec) {
std::string ret;
while (dec > 0) {
auto snafuDigitIdx = (dec + 2) % 5;
ret.push_back(snafuDigits[snafuDigitIdx]);
dec += 2 - snafuDigitIdx;
dec /= 5;
}
std::reverse(ret.begin(), ret.end());
return ret;
}
int main(int argc, char *argv[]) {
auto lines = File::readAllLines(argv[1]);
{
int64_t sum = 0;
for (auto &l : lines) {
sum += snafu2Dec(l);
}
PRINTF(("PART_A: '%s' (%ld)", dec2snafu(sum).c_str(), sum));
}
return 0;
}
|
C++ | UTF-8 | 2,085 | 2.578125 | 3 | [] | no_license | #include <cmath>
#include <Util/exceptions.h>
#include "scene.h"
#include "sphere.h"
using namespace Ray;
using namespace Util;
////////////
// Sphere //
////////////
void Sphere::init( const LocalSceneData &data )
{
// Set the material pointer
if( _materialIndex<0 ) THROW( "negative material index: %d" , _materialIndex );
else if( _materialIndex>=data.materials.size() ) THROW( "material index out of bounds: %d <= %d" , _materialIndex , (int)data.materials.size() );
else _material = &data.materials[ _materialIndex ];
///////////////////////////////////
// Do any additional set-up here //
///////////////////////////////////
WARN_ONCE( "method undefined" );
}
void Sphere::updateBoundingBox( void )
{
///////////////////////////////
// Set the _bBox object here //
///////////////////////////////
THROW( "method undefined" );
}
void Sphere::initOpenGL( void )
{
///////////////////////////
// Do OpenGL set-up here //
///////////////////////////
WARN_ONCE( "method undefined" );
// Sanity check to make sure that OpenGL state is good
ASSERT_OPEN_GL_STATE();
}
double Sphere::intersect( Ray3D ray , RayShapeIntersectionInfo &iInfo , BoundingBox1D range , std::function< bool (double) > validityLambda ) const
{
//////////////////////////////////////////////////////////////
// Compute the intersection of the sphere with the ray here //
//////////////////////////////////////////////////////////////
THROW( "method undefined" );
return Infinity;
}
bool Sphere::isInside( Point3D p ) const
{
//////////////////////////////////////////////////////
// Determine if the point is inside the sphere here //
//////////////////////////////////////////////////////
THROW( "method undefined" );
return false;
}
void Sphere::drawOpenGL( GLSLProgram * glslProgram ) const
{
//////////////////////////////
// Do OpenGL rendering here //
//////////////////////////////
THROW( "method undefined" );
// Sanity check to make sure that OpenGL state is good
ASSERT_OPEN_GL_STATE();
}
|
Markdown | UTF-8 | 966 | 2.671875 | 3 | [] | no_license | # Article D341-14-1
I. - Lorsque le bénéficiaire ne respecte pas, sur l'ensemble de son exploitation, les obligations définies au 2° de l'article
D. 341-10, le préfet applique des réductions au montant total des paiements annuels mentionnés à l'article D. 341-21, selon
les modalités définies aux articles D. 615-57 à D. 615-61.
II. - (Abrogé)
III. - (Abrogé)
**Liens relatifs à cet article**
_Cité par_:
- Arrêté du 30 avril 2009 - art. 2 (Ab)
- Arrêté du 14 septembre 2010 - art. 2 (Ab)
- Arrêté du 19 août 2013 - art. 2 (V)
- Arrêté du 12 août 2014 - art. 2 (V)
- Code rural et de la pêche maritime - art. D341-17 (Ab)
- Code rural et de la pêche maritime - art. D341-20 (Ab)
_Modifié par_:
- Décret n°2015-1901 du 30 décembre 2015 - art. 1
_Abrogé par_:
- Décret n°2017-1286 du 21 août 2017 - art. 1
_Cite_:
- Code rural - art. D341-10
- Code rural - art. D341-21
- Code rural - art. D615-57
|
SQL | UTF-8 | 698 | 3.015625 | 3 | [] | no_license | DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS projects;
DROP TABLE IF EXISTS blogs;
DROP TABLE IF EXISTS papers;
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
CREATE TABLE projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
category TEXT,
sdesc TEXT,
ldesc TEXT,
tools TEXT,
period TEXT
);
CREATE TABLE blogs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
created DATE NOT NULL,
body TEXT
);
CREATE TABLE papers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ref_text TEXT NOT NULL,
category TEXT NOT NULL,
sdesc TEXT,
url TEXT
); |
Java | UTF-8 | 4,164 | 2.3125 | 2 | [] | no_license | package com.moying.energyring.Model;
import java.util.List;
/**
* Created by waylen on 2017/3/17.
*/
public class AllPerson_Model {
/**
* IsSuccess : true
* Msg : 操作成功
* Data : [{"RowNum":1,"TargetID":17,"StartDate":"2017-03-15 00:00:00","EndDate":"2017-03-20 23:59:00","UserID":2066,"ProjectName":"深蹲","P_UNIT":"个","ReportNum":20,"P_PICURL":"http://192.168.1.111:7777/uploads/i/2017/02/ef52c864-4b07-4a32-a9e9-8c2275b410ec.png","AllDays":6,"FinishDays":1,"RowsCount":1}]
* Code : 200
*/
private boolean IsSuccess;
private String Msg;
private int Code;
private List<DataBean> Data;
public boolean isIsSuccess() {
return IsSuccess;
}
public void setIsSuccess(boolean IsSuccess) {
this.IsSuccess = IsSuccess;
}
public String getMsg() {
return Msg;
}
public void setMsg(String Msg) {
this.Msg = Msg;
}
public int getCode() {
return Code;
}
public void setCode(int Code) {
this.Code = Code;
}
public List<DataBean> getData() {
return Data;
}
public void setData(List<DataBean> Data) {
this.Data = Data;
}
public static class DataBean {
/**
* RowNum : 1
* TargetID : 17
* StartDate : 2017-03-15 00:00:00
* EndDate : 2017-03-20 23:59:00
* UserID : 2066
* ProjectName : 深蹲
* P_UNIT : 个
* ReportNum : 20.0
* P_PICURL : http://192.168.1.111:7777/uploads/i/2017/02/ef52c864-4b07-4a32-a9e9-8c2275b410ec.png
* AllDays : 6
* FinishDays : 1
* RowsCount : 1
*/
private int RowNum;
private int TargetID;
private String StartDate;
private String EndDate;
private int UserID;
private String ProjectName;
private String P_UNIT;
private int ReportNum;
private String P_PICURL;
private int AllDays;
private int FinishDays;
private int RowsCount;
public int getRowNum() {
return RowNum;
}
public void setRowNum(int RowNum) {
this.RowNum = RowNum;
}
public int getTargetID() {
return TargetID;
}
public void setTargetID(int TargetID) {
this.TargetID = TargetID;
}
public String getStartDate() {
return StartDate;
}
public void setStartDate(String StartDate) {
this.StartDate = StartDate;
}
public String getEndDate() {
return EndDate;
}
public void setEndDate(String EndDate) {
this.EndDate = EndDate;
}
public int getUserID() {
return UserID;
}
public void setUserID(int UserID) {
this.UserID = UserID;
}
public String getProjectName() {
return ProjectName;
}
public void setProjectName(String ProjectName) {
this.ProjectName = ProjectName;
}
public String getP_UNIT() {
return P_UNIT;
}
public void setP_UNIT(String P_UNIT) {
this.P_UNIT = P_UNIT;
}
public double getReportNum() {
return ReportNum;
}
public void setReportNum(int ReportNum) {
this.ReportNum = ReportNum;
}
public String getP_PICURL() {
return P_PICURL;
}
public void setP_PICURL(String P_PICURL) {
this.P_PICURL = P_PICURL;
}
public int getAllDays() {
return AllDays;
}
public void setAllDays(int AllDays) {
this.AllDays = AllDays;
}
public int getFinishDays() {
return FinishDays;
}
public void setFinishDays(int FinishDays) {
this.FinishDays = FinishDays;
}
public int getRowsCount() {
return RowsCount;
}
public void setRowsCount(int RowsCount) {
this.RowsCount = RowsCount;
}
}
}
|
C# | UTF-8 | 934 | 2.859375 | 3 | [
"Unlicense"
] | permissive | namespace DailyCodingProblems
{
using Base;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
var puzzles = new List<IPuzzle>()
{
//new Puzzles.Day001.Impl(),
//new Puzzles.Day002.Impl(),
//new Puzzles.Day003.Impl(),
//new Puzzles.Day004.Impl(),
//new Puzzles.Day004b.Impl(),
new Puzzles.Day011.Impl(),
//new Puzzles.Day014.Impl(),
//new Puzzles.Day015.Impl(),
};
foreach(var p in puzzles)
{
var r = await p.Execute();
Console.WriteLine(r);
}
Console.WriteLine("---- press any key to exit ----");
Console.ReadLine();
}
}
} |
Python | UTF-8 | 396 | 3.640625 | 4 | [] | no_license | # програма для підрахунку для годиника
# від кількості хвилин
N = int(input("Введіть кількість хвилин, відрахованих після півночі: "))
# скількі хвилин в цьому дні
N = int(N % 1440)
# скільки годин
h = N // 60
# скільки хвилин
m = N % 60
print(h,":",m)
|
JavaScript | UTF-8 | 924 | 2.53125 | 3 | [
"MIT"
] | permissive | const token = getToken()
if (!token && to.name !== LOGIN_PAGE_NAME) {
// 未登录且要跳转的页面不是登录页
next({
name: LOGIN_PAGE_NAME // 跳转到登录页
})
} else if (!token && to.name === LOGIN_PAGE_NAME) {
// 未登陆且要跳转的页面是登录页
next() // 跳转
} else if (token && to.name === LOGIN_PAGE_NAME) {
// 已登录且要跳转的页面是登录页
next({
name: homeName // 跳转到homeName页
})
} else {
if (store.state.user.hasGetInfo) {
turnTo(to, store.state.user.access, next)
} else {
store.dispatch('getUserInfo').then(user => {
// 拉取用户信息,通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组,如:['super_admin'] ['super_admin', 'admin']
turnTo(to, user.access, next)
}).catch(() => {
setToken('')
next({
name: 'login'
})
})
}
}
|
Java | UTF-8 | 337 | 2.796875 | 3 | [] | no_license | package kafka.utils;
public class Three<F,S,T> {
private F f;
private S s;
private T t;
public Three(F f, S s, T t) {
this.f = f;
this.s = s;
this.t = t;
}
public F F() {
return f;
}
public S S() {
return s;
}
public T T() {
return t;
}
}
|
Python | UTF-8 | 647 | 3.953125 | 4 | [] | no_license | alphabet = ["a", "b", "c", "d", "e", "", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
vowels = ["a", "e", "i", "o", "u"]
for i in range(len(alphabet)): # max length is alphabet, if you put vowels it goes out of nums
if alphabet[i] in vowels: # no need to check vowels[i] - it compares the alphabet[i] with the whole vowels list!
print(alphabet[i] + " is a vowel, nice!")
# else:
# # print(alphabet[i] + " is not a vowel!")
# pass # instead if printing not vowels, better passing it
# or even better, put no else condition and just print the vowels, right?
|
Java | UTF-8 | 3,346 | 3.453125 | 3 | [] | no_license | package dlithe.batch2.internship.DLitheBatchTwoInternship;
import java.util.Arrays;
public class Dealer implements DealerOperations
{
Bike[] stock;
public Dealer(){}
public Dealer(Integer size) {stock=new Bike[size];}//5
@Override
public void addToStock(Bike object) {
// TODO Auto-generated method stub
for(int index=0;index<stock.length;index++)
{
if(stock[index]==null)
{
stock[index]=object;
System.out.println(object.getModel()+" was added to stock");
break;
}
}
}
@Override
public void listAll()
{
System.out.println("Listing all stocks");
for(Bike temp:stock)
{
System.out.println(temp);
}
}
@Override
public void update(Integer cc, Integer newone)
{
for(int index=0;index<stock.length;index++)
{
if(stock[index]!=null&&stock[index].getCc().equals(cc))
{
System.out.println(stock[index].getModel()
+" going upgrade new CC of "+newone+" from "+cc);
stock[index].setCc(newone);
}
}
}
@Override
public Bike[] shortlist(Short cc) {
// TODO Auto-generated method stub
Bike[] back=new Bike[stock.length];
int index=0;
for(Bike temp:stock)
{
if(temp!=null&&(int)temp.getCc()<=cc)
{back[index]=temp;index++;}
}
return back;
}
@Override
public Bike[] shortlist(Integer year) {
// TODO Auto-generated method stub
System.out.println("Year wise filter");
Bike[] back=new Bike[stock.length];
int index=0;
for(Bike temp:stock)
{
if(temp!=null&&((int)temp.getYear()==year))
{back[index]=temp;index++;}
}
return back;
}
@Override
public Bike[] shortlist(Double price) {
// TODO Auto-generated method stub
Bike[] back=new Bike[stock.length];
int index=0;
for(Bike temp:stock)
{
if(temp!=null&&((double)temp.getCost()<=price))
{back[index]=temp;index++;}
}
return back;
}
@Override
public void sort()
{
System.out.println("Sorting stocks based on cost");
Bike temp;
for(int hold=0;hold<stock.length;hold++)
{
for(int rest=hold+1;rest<stock.length;rest++)
{
if(stock[hold]!=null&&stock[rest]!=null&&stock[hold].getCost()>=stock[rest].getCost())
{
temp=stock[hold];stock[hold]=stock[rest];stock[rest]=temp;
}
}
}
}
@Override
public Bike remove(Integer index)
{
Bike temp;
if(stock[index]!=null)
{
temp= stock[index];
stock[index]=null;
System.out.println(index+" in stock became empty");
return temp;
}
return null;
}
public static void main(String[] args)
{
Dealer deal=new Dealer(4);
Bike b1=new Bike("HondaR15", 2020, 30, 150, 114000.9);
Bike b2=new Bike("ApacheRTR", 2016, 40, 200, 102000.89);
Bike b3=new Bike("AvengerCruise", 2016, 45, 220, 109000.7);
deal.addToStock(b1);deal.addToStock(b2);deal.addToStock(b3);
deal.listAll();
/*Bike[] got=deal.shortlist((short)200);
System.out.println("Filtered bike by CC \n"+Arrays.toString(got));
deal.update(200, 350);deal.listAll();
got=deal.shortlist(2016);
System.out.println("Filtered bike by Year \n"+Arrays.toString(got));
got=deal.shortlist(110000.8);
System.out.println("Filtered bike by Cost \n"+Arrays.toString(got));*/
deal.sort();
deal.listAll();
System.out.println(deal.remove(1));
deal.listAll();
}
}
|
Markdown | UTF-8 | 2,181 | 3.75 | 4 | [] | no_license | ## 495. 提莫攻击(中等)
日期:
>2020/12/19(第一次刷)
题目
>在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄,他的攻击可以让敌方英雄艾希(编者注:寒冰射手)进入中毒状态。现在,给出提莫对艾希的攻击时间序列和提莫攻击的中毒持续时间,你需要输出艾希的中毒状态总时长。
你可以认为提莫在给定的时间点进行攻击,并立即使艾希处于中毒状态。
示例1:
>输入: [1,4], 2
输出: 4
原因: 第 1 秒初,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒末结束。
第 4 秒初,提莫再次攻击艾希,使得艾希获得另外 2 秒中毒时间。
所以最终输出 4 秒。
示例2:
>输入: [1,2], 2
输出: 3
原因: 第 1 秒初,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒末结束。
但是第 2 秒初,提莫再次攻击了已经处于中毒状态的艾希。
由于中毒状态不可叠加,提莫在第 2 秒初的这次攻击会在第 3 秒末结束。
所以最终输出3。
提示:
>你可以假定时间序列数组的总长度不超过 10000。
你可以假定提莫攻击时间序列中的数字和提莫攻击的中毒持续时间都是非负整数,并且不超过 10,000,000。
**思想**:
>判断每个间隔的时间长度和中毒持续时间之间的大小,将两者小的数累加。
**代码**:
```
class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
//注意空集!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (timeSeries.size() == 0)
return 0;
int dur = 0;
int total_dur = 0;
for(int i = 1; i < timeSeries.size(); i++)
{
if(timeSeries[i] - timeSeries[i-1] > duration)
{
dur = duration;
}
else
{
dur = timeSeries[i] - timeSeries[i-1];
}
total_dur = total_dur + dur;
}
total_dur = total_dur + duration;
return total_dur;
}
};
```
|
Python | UTF-8 | 2,908 | 2.78125 | 3 | [] | no_license | #!/usr/bin/python
from Recorder import Recorder
from SpeechToText import speech_to_text
from TextTranslator import translate_text
from Tkinter import *
#from Tkinter import ttk
import ttk
filename = '/tmp/recorder.wav'
context = {}
def start(*args):
# print(fromOptions[fromLanguage.get()])
context['recorder'] = Recorder(filename)
context['recorder'].start()
def stop(*args):
context['recorder'].stop()
text.set(speech_to_text(fromOptions[fromLanguage.get()],filename))
translatedText.set(translate_text(toOptions[toLanguage.get()],text.get()))
root = Tk()
root.title("Universal Translator")
root.geometry("480x480")
mainframe = Frame(root)
#mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.grid(column=0, row=0)
#mainframe.columnconfigure(0, weight=1)
#mainframe.rowconfigure(0, weight=1)
text = StringVar()
translatedText = StringVar()
fromLanguage = StringVar()
toLanguage = StringVar()
#fromOptions = { 'English' : 'en-US', 'French' : 'fr-FR', 'Spanish': 'es-MX' }
fromOptions = {
'Arabic (Iraq)' : 'ar-IQ',
'Chinese, Mandarin (Simplified, Hong Kong)' : 'cmn-Hans-HK',
'English (United States)' : 'en-US',
'French (France)' : 'fr-FR',
'German (Germany)' : 'de-DE',
'Hebrew (Israel)' : 'he-IL',
'Hindi (India)' : 'hi-IN',
'Italian (Italy)' : 'it-IT',
'Japanese (Japan)' : 'ja-JP',
'Korean (South Korea)' : 'ko-KR',
'Russian (Russia)' : 'ru-RU',
'Spanish (Mexico)' : 'es-MX'
}
#toOptions = { 'English' : 'en', 'French' : 'fr', 'Spanish': 'es' }
toOptions = {
'Arabic (Iraq)' : 'ar',
'Chinese, Mandarin (Simplified, Hong Kong)' : 'cmn-Hans',
'English (United States)' : 'en',
'French (France)' : 'fr',
'German (Germany)' : 'de',
'Hebrew (Israel)' : 'he',
'Hindi (India)' : 'hi',
'Italian (Italy)' : 'it',
'Japanese (Japan)' : 'ja',
'Korean (South Korea)' : 'ko',
'Russian (Russia)' : 'ru',
'Spanish (Mexico)' : 'es'
}
#text.set("Hello, my name is Adam and I love cheesy potatos! They are super cheesy and yummy. How good is that?!")
fromMenu = OptionMenu(mainframe, fromLanguage, *sorted(fromOptions.keys()))
toMenu = OptionMenu(mainframe, toLanguage, *sorted(toOptions.keys()))
fromLanguage.set('English (United States)')
toLanguage.set('Spanish (Mexico)')
Button(mainframe, text="Start Recording", command=start, width=25, height=3).grid(column=1, row=1, sticky=(N,S,W,E))
Button(mainframe, text="Stop Recording", command=stop, width=25, height=3).grid(column=2, row=1, sticky=(N,S,W,E))
fromMenu.grid(column=1, row=2, sticky=(N,W))
Label(mainframe, textvariable=text, wraplength=470).grid(column=1, row=3, columnspan=2, sticky=W)
ttk.Separator(mainframe).grid(column=1,row=4,columnspan=2, sticky=(E,W))
toMenu.grid(column=1, row=5, sticky=(N,W))
Label(mainframe, textvariable=translatedText, wraplength=470).grid(column=1, row=6, columnspan=2,sticky=W)
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()
|
JavaScript | UTF-8 | 1,704 | 2.515625 | 3 | [] | no_license | import React from 'react';
import './about.styles.css';
export const About = () => {
return (
<div id="about" className="container">
<h1>About Us</h1>
<span className="material-icons icon-2" >restaurant</span>
<p>
<b>parambariyam</b> means traditional and true to its name, the recepies
have been passed and tried down from generation to generation and it has
been used and changed to suit the present generation , keeping mind to
maintain the traditional methods fused with the latest technology to
give a very tasty traditional food which is more like veetu saapadu.
parambariyam is a fast emerging catering company, we have carved a niche
for ourselves in this competitive food industry by offering simple but
yet delicious food keeping mind the quality and quantity and hygiene. We
do not use any artificial flavors or mono-sodium glutamate. Our masala's
are freshly grounded. We try to preserve and enhance the original
flavour of the spices , hence we are able to give quality food to
satisfy the taste of our clients to utmost satisfaction.
<br/>
We love the smell of freshness. The masala we use is self made and we use only the simplest ingredients to bring out smells and flavors. Stop by anytime and experience simplicity at it's finest.Cuisine in India is vast and wide ranging as it is a multi ethnic culture. Indian cuisines varying from region to region, different regions adapting different cuisine, parambariyam gives an opportunity for people to explore, in order to embark successfully on this journey of expansion.
</p>
</div>
);
};
|
PHP | UTF-8 | 353 | 2.546875 | 3 | [] | no_license | <?php
namespace hr\sofascore\dz3\htmllib;
/**
* Predstavlja option element.
*/
class HTMLOptionElement extends HTMLElement {
/**
* Stvara option element.
* @param $children HTMLCollection|null
*/
public function __construct(HTMLCollection $children = null) {
parent::__construct("option", true, $children);
}
}
|
C# | UTF-8 | 1,528 | 3.125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConfiguringAssemblies
{
class Product
{
public Int32 ProductId { get; set; }
public String ProductName { get; set; }
public Double ProductPrice { get; set; }
public Int32 StockCount { get; set; }
public Product() : this (000679, "lays classic chips", 1.45, 2500)
{
}
public Product(Int32 productId, String productName, Double productPrice, Int32 stockCount)
{
ProductId = productId; ProductName = productName; ProductPrice = productPrice;
StockCount = stockCount;
}
public override string ToString()
{
return String.Format("Product details:\nId: {0}, Name: {1}, Price: {2}, Count: {3}", ProductId, ProductName, ProductPrice, StockCount);
}
}
class Cart
{
Dictionary<Int32, Product> myCart = new Dictionary<Int32, Product>();
public void Add(Product p)
{
myCart.Add(p.ProductId, p);
}
public void Remove(Product p)
{
myCart.Remove(p.ProductId);
}
public Double CartTotal()
{
Double sum = 0;
if (myCart.Count > 0)
{
foreach (KeyValuePair<Int32, Product> item in myCart)
{
sum += item.Value.ProductPrice;
}
}
return sum;
}
}
}
|
C | UTF-8 | 5,022 | 2.578125 | 3 | [] | no_license | /* Sort code for HAGAR, the NaI gamma detector
*
* Author: Philip Adsley
*
* This code also functions as a template for gamma sort codes for K600 experiments.
*
*
*/
#include "GammaData.h"
#include "ScintillatorSort.h"
#include <math.h>
#include <stdlib.h>
#include <TRandom3.h>
extern int ADCModules;
extern int ADCsize;
// extern int NumberOfScintillator;
extern int *ScintillatorADCChannelLimits;
extern int *ScintillatorTDCChannelLimits;
extern double *ADCOffsets;
extern double *ADCGains;
TRandom3 *randy2 = new TRandom3(0);
//GammaData *ScintillatorSort(float *ADC_import, int ntdc, int *TDC_channel_import, float *TDC_value_import)
void ScintillatorSort(float *ADC_import, int ntdc, int *TDC_channel_import, float *TDC_value_import, GammaData *gammy)
{
//GammaData *gammy = new GammaData();
//Loop over ADC and TDC events and do the following:
//Check whether there are front-back coincidences for a detector and test the energies
//Check to see whether there's a TDC event for the same channel as the front hit ADC - TDCs are apparently in single-hit mode. Don't need to worry about multihits
//Calculate the theta and phi for the valid events
multiTDC *mTDC = new multiTDC;
mTDC->multiTDCSort(ntdc, TDC_channel_import, TDC_value_import);
for(int k=0;k<mTDC->GetSize();k++)//Loop over all of the TDC values - there should only be a small number of these relative to the ADC values
{
if(ScintillatorTDCTest(mTDC->GetChannel(k)))
{
for(int i=ScintillatorADCChannelLimits[0];i<=ScintillatorADCChannelLimits[1];i++)
{
if(ScintillatorADCTDCChannelCheck(i,mTDC->GetChannel(k)))
{
// printf("ADCChannel: %d \t TDCChannel: %d\n",i,mTDC->GetChannel(n));
double GammaEnergy = ScintillatorEnergyCalc(i,ADC_import[i]);
if(GammaEnergy>0.1)
{
gammy->SetEnergy(GammaEnergy);
gammy->SetTime(mTDC->GetValue(k));
gammy->SetDetectorType("Scintillator"); //the detector type will allow to choose between Hagar, Clover or Scintillator
int label= 1 + i - ScintillatorADCChannelLimits[0]; //the detector number starts from 1
gammy->SetDetectorLabel(label);
// gammy->SetGammaRawADC(ADC_import[i]);
// gammy->SetGammaADCChannel(i);
// gammy->SetGammaTDCChannel(mTDC->GetChannel(k));
// gammy->SetGammaTDCMultiplicity(mTDC->GetMult(k));
}
}
}
}
}
gammy->SetHits(gammy->SizeOfEvent());
mTDC->ClearEvent();
delete mTDC;
//return gammy;
}
double ScintillatorThetaCalc(int Channel)
{
return 0;
}
double ScintillatorPhiCalc(int Channel)
{
return 0;
}
double ScintillatorEnergyCalc(int Channel, double ADCValue)
{
double randNum = randy2->Rndm();
// printf("Channel: %i \t ADCValue: %f\n",Channel,ADCValue);
// printf("Offset: %f \t Gain: %f\n",ADCOffsets[Channel],ADCGains[Channel]);
// double result = ADCOffsets[Channel] + ADCGains[Channel]*ADCValue;
// double result = ADCOffsets[Channel] + ADCGains[Channel]*(ADCValue+randNum-0.5);
double result = ADCOffsets[Channel] + ADCGains[Channel]*(ADCValue+randNum);
// printf("ADCValue: %f \n rand(): %f \n result: %f\n", ADCValue, randNum,result);
return result;
}
bool ScintillatorTDCTest(int TDCChannel) // to check if the TDCChannel is the one associated with the Scintillators
{
bool result = false;
if(TDCChannel>=ScintillatorTDCChannelLimits[0] && TDCChannel<=ScintillatorTDCChannelLimits[1])
{
result = true;
}
if(ScintillatorTDCChannelLimits[0]==-1)result = true;
if(ScintillatorTDCChannelLimits[1]==-1)result = true;
return result;
}
bool ScintillatorADCTDCChannelCheck(int ADCChannel, int TDCChannel) // to consider only the TDC/ADC channel associated with a Scintillator
{
bool result = false;
// printf("ADCChannel: %d \t TDC Channel: %d\n",ADCChannel, TDCChannel);
if(ADCChannel>=ScintillatorADCChannelLimits[0] && ADCChannel<=ScintillatorADCChannelLimits[1] && TDCChannel>=ScintillatorTDCChannelLimits[0] && TDCChannel<=ScintillatorTDCChannelLimits[1])//Check to see if the ADC/TDC events are in the same detector
{
if((ADCChannel-ScintillatorADCChannelLimits[0])==(TDCChannel-ScintillatorTDCChannelLimits[0]))
{
// printf("Correlation! ADCChannel: %d \t TDC Channel: %d\n",ADCChannel, TDCChannel);
result = true;
}
}
if(ScintillatorADCChannelLimits[0]==-1)result = true;//If there is no information for some of the MMMs, suppress this test
if(ScintillatorADCChannelLimits[1]==-1)result = true;
if(ScintillatorTDCChannelLimits[0]==-1)result = true;
if(ScintillatorTDCChannelLimits[1]==-1)result = true;
return result;
}
/*
int ScintillatorDetHitNumber(int ADCChannel) //number of hit in one Scintillator
{
int result = 0;
for(int i=0;i<NumberOfScintillator;i++)
{
if(ADCChannel>=ScintillatorADCChannelLimits[i][0] && ADCChannel<=ScintillatorADCChannelLimits[i][1])
{
result = i+1;
}
}
printf("result = %d\n",result);
return result;
}
*/
|
C++ | UTF-8 | 591 | 2.8125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
int feedback[21];
int tscore = 0, kscore = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> feedback[i];
if (feedback[i] == 1)
kscore++;
else if (feedback[i] == 2)
tscore++;
else if (feedback[i] == 3) {
tscore++;
kscore++;
}
else if (feedback[i] == 4) {
tscore--;
kscore--;
}
}
if (tscore == kscore)
cout << "Draw" << endl;
else if (tscore > kscore)
cout << "Tohru" << endl;
else
cout << "Kobayashi" << endl;
}
return 0;
} |
Markdown | UTF-8 | 9,725 | 2.671875 | 3 | [] | no_license | <audio title="050 _ 大杀器Lotus Notes 和被收购的莲花公司" src="https://static001.geekbang.org/resource/audio/ad/2b/ad3cd04f87c36410f7d6fc8922bfd02b.mp3" controls="controls"></audio>
<p>莲花公司在电子表格市场大获成功,但并不甘于局限在电子表格软件里。1984年,公司CEO吉姆 · 曼兹(Jim Manzi)秘密开始了一项影响深远的开发计划:基于莲花公司的设计,委托Iris公司开发一个“大杀器”,也就是后来长期独霸企业协同市场的Lotus Notes系统。</p>
<p>Iris公司的创立者是雷 · 奥茨(Ray Ozzie),一个在计算机发展史上非常著名的人物。他曾是莲花公司的早期员工,但是对电子表格兴趣寥寥,对通过网络连接实现的企业协同软件却极有兴趣,因此1984年他离职创立了Iris来实现自己的梦想。</p>
<p>莲花公司之所以委托Iris公司来开发这款软件,一方面是奥茨是自己人,知根知底,他的兴趣和能力所在都很清晰;另外一方面是,莲花公司内部都沉浸在电子表格软件成功的喜悦中,将电子表格视为公司最核心的业务,因此大部分人对于开始一项全新软件的研发,持观望乃至反对态度。</p>
<p>然而微软节节胜利,尤其是推出Windows 2.0以后,基于图形界面的Excel可以同时跑在苹果机和PC机上,从而占据了非常大的市场优势,而Lotus 1-2-3却依旧基于古老的DOS字符界面。因此,莲花公司面临一个重要抉择:是继续全力以赴地开发基于图形界面的电子表格,还是集中精力做公司已经秘密投资的办公协同软件Lotus Notes?</p>
<!-- [[[read_end]]] -->
<p>选择前者,就意味着要在微软领先的战场与对方真刀真枪地竞争。然而,电子表格的灵魂人物米切尔 · 卡普尔(Mitch Kapor)已经离开,莲花公司CEO对自己能否战胜比尔 · 盖茨领导的微软缺乏信心。而如果选择后者,虽然这意味着公司要做大转型,但是公司CEO曼兹对奥茨这个人充满了信心。</p>
<p>曼兹最终说服了董事会,决定将公司主力投入新战场Lotus Notes,以避免和微软正面冲突。Iris公司和莲花公司联合开发的Lotus Notes在1989年推向市场,并大获成功。但是伴随时间的推移,这种联合开发方式造成了很多不便,最大的问题是作为项目总架构师的奥茨身在Iris公司,却要指挥莲花公司的大量员工。于是1994年莲花公司收购了Iris,让奥茨回归莲花并主导Lotus Notes的开发。</p>
<p>Lotus Notes这个产品,是一个主打企业级通信与协同办公的软件。简单来说,它是一个局域网内联网的客户端/服务器软件,客户端装在每个办公人员的机器上,服务器则用于存储和管理各种信息。</p>
<p>它主要针对让办公人员方便地交流文件、电子邮件,以及讨论问题等各种协同办公的场景,并集合了日历、邮件、通讯录、文件存储、定制化的审批流程等功能,同时提供大量的接口供用户进行定制化操作和二次开发。</p>
<p>整体来说,这个软件给人的感觉非常超前,就类似于在汽车还没怎么跑起来的年代里,混进了一辆跑车。所以有人笑称奥茨是从2004年穿越回1984年,主导开发了这样一套软件。因为其中的很多东西到了21世纪以后,大家才司空见惯,但是早在20世纪80年代后期,Lotus Notes就给企业客户开发出来了。</p>
<p>Lotus Notes不仅仅是最早的客户端/服务器软件,还可能是最复杂的客户端/服务器软件,而且还有一个很大的特点:封闭性。一但用上了这个系统,企业整个办公流程都被套牢在这套系统里,非常难从里面迁移出去。比如,华为公司就经过了十多年的努力,才终于于2015年迁移出了Lotus Notes系统。</p>
<p>这种集先进性和封闭性为一体的软件,既给莲花公司带来了大量客户,也把客户牢牢地捆绑在了莲花公司的战车上。莲花公司的盈利能力因此大大增强了。</p>
<p>莲花公司在缺乏电子表格的精神领袖米切尔 · 卡普尔的情况下,尽量避免和比尔 · 盖茨领导下的微软在电子表格战场正面厮杀,通过另起炉灶,在企业协同办公战场把众多企业捆绑进来,成功完成了转型。</p>
<p>然而这次转型并非没有代价。Lotus 1-2-3可谓莲花公司诸多员工乃至高层的信仰,虽然CEO说服了董事会进行转型,但对Lotus 1-2-3有着浓厚情感的高管们却没有被说服:在转型过程中陆陆续续就有12个副总裁离职。好在,Notes最终大卖特卖。</p>
<p>而与此同时,个人计算机市场发生了巨大变化,IBM这个发明个人计算机的企业正经历有史以来最严重的一场危机。这场危机起于微软和IBM的博弈,当时IBM在DOS时代失去了对操作系统的控制,试图在和微软联合开发的操作系统OS/2中重新取得统治地位。但祸不单行,此时的IBM因为采用了Intel 80286芯片而导致Intel壮大,失去了对芯片的控制权。</p>
<p>于是,当Intel再次推出80386芯片时,IBM放弃了支持这款芯片,自然地打起如意算盘,换用自己和摩托罗拉研发的PowerPC芯片。加之它在和微软开发的下一代操作系统OS/2中掌握主导权,IBM想着通过双管齐下,来巩固自己在个人计算机市场的控制力。</p>
<p>却不料聪明的比尔 · 盖茨和IBM玩起了虚与委蛇的游戏:应付着派几个人去开发OS/2,却自己秘密开发Windows。并且,盖茨还和其他兼容的PC机厂商合作,为对方推出的基于Intel 80386的兼容机提供DOS和Windows系统。</p>
<p>出现重大战略失误的IBM,不但没能够重新控制个人计算机市场,反而被各大兼容机厂商包围。在个人计算机市场,IBM第一的位置很快被兼容机制造厂商康柏超越。落后的IBM兼容机在1993年给IBM带来了80亿美元的亏损,很多经济评论家分析师认为IBM将在几年内破产。</p>
<p>此时,后来大名鼎鼎带领IBM转型成功的董事长兼CEO郭士纳临危受命,开始拯救IBM。他决定把IBM从一个硬件,尤其是个人计算机制造厂商,转变为以软件为高优先级,以企业服务为核心的企业。这就是IBM历史上非常有名的从硬件到软件和服务的转型。</p>
<p>为什么要做这样的转型,后来者众说纷纭。我的理解是,一方面IBM试图以自己的垄断地位,掌控个人计算机市场的操作系统和芯片的走势,并不明智地拒绝使用Intel更先进的处理器,从而导致被各大兼容机厂商超越,也在消费者市场让消费者失去了信心,无法继续攫取大量的利润,反而不断亏损。另外一方面,企业软件和服务市场是利润丰厚的行业,而且IBM一直都很有根基。舍弃亏钱又没太多希望的个人计算机行业,专注企业软件和服务市场,是迅速扭亏为盈走出困境的好选择。</p>
<p>IBM在企业级市场传统上有很多的市场份额,包括大型机、小型机、专用操作系统、数据库等都在企业市场有很高的占有率。这个转型既有利于IBM甩掉赔钱的业务,又有利于巩固利润丰厚且自己早有根基的企业软件市场。</p>
<p>为了成为企业软件和服务的主导者,IBM一边内部整合自己的软件体系,一边开始搜罗外界可以收购的对象。作为企业协同软件领域的唯一主导者莲花公司,很快进入了IBM的视线。1995年,IBM决定恶意并购莲花公司。当时莲花公司的股价32美元一股,IBM开出60美元一股的股价,后来又涨到了64.5美元一股。</p>
<p>但是莲花公司不想卖,还找到了AT&T求助。但AT&T对于莲花公司并非必须要收购,加之IBM又已经将股价翻倍,AT&T不想做“冤大头”。IBM历史上很少有这样强行收购的行为,那为什么当时郭士纳决定不惜成本收购呢?公开的说法是,郭士纳觉得莲花公司的Lotus Notes对IBM转型成为企业软件和服务公司至关重要。</p>
<p>收购之后,莲花公司CEO就直接辞职了,IBM非常担心其他核心开发人员和高管纷纷离职,于是花大价钱收买了高层,包括Lotus Notes的总架构师奥茨,同时对莲花公司员工保证说,收购之后你们公司依旧会保持独立运作。IBM最终通过种种措施稳住了员工,在一定时间里没有让莲花公司变成一个空壳。</p>
<p>然而,2001年IBM对莲花公司进行了一次重组。简单来说,就是把在剑桥的原莲花公司开发人员和机构,都重组到了IBM总部,从而结束了自1995年收购以来IBM承诺的莲花公司独立运作的历史。伴随重组,Lotus.com网站上也被悄悄抹去了莲花公司的痕迹,代之以IBM的商标。奥茨也离开了IBM。</p>
<p>失去首席架构师的Notes,在IBM的开发维护下开始呈现颓势,新功能增加得杂乱不堪,新版客户端有严重的内存泄漏问题。2008年我在IBM研究院实习的时候,使用过Notes,这个软件对内存的消耗到了令人发指的地步,机器经常毫无缘由地卡顿半分钟到几分钟不等。</p>
<p>Notes原本是一个功能上非常先进的产品,性能也很不错,后来被IBM硬生生做成了性能堪忧的产品。再后来,Notes在大部分公司里也渐渐消失了。我有时候在想,如果莲花公司没有被收购,继续独立发展的话,今天不知道会达到一个什么样的高度。</p>
<p></p>
|
JavaScript | UTF-8 | 10,890 | 2.921875 | 3 | [] | no_license | var count = 1;
var checkout = 1;
var edit_exp_id = 1;
var edit_inc_id = 1;
var date = new Date()
var current_date = date.getMonth() + 1
var income_date = date.getMonth() + 1
$("#add").on('click', function(){
$("#category").append(`
<label for="recipient-name" class="col-form-label">Enter your new category :</label>
<input id = ${count} class = "form-control" type='text' required>
`)
$("#description").append(`
<label for="recipient-name" class="col-form-label">Enter your new description :</label>
<input id = ${count+"d"} class = "form-control" type='text' required>
`)
count = count + 1;
console.log(count);
});
// saving the new category
$("#save_category").on("click", function(){
for(let i=0;i<count;i++)
{
var cat = $("#"+i).val();
var description = $("#"+i+"d").val();
console.log(cat);
if (cat == '' || description == ''){
alert("Cannot submit the empty form");
window.location.href = '/dashboard/';
}
let json_data = {};
json_data["title"] = cat;
json_data["description"] = description;
// console.log(json_data)
$.ajax({
method:"POST",
data: json_data,
type: "application/json",
url:"/api/category/",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token " + window.localStorage["token"]);
},
success: function(response) {
console.log("done");
}
});
}
$('#category').empty()
$("#description").empty()
count = 1;
});
// will fetch all the category of the user to render in the delete category div.
//for the delete category button
$("#delete_cat").on("click", function(){
$.ajax({
method: "GET",
url:"/api/category/",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token " + window.localStorage["token"]);
},
success: function(response){
console.log(response);
$("#delcategory").empty();
console.log("here")
checkout = 1;
console.log("here")
for(let i of response)
{
$("#delcategory").append(`
<input type="checkbox" value=${i.id} id=${checkout}>
<label>${i.title}</label><br>
`);
checkout = checkout + 1;
}
}
})
});
// for the add expense button
$("#add_expense").on("click", function(){
$.ajax({
method: "GET",
url:"/api/category/",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token " + window.localStorage["token"]);
},
success: function(response){
$("#select_category").empty();
for(let i of response)
{
$("#select_category").append(`
<option value=${i.id}>${i.title}</option>
`);
}
}
})
});
//for the add income button
$("#add_income").on("click", function(){
$.ajax({
method: "GET",
url:"/api/category/",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token " + window.localStorage["token"]);
},
success: function(response){
$("#select_category_income").empty();
for(let i of response)
{
$("#select_category_income").append(`
<option value=${i.id}>${i.title}</option>
`);
}
}
})
});
// delete category
$("#del_category").on('click', function(){
for(let i =0; i<checkout; i++){
var id = "#"+i;
if( $(id).prop("checked") == true )
{
// console.log($(id).val());
var url = "/api/category/"+$(id).val()+"/";
$.ajax({
method:"DELETE",
url: url,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
console.log("done");
}
});
}
}
});
//For add expense modal.
$("#done").on('click', function(){
let cat_id = $("#select_category").find(":selected").val();
let cost_money = $("#expense_cost").val()
let cost_title = $("#expense_title").val()
let cost_des = $("#expense_des").val()
let expense_date = $("#expense_date").val()
console.log(expense_date);
let json_data = {}
json_data["title"] = cost_title
json_data["categories"] = cat_id
json_data["cost"] = cost_money
json_data["description"] = cost_des
json_data["time"] = expense_date
$.ajax({
method:"POST",
url: "/api/expense/",
type: "application/json",
data: json_data,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
console.log("done")
drawExpenseTable();
drawAllExpenseChart();
drawIncomeChart();
drawAllIncomeChart();
drawExpenseBarChart();
}
});
});
//saving new income
$("#save_income").on("click", function(){
let cat_id = $("#select_category_income").find(":selected").val();
let cost_money = $("#income_money").val()
let cost_title = $("#income_title").val()
let cost_des = $("#income_des").val()
let income_date = $("#income_date").val()
let json_data = {};
json_data["title"] = cost_title
json_data["description"] = cost_des
json_data["money"] = cost_money
json_data["categories"] = cat_id
json_data["time"] = income_date
$.ajax({
method:"POST",
url:"/api/income/",
type:"application/json",
data: json_data,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
console.log("done")
drawExpenseTable();
drawAllExpenseChart();
drawIncomeChart();
drawAllIncomeChart();
drawExpenseBarChart();
}
});
});
// for the edit expense modal;
function edit_expense(month_number){
if(current_date + month_number <= 1){
current_date = 1;
}
else if(current_date + month_number >= 12){
current_date = 12
}
else{
current_date = month_number + current_date
}
let data = {}
data["month"] = current_date
console.log(data);
console.log(current_date);
$.ajax({
method:"GET",
url:"/api/expense/",
type:"application/json",
data: data,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
$("#edit_exp_div").empty();
$("#edit_exp_div").append(`
<div id="edit_exp_div_item">
</div>
`)
$("#edit_exp_div_item").append(`
<table class="table" id="edit_exp_div_item_table">
<thead>
<tr">
<td scope="col"><b>Category</b></td>
<td scope="col"><b>Title</b></td>
<td scope="col"><b>Description</b></td>
<td scope="col"><b>Cost</b></td>
<td scope="col"><b>Option</b></td>
</tr>
</thead>
</table>
`)
edit_exp_id = 1;
for(let i of response){
$("#edit_exp_div_item_table").append(`
<tr scope="row">
<td scope="col">${i.categories.title}</td>
<td scope="col"><input class="form-control" id="${edit_exp_id}title" value="${i.title}"></td>
<td scope="col"><input class="form-control" id="${edit_exp_id}des" value="${i.description}"></td>
<td scope="col"><input class="form-control" id="${edit_exp_id}cost" value="${i.cost}"></td>
<td scope="col"><button class="btn btn-sm btn-success" data-dismiss="modal" onclick="edit_exp_function(${edit_exp_id},${i.id})" style="margin-top:3px;">save</button></td>
</tr>
`)
edit_exp_id = edit_exp_id + 1;
}
}
})
};
// for after editing the expense and clicking on the save button.
function edit_exp_function(id,expense_id){
title_id = "#"+id+"title"
des_id = "#"+id+"des";
cost_id = "#"+id+"cost"
var title = $(title_id).val();
var des = $(des_id).val();
var cost = $(cost_id).val();
let json_data = new Object();
console.log(current_date);
json_data['month'] = current_date;
json_data['title'] = title;
json_data['description'] = des;
json_data['cost'] = cost;
console.log(json_data)
url = "/api/expense/"+expense_id+"/"
$.ajax({
method:"PATCH",
url: url,
data: "application/json",
data: json_data,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
console.log("done");
drawExpenseTable();
drawAllExpenseChart();
drawIncomeChart();
drawAllIncomeChart();
drawExpenseBarChart();
}
})
}
//edit income button modal.
function edit_income(month_number){
if(income_date + month_number <= 1){
income_date = 1;
}
else if(income_date + month_number >= 12){
income_date = 12
}
else{
income_date = month_number + income_date
}
let data = {};
data["month"] = income_date;
console.log(income_date);
$.ajax({
method:"GET",
url:"/api/income/",
type:"application/json",
data: data,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
$("#edit_inc_div").empty();
$("#edit_inc_div").append(`
<div id="edit_inc_div_item">
</div>
`)
$("#edit_inc_div_item").append(`
<table class="table" id="edit_inc_div_item_table">
<thead>
<tr">
<td scope="col"><b>Category</b></td>
<td scope="col"><b>Title</b></td>
<td scope="col"><b>Description</b></td>
<td scope="col"><b>Cost</b></td>
<td scope="col"><b>Option</b></td>
</tr>
</thead>
</table>
`)
edit_inc_id = 1;
for(let i of response){
$("#edit_inc_div_item_table").append(`
<tr scope="row">
<td scope="col">${i.categories.title}</td>
<td scope="col"><input class="form-control" id="${edit_inc_id}titlei" value="${i.title}"></td>
<td scope="col"><input class="form-control" id="${edit_inc_id}desi" value="${i.description}"></td>
<td scope="col"><input class="form-control" id="${edit_inc_id}costi" value="${i.money}"></td>
<td scope="col"><button class="btn btn-sm btn-success" data-dismiss="modal" onclick="edit_inc_function(${edit_inc_id},${i.id})" style="margin-top:3px;">save</button></td>
</tr>
`)
edit_inc_id = edit_inc_id + 1;
}
}
})
};
// after saving the edited modal.
function edit_inc_function(id,income_id){
title_id = "#"+id+"titlei"
des_id = "#"+id+"desi";
cost_id = "#"+id+"costi"
var title = ($(title_id).val());
var des = ($(des_id).val());
var cost = ($(cost_id).val());
let json_data = {}
json_data["month"] = income_date;
json_data["title"] = title;
json_data["description"] = des;
json_data["money"] = cost;
console.log(json_data);
url = "/api/income/"+income_id+"/"
$.ajax({
method:"PATCH",
url: url,
type: "application/json",
data: json_data,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Token "+ window.localStorage["token"])
},
success: function(response){
console.log("done");
drawExpenseTable();
drawAllExpenseChart();
drawIncomeChart();
drawAllIncomeChart();
drawExpenseBarChart();
}
})
}
|
Java | ISO-8859-1 | 10,630 | 2.28125 | 2 | [] | no_license | package Telas;
import servicos.ServicoProcedimento;
import javax.swing.JButton;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.GroupLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AdicionarProcedimento extends javax.swing.JFrame {
/** Creates new form AdicionarProcedimento */
public AdicionarProcedimento() {
initComponents();
}
ServicoProcedimento servico = new ServicoProcedimento();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
labelNome = new javax.swing.JLabel();
labelValor = new javax.swing.JLabel();
labelDescricao = new javax.swing.JLabel();
nomeProcedimento = new JTextFieldLetras();
valorProcedimento = new JTextFieldValor();
descProcedimento = new JTextFieldLetras();
adicionarProcedimento = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Ramira Esttica Facial e Corporal");
jPanel1.setBackground(new java.awt.Color(255, 153, 153));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Adicionar Procedimento");
btnVoltar = new JButton("Voltar");
btnVoltar.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
new TelaProcedimentos().setVisible(true);
dispose();
}
});
btnVoltar.setFont(new Font("Tahoma", Font.BOLD, 12));
btnVoltar.setForeground(new Color(255, 255, 255));
btnVoltar.setBackground(new Color(240, 128, 128));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(158, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addComponent(btnVoltar))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1))
.addComponent(btnVoltar))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel1.setLayout(jPanel1Layout);
labelNome.setText("Nome");
labelValor.setText("Valor");
labelDescricao.setText("Descrio");
descProcedimento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
descProcedimentoActionPerformed(evt);
}
});
adicionarProcedimento.setBackground(new java.awt.Color(255, 153, 153));
adicionarProcedimento.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
adicionarProcedimento.setForeground(new java.awt.Color(255, 255, 255));
adicionarProcedimento.setText("Adicionar");
adicionarProcedimento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
adicionarProcedimentoActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(labelDescricao)
.addComponent(labelValor)
.addComponent(labelNome)
.addComponent(nomeProcedimento)
.addComponent(valorProcedimento)
.addComponent(descProcedimento, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(adicionarProcedimento, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(66, 66, 66))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(labelNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nomeProcedimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(labelValor)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(valorProcedimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelDescricao)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(descProcedimento, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
.addComponent(adicionarProcedimento)
.addGap(21, 21, 21))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void descProcedimentoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void adicionarProcedimentoActionPerformed(java.awt.event.ActionEvent evt) {
adicionarProcedimento();
new NotificarInsercao().setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AdicionarProcedimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AdicionarProcedimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AdicionarProcedimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AdicionarProcedimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdicionarProcedimento().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton adicionarProcedimento;
private javax.swing.JTextField descProcedimento;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel labelNome;
private javax.swing.JLabel labelValor;
private javax.swing.JLabel labelDescricao;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField nomeProcedimento;
private javax.swing.JTextField valorProcedimento;
private JButton btnVoltar;
// End of variables declaration
private void adicionarProcedimento() {
String nome = nomeProcedimento.getText();
String valor = valorProcedimento.getText();
String descricao = descProcedimento.getText();
servico.inserirProcedimento(servico.criarProcedimento(nome, valor, descricao));
new TelaProcedimentos().setVisible(true);
this.dispose();
}
}
|
Python | UTF-8 | 978 | 2.546875 | 3 | [
"Unlicense"
] | permissive | from __future__ import annotations
from mechanics.events.src.Event import Event
from mechanics.events import EventsChannels
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from game_objects.items import Item
class ItemDroppedEvent(Event):
channel = EventsChannels.DropChannel
def __init__(self, item: Item, cell = None):
self.item = item
g = item.game
if cell:
location = cell
else:
if item.owner:
location = g.bf.unit_locations[item.owner]
else:
location = g.random.sample( g.bf.all_cells, 1 )[0]
self.location = location
super().__init__(g, logging=True)
def check_conditions(self):
return True
def resolve(self):
if self.item.slot:
self.item.slot.pop_item()
pass
# TODO enable pickup of dropped items
def __repr__(self):
return f"{self.item} was dropped at {self.location}." |
Markdown | UTF-8 | 3,506 | 3.609375 | 4 | [
"MIT"
] | permissive | ---
navigation_title: "Colour contrast for graphical objects"
position: 5
---
# Colour contrast for graphical objects
**The term "graphical object" typically applies to stand-alone icons and to information graphics. The visual complexity of such objects often requires some differentiation with regards to contrast. The focus lies on the parts of the graphical object required to understand the content.**
[[_TOC_]]
## Minimal contrast ratio
Version 2.1 of the Web Content Accessibility Guidelines (WCAG) specify a [minimal contrast ratio of `3:1` against adjacent colour(s)](https://www.w3.org/TR/WCAG21/#non-text-contrast) for the parts, which are required to understand the meaning or content of a graphical object.
## Example: line chart
The following picture shows a simple line chart with overall insufficient contrast.

The contrast ratio of the main X and Y axis is `2.8:1`, the one of blue trend line is `2.3:1`. The text labels along the X and Y axis have a contrast ratio of `3.9:1` which can also be considered too low because [text has to meet a higher contrast requirement](/knowledge/colours-and-contrast/text) of at least `4.5:1`. All of these values are somewhat close to their formal requirements but it's important to keep in mind that those requirements only set **minimal** standards.
Let's increase the contrast ratio of the aforementioned elements.

The question now is, what should happen with the grid lines in the background. Their contrast ratio is far too low, yet increasing it might result in a visually overloaded chart.
This brings us back to the notion of what is "required to understand the meaning or content" of this chart.
If the purpose of the chart is to just show a general trend, the grid lines might not be required. In that case, why not just remove them altogether? (If that feels like a loss, this might not be the right solution.)
However, if it is in fact important that people can comfortably read the exact values of each measuring point, it might be a good start to mark those points.

Horizontal grid lines might make it easer to gauge the value of the measuring point without overloading the overall appearance.

Or why not add a label to each measuring point, indicating its value?

It's no coincidence that many of these considerations and adjustments go far beyond just colour contrast. Designing accessible user interfaces requires a holistic approach. This means:
- There is rarely a single variable that can be independently tweaked. Accessibility should be built into the foundations of the design.
- There is rarely one generic solution that "just works". The specific context and content have to be taken into account.
- There is no strict separation between "special-purpose accessibility" and "general-purpose usability". In practice they both influence each other. |
Java | UTF-8 | 2,882 | 2.59375 | 3 | [] | no_license | /**
* Java Image Science Toolkit
* ---
* Multi-Object Image Segmentation
*
* Copyright(C) 2012, Blake Lucas (img.science@gmail.com)
* All rights reserved.
*
* Center for Computer-Integrated Surgical Systems and Technology &
* Johns Hopkins Applied Physics Laboratory &
* The Johns Hopkins University
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the The Johns Hopkins University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* @author Blake Lucas (img.science@gmail.com)
*/
package org.imagesci.demo;
import java.awt.Dimension;
import java.io.File;
import javax.vecmath.Point3i;
import org.imagesci.utility.PhantomMetasphere;
import edu.jhu.cs.cisst.vent.VisualizationApplication;
import edu.jhu.cs.cisst.vent.widgets.VisualizationImage2D;
import edu.jhu.ece.iacl.jist.io.NIFTIReaderWriter;
import edu.jhu.ece.iacl.jist.structures.image.ImageData;
// TODO: Auto-generated Javadoc
/**
* The Class Example0c_image4d.
*/
public class Example0c_image4d extends AbstractExample {
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
(new Example0c_image4d()).launch(args);
}
/* (non-Javadoc)
* @see org.imagesci.demo.AbstractExample#getDescription()
*/
@Override
public String getDescription() {
return "Displays a 4D image as a 3D vector field.";
}
/* (non-Javadoc)
* @see org.imagesci.demo.AbstractExample#getName()
*/
@Override
public String getName() {
return "View 3D Vector Field";
}
/* (non-Javadoc)
* @see org.imagesci.demo.AbstractExample#launch(java.io.File, java.lang.String[])
*/
@Override
public void launch(File workingDirectory, String[] args) {
ImageData vecfield = NIFTIReaderWriter.getInstance().read(
new File(workingDirectory, "demons_vecfield.nii"));
PhantomMetasphere metasphere = new PhantomMetasphere(new Point3i(128,
128, 128));
metasphere.setInvertImage(true);
metasphere.solve();
VisualizationImage2D vis = new VisualizationImage2D(600, 600);
vis.addVectorField(vecfield);
VisualizationApplication app = new VisualizationApplication(vis);
app.setPreferredSize(new Dimension(1024, 768));
app.runAndWait();
System.exit(0);
}
}
|
JavaScript | UTF-8 | 496 | 2.578125 | 3 | [] | no_license |
const http = require("http");
const app = http.createServer();
app.on("request", (request, response) => {
const { url, method } = request;
console.log("请求方式", method);
console.log("请求路径", url);
// 设置响应头 防止中文乱码
response.setHeader("content-type", "text/html;charset=utf-8");
// response.end("666");
response.end("中文");
});
app.listen("8080", () => {
console.log("服务器开启成功,请访问:", "http://127.0.0.1:8080");
});
|
JavaScript | UTF-8 | 1,366 | 3.21875 | 3 | [
"MIT"
] | permissive | $("document").ready(function(){
let canvasPixel = $('#pixelCanvas');
//Making the grid
function makeGrid() {
// Selecting size input
const inputHeight = $('#inputHeight').val();
const inputWidth = $('#inputWidth').val();
//Making existing grid empty
canvasPixel.empty();
//creating new grid
//creating rows
for(let i=0;i<inputHeight;i++){
canvasPixel.append('<tr></tr>');
}
let newRows=$('tr');
//creating columns
for(let j=0;j<inputWidth;j++){
newRows.append('<td></td>');
}
}
// size is submitted by the user, calling makeGrid()
$('#sizePicker').submit(function(event) {
event.preventDefault();
makeGrid();
});
//Grid created
//Changing the background color which peforms event listening
canvasPixel.on( "click", "td", function( event ) {
$(this).css("background-color", $("#colorPicker").val());
});
//to remove the colors from grid on double-click
canvasPixel.on('dblclick','td',function(){
$(this).css("background-color","");
});
//to remove the grid
$( ".clearGrid" ).click(function() {
$("#pixelCanvas" ).html('');
});
// //to show the grid
// $( ".showGrid" ).click(function() {
// $("#pixelCanvas" ).show();
// });
// to toggle the grid
$( ".toogleGrid" ).click(function() {
$("#pixelCanvas" ).toggle();
});
});
|
Shell | UTF-8 | 1,882 | 3.46875 | 3 | [] | no_license | #!/bin/bash
shopt -s expand_aliases
source ~/.bash_aliases
# -----------------------------------------------------
# argument parcing
# -----------------------------------------------------
while [[ ${1} ]]; do
case "${1}" in
--RCODE)
RCODE=${2}
shift
;;
--RWD_MAIN)
RWD_MAIN=${2}
shift
;;
--data_dir)
data_dir=${2}
shift
;;
--cluster_extracting)
cluster_extracting=${2}
shift
;;
--METADATA)
METADATA=${2}
shift
;;
--file_metadata)
file_metadata=${2}
shift
;;
--prefix_data)
prefix_data=${2}
shift
;;
--prefix_panel)
prefix_panel=${2}
shift
;;
--prefix_pca)
prefix_pca=${2}
shift
;;
--prefix_merging)
prefix_merging=${2}
shift
;;
--extract_cluster)
extract_cluster=${2}
shift
;;
--extract_dir)
extract_dir=${2}
shift
;;
*)
echo "Unknown parameter: ${1}" >&2
esac
if ! shift; then
echo 'Missing parameter argument.' >&2
fi
done
# -----------------------------------------------------
# function
# -----------------------------------------------------
### Cluster extracting
if ${cluster_extracting}; then
echo "02_cluster_extracting"
RWD=$RWD_MAIN/${data_dir}
ROUT=$RWD/Rout
mkdir -p $ROUT
echo "$RWD"
R33 CMD BATCH --no-save --no-restore "--args rwd='$RWD' extract_outdir='${RWD_MAIN}/${extract_dir}/010_cleanfcs' path_metadata='${METADATA}/${file_metadata}.xlsx' path_clustering='030_heatmaps/${prefix_data}${prefix_panel}${prefix_pca}${prefix_merging}clustering.xls' path_clustering_labels='030_heatmaps/${prefix_data}${prefix_panel}${prefix_pca}${prefix_merging}clustering_labels.xls' extract_cluster=${extract_cluster}" $RCODE/02_cluster_extracting.R $ROUT/02_cluster_extracting.Rout
tail $ROUT/02_cluster_extracting.Rout
fi
#
|
Python | UTF-8 | 4,319 | 2.640625 | 3 | [] | no_license | from collections import defaultdict
import string
f = open("in.txt", "r")
productii = dict()
for i in f.readline().split():
productii.update({i: []})
for i in f.readlines():
i = i.split()
for j in range(1, len(i)):
productii.setdefault(i[0], []).append(i[j])
# ----- PASUL 1 i)
for i in productii.keys():
aux = productii.get(i)
if aux == ['lambda']:
productii.update({i: []})
for j in productii.keys():
p = 0
for k in productii[j]:
if i in k and len(k) == 1:
productii[j][p] = 'lambda'
elif i in k:
productii[j][p] = k.replace(i, "")
p += 1
productii = {k: v for k, v in productii.items() if v}
# ------- PASUL 1 ii)
for i in productii.keys():
aux = productii.get(i)
if 'lambda' in aux:
p = 0
for z in range(len(aux)):
if aux[z] == 'lambda':
productii[i][p] = aux[z].replace('lambda', "")
p -= 1
p += 1
for q in productii.values():
if '' in q:
q.remove('')
for j in productii.keys():
for k in range(len(productii[j])):
if i in productii[j][k] and len(productii[j][k]) != 1:
if productii[j][k].replace(i, i) not in productii[j]:
productii[j].append(productii[j][k].replace(i, i))
productii[j].append(productii[j][k].replace(i, ''))
to_remove = []
# -------- PASUL 2
for i in reversed(productii.keys()):
aux = productii.get(i)
for j in reversed(productii.keys()):
if i in productii[j]:
for k in range(len(aux)):
productii[j].append(productii[i][k])
for m in range(len(productii[j])):
if i == productii[j][m]:
productii[j][m] = i.replace(i, '')
ok = 0
for y in productii.values():
for q in range(len(y)):
if i in y[q] and len(y[q]) != 1:
ok = 1
if ok == 0:
to_remove.append(i)
for q in productii.values():
if '' in q:
q.remove('')
for i in to_remove:
productii.pop(i)
productie1 = list(productii.keys())
# --------- PASUL 3
p = 0
for i in productie1:
for j in range(len(productii[i])):
if productii[i][j].isupper() == False and len(productii[i][j]) > 1:
for k in productii[i][j]:
if k.islower() == True:
productii.update({chr(51 + p): []})
productii[chr(51 + p)].append(k)
productii[i][j] = productii[i][j].replace(k, chr(51 + p))
p += 1
# --------- PASUL 4
p = 0
productie1 = []
while productie1 != list(productii.keys()):
productie1 = list(productii.keys())
for i in productie1:
for j in range(len(productii[i])):
if len(productii[i][j]) > 2:
productii[i].append(productii[i][j][0] + chr(33 + p))
productii.update({chr(33 + p): [productii[i][j][1:]]})
productii[i][j] = productii[i][j].replace(productii[i][j], '')
p += 1
for q in productii.values():
if '' in q:
q.remove('')
print(productii)
def cykFun(substr, productii, cyk, x):
rez = set()
for z in range(x - 1):
var1 = cyk[substr[:z + 1]]
var2 = cyk[substr[z + 1:]]
for var in [x + y for x in var1 for y in var2]:
for key in productii:
if var in productii[key]:
rez.add(key)
cyk[substr] = rez
return cyk
cyk = defaultdict(set)
string = input("Introduceti cuvantul: ")
for x in range(1, len(string) + 1):
for y in range(len(string) + 1 - x):
substr = (string[y:y + x])
if x == 1:
for key in productii.keys():
if substr in productii[key]:
cyk[substr].add(key)
else:
cyk = cykFun(substr, productii, cyk, x)
print("Apartine" if cyk[string] else "NU Apartine")
|
Python | UTF-8 | 252 | 2.84375 | 3 | [] | no_license | class Room:
def __init__(self, game, shape, doors, x, y):
self.game = game
self.shape = shape
self.width = shape['width']
self.height = shape['height']
self.x = x
self.y = y
self.doors = doors |
Python | UTF-8 | 1,049 | 3.484375 | 3 | [
"MIT"
] | permissive | import re
class Tokenizer:
def __init__(self):
self.token_table = {
"NUMBER": r"([0-9]+\.)?[0-9]+",
"+": r"\+",
"-": r"-",
"*": r"\*",
"/": r"/",
"LBRA": r"\(",
"RBRA": r"\)",
"SEPARATOR": r"( |\n)"
}
def build_tokens(self, raw):
tokens = list()
while len(raw) > 0:
for typ in self.token_table:
if re.match(self.token_table[typ], raw):
token_text = re.match(self.token_table[typ], raw).group()
if typ != "SEPARATOR":
tokens.append([typ, token_text])
raw = raw[len(token_text):]
break
else:
raise ValueError("Unknown Token")
return tokens
tokenizer = Tokenizer()
if __name__ == '__main__':
a = tokenizer.build_tokens("1 + 2 + 3 + 5 + 7")
b = tokenizer.build_tokens("1+2+3+4")
c = tokenizer.build_tokens("(1+2) + (3+4)")
pass |
C++ | UTF-8 | 435 | 2.671875 | 3 | [] | no_license | // point.h
// Point class definition.
// Vladimir Rutsky <altsysrq@gmail.com>
// 09.09.2009
#ifndef POINT_H
#define POINT_H
#include "point_fwd.h"
namespace cg
{
struct point_4f
{
float x, y, z, w;
point_4f()
: x(0.0f), y(0.0f), z(0.0f), w(1.0f)
{}
point_4f( float newX, float newY, float newZ, float newW = 1.0f )
: x(newX), y(newY), z(newZ), w(newW)
{}
};
} // End of namespace 'cg'
#endif // POINT_H
|
Go | UTF-8 | 1,653 | 3.015625 | 3 | [] | no_license | package parser
import (
"crawler/src/engine"
"crawler/src/model"
"fmt"
"reflect"
"regexp"
)
var regexs = map[string]*regexp.Regexp{
"Age": regexp.MustCompile(`<td><span class="label">年龄:</span>(.+)</td>`),
"Sex": regexp.MustCompile(`<td><span class="label">性别:</span><span field="">(.+)</span></td>`),
"Height": regexp.MustCompile(`<td><span class="label">身高:</span>(.+)</td>`),
"Marriage": regexp.MustCompile(`<td><span class="label">婚况:</span>([^<]+)</td>`),
"Edu": regexp.MustCompile(`<td><span class="label">学历:</span>(.+)</td>`),
"Job": regexp.MustCompile(`<td><span class="label">职业:.*</span>([^<]+)</td>`),
"JobAddress": regexp.MustCompile(`<td><span class="label">工作地:</span>([^<]+)</td>`),
"HasChild": regexp.MustCompile(`<td><span class="label">有无孩子:</span>(.+)</td>`),
"Income": regexp.MustCompile(`<td><span class="label">月收入:</span>([^<]+)</td>`),
}
func ParseProfile(content []byte, name string) engine.ParseResult {
profile := model.Profile{Name: name}
v := reflect.ValueOf(&profile).Elem()
for k, r := range regexs {
s := extractString(content, r)
if s != "" {
a := v.FieldByName(k)
if a.IsValid() {
a.Set(reflect.ValueOf(s))
}
} else {
//log.Warn("未能解析的属性:%s", k)
}
}
fmt.Printf("用户信息打印, %v",profile)
rs := engine.ParseResult{
Items: []interface{}{profile},
}
return rs
}
func extractString(c []byte, r *regexp.Regexp) string {
match := r.FindSubmatch(c)
if match != nil && len(match) >= 2 {
return string(match[1])
} else {
return ""
}
}
|
Java | UTF-8 | 936 | 2.390625 | 2 | [] | no_license | package cn.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.bean.Emoji;
import cn.bean.PageBean;
import cn.dao.EmojiDao;
import cn.dbc.BaseDao;
public class EmojiDaoImpl extends BaseDao<Emoji> implements EmojiDao
{
@Override
public Emoji findById(Emoji emoji)
{
String sql="select * from emoji where eno=?";
Emoji ej=getQuery(sql, emoji.getEno()).get(0);
if(ej!=null){
return ej;
}
return null;
}
@Override
public PageBean<Emoji> findAll(int pageIndex,int pageSize)
{
String sql="select * from emoji";
return getQueryPage(sql,pageIndex,pageSize);
}
@Override
public Emoji getEntity(ResultSet rs)
{
Emoji ej=new Emoji();
try
{
ej.setEno(rs.getInt(1));
ej.setAddress(rs.getString(2));
ej.setName(rs.getString(3));
} catch (SQLException e)
{
e.printStackTrace();
}
return ej;
}
}
|
JavaScript | UTF-8 | 4,303 | 2.671875 | 3 | [] | no_license | // NOTE: The contents of this file will only be executed if
// you uncomment its entry in "assets/js/app.js".
// To use Phoenix channels, the first step is to import Socket,
// and connect at the socket path in "lib/web/endpoint.ex".
//
// Pass the token on params as below. Or remove it
// from the params if you are not using authentication.
import {Socket} from "phoenix"
let socket = new Socket("/socket", {params: {token: window.userToken}})
// When you connect, you'll often need to authenticate the client.
// For example, imagine you have an authentication plug, `MyAuth`,
// which authenticates the session and assigns a `:current_user`.
// If the current user exists you can assign the user's token in
// the connection for use in the layout.
//
// In your "lib/web/router.ex":
//
// pipeline :browser do
// ...
// plug MyAuth
// plug :put_user_token
// end
//
// defp put_user_token(conn, _) do
// if current_user = conn.assigns[:current_user] do
// token = Phoenix.Token.sign(conn, "user socket", current_user.id)
// assign(conn, :user_token, token)
// else
// conn
// end
// end
//
// Now you need to pass this token to JavaScript. You can do so
// inside a script tag in "lib/web/templates/layout/app.html.eex":
//
// <script>window.userToken = "<%= assigns[:user_token] %>";</script>
//
// You will need to verify the user token in the "connect/3" function
// in "lib/web/channels/user_socket.ex":
//
// def connect(%{"token" => token}, socket, _connect_info) do
// # max_age: 1209600 is equivalent to two weeks in seconds
// case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
// {:ok, user_id} ->
// {:ok, assign(socket, :user, user_id)}
// {:error, reason} ->
// :error
// end
// end
//
// Finally, connect to the socket:
socket.connect()
// Now that you are connected, you can join channels with a topic:
//document.addEventListener("DOMContentLoaded", function(event) {
window.onload = function() {
console.log("Loading Sockets...")
let channel = socket.channel("board:26", {}); //TODOMFD: THis is a hard coded Database ID, needs changed!
channel.join()
.receive("ok", resp => {
console.log("...Sockets Loaded", resp);
var event = new Event("initBoard");
event.board = resp.board.data;
window.dispatchEvent(event);
})
.receive("error", resp => { console.log("Unable to join", resp) });
channel.on("board_output", payload => {
if(payload.type == "swap"){
console.log(payload);
var event = new Event("swapTiles");
var tile1 = {x: payload.body.tile1.x, y:payload.body.tile1.y}
var tile2 = {x: payload.body.tile2.x, y:payload.body.tile2.y}
event.tile1 = tile1;
event.tile2 = tile2;
window.dispatchEvent(event);
}
})
document.addEventListener( 'keydown', function(event) {
switch( event.keyCode ) {
case 73: //I
var event = new Event("keyDownI");
window.dispatchEvent(event);
//channel.push("board_input", {body: "board_input body"});
break;
case 85: //U
var event = new Event("keyDownU");
window.dispatchEvent(event);
break;
}
}, false);
document.addEventListener( 'doJoinChannel', function(event) {
console.log("doJoinChannel")
console.log(event)
let channel = socket.channel(event.channelID, {});
channel.join()
.receive("ok", resp => {
console.log("doJoinChannel response");
console.log(resp.artist.data);
var event = new Event("drawArtist");
event.artist = resp.artist.data;
window.dispatchEvent(event);
})
.receive("error", resp => { console.log("Unable to join " + event.channelID, resp) });
channel.on("channel_output", payload => {
if(payload.type == "place_tile"){
console.log(payload);
var event = new Event("placeTile");
// var tile1 = {x: payload.body.tile1.x, y:payload.body.tile1.y}
// var tile2 = {x: payload.body.tile2.x, y:payload.body.tile2.y}
// event.tile1 = tile1;
// event.tile2 = tile2;
window.dispatchEvent(event);
}
})
});
};
export default socket
|
TypeScript | UTF-8 | 727 | 3.109375 | 3 | [] | no_license | import { MutiMap } from "../Map/index";
export class EventEmitter{
private eventMap = new MutiMap<string, (...params:Array<any>) => void>();
addListener(eventName: string, listener: (...any:Array<any>)=> any){
this.eventMap.add(eventName, listener);
}
removeListener(eventName: string, listener: (...any:Array<any>)=> any){
this.eventMap.deleteItem(eventName, listener);
}
emit(eventName: string, ...params:Array<any>){
const listeners = this.eventMap.get(eventName);
for(let i = 0; i< listeners.length; i++ ){
try{
listeners[i](...params);
}catch(error){
console.error(error);
}
}
}
} |
C++ | UTF-8 | 4,012 | 3.1875 | 3 | [] | no_license | #ifndef POSITION_H
#define POSITION_H
/*!
* \brief Espace de nom de Guillaume Jouret & Guillaume Walravens.
*/
namespace GJ_GW{
/*!
* \brief Classe représentant la \ref Position d'une case du \ref Board.
*
* Une position est atteignable par son abscisse et son ordonnée.
*/
class Position{
friend class Bric;
unsigned x_;
/*!< L'abscisse de la position. */
unsigned y_;
/*!< L'ordonnée de la position. */
public:
/*!
* \brief Constructeur sans argument de \ref Position.
*
* Il initialise la position à la localisation par défaut.
*/
Position();
/*!
* \brief Constructeur de \ref Position.
*
* Une position nouvellement créée est toujours vide.
*
* \param x l'abscisse de la position
* \param y l'ordonnée de la position
*/
Position(unsigned x, unsigned y);
/*!
* \brief Accesseur en lecture de l'abscisse.
*
* \return l'abscisse de la \ref Position
*/
inline unsigned getX() const;
/*!
* \brief Accesseur en lecture de l'ordonnée.
*
* \return l'ordonnée de la \ref Position
*/
inline unsigned getY() const;
/*!
* \brief Méthode permettant de savoir si une \ref Position
* est adjacente à une autre selon son abscisse et son ordonnée.
*
* \param x l'abscisse de la position
* \param y l'ordonnée de la position
* \return vrai si les positions sont adjacentes, faux sinon
*/
bool isAdjacent(const unsigned & x, const unsigned & y) const;
private:
/*!
* \brief Accesseur en écriture de l'abscisse.
* \param x la nouvelle abscisse de la \ref Position
*/
void setX(int x);
/*!
* \brief Accesseur en écriture de l'ordonnée.
* \param y la nouvelle ordonnée de la \ref Position
*/
void setY(int y);
/*!
* \brief Méthode permettant de savoir si une \ref Position
* est adjacente à une autre position.
*
* \param other l'autre position
* \return vrai si les positions sont adjacentes, faux sinon
*/
bool isAdjacent(const Position & other) const;
};
//prototypes
/*!
* \brief Opérateur de test d'égalité de deux \ref Position.
* \param lhs le membre de gauche
* \param rhs le membre de droite
* \return true si les deux membres de la comparaison sont égaux, false sinon
*/
inline bool operator==(const Position & lhs, const Position & rhs);
/*!
* \brief Opérateur de test d'inégalité de deux \ref Position.
* \param lhs le membre de gauche
* \param rhs le membre de droite
* \return true si les deux membres de la comparaison sont différents, false sinon
*/
inline bool operator!=(const Position & lhs, const Position & rhs);
/*!
* \brief Opérateur de comparaison de deux \ref Position.
*
* \param lhs le membre de gauche
* \param rhs le membre de droite
* \return true si le membre de gauche est strictement inférieur au membre de droite, false sinon
*/
inline bool operator<(const Position & lhs, const Position & rhs);
/*!
* \brief Opérateur de comparaison de deux \ref Position.
*
* \param lhs le membre de gauche
* \param rhs le membre de droite
* \return true si le membre de gauche est strictement supérieur au membre de droite, false sinon
*/
inline bool operator>(const Position & lhs, const Position & rhs);
//implémentations inline
//fonctions inline
bool operator==(const Position & lhs, const Position & rhs){
return (lhs.getX() == rhs.getX()) && (lhs.getY() == rhs.getY());
}
bool operator!=(const Position & lhs, const Position & rhs){
return ! (lhs == rhs);
}
bool operator<(const Position & lhs, const Position & rhs){
return lhs.getY() < rhs.getY() || (lhs.getY() == rhs.getY() && lhs.getX() < rhs.getX());
}
bool operator>(const Position & lhs, const Position & rhs){
return rhs < lhs;
}
//méthodes inline
unsigned Position::getX() const{
return x_;
}
unsigned Position::getY() const{
return y_;
}
} // namespace GJ_GW
#endif // POSITION_H
|
Java | UTF-8 | 677 | 3.734375 | 4 | [] | no_license | package CH16_Thread;
public class Test01 {
public static void main(String[] args) {
Food worker1 = new Food();
Phone worker2 = new Phone();
worker1.start();
worker2.start();
for(int i=1; i<=1000; i++){
System.out.println("WATCHING TV : "+ i);
}
}
}
class Food extends Thread{
public void run(){
for(int i=1; i <= 1000; i++){
System.out.println("EATING FOOD : " + i);
}
}
}
class Phone extends Thread{
public void run(){
for(int i=1; i <= 1000; i++){
System.out.println("INCOMING CALL : " + i);
}
}
} |
Java | UTF-8 | 1,044 | 2.234375 | 2 | [] | no_license | package com.zy.alg.demo;
import com.zy.alg.service.NaiveBayes;
import com.zy.alg.service.NaiveBayesImpl;
import com.zy.alg.util.CategoryCorpusInfo;
import com.zy.alg.util.FileReader;
import java.util.List;
/**
* @author zhangycqupt@163.com
* @date 2018/08/26 21:24
*/
public class NaiveBayesTrainDemo {
public static void main(String[] args) {
// 输入训练语料路径
String trainCorpusPath = "G:\\project\\Bayes\\input\\";
// 输出模型文件路径
String outPutModelPath = "G:\\project\\Bayes\\output\\";
// 训练语料
String trainFile = trainCorpusPath + "TrainCorpus.csv";
// 读取模型训练语料
List<CategoryCorpusInfo> trainData = FileReader.getTrainData(trainFile);
// 类目标签库
String categoryTagFile = trainCorpusPath + "CategoryTagLibrary";
// 模型训练
NaiveBayes naiveBayes = new NaiveBayesImpl(categoryTagFile);
naiveBayes.modelTrainer(trainData, outPutModelPath);
}
}
|
Python | UTF-8 | 1,522 | 2.96875 | 3 | [
"MIT"
] | permissive | # -*- coding:utf-8 -*-
import numpy as np
import tensorflow.keras as keras
import matplotlib.pyplot as plt
from matplotlib import style
# This is used for converting 1D label to nD one-hot label
def check_label(label, num_classes):
if len(label.shape) == 1 and num_classes >=2:
return keras.utils.to_categorical(label, num_classes=len(np.unique(label)))
return label
# This function is used for checking model construction parameters, different dimensions.
def check_dims(dims, is_2d, is_3d):
if is_2d and dims is None:
return '2D'
elif is_3d or dims is not None:
return '3D'
# This is used for ploting accuracy and loss curve
def plot_acc_loss(his, plot_acc=True, plot_loss=True, figsize=(8, 6)):
style.use('ggplot')
if plot_acc:
fig_1, ax_1 = plt.subplots(1, 1, figsize=figsize)
ax_1.plot(his.history['acc'], label='Train Accuracy')
ax_1.plot(his.history['val_acc'], label='Validation Accuracy')
ax_1.set_title('Train & Validation Accuracy curve')
ax_1.set_xlabel('Epochs')
ax_1.set_ylabel('Accuracy score')
plt.legend()
if plot_loss:
fig_2, ax_2 = plt.subplots(1, 1, figsize=figsize)
ax_2.plot(his.history['loss'], label='Train Loss')
ax_2.plot(his.history['val_loss'], label='Validation Loss')
ax_2.set_title('Train & Validation Loss curve')
ax_2.set_xlabel('Epochs')
ax_2.set_ylabel('Loss score')
plt.legend() |
Swift | UTF-8 | 3,287 | 2.5625 | 3 | [] | no_license | //
// gameViewController.swift
// garbage
//
// Created by Maoko Furuya on 2018/01/26.
// Copyright © 2018年 Maoko Furuya. All rights reserved.
//
import UIKit
class gameViewController: UIViewController {
var timer : Timer = Timer()
var point : Int = 0
@IBOutlet var pointLabel : UILabel!
@IBOutlet var timeLabel : UILabel!
var timeCount : Float = 6.0
var snowTimer: Timer = Timer()
@IBAction func start() {
timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in
self.timeCount = self.timeCount - 0.05
self.timeLabel.text = String(format: "%.2f",self.timeCount)
if self.timeCount < 0 {
self.performSegue(withIdentifier: "toResult", sender: nil)
self.timer.invalidate()
}
}
snowTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
self.createSnow()
}
}
func pluspoint() {
point = point + 1
pointLabel.text = String(point)
}
func createSnow() {
let snowImageView: UIImageView = UIImageView(frame: CGRect(x: CGFloat(arc4random_uniform(UInt32(UIScreen.main.bounds.width))), y: 0, width: 50, height: 50))
snowImageView.image = UIImage(named: "snow.png")
self.view.addSubview(snowImageView)
Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { fallTimer in
snowImageView.frame.origin.y += 2
if self.yukidarumaImageView.frame.contains(snowImageView.frame) {
print("当たった")
snowImageView.removeFromSuperview()
fallTimer.invalidate()
self.pluspoint()
}
if snowImageView.frame.origin.y > UIScreen.main.bounds.height {
snowImageView.removeFromSuperview()
fallTimer.invalidate()
}
}
}
@IBOutlet var yukidarumaImageView: UIImageView!
@IBAction func moveLeft() {
yukidarumaImageView.frame.origin.x -= 20
}
@IBAction func moveRight() {
yukidarumaImageView.frame.origin.x += 20
}
@IBAction func moveLeft2() {
yukidarumaImageView.frame.origin.x -= 50
}
@IBAction func moveRight2() {
yukidarumaImageView.frame.origin.x += 50
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultViewController = segue.destination as! ResultViewController
resultViewController.snowPoint = self.point
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
C | GB18030 | 429 | 3.796875 | 4 | [] | no_license | ////дһӡarrݣʹ±꣬ʹָ롣(һά)
//#include <stdio.h>
//#include <stdlib.h>
//
//void myPrint(int* arr, int size) {
// for (int i = 0; i < size; i++) {
// printf("%d\n", *(arr + i));
// }
//}
//
//int main() {
// int arr[] = {2000, 2001, 2002, 2003};
// int len = sizeof(arr) / sizeof(arr[0]);
// myPrint(arr, len);
//
// system("pause");
// return 0;
//} |
Java | UTF-8 | 331 | 2.703125 | 3 | [] | no_license | import org.junit.*;
import static org.junit.Assert.*;
public class TheEasyChaseTest {
@Test
public void test() {
TheEasyChase chase = new TheEasyChase();
assertEquals("BLACK 2", chase.winner(2, 1, 1, 2, 2));
assertEquals("WHITE 1", chase.winner(2, 2, 2, 1, 2));
assertEquals("BLACK 6", chase.winner(3, 1, 1, 3, 3));
}
} |
Java | UTF-8 | 1,095 | 3.65625 | 4 | [] | no_license | package com.zh.pattern.design.behaviourMode.memento;
/*
* 备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象外保存这个状态,这样以后可将此对象恢复成原来的状态。
*
* 原发器类(Originator):创建一个备忘录对象,使用备忘录存储它的内部状态。
负责人类(CareTaker):负责保存好备忘录对象,不能检查或操作备忘录的内容。
备忘录类(Memento):将原发器的内部状态存储起来,原发器根据需要决定备忘录存储原发器的哪些内部状态。
* */
public class Client22 {
public static void main(String[] args) {
//初始化状态
Dante dante = new Dante();
dante.getInitState();
dante.showState();
MemoryCardCreataker cardCreataker = new MemoryCardCreataker();
cardCreataker.setMemoryCard(dante.saveState());
dante.deathState();
dante.showState();
dante.recoveryState(cardCreataker.getMemoryCard());
dante.showState();
}
}
|
C++ | UTF-8 | 869 | 2.53125 | 3 | [] | no_license | #ifndef LOGINDATAPROVIDER_H
#define LOGINDATAPROVIDER_H
#include <QByteArray>
#include <QString>
namespace ForumHandler
{
class ILoginDataProvider
{
public:
virtual ~ILoginDataProvider()
{};
virtual QByteArray getData() = 0;
virtual void setParams(QString, QString, QString) = 0;
};
class LoginDataProvider : public ILoginDataProvider
{
public:
LoginDataProvider();
LoginDataProvider(QString p_username, QString p_password, QString p_login = "Zaloguj");
virtual ~LoginDataProvider();
virtual QByteArray getData();
virtual void setParams(QString p_username, QString p_password, QString p_login = "Zaloguj");
private:
QString m_username;
QString m_password;
QString m_login;
};
class LoginDataProviderFactory
{
public:
LoginDataProvider* create();
};
} // namespace ForumHandler
#endif // LOGINDATAPROVIDER_H
|
Java | UTF-8 | 2,154 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package com.jun.converter.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.core.convert.support.GenericConversionService;
import javax.annotation.PostConstruct;
import java.util.Set;
public class MyConversionService implements ConversionService {
@Autowired
private GenericConversionService conversionService;
private Set<?> converters;
@PostConstruct
public void afterPropertiesSet() {
if (converters != null) {
for (Object converter : converters) {
if (converter instanceof Converter<?, ?>) {
conversionService.addConverter((Converter<?, ?>) converter);
} else if (converter instanceof ConverterFactory<?, ?>) {
conversionService.addConverterFactory((ConverterFactory<?, ?>) converter);
} else if (converter instanceof GenericConverter) {
conversionService.addConverter((GenericConverter) converter);
}
}
}
}
public boolean canConvert(Class<?> sourceType, Class<?> targetType) {
return conversionService.canConvert(sourceType, targetType);
}
public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
return conversionService.canConvert(sourceType, targetType);
}
public <T> T convert(Object source, Class<T> targetType) {
return conversionService.convert(source, targetType);
}
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
return conversionService.convert(source, sourceType, targetType);
}
public Set<?> getConverters() {
return converters;
}
public void setConverters(Set<?> converters) {
this.converters = converters;
}
}
|
SQL | UTF-8 | 1,249 | 3.546875 | 4 | [] | no_license | DROP TABLE IF EXISTS employees;
DROP TABLE IF EXISTS departments;
DROP TABLE IF EXISTS titles;
DROP TABLE IF EXISTS salaries;
DROP TABLE IF EXISTS dept_manager;
DROP TABLE IF EXISTS dept_emp;
CREATE TABLE "employees" (
"emp_no" VARCHAR PRIMARY KEY,
"birth_date" DATE,
"first_name" VARCHAR,
"last_name" VARCHAR,
"gender" VARCHAR,
"hire_date" DATE);
CREATE TABLE "departments" (
"dept_no" VARCHAR PRIMARY KEY,
"dept_name" VARCHAR
);
CREATE TABLE "titles" (
"emp_no" VARCHAR,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no),
"title" VARCHAR,
"from_date" DATE,
"to_date" DATE
);
CREATE TABLE "salaries" (
"emp_no" VARCHAR,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no),
"salary" INTEGER,
"from_date" DATE,
"to_date" DATE
);
CREATE TABLE "dept_manager" (
"dept_no" VARCHAR,
FOREIGN KEY (dept_no) REFERENCES departments(dept_no),
"emp_no" VARCHAR,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no),
"from_date" DATE,
"to_date" DATE
);
CREATE TABLE "dept_emp" (
"emp_no" VARCHAR,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no),
"dept_no" VARCHAR,
FOREIGN KEY (dept_no) REFERENCES departments(dept_no),
"from_date" DATE,
"to_date" DATE
);
|
C# | UTF-8 | 507 | 2.9375 | 3 | [
"MIT"
] | permissive | namespace Patching_Auxilary
{
using HarmonyLib;
using System.Collections.Generic;
using System.Reflection;
class Foo { }
class Bar { }
class Example
{
// <yield>
static IEnumerable<MethodBase> TargetMethods()
{
// if possible use nameof() or SymbolExtensions.GetMethodInfo() here
yield return AccessTools.Method(typeof(Foo), "Method1");
yield return AccessTools.Method(typeof(Bar), "Method2");
// you could also iterate using reflections over many methods
}
// </yield>
}
}
|
C++ | UTF-8 | 2,490 | 2.671875 | 3 | [
"MIT"
] | permissive | //
// main.cpp
// cart-pole
//
// Created by Dmitry Alexeev on 04/06/15.
// Copyright (c) 2015 Dmitry Alexeev. All rights reserved.
//
#include "smarties.h"
#include "../cart_pole_cpp/cart-pole.h"
#include <iostream>
#include <cstdio>
inline int app_main(
smarties::Communicator*const comm, // communicator with smarties
MPI_Comm mpicom, // mpi_comm that mpi-based apps can use
int argc, char**argv // arguments read from app's runtime settings file
)
{
int myRank, simSize;
MPI_Comm_rank(mpicom, & myRank);
MPI_Comm_size(mpicom, & simSize);
const int otherRank = myRank == 0? 1 : 0;
assert(simSize == 2 && myRank < 2); // app designed to be run by 2 ranks
comm->setStateActionDims(6, 1);
//OPTIONAL: action bounds
bool bounded = true;
std::vector<double> upper_action_bound{10}, lower_action_bound{-10};
comm->setActionScales(upper_action_bound, lower_action_bound, bounded);
//OPTIONAL: hide angle, but not cosangle and sinangle.
std::vector<bool> b_observable = {true, true, true, false, true, true};
comm->setStateObservable(b_observable);
CartPole env;
MPI_Barrier(mpicom);
while(true) //train loop
{
//reset environment:
env.reset(comm->getPRNG());
comm->sendInitState(env.getState()); //send initial state
while (true) //simulation loop
{
//advance the simulation:
const std::vector<double> action = comm->recvAction();
int terminated[2] = {0, 0};
terminated[myRank] = env.advance(action);
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT,
terminated, 1, MPI_INT, mpicom);
const bool myEnvTerminated = terminated[myRank];
const bool otherTerminated = terminated[otherRank];
const std::vector<double> state = env.getState();
const double reward = env.getReward();
// Environment simulation is distributed across two processes.
// Still, if one processes says the simulation has terminated
// it should terminate in all processes! (and then can start anew)
if(myEnvTerminated || otherTerminated) {
if(myEnvTerminated) comm->sendTermState(state, reward);
else comm->sendLastState(state, reward);
break;
}
else comm->sendState(state, reward);
}
}
}
int main(int argc, char**argv)
{
smarties::Engine e(argc, argv);
if( e.parse() ) return 1;
// this app is designed to require 2 processes per each env simulation:
e.setNworkersPerEnvironment(2);
e.run( app_main );
return 0;
} |
Java | UTF-8 | 2,824 | 1.960938 | 2 | [] | no_license | package com.bg.plzSeatdown.admin.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.bg.plzSeatdown.admin.model.service.AdminReplyReportService;
import com.bg.plzSeatdown.admin.model.vo.AdminReplyReport;
import com.bg.plzSeatdown.common.Pagination;
import com.bg.plzSeatdown.common.vo.PageInfo;
@SessionAttributes({"loginMember","msg"})
@Controller
@RequestMapping("/admin/reply_report/*")
public class AdminReplyReportController {
@Autowired
private AdminReplyReportService adminReplyReportService;
@RequestMapping("list")
public String replyRerpotList(Model model,
@RequestParam(value="currentPage", required=false) Integer currentPage,
@RequestParam(value="searchKey", required=false) String searchKey,
@RequestParam(value="searchValue", required=false) String searchValue
){
try {
Map<String, String> map = null;
if(searchKey != null && searchValue != null) {
map = new HashMap<String, String>();
map.put("searchKey", searchKey);
map.put("searchValue", searchValue);
System.out.println(map);
}
// 전체 게시글 수 조회
int listCount = adminReplyReportService.getListCount(map);
// 현재 페이지 확인
if(currentPage == null) currentPage = 1;
// 페이지 정보 저장
PageInfo pInf = Pagination.getPageInfo(10, 5, currentPage, listCount);
// 게시글 목록 조회
List<AdminReplyReport> list = adminReplyReportService.selectList(map, pInf);
model.addAttribute("list", list);
model.addAttribute("pInf", pInf);
return "admin/reply_report";
}catch(Exception e) {
e.printStackTrace();
model.addAttribute("errorMsg", "커뮤니티 관리 게시판 조회 과정에서 오류 발생");
return "common/errorPage";
}
}
@RequestMapping("updateRpCnt")
public String updateRpCnt(Model model, int no, int reportNo) {
try {
int result = adminReplyReportService.updateRpCnt(no, reportNo);
if(result > 0) {
model.addAttribute("no", no);
return "redirect:list";
}else {
model.addAttribute("msg", "신고처리 업데이트를 실패했습니다.");
return "redirect:list";
}
}catch(Exception e) {
e.printStackTrace();
model.addAttribute("errorMsg", "댓글 신고글 처리 과정에서 오류 발생");
return "common/errorPage";
}
}
}
|
Java | UTF-8 | 2,323 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /*
*
* Copyright (c) 2017 Rabitka Framework
*
* 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 io.rabitka.sample.todolist.application;
import io.rabitka.core.ddd.ApplicationService;
import io.rabitka.sample.todolist.domain.TodoItem;
import io.rabitka.sample.todolist.domain.TodoItemRepository;
import java.time.LocalDate;
import java.util.List;
import static io.rabitka.sample.todolist.domain.TodoItemPredicates.*;
/**
* @author Wassim ABID wassim.abid@rabitka.io
*/
@ApplicationService
public class GetTodoItem {
private TodoItemRepository todoItemRepository;
public GetTodoItem(
io.rabitka.sample.todolist.domain.TodoItemRepository todoItemRepository) {
this.todoItemRepository = todoItemRepository;
}
public List<TodoItem> all(){
return this.todoItemRepository.getAllInList();
}
public List<TodoItem> completed(){
return this.todoItemRepository.findBy(
completedIsEqualsTo(Boolean.TRUE))
.getInList();
}
public List<TodoItem> notCompleted(){
return
this.todoItemRepository
.findBy(
completedIsEqualsTo(Boolean.FALSE)
).getInList();
}
public List<TodoItem> byTitle(String title){
return
this.todoItemRepository.findBy(
titleIsEqualsTo(title)
).getInList();
}
public List<TodoItem> byPriority(Integer priority){
return
this.todoItemRepository.findBy(
priorityIsEqualsTo(priority)
).getInList();
}
public List<TodoItem> createdToday(){
return
this.todoItemRepository
.findBy(
creationDateIsEqualsTo(LocalDate.now())
).getInList();
}
}
|
Python | UTF-8 | 3,770 | 2.671875 | 3 | [] | no_license | import tkinter as tk
from tkinter import messagebox
import sqlite3
from tkinter.ttk import *
import cv2 as cv
import numpy as np
import os
import mask_check # the other code that will check the mask
# connect to the database of employees
conn = sqlite3.connect(r'C:\Users\komsi\Desktop\Projects\Employee_Database1.db')
cursor = conn.cursor()
root = tk.Tk()
root.title('Login')
# the next lines are used to center the interface
window_width = root.winfo_reqwidth()
window_height = root.winfo_reqheight()
pos_r = int(root.winfo_screenwidth() / 2 - window_width / 2)
pos_l = int(root.winfo_screenheight() / 2 - window_height / 2)
root.geometry("+{}+{}".format(pos_r, pos_l))
# the next lines for the label and entry of id and password
id_label = tk.Label(root, text=' ID : ').grid(row=0, column=0)
id_entry = tk.Entry(root, width=30)
id_entry.grid(row=0, column=1)
password_label = tk.Label(root, text=' Password : ').grid(row=1, column=0)
password_entry = tk.Entry(root, show="*", width=30)
password_entry.grid(row=1, column=1)
def user_click():
'''
when the user click Login
'''
user_id = id_entry.get()
user_password = password_entry.get()
try: # Check the data base for the user information
cursor.execute("select * from empl where id ='{}' and password = '{}'".format(user_id, user_password))
emp_info = cursor.fetchone()
messagebox.showinfo('Welcome',
"Welcome {} {} ! \n\nPlease WEAR your mask and be save\nThe Camera will load in a few seconds . . .".format(
emp_info[1].capitalize(), emp_info[2].capitalize()))
# call the "call_cam" function from the other code which handle the detection of wearing mask
mask_check.call_cam()
except TypeError:
messagebox.showerror('ERROR!', 'Wrong Informations !')
def admin_click():
'''
when the admin Admin login to edit the data base
'''
def submit_click():
'''
when the admin press submit
'''
try: # try to execute the commands of the admin
exec(sql_commands.get("1.0", 'end'))
messagebox.showinfo('Done', 'Your changes have been submitted')
except: # show an error that the code wasn't correct
messagebox.showerror('ERROR!', 'Could not execute, please make sure you wrote the code correctly. ')
admin_id = id_entry.get()
admin_password = password_entry.get()
try: # check the admin informations
cursor.execute("select password from empl where id = '{}'".format(admin_id))
database_password = cursor.fetchone()[0]
if admin_id == 'admin' and admin_password == database_password:
admin_window = tk.Toplevel(root)
admin_window.title('Admin Window')
admin_window.geometry("450x450")
sql_commands = tk.Text(admin_window)
sql_commands.insert('end', "cursor.execute(''' \n#Your code here\n''') \nconn.commit()")
sql_commands.place(height=350, width=350, relx=0.5, rely=0.5, anchor='center')
submit_button = tk.Button(admin_window, text=' Submit ', command=submit_click)
submit_button.place(anchor='center', y=200, relx=0.5, rely=0.5, )
else:
messagebox.showerror('ERROR!', 'Wrong Informations !')
except TypeError:
messagebox.showerror('ERROR!', 'Wrong Informations !')
user_login_button = tk.Button(root, text=' Login ', command=user_click)
user_login_button.grid(row=3, column=0)
admin_button = tk.Button(root, text=' Login as Admin ', command=admin_click)
admin_button.grid(row=3, column=1)
root.mainloop()
|
Markdown | UTF-8 | 1,217 | 2.828125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: Hitting with a man on second
---
## What to do?
I grew up in a baseball family. Baseball was (and is) a huge deal in my family.
My brother is a private instructor and baseball coach even. He's also the one that
got me a ticket to game 5 of the 2017 World Series. It was epic. I told my
brother about having a wealth of data, but not exactly sure what questions
to ask it. So he gave me a few interesting ideas. Here is the first:
# Which is the best pitch and count to hit when there is a runner on 2nd base?
## The Setup
I have a mysql database filled with a ton of information on my laptop. I started
with a query to pull all pitches that resulted with a hit where the ball was hit
into play and there wasn't an out. We don't care if you just make contact, but
they need to put it into play and make it to base safely. From 2010 to the end
of 2018 I found over 180,000 hits with men on second base. Let's take a look at
what we got.
{% include man_on_second.html %}
## Conclusion
So it would appear that you need to swing early at fastballs. This seems
pretty consistant over the past 9 seasons as well. Get the bat off
your shoulder before the pitch has time to mess with you! Haha.
|
Python | UTF-8 | 226 | 3.484375 | 3 | [] | no_license | A=int(input())
B=int(input())
C=int(input())
X=int(input())
count = 0
for i in range(A+1):
for j in range(B+1):
for k in range(C+1):
sum = 500*i + 100*j + 50*k
if X==sum:
count+=1
print(str(count)) |
Python | UTF-8 | 777 | 2.875 | 3 | [
"MIT"
] | permissive | from uuid import uuid1
from random import randint
class User:
__slots__ = ("username", "avatar", "color", "uuid", "group_id", "websocket")
def __init__(self, username, avatar, color, group_id=None):
self.username = username + f"#{randint(1000, 9999)}"
self.avatar = avatar
self.color = color
self.uuid = str(uuid1())
self.group_id = group_id
self.websocket = None
def __hash__(self) -> int:
return hash(self.uuid)
def __eq__(self, other) -> bool:
return self.uuid == other.uuid
def __str__(self) -> str:
return self.username
def set_websocket(self, websocket):
self.websocket = websocket
def set_group_id(self, group_id: str):
self.group_id = group_id
|
Python | UTF-8 | 14,489 | 2.828125 | 3 | [] | no_license | __author__ = 'dlonardoni'
#
# Utilities and statistic procedure
#
import time
import networkx as nx
import pylab as plt
import numpy as np
import numpy.random as rnd
import scipy.stats
from scipy.spatial.distance import pdist, squareform
'''
******** Utility procedures ********
'''
def Save_Traces(CellList, groupname, sname):
trace = []
plt.figure()
flags = 0
for cell in CellList:
try:
diction = {'ID_syn': cell.ID_syn, 'ID': cell.num, 'x': cell.pos['x'],
'y': cell.pos['y'], 't': np.array(cell.record['time']),
'v': np.asarray(cell.record['voltage']),
'gAMPA': np.asarray(cell.record['gAMPA']),
'gGABA': np.asarray(cell.record['gGABA']),
'iAMPA': np.asarray(cell.record['iAMPA']),
'iGABA': np.asarray(cell.record['iGABA']),
}
if cell.nmda:
diction['gNMDA'] = np.asarray(cell.record['gNMDA'])
diction['iNMDA'] = np.asarray(cell.record['iNMDA'])
trace.append(diction)
flags += 1
except:
pass
np.save(open('Results' + groupname + '/' + sname + '_tt.npy', 'w'), trace)
'''
******** Graph procedures ********
'''
def CreateRandomGraph(N, p=0.1):
"""
Procedure to create a random graph G(N,p):
- a pair of node in the graph is connected with probability p independently
- the edge orientation is chosen randomly
Some statistics of the graph are printed:
Average Shortest Path
Clustering Coefficient
If the constructed graph is disconnected return an error
See "erdos_renyi()" function of Networkx package
Input:
N: Number of nodes
p: Probability [0,1] of connection
Output:
G: Generated graph
"""
G = nx.erdos_renyi_graph(N, p, directed=True)
for _ in G:
pass
H = G.to_undirected()
try:
n = nx.average_shortest_path_length(G)
print("Average Shortest Path : ", n)
except nx.NetworkXError:
print('Average Shortest Path : Disconnected')
print("Clustering Coefficient ", nx.average_clustering(H))
return G
def random_geometric_gauss(N, dim=2, sigma=1, grad=0, torus=0):
"""
Return a random geometric graph with gaussian distribution of connection as a function of distance.
The nodes are selected randomly in a hypercube in the dimension provided.
The random geometric graph model
- places n nodes uniformly at random in the unit cube of dimension dim
- connect two nodes `u,v` with an edge in such a way that `d(u,v)`
generates a unilateral gaussian distribution N(0,sigma)
where `d(u,v)` is the Euclidean distance between node u and v.
Input:
N: Number of nodes
sigma: Variance of the Gaussian
dim : optional, Dimension of graph
Output:
G Constructed graph
Position is added to each node
"""
G = nx.Graph()
G.name = "Random Geometric Graph"
G.add_nodes_from(list(range(N)))
# sample node position uniformly
for n in G:
G.node[n]['pos'] = rnd.random(dim)
if dim == 3:
for n in range(len(G.nodes())):
G.node[n]['pos'][2] = (1 - G.node[n]['pos'][2] ** grad) * .25
nodes = G.nodes(data=True)
# create the connections
dmax = 0
i = 0
s = .5
prob = rnd.random(N * N / 2).tolist()
while nodes:
u, du = nodes.pop()
print(u)
pu = du['pos']
for v, dv in nodes:
i += 1
pv = dv['pos']
d = sum(((a - b) ** 2 for a, b in zip(pu, pv)))
if dim == 3:
dxy = sum(((a - b) ** 2 for a, b in zip(pu[:-1], pv[:-1])))
dz = (pu[-1] - pv[-1]) ** 2
d = (s * dxy + (1 - s) * dz) * 1. / s
if torus:
d = sum(((min(abs(a - b), 1 - abs(a - b))) ** 2 for a, b in zip(pu, pv)))
if d < .5 ** 2:
p = scipy.stats.chi2(1).cdf(d / sigma)
if p <= prob.pop():
G.add_edge(u, v)
dmax = max(d, dmax)
return G
def DirectGraph(G):
"""
Unefficien procedure to convert an undirected graph into a directed one
The direction of an edges is chosen randomly
Input:
G: networkx undirected graph
Output:
H: directed realization of G
"""
import time
start = time.time()
pivot = rnd.random(len(G.edges()))
H = G.to_directed()
import copy
GG = copy.deepcopy(G)
edges = np.array(G.edges())
H.remove_edges_from(edges[pivot > .5])
GG.remove_edges_from(edges[pivot > .5])
G2 = GG.to_directed()
a1 = set(G2.edges())
a2 = a1.difference(set(GG.edges()))
H.remove_edges_from(a2)
print("elapsed:", time.time() - start)
return H
def CreateGauss(N, dim=2, sigma=1, torus=0):
"""
Return a random geometric graph with gaussian distribution of connection as a function of distance.
The nodes are selected randomly in a hypercube in the dimension provided.
The random geometric graph model
- places n nodes uniformly at random in the unit cube of dimension dim
- connect two nodes `u,v` with an edge in such a way that `d(u,v)`
generates a unilateral gaussian distribution N(0,sigma)
where `d(u,v)` is the Euclidean distance between node u and v.
Some statistics of the graph are printed:
Average Shortest Path
Clustering Coefficient
If the constructed graph is disconnected return an error
Input:
N: Number of nodes
sigma: Variance of the Gaussian
dim : optional, Dimension of graph
Output:
G Constructed graph
Position is added to each node
"""
G, edge_list = random_geometric_gauss2(N=N, dim=dim, sigma=sigma, torus=torus)
print("done")
# nx.draw(G,pos=nx.get_node_attributes(G,'pos'))
# edge_list=G.edges()
import time
start = time.time()
def shuffle(xVec):
if np.random.random() > .5:
xVec = xVec[::-1]
return xVec
edge_list.extend([(ele[1], ele[0]) for ele in edge_list])
edge_list = [shuffle(edge) for edge in edge_list if edge[0] > edge[1]]
H = G.to_directed()
print(time.time() - start)
H.remove_edges_from(H.edges())
print(time.time() - start)
H.add_edges_from(edge_list)
print(time.time() - start)
# H=DirectGraph(G)
# try:
# n=nx.average_shortest_path_length(H)
# print "Average Shortest Path : ",n
# except nx.NetworkXError:
# print 'Average Shortest Path : Disconnected'
# print "Clustering Coefficient ",nx.average_clustering(G)
# plt.figure()
# nx.draw(H,pos=nx.get_node_attributes(H,'pos'))
return H
def CreateRadiusGraph(N, r=0.1):
"""
Return a radius graph embedeed in a square of side one in the plane.
The radius graph model
- places n nodes uniformly at random in the unit cube of dimension two
- connect two nodes `u,v` with an edge if `d(u,v)` < r
where `d(u,v)` is the Euclidean distance between node u and v.
See "random_geometric_graph()" function of Networkx package
Some statistics of the graph are printed:
Average Shortest Path
Clustering Coefficient
If the constructed graph is disconnected return an error
Input:
N: Number of nodes
r: Radius of interaction
Output:
G Directed realization of the constructed graph
Position is added to each node
"""
G = nx.random_geometric_graph(N, r, 2)
H = G.to_directed()
listed = H.edges()
k = 0
for i in range(len(listed) / 2):
while listed:
if (listed[k][1], listed[k][0]) in H.edges():
if rnd.random() < 0.5:
H.remove_edge(*listed[k])
break
else:
H.remove_edge(listed[k][1], listed[k][0])
break
k += 1
listed = H.edges()
try:
n = nx.average_shortest_path_length(H)
print("Average Shortest Path : ", n)
except nx.NetworkXError:
print('Average Shortest Path : Disconnected')
print("Clustering Coefficient ", nx.average_clustering(G))
return H
'''
******** Plot procedures ********
'''
def PlotRaster(LS, ts, reo=1):
"""
Procedure to draw a raster plot of the activity
A line divides the excitatory neurons (top)
from the inhibitory ones (bottom)
Input:
LS: List of neuron cells
ts: Plot up to time "ts"
reo: Reorder neurons
Output:
Raster plot
"""
spike = []
tmpe = []
tmpi = []
N = len(LS)
# retrive the spike of each cell splitting into excitatory and inhibitory
for i in range(N):
if LS[i].ID_syn.rfind('EXC'):
tmpe.append(np.array(LS[i].record['spk']))
else:
tmpi.append(np.array(LS[i].record['spk']))
if reo == 1:
# reordering of the vector
for i in range(N):
if i < len(tmpe):
spike.append(tmpe[i])
if i == len(tmpe):
print(ts)
spike.append([0, ts])
if i > len(tmpe):
spike.append(tmpi[i - len(tmpe)])
else:
CellPos = {}
NCells = len(LS)
for i in range(NCells):
# check if it is possible to color differently exc/inh neurons ?!
CellPos[i] = np.array(list(LS[i].pos.values()))
index = sorted(list(range(NCells)), key=lambda k: CellPos[k][1])
for i in range(NCells):
spike.append(np.array(LS[index[i]].record['spk']))
# generating the plot
for i, spk in spike:
plt.plot(spk, np.ones_like(spike) * i, 'ok')
plt.xlabel('Time (ms)')
plt.ylabel('Neuron ID')
def PlotVoltage(cell):
"""
Plot voltage of a single cell "cell" vs time (works when recordAll=TRUE)
"""
# check before if "recordAll" was TRUE
t = np.asarray(cell.record['time']) * .001
v = np.asarray(cell.record['voltage']) * .001
plt.plot(t, v)
plt.xlabel('Time (s)')
plt.ylabel('Voltage (mV)')
# if ShowPlot: plt.show()
# if HoldPlot: plt.hold(1)
def PlotG(cell):
"""
Plot synaptic conductance of a single cell "cell" vs time
"""
t = np.asarray(cell.record['time']) * .001
gAMPA = np.asarray(cell.record['gAMPA'])
plt.plot(t, -gAMPA, 'orange', label='gAMPA')
gGABA = np.asarray(cell.record['gGABA'])
plt.plot(t, -gGABA, 'b', label='gGABA')
gNMDA = np.asarray(cell.record['gNMDA'])
plt.plot(t, -gNMDA, 'r', label='gNMDA')
plt.ylabel('conductances (nS)')
plt.xlabel('time (s)')
plt.legend()
def PlotCurrent(cell):
"""
Plot synaptic current of a single cell "cell" vs time
"""
t = np.asarray(cell.record['time']) * .001
iAMPA = np.asarray(cell.record['iAMPA']) * .001
iGABA = np.asarray(cell.record['iGABA']) * .001
iNMDA = np.asarray(cell.record['iNMDA']) * .001
plt.plot(t, iAMPA, 'orange', lw=2, label='iAMPA')
plt.plot(t, iGABA, 'b', lw=2, label='iGABA')
plt.plot(t, iNMDA, 'r', lw=2, label='iNMDA')
plt.xlabel('time (s)')
plt.ylabel('currents (nA)')
plt.legend()
def crop_graph(G, pt=.5):
H = G.subgraph([i for i in G.nodes() if G.node[i]['pos'][0] < pt and G.node[i]['pos'][1] < pt])
return nx.convert_node_labels_to_integers(H)
def draw_node(G, node=0):
pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_edges(G, pos=pos, alpha=.05, edge_color='k')
nx.draw_networkx_edges(G, pos=pos, alpha=.8, edge_color='r', edgelist=G.in_edges(node), width=2)
nx.draw_networkx_edges(G, pos=pos, alpha=.8, edge_color='g', edgelist=G.out_edges(node), width=2)
plt.xlim([0, np.max(list(pos.values()))])
plt.ylim([0, np.max(list(pos.values()))])
def random_geometric_gauss2(N, dim=2, sigma=1, grad=0, torus=0):
"""
Return a random geometric graph with gaussian distribution of connection as a function of distance.
The nodes are selected randomly in a hypercube in the dimension provided.
The random geometric graph model
- places n nodes uniformly at random in the unit cube of dimension dim
- connect two nodes `u,v` with an edge in such a way that `d(u,v)`
generates a unilateral gaussian distribution N(0,sigma)
where `d(u,v)` is the Euclidean distance between node u and v.
Input:
N: Number of nodes
sigma: Variance of the Gaussian
dim : optional, Dimension of graph
Output:
G Constructed graph
Position is added to each node
"""
G = nx.Graph()
G.name = "Random Geometric Graph"
G.add_nodes_from(list(range(N)))
# sample node position uniformly
for n in G:
G.node[n]['pos'] = rnd.random(dim)
if dim == 3:
for n in range(len(G.nodes())):
G.node[n]['pos'][2] = (1 - G.node[n]['pos'][2] ** grad) * .25
start = time.time()
pos = np.asarray(list(nx.get_node_attributes(G, 'pos').values()))
if torus:
Dmat = squareform(pdist(pos, metric=lambda x, y: (
min(1 - abs(x[0] - y[0]) % 1, abs(x[0] - y[0])) ** 2 + min(1 - abs(x[1] - y[1]) % 1,
abs(x[1] - y[1])) ** 2)))
else:
Dmat = squareform(pdist(pos, 'sqeuclidean'))
print('%d s' % (time.time() - start))
Dmat = scipy.stats.chi2(1).cdf(Dmat / sigma)
Dmat += np.eye(len(Dmat)) * 10
print('%d s' % (time.time() - start))
Pmat = np.random.random(Dmat.shape)
print('%d s' % (time.time() - start))
edges = np.where(Dmat - Pmat < 0.0)
print('%d s' % (time.time() - start))
# G.add_edges_from()
return G, list(zip(*edges))
|
C# | UTF-8 | 3,419 | 2.671875 | 3 | [] | no_license | // C# port of md5main.c https://sourceforge.net/projects/libmd5-rfc/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tool
{
class Program
{
private static readonly string usage =
@"Usage:
md5main --test # run the self-test (A.5 of RFC 1321)
md5main --t-values # print the T values for the library
md5main --version # print the version of the package
";
private static readonly string version = "2002-04-13";
private static IList<TestCase> testCases = new List<TestCase>
{
new TestCase { Input = "", Hash = "d41d8cd98f00b204e9800998ecf8427e" },
new TestCase { Input = "a", Hash = "0cc175b9c0f1b6a831c399e269772661" },
new TestCase { Input = "abc", Hash = "900150983cd24fb0d6963f7d28e17f72" },
new TestCase { Input = "message digest", Hash = "f96b697d7cb7938d525a2f31aaf161d0" },
new TestCase { Input = "abcdefghijklmnopqrstuvwxyz", Hash = "c3fcd3d76192e4007dfb496cca67e13b" },
new TestCase { Input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", Hash = "d174ab98d277d9f5a5611c2c9f419d9f" },
new TestCase { Input = "12345678901234567890123456789012345678901234567890123456789012345678901234567890", Hash = "57edf4a22be3c955ac49da2e2107b67a" }
};
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine(usage);
return;
}
var command = args.First();
if (command == "--test")
{
var status = Test();
Environment.Exit(status);
}
if (command == "--t-values")
{
PrintValues();
return;
}
if (command == "--version")
{
Console.WriteLine(version);
return;
}
}
private static int Test()
{
var status = 0;
foreach (var testCase in testCases)
{
var inputBytes = Encoding.ASCII.GetBytes(testCase.Input);
var hashBytes = libmd5.Md5.ComputeHash(inputBytes);
var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
if (hash != testCase.Hash)
{
Console.WriteLine($"MD5 (\"{testCase.Input}\") = {hash}");
Console.WriteLine($"**** ERROR, should be: {testCase.Hash}");
status = 1;
}
}
if (status == 0)
{
Console.WriteLine("md5 self-test completed successfully.");
}
return status;
}
private static void PrintValues()
{
for (var i = 0; i <= 64; ++i)
{
var v = (ulong) (4294967296.0 * Math.Abs(Math.Sin(i)));
if (v >> 31 != 0)
{
Console.WriteLine($"#define T{i} /* 0x{v:x8} */ (T_MASK ^ 0x{(ulong)(uint)~v:x8})");
} else {
Console.WriteLine($"#define T{i} 0x{v:x8}");
}
}
}
}
class TestCase
{
public string Input { get; set; }
public string Hash { get; set; }
}
}
|
PHP | UTF-8 | 1,140 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: lets
* Date: 16/11/2018
* Time: 10:33
*/
namespace App\Repositories;
use App\Base\Repository;
use App\Models\Product;
use App\Traits\UploadableTrait;
class ProductsRepository extends Repository
{
use UploadableTrait;
protected function getClass()
{
return Product::class;
}
public function create($productData)
{
$price = $productData['price'];
$price = str_replace('.', '', $price);
$price = str_replace(',', '.', $price);
$productData['price'] = $price;
$this->model->create($productData);
}
public function update($id, $productData)
{
$product = $this->find($id);
$price = $productData['price'];
$config = $productData['config'];
$price = str_replace('.', '', $price);
$price = str_replace(',', '.', $price);
$productData['price'] = $price;
$product->update($productData);
}
public function delete($id)
{
$product = $this->find($id);
$this->deleteUploadedFilesFor($product);
$product->delete();
}
}
|
Markdown | UTF-8 | 644 | 2.65625 | 3 | [] | no_license | # Inventory-Management-System
* This System helps to manage Inventory of any Shop.
* It provides User of the System with several options like add, delete, view and edit Information of the product.
* The System has a simple to use GUI.
* Inventory is connected with a billing System.
* So whenever a bill is made, All the products from inventory automatically get deducted.
* Also it warns the user if any of the product's quantity is below threshold value.






|
Markdown | UTF-8 | 692 | 3.140625 | 3 | [] | no_license | # KeyValueStore
A simple flask REST service to store key value pairs.
## Functions
• get: To fetch the value of a Key
• set: To set a Key Value pair
• search: To search if a Key starts or ends with a pattern
### Local development
• To run the project via Docker, run the following commands:
1. docker build --tag key-value-server .
2. docker run -p 80:80 key-value-server
• Access the APIs at `http://0.0.0.0/`
### Deploy on Cloud (AWS)
• If you have AWS configured on your local system then follow this guide for deployment
• Install terraform on your system
• Run the following commands in order to deploy:
1. terraform plan
2. terraform apply
|
JavaScript | UTF-8 | 7,696 | 3.125 | 3 | [] | no_license | $(document).ready(function() {
var commentSort = 'recent'; // This represents two values. 'recent' or 'flags'
var lastCommentId = null;
// Listen for User tools selection.
$('#show-comments').on('click', function() {
$('#users').html('');
$('#search-url').show();
$('#search-comments').show();
$('#search-users').hide();
$('#load-more-users').hide();
$('#load-more-comments').show();
$('#sort-type').text('Showing Comments:');
getComments();
});
// Use this to build out HTML for individual comments.
// Basically, our AJAX call will get data back, loop over the array of comments
// then send each individiaul comment here to build out the comment.
var buildComments = function(comment) {
var commentHTML = '<div class="comment" data-commentid="' + comment.id + '"><p>Comment ID:' + comment.id + '<br/>Username: ' + comment.username + ' | ' +
comment.createdAt + '<br/>Site: <a href="http://' + comment.url + '" target="_blank">http://' + comment.url + '</a><br/>' + comment.text + '<br/>' +
'<a href="#" class="delete" data-comment-id="' + comment.id + '">DELETE</a> || <a href="#" class="unflag" data-comment-id="' + comment.id + '">REMOVE FLAGS</a> <br/>' +
'TOTAL FAVS: <span id="faves-' + comment.id + '">' + comment.HeartCount + '</span> || TOTAL FLAGS: <span id="flags-' + comment.id + '">' + comment.FlagCount + '</span></p></div>';
return commentHTML;
};
// Wrapping our AJAX call to the server to get comments in a function. Why?
// That way we can update the server if I input a new URL to look at in the
// input box at the top of the screen.
var getComments = function(url) {
adminSettings.url = url || null;
// Default website to show comments from on page load.
// If this is for a POST request, we need to JSON.stringify() data.
// If it's for a GET request, we don't need to stringify data.
// Setting this to nothing (e.g., data = {}) returns ALL comments.
var data = {};
if (lastCommentId !== null) {
data.lastCommentId = lastCommentId;
}
// Check if we're sorting by flags.
if (commentSort === 'flags') {
data.orderByFlags = 'DESC';
}
// Check if we're sorting by flags.
if (commentSort === 'recent') {
//data.orderByFlags = 'DESC';
}
if (url) {
data.url = url;
}
// AJAX call to server to get comments from a particular URL.
$.ajax({
type: "GET",
url: window.location.origin + '/api/comments',
data: data,
contentType: 'application/json', // content type sent to server
dataType: 'json', //Expected data format from server
success: function(data) {
$('#comments').html('');
var commentData = data['comments'];
console.log('DATA: ', data);
console.log('LAST COMMENT ID: ', data['comments'][commentData.length-1].id);
//console.log('DONE!');
lastCommentId = data['comments'][commentData.length-1].id;
// Set the logged in user's ID so we can pass into fav / flag functions.
adminSettings.userId = data.userInfo.userId;
var commentArrayHTML = '';
// Render comment HTML
data.comments.forEach(function(element, index) {
// Check if Total Flags or Total Hearts is Null set to 0.
if (data['comments'][index].FlagCount === null) {
data['comments'][index].FlagCount = 0;
}
if (data['comments'][index].HeartCount === null) {
data['comments'][index].HeartCount = 0;
}
commentArrayHTML = commentArrayHTML.concat(buildComments(data['comments'][index]));
});
$('#comments').html(commentArrayHTML);
},
error: function(err) {
$('#comments').html('Please login with valid credentials first :)');
}
});
};
// On Initial Page Load (Providing we're ultimately logged into Google):
// GET NEW COMMENTS!
// We don't need to pass in an initial URL since the getComments() function will
// check if anything exists, otherwise it's set to a default.
getComments();
// SEARCH COMMENTS FROM URL
$("#url-search").keydown(function(event){
if(event.keyCode == 13){
var getURL = $("#url-search").val();
// Allow posting paths only and not URLs by prepending 'http://'
if (getURL === undefined || getURL === '') {
// DO NOTHING cause we'll just return all URLs
getURL = '';
void 0;
} else if (getURL.substr(0, 5) === 'http:' || getURL.substr(0, 6) === 'https:') {
// ALSO DO NOTHING. WHY IS THIS HERE?
// WHO KNOWS. BUT IT WORKS.
// ¯\_(ツ)_/¯
} else {
getURL = 'http://' + getURL;
}
adminSettings.url = getURL;
$('#comments').html();
getComments(getURL);
}
});
// SORT COMMENTS BY NUMBER OF FLAGS
$(document).on('click', '#sort-flags', function(event) {
// Update Mode:
commentSort = 'flags';
lastCommentId = null;
adminSettings.currentMode = "flags";
console.log('Current Sort Mode:', adminSettings.currentMode);
// Reset Comments HTML and get comments again.
$('#comments').html('');
getComments();
});
// SORT COMMENTS BY WHEN THEY WERE RECENTLY POSTED
$(document).on('click', '#sort-recent', function(event) {
// Update Mode:
commentSort = 'recent';
lastCommentId = null;
adminSettings.currentMode = "recent";
console.log('Current Sort Mode:', adminSettings.currentMode);
// Reset Comments HTML and get comments again.
$('#comments').html('');
getComments();
});
$(document).on('click', '#load-more-comments', function(event) {
// Reset Comments HTML and get comments again.
if (adminSettings.currentMode !== 'users') {
$('#comments').html('');
$('#users').html('');
getComments();
}
});
// DELETE COMMENT FROM DATABASE!!!!
$(document).on('click', '.delete', function(event) {
event.preventDefault();
console.log('DELETE clicked!');
console.log('DELETE CLICKED, ID = ', $(this).attr('data-comment-id'));
var commentId = $(this).attr('data-comment-id');
$.ajax({
url: window.location.origin + '/api/comments/remove/' + commentId,
method: 'DELETE',
//dataType: 'json',
success: function(data) {
console.log('Removing comment: ', commentId);
var getDivId = 'div[data-commentid="' + commentId +'"]';
$(getDivId).hide();
},
error: function(xhr, status, err) {
console.error(xhr, status, err.message);
}
});
});
// REMOVE FLAGS FROM COMMENT
$(document).on('click', '.unflag', function(event) {
event.preventDefault();
console.log('UNFLAG clicked!');
console.log('UNFLAG CLICKED, ID = ', $(this).attr('data-comment-id'));
var commentId = $(this).attr('data-comment-id');
$.ajax({
url: window.location.origin + '/api/flags/remove/' + commentId,
method: 'DELETE',
//dataType: 'json',
success: function(data) {
console.log('Removing flags: ', commentId);
var getDivId = 'div[data-commentid="' + commentId +'"]';
// If current mode is for flags only, then let's go ahead and
// hide the div as well, since we reset current flags.
if (adminSettings.currentMode === 'flags') {
$(getDivId).hide();
} else {
$('#flags-' + commentId).text('0');
}
},
error: function(xhr, status, err) {
console.error(xhr, status, err.message);
}
});
});
}); |
Java | UTF-8 | 1,673 | 2.0625 | 2 | [] | no_license | /**
* Copyright Trimble Inc., 2014 - 2015 All rights reserved.
*
* Licensed Software Confidential and Proprietary Information of Trimble Inc.,
* made available under Non-Disclosure Agreement OR License as applicable.
*
* Product Name:
*
*
* Module Name:
* com.neural.fragment
*
* File name:
* GameFragment.java
*
* Author:
* sprabhu
*
* Created On:
* 17-Jan-201512:51:04 pm
*
* Abstract:
*
*
* Environment:
* Mobile Profile :
* Mobile Configuration :
*
* Notes:
*
* Revision History:
*
*
*/
package com.neural.fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.neural.view.MultiTouchView;
/**
* @author sprabhu
*
*/
public class GameFragment extends SettingAbstractFragment {
/**
*
*/
public GameFragment() {
}
public static GameFragment newInstance(int index) {
GameFragment f = new GameFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final MultiTouchView multiTouchView = new MultiTouchView(getActivity());
return multiTouchView;
}
@Override
public int getShownIndex() {
return SettingListFragment.GAME_SETTING;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}
}
|
C# | UTF-8 | 787 | 3.171875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOPSDemo1
{
class StudentDemo
{
static void Main()
{
Students s1 = new Students(101, "Marry");
//s1.Name = "Steve"; //complilation error
// s1.Rollno = 100;
s1.Course = "Computer Science"; //accessing write only property
s1.City = "Benguluru"; //store value in auto-implemented property
Console.WriteLine(s1.Rollno + " " + s1.Name);
// Console.WriteLine(s1.Course);//complie error-trying to access write only property
s1.display();
Console.WriteLine(s1.City);
Console.ReadKey();
}
}
}
|
JavaScript | UTF-8 | 554 | 2.796875 | 3 | [] | no_license | const fs = require('fs')
fs.readFile('package.json', 'utf-8', (error, contenido) => {
if(error) throw new Error(`Error en lectura: ${error}`)
console.log('package.json: lectura exitosa')
let info = {}
info.contenidoStr = contenido,
info.contenidoObj = JSON.parse(contenido),
info.size = contenido.length
console.log(info)
fs.writeFile('info.txt', JSON.stringify(info, null,'\t'), error => {
if(error) throw new Error(`Error en escritura: ${error}`)
console.log('info.txt: escritura exitosa')
})
})
|
C | UTF-8 | 8,721 | 2.828125 | 3 | [] | no_license | #include "sae_par.h"
#include "cupid.h"
#include <limits.h>
int cupidRFillClumps( int *ipa, int *out, int nel, int ndim, int skip[ 3 ],
int dims[ 3 ], int peakval, int *status ){
/*
*+
* Name:
* cupidRFillClumps
* Purpose:
* Identify clumps by filling in the volume enclosed by the marked
* edges.
* Language:
* Starlink C
* Synopsis:
* int cupidRFillClumps( int *ipa, int *out, int nel, int ndim,
* int skip[ 3 ], int dims[ 3 ], int peakval,
* int *status )
* Description:
* This function is supplied with an array in which pixels marking the
* edges of clumps are flagged using the value CUPID__KEDGE, and
* pixels marking the peak value within a clump are marked by the
* value "peakval". It assigns a unique integer index to each peak
* and then finds the extent of the clump surrounding the peak. In the
* returned array, all pixels assigned to a peaks clump hold the integer
* index associated with the clump. Pixels not in any clump have the
* value -INT_MAX. Edge pixels are not considered to be part of any clump.
*
* If more than one peak claims a pixel, the pixel is given to the
* closest peak.
*
* Note, the algorithm used for filling is not fool-proof and cannot
* in general deal with clumps which are "S" shaped (for instance).
* Parameters:
* ipa
* Pointer to an array which is the same shape and size as the data
* array, and which holds a flag for every pixel. On entry, if the
* pixel is an edge pixel this flag will be CUPID__KEDGE. If it is a
* peak pixel it will have the value "peakval". Unchanged on exit.
* out
* Pointer to an array which is the same shape and size as the data
* array, and which holds a flag for every pixel. On exit it holds
* the pixel index (0 or more) at all pixels which are deemed to be
* within a clump, and -INT_MAX everywhere else.
* nel
* The number of elements in "ipa".
* ndim
* The number of pixel axes in the data (this can be less than 3).
* skip
* The increment in 1D vector index required to move a distance of 1
* pixel along each axis. This allows conversion between indexing
* the array using a single 1D vector index and using nD coords. This
* array should have 3 elements even if there are less than 3 pixel
* axes, and the extra elements should be filled with zero's.
* dims
* The no. of pixels along each pixel axis. This array should have 3
* elements even if there are less than 3 pixel axes, and the extra
* elements should be filled with one's.
* peakval
* The "ipa" value used to flag peaks.
* status
* Pointer to the inherited status value.
* Returned Value:
* The largest integer clump identifier present in the "out" array.
* The smallest identifier value is zero.
* Copyright:
* Copyright (C) 2006 Particle Physics & Astronomy Research Council.
* All Rights Reserved.
* Licence:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street,Fifth Floor, Boston, MA
* 02110-1301, USA
* Authors:
* DSB: David S. Berry
* {enter_new_authors_here}
* History:
* 24-JAN-2006 (DSB):
* Original version.
* {enter_further_changes_here}
* Bugs:
* {note_any_bugs_here}
*-
*/
/* Local Variables: */
int *pa; /* Pointer to next "ipa" element */
int gp[ 3 ]; /* Grid coords of peak position */
int i; /* Index of next "ipa" element */
int ipeak; /* Index of next clump */
int ix; /* The X Grid coord of the current pixel */
int iy; /* The Y Grid coord of the current pixel */
int iz; /* The Z Grid coord of the current pixel */
int npeak; /* Number of peaks being produced */
int *gpeak[ 3 ]; /* Pointers to arrays of peak axis values */
/* Initialise */
ipeak = -1;
/* Abort if an error has already occurred. */
if( *status != SAI__OK ) return ipeak;
/* Fill the output array with -INT_MAX. */
for( i = 0; i < nel; i++ ) out[ i ] = -INT_MAX;
/* So far we have no peaks */
npeak = 0;
gpeak[ 0 ] = astMalloc( sizeof( int )*30 );
gpeak[ 1 ] = astMalloc( sizeof( int )*30 );
gpeak[ 2 ] = astMalloc( sizeof( int )*30 );
/* Scan the ipa array looking for peaks. */
pa = ipa;
i = 0;
for( iz = 1; iz <= dims[ 2 ]; iz++ ) {
for( iy = 1; iy <= dims[ 1 ]; iy++ ) {
for( ix = 1; ix <= dims[ 0 ]; ix++, i++, pa++ ) {
if( *pa == peakval ) {
/* Find the integer identifier for this peak. */
ipeak = npeak++;
/* Save thre grid coords of the peak in the gpeak array, extending it if
necessary to make room. */
gpeak[ 0 ] = astGrow( gpeak[ 0 ], npeak, sizeof( int ) );
gpeak[ 1 ] = astGrow( gpeak[ 1 ], npeak, sizeof( int ) );
gpeak[ 2 ] = astGrow( gpeak[ 2 ], npeak, sizeof( int ) );
if( gpeak[ 2 ] ) {
gpeak[ 0 ][ ipeak ] = ix;
gpeak[ 1 ][ ipeak ] = iy;
gpeak[ 2 ][ ipeak ] = iz;
}
/* Fill the volume between the edges marked in the "ipa" array by first
moving out away from the peak along a 1D line parallel to the X axis
until edge pixels are encountered. At each position along this line,
store the "ipeak" value in the corresponding pixel of the "out" array,
and then move out away from the position along a 1D line parallel to
the Y axis until edge pixels are encountered. At each position along
this line, store the "ipeak" value in the corresponding pixel of the
"out" array, and then move out away from the position along a 1D line
parallel to the Z axis until edge pixels are encountered. At each
position along this line, store the "ipeak" value in the corresponding
pixel of the "out" array. */
gp[ 0 ] = ix;
gp[ 1 ] = iy;
gp[ 2 ] = iz;
cupidRFillLine( ipa, out, nel, ndim, skip, dims, gp, i, 0,
ipeak, 1, gpeak, status );
}
}
}
}
/* If we are dealing with 2 or 3 d data, we do the whole process again
(without re-initialising the "out" array), but this time scanning the
axes in the order Y, Z, X (instead of X,Y,Z). */
if( ndim > 1 ) {
npeak = 0;
pa = ipa;
i = 0;
for( iz = 1; iz <= dims[ 2 ]; iz++ ) {
for( iy = 1; iy <= dims[ 1 ]; iy++ ) {
for( ix = 1; ix <= dims[ 0 ]; ix++, i++, pa++ ) {
if( *pa == peakval ) {
ipeak = npeak++;
gp[ 0 ] = ix;
gp[ 1 ] = iy;
gp[ 2 ] = iz;
cupidRFillLine( ipa, out, nel, ndim, skip, dims, gp, i, 1,
ipeak, 1, gpeak, status );
}
}
}
}
/* If we are dealing with 3 d data, we do the whole process again (without
re-initialising the "out" array), but this time scanning the axes in the
order Z, X, Y. */
if( ndim > 2 ) {
npeak = 0;
pa = ipa;
i = 0;
for( iz = 1; iz <= dims[ 2 ]; iz++ ) {
for( iy = 1; iy <= dims[ 1 ]; iy++ ) {
for( ix = 1; ix <= dims[ 0 ]; ix++, i++, pa++ ) {
if( *pa == peakval ) {
ipeak = npeak++;
gp[ 0 ] = ix;
gp[ 1 ] = iy;
gp[ 2 ] = iz;
cupidRFillLine( ipa, out, nel, ndim, skip, dims, gp, i, 2,
ipeak, 1, gpeak, status );
}
}
}
}
}
}
/* Free resources. */
gpeak[ 0 ] = astFree( gpeak[ 0 ] );
gpeak[ 1 ] = astFree( gpeak[ 1 ] );
gpeak[ 2 ] = astFree( gpeak[ 2 ] );
/* Return the largest identifier present in "out". */
return ipeak;
}
|
JavaScript | UTF-8 | 179 | 2.53125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | var tap = require('../tap');
tap.count(1);
var arr = [{a:1}, {a:6},{a:2}, {a:4}]
arr.sort(function(a, b) {
console.log(a, b);
return a.a - b.a
})
arr.sort();
tap.ok(true);
|
Python | UTF-8 | 10,576 | 3.1875 | 3 | [] | no_license | import sys, random
# BioE 131 Assignment 4, Michael Vredenburgh --- From command line -h for help
# Analyzes amino acid frequency in a gene, and displays those frequencies, as
# well as generate new sequences with similar frequencies from that of the input sequence.
class InputFASA:
fileName = ""
myRawFile = [""]
myGenes = []
def __init__(self, myFileName):
self.fileName = myFileName
self.myRawFile = InputFASA.extractSequence(myFileName)
self.parseGene()
def extractSequence(myFileName):
# Parses the FASTA file, and creates a string for the sequence.
infile = open(myFileName) # Creates a variable to store the opened file to reference later
myRawFile= infile.readlines()
return myRawFile
def parseGene(self):
# Creates an array of Gene objects called myGenes.
n=0
HeaderList = []
for line in self.myRawFile:
if line[0][:1]=='>':
HeaderList.append(n)
n+=1
HeaderList.append(len(self.myRawFile)+1)
n=0
while n < len(HeaderList)-1:
self.myGenes.append(Gene(self.myRawFile[HeaderList[n]:HeaderList[n+1]-1]))
n+=1
class Gene:
header = ""
mySequence = ""
length=0
A=0
T=0
G=0
C=0
myNewSequence = ""
def __init__(self, FASTAchunk):
# FASTAchunk is the header line plus the genetic infomation.
self.header = FASTAchunk[0]
self.makeSequence(FASTAchunk)
self.geneParams()
self.makeNewSequence()
def makeSequence(self, FASTAchunk):
# Makes a long string out of the FASTAarray. Also removes all instances of "\n".
FASTAgene=FASTAchunk[1:]
for line in FASTAgene:
line = line.replace("\n","")
self.mySequence += line
def addLength(self):
myLength = len(self.mySequence)
self.header = self.header.replace("\n","")
self.header += " %d bp" % myLength
def geneParams(self):
self.length = len(self.mySequence)
for basepair in self.mySequence:
self.length+=1
if basepair == "A":
self.A+=1
if basepair == "T":
self.T+=1
if basepair == "G":
self.G+=1
if basepair == "C":
self.C+=1
def makeNewSequence(self):
self.myNewSequence = newSeq(self.length, self.A, self.T, self.G, self.C).newSeq
class newSeq:
newSeq = "TAC"
length= 0
A = 0
T = 0
G = 0
C = 0
def __init__(self, length, A, T, G, C):
self.length = length
self.A=A
self.T=T
self.G=G
self.C=C
self.makeSeq()
self.toString()
def makeSeq(self):
numOfCodons = int(self.length/3) # Rounds off to insure multiple of 3
for i in range(0,numOfCodons):
self.newSeq += self.genCodon()
self.newSeq+="TAG"
#print(self.newSeq)
def genCodon(self):
BP=[]
for i in range(0,self.A):
BP.append("A")
for i in range(0,self.T):
BP.append("T")
for i in range(0,self.G):
BP.append("G")
for i in range(0,self.C):
BP.append("C")
codon = random.sample(BP,3)
codon = codon[0] + codon[1] + codon[2]
if codon == "TAA":
return self.genCodon()
if codon == "TAG":
return self.genCodon()
if codon == "TGA":
return self.genCodon()
return codon
def toString(self):
print("> Length:%s A:%s T:%s G:%s C:%s" % (self.length, self.A, self.T, self.G, self.C))
copySeq = self.newSeq
while True:
if len(copySeq) <= 80:
print(copySeq[:80])
copySeq = copySeq[80:]
else:
print(copySeq)
break
class loadParam:
length= 0
A = 0
T = 0
G = 0
C = 0
def __init__(self, myFileName):
infile = open(myFileName)
myRawFile= infile.readlines()
myRawFileArray = []
for lines in myRawFile:
myRawFileArray.append(lines)
self.length = int(myRawFileArray[0][2:])
self.A = int(myRawFileArray[1][2:])
self.T = int(myRawFileArray[2][2:])
self.G = int(myRawFileArray[3][2:])
self.C = int(myRawFileArray[4][2:])
def inputCMD(argv1,argv2,argv3,argv4):
if argv1 == "--calc":
param=InputFASA(argv2)
newSeq(param.myGenes[0].length, param.myGenes[0].A, param.myGenes[0].T, param.myGenes[0].G, param.myGenes[0].C)
if argv3 == "--save":
file = open(argv4,"w")
paramString = """L:%s
A:%s
T:%s
G:%s
C:%s
""" % (param.myGenes[0].length, param.myGenes[0].A, param.myGenes[0].T, param.myGenes[0].G, param.myGenes[0].C)
file.write(paramString)
file.close()
return param.myGenes[0].myNewSequence
if argv1 == "--load":
param=loadParam(argv2)
mySeq = newSeq(param.length, param.A, param.T, param.G, param.C)
if argv3 == "--save":
file = open(argv4,"w")
paramString = """L:%s
A:%s
T:%s
G:%s
C:%s
""" % (param.length, param.A, param.T, param.G, param.C)
file.write(paramString)
file.close()
return mySeq.newSeq
def aminoAcid(sequence):
myDict = {"ATT":"I", "ATC":"I", "ATA":"I", "CTT":"L", "CTC":"L", "CTA":"L", "CTG":"L", "TTA":"L", "TTG":"L", "GTT":"V", "GTC":"V", "GTA":"V", "GTG":"V", "TTT":"F", "TTC":"F", "ATG":"M", "TGT":"C", "TGC":"C", "GCT":"A",
"GCC":"A", "GCA":"A", "GCG":"A", "GGT":"G", "GGC":"G", "GGA":"G", "GGG":"G", "CCT":"P", "CCC":"P", "CCA":"P", "CCG":"P", "ACT":"T", "ACC":"T", "ACA":"T", "ACG":"T", "TCT":"S", "TCC":"S", "TCA":"S", "TCA":"S",
"TCG":"S", "AGT":"S", "AGC":"S", "TAT":"Y", "TAC":"Y", "TGG":"W", "CAA":"Q", "CAG":"Q", "AAT":"N", "AAC":"N", "CAT":"H", "CAC":"H", "GAA":"E", "GAG":"E", "GAT":"D", "GAC":"D", "AAA":"K", "AAG":"K", "CGT":"R",
"CGC":"R", "CGA":"R", "CGG":"R", "AGA":"R", "AGG":"R"}
length = len(sequence)/3
I=0
L=0
V=0
F=0
M=0
C=0
A=0
G=0
P=0
T=0
S=0
Y=0
W=0
Q=0
N=0
H=0
E=0
D=0
K=0
R=0
for i in range(0,len(sequence)-6):
if i % 3 == 0:
if myDict[sequence[3+i:6+i]] == "I":
I+=1
if myDict[sequence[3+i:6+i]] == "L":
L+=1
if myDict[sequence[3+i:6+i]] == "V":
V+=1
if myDict[sequence[3+i:6+i]] == "F":
F+=1
if myDict[sequence[3+i:6+i]] == "M":
M+=1
if myDict[sequence[3+i:6+i]] == "C":
C+=1
if myDict[sequence[3+i:6+i]] == "A":
A+=1
if myDict[sequence[3+i:6+i]] == "G":
G+=1
if myDict[sequence[3+i:6+i]] == "P":
P+=1
if myDict[sequence[3+i:6+i]] == "T":
T+=1
if myDict[sequence[3+i:6+i]] == "S":
S+=1
if myDict[sequence[3+i:6+i]] == "Y":
Y+=1
if myDict[sequence[3+i:6+i]] == "W":
W+=1
if myDict[sequence[3+i:6+i]] == "Q":
Q+=1
if myDict[sequence[3+i:6+i]] == "N":
N+=1
if myDict[sequence[3+i:6+i]] == "H":
H+=1
if myDict[sequence[3+i:6+i]] == "E":
E+=1
if myDict[sequence[3+i:6+i]] == "D":
D+=1
if myDict[sequence[3+i:6+i]] == "K":
K+=1
if myDict[sequence[3+i:6+i]] == "R":
R+=1
AminoAcidString="""
The following is the frequency of each amino acid, represented by their one letter code.
I:%s
L:%s
V:%s
F:%s
M:%s
C:%s
A:%s
G:%s
P:%s
T:%s
S:%s
Y:%s
W:%s
Q:%s
N:%s
H:%s
E:%s
D:%s
K:%s
R:%s""" % ( I/length, L/length, V/length, F/length, M/length, C/length, A/length, G/length, P/length, T/length, S/length, Y/length, W/length, Q/length, N/length, H/length, E/length, D/length, K/length, R/length)
print(AminoAcidString)
if len(sys.argv) == 6:
if sys.argv[5] == "--more":
mySeq = inputCMD(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
aminoAcid(mySeq)
else:
raise("The 5th option is reserved only for --more, to display amino acid distribution.")
if len(sys.argv) == 5:
inputCMD(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
if len(sys.argv) == 4:
raise("You must give a name to your saved configuration.")
if len(sys.argv) == 3:
inputCMD(sys.argv[1],sys.argv[2],"","")
if len(sys.argv) == 2:
if sys.argv[1] == "-h":
helpInfo = """HELP INFORMATION
(Script by Michael Vredenburgh for BioE131 Assignment 4)
This program generates semi-random sequences of DNA that begin and end with the appropriate start and stop codons. The frequency of base pair expression can be determined in two ways. First, the –calc can be used to calculate the expression from a FASTA DNA file. The second method is to load in a parameters file. The specifics of the parameter file will be covered at the end of the help menu. Statistics about the amino acid distribution can also be displayed.
The following three lines are example command line inputs.
$ python3 Assignment4.py –calc myglobin.txt –save myparams
$ python3 Assignment4.py –load myparams
$ python3 Assignment4.py –load myparams –save myparams2
The previous inputs will not display any information about the amino acid content. This feature was added to try to meet the extra credit requirement. To see the distribution there must be all four options used, plus a fifth –more option. To do that, enter something similar to the following example.
$ python3 Assignment4.py –calc myglobin.txt –save myparams –more
The parameter files are simple .txt files that hold only the following information.
**
L:#
A:#
T:#
G:#
C:#
**
L being length, and the other letters representing the number of respected base pairs.
"""
print(helpInfo)
else:
raise("Not enough information provided. Try entering like this example. Assignment4.py --calc seqfile.fasa --save myparams. For additional help try the help menue, -h.")
if len(sys.argv) == 1:
raise("Not enough information provided. Try entering like this example. Assignment4.py --calc seqfile.fasa --save myparams. For additional help try the help menue, -h.")
|
Markdown | UTF-8 | 1,354 | 2.734375 | 3 | [
"MIT"
] | permissive | #################################
# How to generate documentation #
#################################
The flux-python-api documentation is generated with Sphinx, which is built
within this directory as part of the code repository and therefore requires
no installation on the client end.
The master documentation file is **index.rst** in this directory. This file
uses **reStructuredText** markup. Whenever changes are made to this file,
documentation needs to be rebuilt using these steps:
$ cd ./docs
$ make html
That's it.
Then you can access and view the documentation that was just generated by
going to this location in a web browser:
file:///usr/local/project/flux-python-api/docs/_build/html/index.html
########################
# Using Sphinx's autodoc
Sphinx's [**autodoc**] (http://sphinx-doc.org/ext/autodoc.html) plug-in
automatically generates documentation from docstrings of methods within the
specific module. As of this writing, **autodoc** is used to document the
**models** and **mediators** modules. The following text is pasted directly
into the **index.rst**, e.g.:
.. automodule:: fluxpy.models
:members:
:show-inheritance:
Autodoc has it's own markup syntax allowing more fancy/customizable formatting
for method documentation. See examples [here](http://sphinx-doc.org/domains.html#info-field-lists)
|
Python | UTF-8 | 657 | 3.234375 | 3 | [] | no_license | import os
from mutagen.mp3 import MP3
from tqdm import tqdm
import sys
def calcTotalLength(path):
totalLength = 0
iterator = tqdm(os.listdir(path))
for no, file in enumerate(iterator):
if file.split('.')[-1] == "mp3":
try:
audio = MP3(path + '/' + file)
totalLength = totalLength + audio.info.length
iterator.set_description("Current Avg Length: " + str(totalLength/(no + 1)) + ' Total Length: ' + str(totalLength))
except:
print('Could Not read file:', file, '\n')
print('Average Length: ', totalLength/len(iterator))
print('Total Length: ', totalLength)
if __name__ == "__main__":
calcTotalLength(path = sys.argv[1]) |
Shell | UTF-8 | 1,152 | 3.9375 | 4 | [
"MIT"
] | permissive | #!/bin/bash
# Copyright (c) ben@diraux.com
HELP='convert a written text in a spocken mp3 file'
USAGE='<text file> [voice]'
file_input="$1"
voice_input="$2"
voice_default="Petra"
warn () { echo "$@" 1>&2; }
die () { echo "$@" 1>&2; exit 1; }
usage () { die "usage '$(basename $0)': $USAGE" ; }
[ -n "$file_input" ] || usage
case "$file_input" in
-h|--help) warn "$HELP" ; usage ;;
*) : ;;
esac
[ -f "$file_input" ] || die "Err: no text file"
os=$(uname)
[ "$os" = "Darwin" ] || die "Err: only runs on macos"
voice=
if [ -n "$voice_input" ]; then
voice="$voice_input"
else
voice="$voice_default"
fi
[ -n "$voice" ] || die "err: no voice"
aiff_tmp=$(mktemp)
[ -f "$aiff_tmp" ] || die "err: no temp aiff_tmp"
say -v Petra -f "$file_input" -o "$aiff_tmp"
[ "$?" = "0" ] || die "err: something went wrong with the 'say' command"
[ -f "$aiff_tmp" ] || die "err: no temp aiff_tmp"
dirpath=$(dirname "$file_input")
filename=$(basename "$file_input")
filebase=${filename%.*}
mp3_file="$dirpath/$filebase.mp3"
lame -m m "$aiff_tmp" "$mp3_file" 2> /dev/null
[ "$?" = "0" ] || die "err: something went wrong with the 'lame' command"
|
Python | UTF-8 | 3,511 | 2.53125 | 3 | [] | no_license | import torch
import torch.nn as nn
from torch.nn import Parameter
from torch_geometric.nn.inits import glorot, zeros
from torch_scatter import scatter_add
from torch_sparse import spspmm, coalesce
from torch_geometric.utils import remove_self_loops
from torch_geometric.utils import add_remaining_self_loops
from torch_geometric.nn import GCNConv
from torch_geometric.nn.conv import MessagePassing
# Todo;这里的GCNlayer是没有squash的
class SparseGCNConv(MessagePassing):
r"""See :class:`torch_geometric.nn.conv.GCNConv`.
"""
def __init__(self, in_channels, out_channels, improved=False, bias=True):
super(SparseGCNConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.improved = improved
self.weight = Parameter(torch.Tensor(in_channels, out_channels))
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
glorot(self.weight)
zeros(self.bias)
@staticmethod
def norm(edge_index, num_nodes, edge_weight, dtype=None, improved=False):
if edge_weight is None:
edge_weight = torch.ones((edge_index.size(1),), dtype=dtype,
device=edge_index.device)
# ToDo 在归一化的时候是否需要再添加自环
# fill_value = 1 if not improved else 2
# edge_index, edge_weight = add_remaining_self_loops(
# edge_index, edge_weight, fill_value, num_nodes)
row, col = edge_index
# 计算节点度数
deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)
deg_inv_sqrt = deg.pow(-0.5)
deg_inv_sqrt[deg_inv_sqrt==float('inf')] = 0
# D^(1/2)*A*D^(1/2)
return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]
def forward(self, x, edge_index, edge_weight, add_loop=True):
r"""
稀疏矩阵模式下的GCN
add_loop: 如果为True,则会删除edge_index的自环,并且添加新的自环
input:
x: (num_of_nodes, hidden)
edge_index: (2, num_of_edges)
edge_weight: (num_of_edges)
"""
x = torch.matmul(x, self.weight)
# batch中graph中节点的总数
N = x.size(0)
# 添加自环
# ToDO: 这里需要考虑,是否需要删除之前edge_index对角线上的元素, 然后重新添加自环
if add_loop:
# 删除原先的自环
edge_index, edge_weight = remove_self_loops(edge_index=edge_index, edge_attr=edge_weight)
if self.improved:
fill_value = 2
else:
fill_value = 1
edge_index, edge_weight = add_remaining_self_loops(edge_index, edge_weight, fill_value=fill_value, num_nodes=N)
edge_index, norm = self.norm(edge_index, x.size(0), edge_weight, x.type)
return self.propagate(edge_index, x=x, norm=norm)
def message(self, x_j, norm):
return norm.view(-1, 1) * x_j if norm is not None else x_j
def update(self, aggr_out):
if self.bias is not None:
aggr_out = aggr_out + self.bias
return aggr_out
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.in_channels,
self.out_channels) |
Java | UTF-8 | 2,083 | 2.0625 | 2 | [] | no_license | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.file.remote;
import java.net.ServerSocket;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
/**
* Test class used to demonstrate the problematic disconnect sequence of the {@link FtpOperations}.
* <p>
* Setting the logging level of {@code org.apache.camel.file.remote} to {@code TRACE} will provide useful information
*
* @author l.chiarello
*/
public class FtpSoTimeoutTest extends CamelTestSupport {
private ServerSocket serverSocket;
// --- Tests
@Test(timeout = 10000, expected = CamelExecutionException.class)
public void testWithDefaultTimeout() throws Exception {
// send exchange to the route using the custom FTPClient (with a default timeout)
// the soTimeout triggers in time and test is successful
template.sendBody("direct:with", "");
}
@Test(timeout = 10000, expected = CamelExecutionException.class)
public void testWithoutDefaultTimeout() throws Exception {
// send exchange to the route using the default FTPClient (without a default timeout)
// the soTimeout never triggers and test fails after its own timeout
template.sendBody("direct:without", "");
}
}
|
JavaScript | UTF-8 | 1,527 | 4.78125 | 5 | [] | no_license | /*
Array: Binary Search (non recursive)
Given a sorted array and a value, return whether the array contains that value.
Do not sequentially iterate the array. Instead, ‘divide and conquer’,
taking advantage of the fact that the array is sorted .
*/
// if n is the number of elements
// then a normal search through an array would be n operations O(n)
// binary search is O(log(n)) this is much faster than O(n)
const nums1 = [1, 3, 5, 6];
const searchNum1 = 4;
const expected1 = false;
const nums2 = [4, 5, 6, 8, 12];
const searchNum2 = 5;
const expected2 = true;
const nums3 = [3, 4, 6, 8, 12];
const searchNum3 = 3;
const expected3 = true;
const nums4 = [4, 5, 6, 8, 12];
const searchNum4 = 12;
const expected4 = true;
const nums5 = [3, 4, 6, 8, 12];
const searchNum5 = 22;
const expected5 = false;
function binarySearch(sortedNums, searchNum) {
while(true){
if(sortedNums.length <1) return false
if(sortedNums.length ==1 && sortedNums[0] != searchNum) return false
mid = parseInt(sortedNums.length/2)
if(sortedNums[mid] == searchNum)
return true;
if(sortedNums[mid]>searchNum){
sortedNums = sortedNums.slice(0,mid)
}
else{
sortedNums = sortedNums.slice(mid+1)
}
}
}
console.log(binarySearch(nums1,searchNum1))
console.log(binarySearch(nums2,searchNum2))
console.log(binarySearch(nums3,searchNum3))
console.log(binarySearch(nums4,searchNum4))
console.log(binarySearch(nums5,searchNum5)) |
JavaScript | UTF-8 | 503 | 3.515625 | 4 | [] | no_license | // Input: [2, 6, 4, 8, 10, 9, 15]
// Output: 5
var findUnsortedSubarray = function(nums) {
var be = nums.length - 1, en = nums.length - 1;
var sorted = nums.slice(0).sort((a,b) => { return a-b; });
for(let i=0; i<nums.length;i++){
if(sorted[i] != nums[i]){
be = i;
break;
}
}
for(let i=nums.length-1; i> be; i--) {
if(sorted[i] != nums[i]){
en = i;
break;
}
}
return (en==be)?0:(en-be+1);
};
|
C++ | UTF-8 | 3,456 | 2.921875 | 3 | [
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.0-or-later",
"MIT"
] | permissive | #include "ImageFlipper.hpp"
#include <FAST/Data/Image.hpp>
namespace fast {
ImageFlipper::ImageFlipper() {
createInputPort<Image>(0);
createOutputPort<Image>(0);
createBooleanAttribute("vertical", "Vertical", "Flip vertical", false);
createBooleanAttribute("horizontal", "Horizontal", "Flip horizontal", false);
createBooleanAttribute("depth", "Depth", "Flip depth", false);
createOpenCLProgram(Config::getKernelSourcePath() + "Algorithms/ImageFlipper/ImageFlipper2D.cl", "2D");
createOpenCLProgram(Config::getKernelSourcePath() + "Algorithms/ImageFlipper/ImageFlipper3D.cl", "3D");
}
ImageFlipper::ImageFlipper(bool flipHorizontal, bool flipVertical, bool flipDepth) : ImageFlipper() {
m_flipHorizontal = flipHorizontal;
m_flipVertical = flipVertical;
m_flipDepth = flipDepth;
}
void ImageFlipper::execute() {
auto input = getInputData<Image>();
if(!m_flipHorizontal && !m_flipVertical && !m_flipDepth)
throw Exception("You must select which axes to flip in ImageFlipper");
auto output = Image::createFromImage(input);
output->setSpacing(input->getSpacing());
if(input->getDimensions() == 3) {
// 3D
auto device = std::dynamic_pointer_cast<OpenCLDevice>(getMainDevice());
auto inputAccess = input->getOpenCLImageAccess(ACCESS_READ, device);
auto outputAccess = output->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
auto program = getOpenCLProgram(device, "3D", "-DTYPE=" + getCTypeAsString(input->getDataType()));
cl::Kernel kernel(program, "flip3D");
kernel.setArg(0, *inputAccess->get3DImage());
kernel.setArg(1, *outputAccess->get());
kernel.setArg(2, (char)(m_flipHorizontal ? 1 : 0));
kernel.setArg(3, (char)(m_flipVertical ? 1 : 0));
kernel.setArg(4, (char)(m_flipDepth ? 1 : 0));
kernel.setArg(5, (int)input->getNrOfChannels());
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(input->getWidth(), input->getHeight(), input->getDepth()),
cl::NullRange
);
} else {
// 2D
auto device = std::dynamic_pointer_cast<OpenCLDevice>(getMainDevice());
auto inputAccess = input->getOpenCLImageAccess(ACCESS_READ, device);
auto outputAccess = output->getOpenCLImageAccess(ACCESS_READ_WRITE, device);
auto program = getOpenCLProgram(device, "2D");
cl::Kernel kernel(program, "flip2D");
kernel.setArg(0, *inputAccess->get2DImage());
kernel.setArg(1, *outputAccess->get2DImage());
kernel.setArg(2, (char)(m_flipHorizontal ? 1 : 0));
kernel.setArg(3, (char)(m_flipVertical ? 1 : 0));
device->getCommandQueue().enqueueNDRangeKernel(
kernel,
cl::NullRange,
cl::NDRange(input->getWidth(), input->getHeight()),
cl::NullRange
);
}
addOutputData(0, output);
}
void ImageFlipper::setFlipHorizontal(bool flip) {
m_flipHorizontal = flip;
}
void ImageFlipper::setFlipVertical(bool flip) {
m_flipVertical = flip;
}
void ImageFlipper::setFlipDepth(bool flip) {
m_flipDepth = flip;
}
void ImageFlipper::loadAttributes() {
setFlipHorizontal(getBooleanAttribute("horizontal"));
setFlipVertical(getBooleanAttribute("vertical"));
setFlipDepth(getBooleanAttribute("depth"));
}
}
|
C# | UTF-8 | 1,800 | 2.828125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using 在线考试系统.Dal;
using System.Windows.Forms;
namespace 在线考试系统.Bll
{
class CourseBll
{
static CourseDal course = new CourseDal();
/// <summary>
/// 获取科目信息
/// </summary>
/// <returns>DataSet类型,返回科目信息数据集</returns>
public static DataSet CourseFillDs()
{
return course.FillDs();
}
/// <summary>
/// 添加科目信息
/// </summary>
/// <param name="CName">string类型,表示科目名称</param>
public static void CourseAdd(string CName)
{
course.AddCou(CName);
}
/// <summary>
/// 删除科目信息
/// </summary>
/// <param name="courseID">科目编号</param>
public static void CourseDel(string courseID)
{
course.DeleteCou(courseID);
}
/// <summary>
/// 绑定ComboBox
/// </summary>
/// <param name="cbo">将要绑定的ComboBox</param>
public static void FillcboCourse(ComboBox cbo)
{
cbo.ValueMember = "courseID";
cbo.DisplayMember = "courseName";
cbo.DataSource = CourseFillDs().Tables[0];
}
/// <summary>
/// 判断是否存在科目
/// </summary>
/// <param name="courseName">科目名称</param>
/// <returns>bool类型,不存在返回true,存在返回false值</returns>
public static bool GetCourse(string courseName)
{
return course.GetCourse(courseName);
}
}
}
|
Java | UTF-8 | 2,010 | 2.984375 | 3 | [] | no_license | package kernel.stackvm;
public class Bytecode {
public static class Instruction {
public final String name; // E.g., "iadd", "call"
public int n = 0;
public Instruction(String name) {
this(name,0);
}
public Instruction(String name, int nargs) {
this.name = name;
this.n = nargs;
}
}
// INSTRUCTION BYTECODES (byte is signed; use a int to keep 0..255)
public static final int NOP = 0;
public static final int IADD = 1; // int add
public static final int ISUB = 2;
public static final int IMUL = 3;
public static final int ILT = 4; // int less than
public static final int IEQ = 5; // int equal
public static final int BR = 6; // branch
public static final int BRT = 7; // branch if true
public static final int BRF = 8; // branch if false
public static final int ICONST = 9; // push constant integer
public static final int GLOAD = 10; // load from global memory
public static final int GSTORE = 11; // store in global memory
public static final int POP = 12; // throw away top of stack
public static final int INT = 15; // interrupt
public static Instruction[] instructions = new Instruction[] {
new Instruction("nop"), // no operation
new Instruction("iadd"), // index is the opcode
new Instruction("isub"),
new Instruction("imul"),
new Instruction("ilt"),
new Instruction("ieq"),
new Instruction("br", 1),
new Instruction("brt", 1),
new Instruction("brf", 1),
new Instruction("iconst", 1),
new Instruction("gload", 1),
new Instruction("gstore", 1),
new Instruction("pop"),
null,
null,
new Instruction("int", 1),
null,
null,
null,
null,
};
}
|
Java | UTF-8 | 251 | 1.523438 | 2 | [] | no_license | package com.zzl.sso.service;
import com.zzl.common.pojo.TaotaoResult;
import com.zzl.pojo.TbUser;
public interface UserRegisterService {
public TaotaoResult checkDate(String param,Integer type);
public TaotaoResult register(TbUser tbUser);
}
|
Markdown | UTF-8 | 4,467 | 3.5 | 4 | [] | no_license | # shiyan3
接口及异常处理
### 实验目的
1.掌握Java中抽象类和抽象方法的定义;
2.掌握Java中接口的定义,熟练掌握接口的定义形式以及接口的实现方法
3.了解异常的使用方法,并在程序中根据输入情况做异常处理
### 实验内容
1.某学校为了给学生提供勤工俭学机会,也减轻授课教师的部分压力,准许博士研究生参与课程的助教工作。此时,该博士研究生有双重身份:学生和助教教师。
2.设计两个管理接口:学生管理接口和教师管理接口。学生接口必须包括缴纳学费、查学费的方法;教师接口包括发放薪水和查询薪水的方法。
3.设计博士研究生类,实现上述的两个接口,该博士研究生应具有姓名、性别、年龄、每学期学费、每月薪水等属性。(其他属性及方法,可自行发挥)
4.编写测试类,并实例化至少两名博士研究生,统计他们的年收入和学费。根据两者之差,算出每名博士研究生的年应纳税金额(国家最新工资纳税标准,请自行检索)。
### 实验要求
1.在博士研究生类中实现各个接口定义的抽象方法;
2.对年学费和年收入进行统计,用收入减去学费,求得纳税额;
3.国家最新纳税标准(系数),属于某一时期的特定固定值,与实例化对象没有关系,考虑如何用static final修饰定义。
4.实例化研究生类时,可采用运行时通过main方法的参数args一次性赋值,也可采用Scanner类实现运行时交互式输入。
5.根据输入情况,要在程序中做异常处理。
### 实验过程:
首先创建一个类,在其中设置诸多变量,如name age number等,用作数据的输入。然后用两个interface接口分别实现学生的student和teacher两种属性,其中student下应给出定义学费金额,teacher下应给出定义工资和税率。由于都是数字类型所以都用double来定义。
在主类下用catch用作预处理,若出现错误则输出:数据异常。
最后完善主类中内容,为变量赋值,并在后面用this进行引用。
输出结果,中途出现数据异常,返回调试。
结果符合预期,实验结束。
### 核心代码
```
public static void main(String[] args) {
try {
System.out.println("博士研究生:");
Doctor hkl = new Doctor();
hkl.setName("胡凯莉");
hkl.setAge(20);
hkl.setNumber(2019310000);
hkl.setSex("男");
hkl.setTuition(5500);
hkl.setSalary(1800);
System.out.println("学生姓名:" + hkl.getName());
System.out.println("学生年龄:" + hkl.getAge());
System.out.println("学生编号:" + hkl.getNumber());
System.out.println("学生性别:" + hkl.getSex());
hkl.find_tuition();
hkl.find_salary();
hkl.taxation();
System.out.println("博士研究生2:");
Doctor zsy = new Doctor();
zsy.setName("周淑怡");
zsy.setAge(22);
zsy.setNumber(2017310001);
zsy.setSex("女");
zsy.setTuition(5500);
zsy.setSalary(2000);
System.out.println("学生姓名:" + zsy.getName());
System.out.println("学生年龄:" + zsy.getAge());
System.out.println("学生编号:" + zsy.getNumber());
System.out.println("学生性别:" + zsy.getSex());
zsy.find_tuition();
zsy.find_salary();
zsy.taxation();
} catch (Exception e) {
System.out.println("数据异常");
}
}
```
### 实验结果
博士研究生1:
学生姓名:胡凯莉
学生年龄:20
学生编号:2019310000
学生性别:男
学费缴纳成功,金额为:5500.0
工资发放成功,金额为:1600.0
每年纳税额度为:2400.0
博士研究生2:
学生姓名:周淑怡
学生年龄:20
学生编号:2017310001
学生性别:女
学费缴纳成功,金额为:5500.0
工资发放成功,金额为:1760.0
每年纳税额度为:2880.0
### 实验感想
通过这次实验我掌握了不同接口的用法,并用预处理方式处理了实验中的问题,最后通过不断修改完成了实验内容。提交后我会再根据不足和以后对代码的理解再加深之后再对程序进行修改和完善。
|
C | UTF-8 | 4,776 | 3.65625 | 4 | [] | no_license | //Singly Circular linked List without menu driven switch cases
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int Data;
struct Node *Next;
}NODE,*PNODE,**PPNODE;
/*
typedef struct Node NODE;
typedef struct Node* PNODE;
typedef struct Node** PPNODE;
*/
/////////////////////////////////////////////////////////////////////////////
void Display(PNODE First,PNODE Last)
{
do
{
printf("|%d|<=>",First->Data);
First=(First)->Next;
}while(First != Last->Next);
printf("\n");
}
/////////////////////////////////////////////////////////////////////////////
int Count(PNODE First,PNODE Last)
{
int Cnt=0;
do
{
Cnt++;
First=(First)->Next;
}while(First != Last->Next);
return Cnt;
}
////////////////////////////////////////////////////////////////////////////////
void InsertFirst(PPNODE First,PPNODE Last)
{
int No=0;
PNODE newn=NULL;
newn=(PNODE)malloc(sizeof(NODE));
printf("Enter value:");
scanf("%d",&No);
newn->Data=No;
newn->Next=NULL;
if((*First==NULL)&&(*Last==NULL)) //LL is empty
{
*First=newn;
*Last=newn;
}
else //LL contains atleast one node
{
newn->Next=*First; // navin node chya next mdhe pahilyacha address takla
*First=newn; //teacher chya dokyat navin node cha address takla
}
(*Last)->Next=*First; //shevtchya chya next mdhe pahilya node address takla
}
/////////////////////////////////////////////////////////////////////////////////
void InsertLast(PPNODE First,PPNODE Last)
{
int No=0;
PNODE newn=NULL;
newn=(PNODE)malloc(sizeof(NODE));
printf("Enter value:");
scanf("%d",&No);
newn->Data=No;
newn->Next=NULL;
if((*First == NULL) && (*Last == NULL)) //LL is empty
{
*First=newn;
*Last=newn;
}
else //LL contains atleast one node
{
(*Last)->Next=newn; // shevtchya chya next mdhe navin node cha addr takla
*Last=newn; // last pointer navin last node la point krun dila or //*Last=(*Last)->Next
}
(*Last)->Next=*First; //shevtchya chya next mdhe pahilya node address takla
}
////////////////////////////////////////////////////////////////////////////
void InsertAtPos(PPNODE First,PPNODE Last)
{
int size=0;
int Pos=0;
int No=0;
int i=0;
PNODE temp= *First;
PNODE newn =NULL;
newn=(PNODE)malloc(sizeof(NODE));
printf("Enter postion to insert node:");
scanf("%d",&Pos);
size=Count(*First,*Last);
if((*First==NULL)&&(*Last==NULL))
{
return;
}
else if((Pos<1) ||(Pos>size))
{
return;
}
else if(Pos==1) //contains only one node
{
InsertFirst(First,Last);
}
else if(Pos==size+1)
{
InsertLast(First,Last);
}
else
{
printf("Enter value to insert:");
scanf("%d",&No);
newn->Data=No;
newn->Next=NULL;
for(i=1;i<Pos-1;i++)
{
temp=temp->Next;
}
newn->Next=temp->Next;
temp->Next=newn;
}
}
///////////////////////////////////////////////////////////////////////////////
void DeleteFirst(PPNODE First,PPNODE Last)
{
if((*First==NULL)&&(*Last==NULL))
{
return;
}
else if(*First==*Last) //contains only one node
{
free(*First);
*First=NULL;
*Last=NULL;
}
else //more than one node
{
*First=(*First)->Next;
free((*Last)->Next);
}
(*Last)->Next=*First;
}
//////////////////////////////////////////////////////////////////////////////
void DeleteLast(PPNODE First,PPNODE Last)
{
PNODE temp=*First;
if((*First==NULL)&&(*Last==NULL))
{
return;
}
else if(*First==*Last) //contains only one node
{
free(*First);
*First=NULL;
*Last=NULL;
}
else //more than one node
{
while(temp->Next != *Last)
{
temp=temp->Next;
}
free(temp->Next);
*Last=temp;
}
(*Last)->Next=*First;
}
////////////////////////////////////////////////////////////////////////////
void DeleteAtPos(PPNODE First,PPNODE Last)
{
int Pos=0;
int size = 0;
int i=0;
PNODE temp=*First;
PNODE target=NULL;
size = Count(*First,*Last);
printf("Enter position to delete node:");
scanf("%d",&Pos);
if((Pos<1) || (Pos>size))
{
return;
}
else if(Pos==1)
{
DeleteFirst(First,Last);
}
else if(Pos==size)
{
DeleteLast(First,Last);
}
else
{
printf("I am in else part\n");
for(i=1;i<Pos-1;i++)
{
temp=temp->Next;
}
target=temp->Next;
temp->Next=target->Next;
free(target);
}
}
/////////////////////////////////////////////////////////////////////////////
int main()
{
PNODE Head=NULL;
PNODE Tail=NULL;
int No=0;
int iRet;
InsertFirst(&Head,&Tail);
InsertFirst(&Head,&Tail);
InsertFirst(&Head,&Tail);
InsertLast(&Head,&Tail);
InsertLast(&Head,&Tail);
InsertLast(&Head,&Tail);
Display(Head,Tail);
DeleteFirst(&Head,&Tail);
DeleteLast(&Head,&Tail);
Display(Head,Tail);
DeleteAtPos(&Head,&Tail);
Display(Head,Tail);
InsertAtPos(&Head,&Tail);
Display(Head,Tail);
iRet=Count(Head,Tail);
printf("Total number of noes in LL are:%d\n",iRet);
return 0;
}
|
Java | UTF-8 | 2,855 | 2.859375 | 3 | [
"MIT"
] | permissive | /*
* Copyright 2017 Turn s.r.o.
*
* 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 sk.turn.gwtmvp.client;
import com.google.gwt.dom.client.Element;
/**
* A {@link View} sub-interface that allows direct event handler method mapping.
* <p>
* In plain {@code View} interface you had to define a setter for event handler and later call that
* to bind a handler implementation:
* <pre><code>{@literal @}HtmlHandler("") void setLinkClickHandler(ClickHandler handler);
*...
*view.setLinkClickHandler(new ClickHandler() {
* {@literal @}Override
* public void onClick(ClickEvent event) {
* // Implementation here
* }
*});</code></pre>
* <p>
* In {@code HandlerView} you define the class that will implement the handler methods for this view
* <pre><code>interface MyView extends HandlerView<DivElement, MyEventHandler></code></pre>
* Add the handlers directly in the class implementation
* <pre><code>class MyEventHandler { // This may as well (and often will) be the Presenter itself
* ...
* {@literal @}HtmlHandler("link") // Here goes the data-mvp-id attribute(s) for which to handle the event
* void onLinkClicked(ClickEvent event) { // The method name does not matter, the only one parameter must be a DomEvent<?> class.
* // Implementation here
* }
*}</code></pre>
* And let the view know which instance to use
* <pre><code>myView.setHandler(myEventHandler);</code></pre>
* <p>
* Although this View-Presenter coupling is against the strict MVP pattern, it helps code readability and to reduce verbosity.
* If you plan to have proper unit testing or need to decouple View-Presenter for any other reason,
* either use the plain {@link View} interface or pull the handler methods out in a separate interface.
*
* @param <E> The HTML element that represents the root node of the view.
* @param <H> The class that has the {@literal @}HtmlHandler annotated handler methods.
*/
public interface HandlerView<E extends Element, H> extends View<E> {
/**
* Sets the instance of event handler class. Calling this method multiple times only keeps the last instance.
* This method can be considered "cheap" in terms of processing and may be called even before {@link View#getRootElement()} was called.
* @param handler The event handler instance.
*/
void setHandler(H handler);
}
|
Python | UTF-8 | 326 | 4.53125 | 5 | [] | no_license | #Exercicio 10 do site Python Brasil
#Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Farenheit.
#Formula => tf = (tc * (9/5)) + 32
tc = input("Digite uma temperatura em graus celsius ")
tf = (float(tc) * (9/5)) + 32
print("A conversao de {}ºC e igual a {:.0f}ºF".format(tc, tf)) |
C# | UTF-8 | 10,224 | 2.90625 | 3 | [
"MIT"
] | permissive | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace NHLStats
{
public class Schedule
{
public string totalItems { get; set; }
public string totalEvents { get; set; }
public string totalGames { get; set; }
public string totalMatches { get; set; }
public string season { get; set; }
public string scheduleDate { get; set; }
public List<Game> games { get; set; }
public JObject scheduleJson { get; set; } //Storage of the raw JSON feed
// Important URLs: https://statsapi.web.nhl.com/api/v1/schedule?date=2018-11-21
// Default constructor: shows today's schedule
public Schedule()
{
string gameDateScheduleURL = NHLAPIServiceURLs.todaysGames;
var json = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
totalItems = json["totalItems"].ToString();
totalEvents = json["totalEvents"].ToString();
totalGames = json["totalGames"].ToString();
totalMatches = json["totalMatches"].ToString();
List<Game> scheduledGames = new List<Game>();
var scheduleArray = JArray.Parse(json.SelectToken("dates").ToString());
foreach (var game in scheduleArray[0]["games"])
{
Game aGame = new Game(game["gamePk"].ToString());
scheduledGames.Add(aGame);
}
games = scheduledGames;
}
// NOTE: Parameter format for date is YYYY-MM-DD
public Schedule(string gameDate)
{
string gameDateScheduleURL = NHLAPIServiceURLs.todaysGames + "?date=" + gameDate;
var json = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
// Populate the raw JSON feed to the scheduleJson property.
scheduleJson = json;
if (json.ContainsKey("totalItems"))
totalItems = json["totalItems"].ToString();
else
totalItems = "0";
if (json.ContainsKey("totalEvents"))
totalEvents = json["totalEvents"].ToString();
else
totalEvents = "0";
if (json.ContainsKey("totalGames"))
totalGames = json["totalGames"].ToString();
else
totalGames = "0";
if (json.ContainsKey("totalMatches"))
totalMatches = json["totalMatches"].ToString();
else
totalMatches = "0";
scheduleDate = gameDate;
List<Game> scheduledGames = new List<Game>();
var scheduleArray = JArray.Parse(json.SelectToken("dates").ToString());
// If the day has schedule games, add them to the object.
if (scheduleArray.Count > 0)
{
foreach (var game in scheduleArray[0]["games"])
{
Game aGame = new Game(game["gamePk"].ToString());
scheduledGames.Add(aGame);
if (season == "" || season == null)
{
season = aGame.season;
}
}
games = scheduledGames;
}
}
// Constructor with featureFlag denotes that not all data on the schedule downward is being populated (think "Schedule Light")
public Schedule (string gameDate, int featureFlag)
{
string gameDateScheduleURL = NHLAPIServiceURLs.todaysGames + "?date=" + gameDate;
var json = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
totalItems = json["totalItems"].ToString();
totalEvents = json["totalEvents"].ToString();
totalGames = json["totalGames"].ToString();
totalMatches = json["totalMatches"].ToString();
List<Game> scheduledGames = new List<Game>();
var scheduleArray = JArray.Parse(json.SelectToken("dates").ToString());
foreach (var game in scheduleArray[0]["games"])
{
Game aGame = new Game(game["gamePk"].ToString(), featureFlag);
scheduledGames.Add(aGame);
}
games = scheduledGames;
}
public static List<string> GetListOfGameIDs(string scheduleDate)
{
string gameDateScheduleURL = NHLAPIServiceURLs.todaysGames + "?date=" + scheduleDate;
var json = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
List<string> listOfGameIDs = new List<string>();
var scheduleArray = JArray.Parse(json.SelectToken("dates").ToString());
if (scheduleArray.Count > 0)
{
foreach (var game in scheduleArray[0]["games"])
{
listOfGameIDs.Add(game["gamePk"].ToString());
}
}
return listOfGameIDs;
}
public static string[,] GetListOfGameIDsWithMetadata(string scheduleDate)
{
string gameDateScheduleURL = NHLAPIServiceURLs.todaysGames + "?date=" + scheduleDate;
//string[,] returnArray = new string[,]();
var json = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
List<string> listOfGameIDs = new List<string>();
int count = 0;
JObject gameJson = new JObject();
string metadata;
var scheduleArray = JArray.Parse(json.SelectToken("dates").ToString());
string[,] returnArray = new string[Convert.ToInt16(scheduleArray[0]["totalGames"]), 2];
if (scheduleArray.Count > 0)
{
foreach (var game in scheduleArray[0]["games"])
{
// Get the URL for the API call to a specific Game
string theGame = NHLAPIServiceURLs.specificGame;
// Replace placeholder value ("###") in the placeholder URL with the requested GameID.
string gameLink = theGame.Replace("###", game["gamePk"].ToString());
// Execute the API call
gameJson = DataAccessLayer.ExecuteAPICall(gameLink);
returnArray[count, 0] = gameJson.SelectToken("gamePk").ToString();
metadata = "(" + gameJson.SelectToken("gameData.teams.away.name").ToString() + " at " + gameJson.SelectToken("gameData.teams.home.name").ToString() + ")";
returnArray[count, 1] = metadata;
count++;
}
}
return returnArray;
}
public static JObject GetScheduleJson(string scheduleDate)
{
JObject scheduleJson = new JObject();
string gameDateScheduleURL;
if (scheduleDate is null)
{
gameDateScheduleURL = NHLAPIServiceURLs.todaysGames;
}
else
{
gameDateScheduleURL = NHLAPIServiceURLs.todaysGames + "?date=" + scheduleDate;
}
scheduleJson = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
return scheduleJson;
}
public static int GameCount(string scheduleDate)
{
string gameDateScheduleURL = NHLAPIServiceURLs.todaysGames + "?date=" + scheduleDate;
int totalGames;
var json = DataAccessLayer.ExecuteAPICall(gameDateScheduleURL);
if (json.ContainsKey("totalGames"))
totalGames = Convert.ToInt32(json["totalGames"].ToString());
else
totalGames = 0;
return totalGames;
}
public static List<Game> TeamSchedule(string teamId, string season)
{
List<Game> gameList = new List<Game>();
// Create the URL call to get the schedule for the specified team in the specified season
string teamScheduleExtension = NHLAPIServiceURLs.schedule_season_team.Replace("########", season);
teamScheduleExtension = teamScheduleExtension.Replace("@@", teamId);
string teamScheduleURL = NHLAPIServiceURLs.schedule + teamScheduleExtension;
var json = DataAccessLayer.ExecuteAPICall(teamScheduleURL);
var gameListJSON = JArray.Parse(json.SelectToken("dates").ToString());
Game aGame = new Game();
string gameId;
// Check to see if there is a schedule list, if yes then parse through the games.
if (gameListJSON.Count > 0)
{
foreach (var eachGame in gameListJSON)
{
var gameArray = eachGame.SelectToken("games");
gameId = gameArray[0].SelectToken("gamePk").ToString();
aGame = new Game();
// Populate the Game Object
aGame.gameID = gameId;
aGame.season = season;
aGame.gameType = gameArray[0].SelectToken("gameType").ToString();
aGame.gameDate = gameArray[0].SelectToken("gameDate").ToString();
aGame.abstractGameState = gameArray[0].SelectToken("status.abstractGameState").ToString();
aGame.codedGameState = gameArray[0].SelectToken("status.codedGameState").ToString();
aGame.detailedState = gameArray[0].SelectToken("status.detailedState").ToString();
aGame.statusCode = gameArray[0].SelectToken("status.statusCode").ToString();
aGame.homeTeam = new Team(gameArray[0].SelectToken("teams.home.team.id").ToString());
aGame.awayTeam = new Team(gameArray[0].SelectToken("teams.away.team.id").ToString());
if (gameArray[0].SelectToken("venue.id") != null)
aGame.gameVenue = new Venue(gameArray[0].SelectToken("venue.id").ToString());
gameList.Add(aGame);
}
}
return gameList;
}
}
}
|
C++ | UTF-8 | 278 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include "quick_sort.cpp"
using namespace std;
int main()
{
int arr[10] = {
12, 2, 23, 11, 33, 50, 21, 1, 34, 2
};
cout << 10 << endl;
int* j = partion(arr, arr + 9);
cout << j[10] << endl;
}
|
Java | UTF-8 | 4,246 | 2.140625 | 2 | [] | no_license | package cn.com.gome.page.field;
import cn.com.gome.page.core.PageConfig;
import cn.com.gome.page.core.PageService;
import cn.com.gome.page.field.domain.PageDomainProvider;
import cn.com.gome.page.plugins.style.StylePlugin;
import cn.com.gome.page.utils.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
public class DomainStringFieldDefinition extends StringFieldDefinition {
private String domainFieldName = "id";
private PageDomainProvider pageDomainProvider;
public DomainStringFieldDefinition(String fieldName, String description, PageDomainProvider pageDomainProvider) {
super(fieldName, description);
this.pageDomainProvider = pageDomainProvider;
}
public DomainStringFieldDefinition(String fieldName, String description, PageDomainProvider pageDomainProvider, String domainFieldName) {
super(fieldName, description);
this.pageDomainProvider = pageDomainProvider;
this.domainFieldName = domainFieldName;
}
@Override
public String formatColumnValue(PageConfig pageConfig, Object value) {
String id = (String)value;
Object obj = pageDomainProvider.findByReferId(id);
if(obj==null){
return "已被删除";
}
String domainLinkName = (String) BeanUtils.getPropertyValue(obj,pageDomainProvider.getDisplayFieldName());
String domainName = pageDomainProvider.getDomainName();
String domainChineseName = pageDomainProvider.getDomainChineseName();
return String.format("<a style=\"text-decoration:none\" class=\"ml-5 c-primary\" onclick=\"layer_show('%s详细信息','/admin/%s/lay_detail?referId=%s')\" href=\"javascript:;\" title=\"%s\">%s</a>", domainChineseName, domainName, id, id, domainLinkName);
}
@Override
public String generateFormItemReadHtml(PageConfig pageConfig, HttpServletRequest request, Object entity) {
String domainName = pageDomainProvider.getDomainName();
String domainChineseName = pageDomainProvider.getDomainChineseName();
String id = (String) entity;
Object obj = pageDomainProvider.findByReferId(id);
if(obj==null){
return "已删除";
}
String domainLinkName = (String) BeanUtils.getPropertyValue(obj,pageDomainProvider.getDisplayFieldName());
return String.format("<a style=\"text-decoration:none\" class=\"ml-5 c-primary\" onclick=\"layer_show('%s详细信息','/admin/%s/lay_detail?referId=%s')\" href=\"javascript:;\" title=\"%s\">%s</a>", domainChineseName, domainName, id, id, domainLinkName);
}
@Override
public FieldType getFieldType() {
return FieldType.DomainLong;
}
@Override
public String buildSearchFilterHtml(PageService pageService, HttpServletRequest request) {
HashMap<String, String> optionHashMap = new HashMap<>();
for (Object object : pageDomainProvider.findAll()) {
optionHashMap.put(String.valueOf(BeanUtils.getPropertyValue(object,domainFieldName)),String.valueOf(BeanUtils.getPropertyValue(object,pageDomainProvider.getDisplayFieldName())));
}
StylePlugin stylePlugin = pageContext.getStylePlugin();
String selectValue = request.getParameter(fieldName);
return stylePlugin.buildSelectBoxFilterHtml(optionHashMap,fieldName,description,selectValue);
}
@Override
public String generateFormItemHtml(PageService pageService, HttpServletRequest request, Object entity) {
HashMap<String, String> optionHashMap = new HashMap<>();
for (Object object : pageDomainProvider.findAll()) {
optionHashMap.put(String.valueOf(BeanUtils.getPropertyValue(object,domainFieldName)),String.valueOf(BeanUtils.getPropertyValue(object,pageDomainProvider.getDisplayFieldName())));
}
String selectValue = "";
if (entity != null) {
Enum<?> requestValue = (Enum<?>) BeanUtils.getPropertyValue(entity, fieldName);
if(requestValue!=null){
selectValue = requestValue.name();
}
}
return pageContext.getStylePlugin().buildSelectBoxFilterHtml(optionHashMap,fieldName,description,selectValue);
}
}
|
Markdown | UTF-8 | 1,084 | 3.3125 | 3 | [
"MIT"
] | permissive | # anseml 
ANSEML is ANother S-Expression Markup Language inspired by XML format.
The library provides a simple API to work with documents and a tool to convert the document to HTML format.
The document format is pretty straightforward.
- Each ANSEML document has exactly one single root element, which encloses all the other elements.
- Each element may or may not have a set of attributes.
More specifically, the format is following:
```
(:tag-name
attr-map?
body)
```
Where `attr-map?` is an associative array of `{ key value }` pairs,
where `key` is `keyword` and `value` is one of the following _primitives_: `string, integer, float`; and `body` contains zero or more _primitives_ or enclosed elements.
Here are few examples:
```
(:root
{ :id "Root" }
"Here is a number:" 123
"And here is the text:"
(:text
"Some text")
:br
(:text
"Another text"))
```
Note that you don't need to put parenthesis around the element consisting only of a tag-name.
|
C# | UTF-8 | 5,128 | 2.921875 | 3 | [] | no_license | using Matrices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UsefulStaticMethods;
using ActionSet;
namespace SearchAbstractDataTypes
{
[Serializable]
public class SearchNodeAsString
{
//Internal fields
private SearchNode _parentNode = null;
internal SearchNode parentNode
{
get { return this._parentNode; }
set { this._parentNode = value; }
}
//Constructors
internal SearchNodeAsString(SearchNode parentNode)
{
this.parentNode = parentNode;
}
//Internal methods
/// <summary>
/// Returns a string that is essentially a sequence of search node information -
/// this node's parents all list their information in order from start to this node.
/// </summary>
/// <returns></returns>
internal Stack<SearchNodeInformation> deriveSearchTreeUpToThisNodeAsString(SearchNode n)
{
Stack<SearchNodeInformation> solutionStack = buildSearchNodeAsStringStack(n);
return solutionStack;
}
/// <summary>
/// Parses the SearchNode's possibly compound action into a list of chars
/// corresponding to ActionMap's actionChars.
/// </summary>
/// <returns></returns>
internal char[] parseMethodUsedToDeriveNodeToCharArray(SearchNode n)
{
List<ElementaryAction> methodSequence = parseMethodUsedToDeriveNodeToElementaryActionList(n);
char[] actionCharSequence = mapElementaryActionArrayToCharArray(methodSequence.ToArray());
return actionCharSequence;
}
//Private methods
private Stack<CompoundAction> buildCompoundActionStack()
{
if (this.parentNode.parent == null)
return new Stack<CompoundAction>();
else
return fillCompoundActionStack();
}
//database
private Stack<CompoundAction> buildMethodStack(SearchNode expansionLimit)
{
return this.parentNode.behavior.buildMethodStack(expansionLimit);
}
private Stack<SearchNodeInformation> buildSearchNodeAsStringStack(SearchNode n)
{
if (n.parent == null)
return new Stack<SearchNodeInformation>();
else
return fillSearchNodeInformationStack(n);
}
private Stack<CompoundAction> fillCompoundActionStack()
{
Stack<CompoundAction> compoundActionStack = new Stack<CompoundAction>();
SearchNode nextNode = this.parentNode.parent;
while (nextNode.parent != null)
{
compoundActionStack.Push(nextNode.methodUsedToDeriveNodeFromParent);
nextNode = nextNode.parent;
}
return compoundActionStack;
}
private Stack<SearchNodeInformation> fillSearchNodeInformationStack(SearchNode n)
{
Stack<SearchNodeInformation> searchNodeInfoStack = startSearchNodeInfoStack(n);
SearchNode nextNode = n.parent;
do
{
searchNodeInfoStack.Push(new SearchNodeInformation(nextNode));
nextNode = nextNode.parent;
}
while (nextNode != null);
return searchNodeInfoStack;
}
private char[] mapElementaryActionArrayToCharArray(ElementaryAction[] elementaryActionSequence)
{
char[] actionCharSequence = new char[elementaryActionSequence.Length];
int i = 0;
foreach (ElementaryAction elementaryAction in elementaryActionSequence)
{
if (StringMethods.stringsAreTheSame(elementaryAction, ElementaryAction.START))
{
i++;
continue;
}
try
{
actionCharSequence[i] = ActionMap.methodNameToActionCharMap[elementaryAction];
}
catch (Exception)//TODO : figure out what type of exception this should be
{
//catch the possibility that the char is nonsense somehow
continue;
}
i++;
}
return actionCharSequence;
}
/// <summary>
/// Parses the SearchNode's possibly compound action into a list of elementary ones.
/// </summary>
/// <returns></returns>
private List<ElementaryAction> parseMethodUsedToDeriveNodeToElementaryActionList(SearchNode n)
{
return n.methodUsedToDeriveNodeFromParent.parseCompoundMethodIntoElementaryActions();
}
private Stack<SearchNodeInformation> startSearchNodeInfoStack(SearchNode n)
{
Stack<SearchNodeInformation> searchNodeInfoStack = new Stack<SearchNodeInformation>();
searchNodeInfoStack.Push(new SearchNodeInformation(n));
return searchNodeInfoStack;
}
}
}
|
PHP | UTF-8 | 790 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* @author Masaru Yamagishi <m-yamagishi@infiniteloop.co.jp>
* @copyright 2020- Masaru Yamagishi
*/
declare(strict_types=1);
namespace Tests\Bleeding\Console;
use Bleeding\Console\Command;
use Tests\TestCase;
/**
* @package Tests\Bleeding\Console
* @coversDefaultClass \Bleeding\Console\Command
* @immutable
*/
final class CommandTest extends TestCase
{
/**
* @test
* @covers ::__construct
* @covers ::getDefinition
* @covers ::getFunc
*/
public function testConstruct()
{
$command = new Command(
$definition = 'hello',
$func = fn () => true
);
$this->assertInstanceOf(Command::class, $command);
$this->assertSame($definition, $command->getDefinition());
$this->assertSame($func, $command->getFunc());
}
}
|
JavaScript | UTF-8 | 1,163 | 2.734375 | 3 | [
"MIT"
] | permissive | // @flow
const { assert } = require("chai");
const { Memory } = require("../../../lib/interpreter/runtime/values/memory");
const { createAllocator } = require("../../../lib/interpreter/kernel/memory");
describe("kernel - memory management", () => {
const memory = new Memory({ initial: 100 });
describe("memory allocation", () => {
it("should start from NULL and increment", () => {
const size = 8;
const allocator = createAllocator(memory);
const p = allocator.malloc(size);
assert.equal(p.index, size);
const p2 = allocator.malloc(size);
assert.equal(p2.index, size * 2);
});
});
describe("set/get", () => {
it("should get an empty value", () => {
const allocator = createAllocator(memory);
const p = allocator.malloc(8);
const value = allocator.get(p);
assert.equal(value, undefined);
});
it("should get and set a value", () => {
const allocator = createAllocator(memory);
const data = 1;
const p = allocator.malloc(1);
allocator.set(p, data);
const value = allocator.get(p);
assert.equal(value, data);
});
});
});
|
Python | UTF-8 | 3,564 | 3.109375 | 3 | [] | no_license | import time
import cv2
import mss
import numpy as np
from directInput import PressKey, ReleaseKey, W, A, S, D
# Define part of the screen to capture
# GTA V resolution must be 1024x768 and placed at top left of screen.
HEIGHT = 768
WIDTH = 1024
monitor = {'top': 40, 'left': 0, 'width': WIDTH, 'height': HEIGHT}
# Define a gap so that lines corresponding to window edges aren't detected.
window_gap = 10
# Defined as [X,Y] points, rather than [Y,X] as usual with images.
lane_roi_vertices = np.array([[window_gap, HEIGHT-window_gap*4], [window_gap, HEIGHT*2/3], [WIDTH*1/3, HEIGHT*1/3],
[WIDTH*2/3, HEIGHT*1/3], [WIDTH-window_gap, HEIGHT*2/3],
[WIDTH-window_gap, HEIGHT-window_gap*4]], np.int32)
# Blackens out the entire image with the exception of the region of interest specified by polygon vertices.
def img_roi(img, vertices):
# Matrix of zeros with same size as image.
mask = np.zeros_like(img)
# Fill in the region of interest with white (full color).
cv2.fillPoly(mask, vertices, [255, 255, 255])
# Now bitwise AND the image with the given region of interest. Since the mask is white then
# colors are preserved.
masked_img = cv2.bitwise_and(img, mask)
return masked_img
# Draws the lines parametrized by two points in the given image.
def draw_lines_in_img(image, lines):
if lines is not None:
for line in lines:
coords = line[0] # Line format: [[x1,y1,x2,y2]]
cv2.line(image, (coords[0], coords[1]), (coords[2], coords[3]), [0, 255, 0], 4)
# Given lines parametrized by two points, calculates the pair most likely to correspond to a lane.
def get_best_lane(lines):
pass
def process_img(img):
# Convert image to grayscale.
gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Get edges for easier line detection.
edge_img = cv2.Canny(gray_img, 100, 150)
# Keep edges only in region of interest (likely to correspond to lanes). Gets rid of lines corresponding to
# electricity poles, mountains, the horizon, etc.
lane_edges = img_roi(edge_img, [lane_roi_vertices])
# Detect lines and draw them on the original image.
lines = cv2.HoughLinesP(image=lane_edges,
rho=1, # Resolution
theta=np.pi/180, # Resolution
threshold=50,
minLineLength=100,
maxLineGap=15)
draw_lines_in_img(img, lines)
# Calculate which pair (if any) of lines is most likely to correspond to the lane.
# line_l, line_r = get_best_lane(lines)
return img
# Counts down starting from a given time.
def countdown(timer):
for i in list(range(timer))[::-1]:
print(i+1)
time.sleep(1)
def main():
with mss.mss() as sct:
# Count down to give user time to prepare game window.
countdown(2)
while True:
last_time = time.time()
# Get raw pixels from the screen, save it to a numpy array.
img = np.array(sct.grab(monitor))
processed_img = process_img(img)
# Display image.
cv2.imshow('screenshot', processed_img)
print('fps: {0}'.format(1 / (time.time() - last_time)))
# Press "q" to quit (bitwise AND so that CAPS LOCK Q works as well)
k = cv2.waitKey(10) & 0b11111111
if k == ord('q'):
cv2.destroyAllWindows()
break
if __name__ == '__main__':
main() |
Java | UTF-8 | 1,771 | 1.992188 | 2 | [
"CDDL-1.1",
"Apache-2.0",
"CDDL-1.0"
] | permissive | package com.ucar.datalink.manager.core.web.dto.group;
import java.util.Date;
/**
* group视图类.
* Created by csf on 2017/2/22.
*/
public class GroupView {
private Long id;
private String groupName;
private String groupDesc;
private Date createTime;
private Date modifyTime;
private String groupState = "";
private Integer generationId = 0;
private String lastReblanceTime = "";//分组最近一次的Reblance时间
public String getGroupState() {
return groupState;
}
public void setGroupState(String groupState) {
this.groupState = groupState;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDesc() {
return groupDesc;
}
public void setGroupDesc(String groupDesc) {
this.groupDesc = groupDesc;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public Integer getGenerationId() {
return generationId;
}
public void setGenerationId(Integer generationId) {
this.generationId = generationId;
}
public String getLastReblanceTime() {
return lastReblanceTime;
}
public void setLastReblanceTime(String lastReblanceTime) {
this.lastReblanceTime = lastReblanceTime;
}
}
|
Swift | UTF-8 | 2,087 | 2.671875 | 3 | [] | no_license | //
// LoginViewController.swift
// TopWalker
//
// Created by Hassan Amjad on 4/27/21.
//
import UIKit
import Parse
class LoginViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
usernameField.layer.cornerRadius = 15
usernameField.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
usernameField.layer.borderWidth = 1
usernameField.clipsToBounds = true
passwordField.layer.cornerRadius = 15
passwordField.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
passwordField.layer.borderWidth = 1
passwordField.clipsToBounds = true
usernameField.attributedPlaceholder = NSAttributedString(string: "USERNAME",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
passwordField.attributedPlaceholder = NSAttributedString(string: "PASSWORD",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
// Do any additional setup after loading the view.
}
@IBAction func onSignIn(_ sender: Any) {
let username = usernameField.text!
let password = passwordField.text!
PFUser.logInWithUsername(inBackground: username, password: password) { (user, error) in
if user != nil {
self.performSegue(withIdentifier: "loginSegue", sender: nil)
} else{
print("Error: \(error?.localizedDescription)")
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
Markdown | UTF-8 | 19,174 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | # Docker Swarm Tutorial
> **Note:** This tutorial uses Docker Machine to simulate multiple machines on your desktop. There's an easier way to learn swarm mode, and that is using [Play with Docker](http://training.play-with-docker.com/swarm-mode-intro/). This tutorial is preserved for legacy reasons, and also in case you really want to learn to do this on your own machine.
Docker includes swarm mode for natively managing a cluster of Docker Engines called a swarm. You can use the Docker CLI to create a swarm, deploy application services to a swarm, and manage swarm behavior. This tutorial uses [Docker Machine](https://docs.docker.com/machine/) to create multiple nodes on your desktop. If you prefer you can create those nodes in your own cloud or on multiple machines.
> **Important Note**
You don't need to use the Docker CLI to perform these operations. You can use `docker stack deploy --compose-file STACKNAME.yml STACKNAME` instead. For an introduction to using a stack file in a compose file format to deploy an app, check out [Deploying an app to a Swarm](https://github.com/docker/labs/blob/master/beginner/chapters/votingapp.md).
## Preparation
You need to have Docker and Docker Machine installed on your system. [Download Docker](https://docker.com/getdocker) for your platform and install it.
> **Tips:**
>
* If you are using Docker for Mac or Docker for Windows, you already have Docker Machine, as it is installed with those applications. See [Download Docker for Mac](https://docs.docker.com/docker-for-mac/#/download-docker-for-mac) and [Download Docker for Windows](https://docs.docker.com/docker-for-windows/#/download-docker-for-windows) for install options and details on what gets installed.
>
* If you are using Docker for Windows you will need to use the Hyper-V driver for Docker Machine. That will require a bit more set-up. See the [Microsoft Hyper-V driver documentation](https://docs.docker.com/machine/drivers/hyper-v/) for directions on setting it up.
>
* If you are using Docker directly on a Linux system, you will need to [install Docker Machine](https://docs.docker.com/machine/install-machine/) (after installing [Docker Engine](https://docs.docker.com/engine/installation/linux/)).
## Creating the nodes and Swarm
[Docker Machine](https://docs.docker.com/machine/overview/) can be used to:
* Install and run Docker on Mac or Windows
* Provision and manage multiple remote Docker hosts
* Provision Swarm clusters
But it can also be used to create multiple nodes on your local machine. There's a [bash script](https://github.com/docker/labs/blob/master/swarm-mode/beginner-tutorial/swarm-node-vbox-setup.sh) in this repository that does just that and creates a swarm. There's also [a powershell Hyper-V version](https://github.com/docker/labs/blob/master/swarm-mode/beginner-tutorial/swarm-node-hyperv-setup.ps1). On this page we're walking through the bash script, but the steps, aside from set-up, are a basically the same for the Hyper-V version.
This first step creates three machines, and names the machines manager1, manager2, and manager3
```
#!/bin/bash
# Swarm mode using Docker Machine
#This configures the number of workers and managers in the swarm
managers=3
workers=3
# This creates the manager machines
echo "======> Creating $managers manager machines ...";
for node in $(seq 1 $managers);
do
echo "======> Creating manager$node machine ...";
docker-machine create -d virtualbox manager$node;
done
```
This second step creates three more machines, and names them worker1, worker2, and worker3
```
# This create worker machines
echo "======> Creating $workers worker machines ...";
for node in $(seq 1 $workers);
do
echo "======> Creating worker$node machine ...";
docker-machine create -d virtualbox worker$node;
done
# This lists all machines created
docker-machine ls
```
Next you create a swarm by initializing it on the first manager. You do this by using `docker-machine ssh` to run `docker swarm init`
```
# initialize swarm mode and create a manager
echo "======> Initializing first swarm manager ..."
docker-machine ssh manager1 "docker swarm init --listen-addr $(docker-machine ip manager1) --advertise-addr $(docker-machine ip manager1)"
```
Next you get join tokens for managers and workers.
```
# get manager and worker tokens
export manager_token=`docker-machine ssh manager1 "docker swarm join-token manager -q"`
export worker_token=`docker-machine ssh manager1 "docker swarm join-token worker -q"`
```
Then join the other masters to the Swarm
```
for node in $(seq 2 $managers);
do
echo "======> manager$node joining swarm as manager ..."
docker-machine ssh manager$node \
"docker swarm join \
--token $manager_token \
--listen-addr $(docker-machine ip manager$node) \
--advertise-addr $(docker-machine ip manager$node) \
$(docker-machine ip manager1)"
done
```
Finally, add the worker machines and join them to the swarm.
```
# workers join swarm
for node in $(seq 1 $workers);
do
echo "======> worker$node joining swarm as worker ..."
docker-machine ssh worker$node \
"docker swarm join \
--token $worker_token \
--listen-addr $(docker-machine ip worker$node) \
--advertise-addr $(docker-machine ip worker$node) \
$(docker-machine ip manager1):2377"
done
# show members of swarm
docker-machine ssh manager1 "docker node ls"
```
That last line will show you a list of all the nodes, something like this:
```
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
3cq6idpysa53n6a21nqe0924h manager3 Ready Active Reachable
64swze471iu5silg83ls0bdip * manager1 Ready Active Leader
7eljvvg0icxlw20od5f51oq8t manager2 Ready Active Reachable
8awcmkj3sd9nv1pi77i6mdb1i worker1 Ready Active
avu80ol573rzepx8ov80ygzxz worker2 Ready Active
bxn1iivy8w7faeugpep76w50j worker3 Ready Active
```
You can also find all your machines by running
```
$ docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
manager1 - virtualbox Running tcp://192.168.99.100:2376 v17.03.0-ce
manager2 - virtualbox Running tcp://192.168.99.101:2376 v17.03.0-ce
manager3 - virtualbox Running tcp://192.168.99.102:2376 v17.03.0-ce
worker1 - virtualbox Running tcp://192.168.99.103:2376 v17.03.0-ce
worker2 - virtualbox Running tcp://192.168.99.104:2376 v17.03.0-ce
worker3 - virtualbox Running tcp://192.168.99.105:2376 v17.03.0-ce
```
The next step is to create a service and list out the services. This creates a single service called `web` that runs the latest nginx:
```
$ docker-machine ssh manager1 "docker service create -p 80:80 --name web nginx:latest"
$ docker-machine ssh manager1 "docker service ls"
ID NAME REPLICAS IMAGE COMMAND
2x4jsk6313az web 1/1 nginx:latest
```
Now open the machine's IP address in your browser. You can see above manager1 had an IP address of 192.168.99.100

You can actually load any of the node ip addresses and get the same result because of [Swarm Mode's Routing Mesh](https://docs.docker.com/engine/swarm/ingress/).

Next let's inspect the service
```
$ docker-machine ssh manager1 "docker service inspect web"
[
{
"ID": "2x4jsk6313azr6g1dwoi47z8u",
"Version": {
"Index": 104
},
"CreatedAt": "2016-08-23T22:43:23.573253682Z",
"UpdatedAt": "2016-08-23T22:43:23.576157266Z",
"Spec": {
"Name": "web",
"TaskTemplate": {
"ContainerSpec": {
"Image": "nginx:latest"
},
"Resources": {
"Limits": {},
"Reservations": {}
},
"RestartPolicy": {
"Condition": "any",
"MaxAttempts": 0
},
"Placement": {}
},
"Mode": {
"Replicated": {
"Replicas": 1
}
},
"UpdateConfig": {
"Parallelism": 1,
"FailureAction": "pause"
},
"EndpointSpec": {
"Mode": "vip",
"Ports": [
{
"Protocol": "tcp",
"TargetPort": 80,
"PublishedPort": 80
}
]
}
},
"Endpoint": {
"Spec": {
"Mode": "vip",
"Ports": [
{
"Protocol": "tcp",
"TargetPort": 80,
"PublishedPort": 80
}
]
},
"Ports": [
{
"Protocol": "tcp",
"TargetPort": 80,
"PublishedPort": 80
}
],
"VirtualIPs": [
{
"NetworkID": "24r1loluvdohuzltspkwbhsc8",
"Addr": "10.255.0.9/16"
}
]
},
"UpdateStatus": {
"StartedAt": "0001-01-01T00:00:00Z",
"CompletedAt": "0001-01-01T00:00:00Z"
}
}
]
```
That's lots of info! Now, let's scale the service:
```
$ docker-machine ssh manager1 "docker service scale web=15"
web scaled to 15
$ docker-machine ssh manager1 "docker service ls"
ID NAME REPLICAS IMAGE COMMAND
2x4jsk6313az web 15/15 nginx:latest
```
Docker has spread the 15 services evenly over all of the nodes
```
$ docker-machine ssh manager1 "docker service ps web"
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR
61wjx0zaovwtzywwbomnvjo4q web.1 nginx:latest worker3 Running Running 13 minutes ago
bkkujhpbtqab8fyhah06apvca web.2 nginx:latest manager1 Running Running 2 minutes ago
09zkslrkgrvbscv0vfqn2j5dw web.3 nginx:latest manager1 Running Running 2 minutes ago
4dlmy8k72eoza9t4yp9c9pq0w web.4 nginx:latest manager2 Running Running 2 minutes ago
6yqabr8kajx5em2auvfzvi8wi web.5 nginx:latest manager3 Running Running 2 minutes ago
21x7sn82883e7oymz57j75q4q web.6 nginx:latest manager2 Running Running 2 minutes ago
14555mvu3zee6aek4dwonxz3f web.7 nginx:latest worker1 Running Running 2 minutes ago
1q8imt07i564bm90at3r2w198 web.8 nginx:latest manager1 Running Running 2 minutes ago
encwziari9h78ue32v5pjq9jv web.9 nginx:latest worker3 Running Running 2 minutes ago
aivwszsjhhpky43t3x7o8ezz9 web.10 nginx:latest worker2 Running Running 2 minutes ago
457fsqomatl1lgd9qbz2dcqsb web.11 nginx:latest worker1 Running Running 2 minutes ago
7chhofuj4shhqdkwu67512h1b web.12 nginx:latest worker2 Running Running 2 minutes ago
7dynic159wyouch05fyiskrd0 web.13 nginx:latest worker1 Running Running 2 minutes ago
7zg9eki4610maigr1xwrx7zqk web.14 nginx:latest manager3 Running Running 2 minutes ago
4z2c9j20gwsasosvj7mkzlyhc web.15 nginx:latest manager2 Running Running 2 minutes ago
```
You can also drain a particular node, that is remove all services from that node. The services will automatically be rescheduled on other nodes.
```
$ docker-machine ssh manager1 "docker node update --availability drain worker1"
worker1
$ docker-machine ssh manager1 "docker service ps web"
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR
61wjx0zaovwtzywwbomnvjo4q web.1 nginx:latest worker3 Running Running 15 minutes ago
bkkujhpbtqab8fyhah06apvca web.2 nginx:latest manager1 Running Running 4 minutes ago
09zkslrkgrvbscv0vfqn2j5dw web.3 nginx:latest manager1 Running Running 4 minutes ago
4dlmy8k72eoza9t4yp9c9pq0w web.4 nginx:latest manager2 Running Running 4 minutes ago
6yqabr8kajx5em2auvfzvi8wi web.5 nginx:latest manager3 Running Running 4 minutes ago
21x7sn82883e7oymz57j75q4q web.6 nginx:latest manager2 Running Running 4 minutes ago
8so0xi55kqimch2jojfdr13qk web.7 nginx:latest worker3 Running Running 3 seconds ago
14555mvu3zee6aek4dwonxz3f \_ web.7 nginx:latest worker1 Shutdown Shutdown 4 seconds ago
1q8imt07i564bm90at3r2w198 web.8 nginx:latest manager1 Running Running 4 minutes ago
encwziari9h78ue32v5pjq9jv web.9 nginx:latest worker3 Running Running 4 minutes ago
aivwszsjhhpky43t3x7o8ezz9 web.10 nginx:latest worker2 Running Running 4 minutes ago
738jlmoo6tvrkxxar4gbdogzf web.11 nginx:latest worker2 Running Running 3 seconds ago
457fsqomatl1lgd9qbz2dcqsb \_ web.11 nginx:latest worker1 Shutdown Shutdown 3 seconds ago
7chhofuj4shhqdkwu67512h1b web.12 nginx:latest worker2 Running Running 4 minutes ago
4h7zcsktbku7peh4o32mw4948 web.13 nginx:latest manager3 Running Running 3 seconds ago
7dynic159wyouch05fyiskrd0 \_ web.13 nginx:latest worker1 Shutdown Shutdown 4 seconds ago
7zg9eki4610maigr1xwrx7zqk web.14 nginx:latest manager3 Running Running 4 minutes ago
4z2c9j20gwsasosvj7mkzlyhc web.15 nginx:latest manager2 Running Running 4 minutes ago
```
You can check out the nodes and see that `worker1` is still active but drained.
```
$ docker-machine ssh manager1 "docker node ls"
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
3cq6idpysa53n6a21nqe0924h manager3 Ready Active Reachable
64swze471iu5silg83ls0bdip * manager1 Ready Active Leader
7eljvvg0icxlw20od5f51oq8t manager2 Ready Active Reachable
8awcmkj3sd9nv1pi77i6mdb1i worker1 Ready Drain
avu80ol573rzepx8ov80ygzxz worker2 Ready Active
bxn1iivy8w7faeugpep76w50j worker3 Ready Active
```
You can also scale down the service
```
$ docker-machine ssh manager1 "docker service scale web=10"
web scaled to 10
$ docker-machine ssh manager1 "docker service ps web"
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR
61wjx0zaovwtzywwbomnvjo4q web.1 nginx:latest worker3 Running Running 22 minutes ago
bkkujhpbtqab8fyhah06apvca web.2 nginx:latest manager1 Shutdown Shutdown 54 seconds ago
09zkslrkgrvbscv0vfqn2j5dw web.3 nginx:latest manager1 Running Running 11 minutes ago
4dlmy8k72eoza9t4yp9c9pq0w web.4 nginx:latest manager2 Running Running 11 minutes ago
6yqabr8kajx5em2auvfzvi8wi web.5 nginx:latest manager3 Running Running 11 minutes ago
21x7sn82883e7oymz57j75q4q web.6 nginx:latest manager2 Running Running 11 minutes ago
8so0xi55kqimch2jojfdr13qk web.7 nginx:latest worker3 Running Running 7 minutes ago
14555mvu3zee6aek4dwonxz3f \_ web.7 nginx:latest worker1 Shutdown Shutdown 7 minutes ago
1q8imt07i564bm90at3r2w198 web.8 nginx:latest manager1 Running Running 11 minutes ago
encwziari9h78ue32v5pjq9jv web.9 nginx:latest worker3 Shutdown Shutdown 54 seconds ago
aivwszsjhhpky43t3x7o8ezz9 web.10 nginx:latest worker2 Shutdown Shutdown 54 seconds ago
738jlmoo6tvrkxxar4gbdogzf web.11 nginx:latest worker2 Running Running 7 minutes ago
457fsqomatl1lgd9qbz2dcqsb \_ web.11 nginx:latest worker1 Shutdown Shutdown 7 minutes ago
7chhofuj4shhqdkwu67512h1b web.12 nginx:latest worker2 Running Running 11 minutes ago
4h7zcsktbku7peh4o32mw4948 web.13 nginx:latest manager3 Running Running 7 minutes ago
7dynic159wyouch05fyiskrd0 \_ web.13 nginx:latest worker1 Shutdown Shutdown 7 minutes ago
7zg9eki4610maigr1xwrx7zqk web.14 nginx:latest manager3 Shutdown Shutdown 54 seconds ago
4z2c9j20gwsasosvj7mkzlyhc web.15 nginx:latest manager2 Shutdown Shutdown 54 seconds ago
```
Now bring `worker1` back online and show it's new availability
```
$ docker-machine ssh manager1 "docker node update --availability active worker1"
worker1
$ docker-machine ssh manager1 "docker node inspect worker1 --pretty"
ID: 8awcmkj3sd9nv1pi77i6mdb1i
Hostname: worker1
Joined at: 2016-08-23 22:30:15.556517377 +0000 utc
Status:
State: Ready
Availability: Active
Platform:
Operating System: linux
Architecture: x86_64
Resources:
CPUs: 1
Memory: 995.9 MiB
Plugins:
Network: bridge, host, null, overlay
Volume: local
Engine Version: 17.03.0-ce
Engine Labels:
- provider = virtualbox
```
Now let's take the manager1 node, the leader, out of the Swarm
```
$ docker-machine ssh manager1 "docker swarm leave --force"
Node left the swarm.
```
Wait about 30 seconds just to be sure. The Swarm still functions, but must elect a new leader. This happens automatically.
```
$ docker-machine ssh manager2 "docker node ls"
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
3cq6idpysa53n6a21nqe0924h manager3 Ready Active Reachable
64swze471iu5silg83ls0bdip manager1 Down Active Unreachable
7eljvvg0icxlw20od5f51oq8t * manager2 Ready Active Leader
8awcmkj3sd9nv1pi77i6mdb1i worker1 Ready Active
avu80ol573rzepx8ov80ygzxz worker2 Ready Active
bxn1iivy8w7faeugpep76w50j worker3 Ready Active
```
You see that `manager1` is Down and Unreachable and `manager2` has been elected leader. It's also easy to remove a service:
```
$ docker-machine ssh manager2 "docker service rm web"
web
```
## Cleanup
There's also a [bash script](https://github.com/ManoMarks/labs/blob/master/swarm-mode/beginner-tutorial/swarm-node-vbox-teardown.sh) that will clean up your machine by removing all the Docker Machines.
```
$ ./swarm-node-vbox-teardown.sh
Stopping "manager3"...
Stopping "manager2"...
Stopping "worker1"...
Stopping "manager1"...
Stopping "worker3"...
Stopping "worker2"...
Machine "manager3" was stopped.
Machine "manager1" was stopped.
Machine "manager2" was stopped.
Machine "worker2" was stopped.
Machine "worker1" was stopped.
Machine "worker3" was stopped.
About to remove worker1, worker2, worker3, manager1, manager2, manager3
Are you sure? (y/n): y
Successfully removed worker1
Successfully removed worker2
Successfully removed worker3
Successfully removed manager1
Successfully removed manager2
Successfully removed manager3
```
## Next steps
Check out the documentation on [Docker Swarm Mode](https://docs.docker.com/engine/swarm/) for more information.
|
Python | UTF-8 | 2,907 | 3 | 3 | [] | no_license | import torch
import torch.nn as nn
EPS=1e-12
"""
Scale-invariant-SDR (source-to-distortion ratio)
See "SDR - half-baked or well done?"
https://arxiv.org/abs/1811.02508
"""
def sisdr(input, target, eps=EPS):
"""
Scale-invariant-SDR (source-to-distortion ratio)
Args:
input (batch_size, T) or (batch_size, n_sources, T), or (batch_size, n_sources, n_mics, T)
target (batch_size, T) or (batch_size, n_sources, T) or (batch_size, n_sources, n_mics, T)
Returns:
loss (batch_size,) or (batch_size, n_sources) or (batch_size, n_sources, n_mics)
"""
n_dim = input.dim()
assert n_dim in [2, 3, 4], "Only 2D or 3D or 4D tensor is acceptable, but given {}D tensor.".format(n_dim)
alpha = torch.sum(input * target, dim=n_dim-1, keepdim=True) / (torch.sum(target**2, dim=n_dim-1, keepdim=True) + eps)
loss = (torch.sum((alpha * target)**2, dim=n_dim-1) + eps) / (torch.sum((alpha * target - input)**2, dim=n_dim-1) + eps)
loss = 10 * torch.log10(loss)
return loss
class SISDR(nn.Module):
def __init__(self, eps=EPS):
super().__init__()
self.maximize = True
self.eps = eps
def forward(self, input, target, batch_mean=True):
"""
Args:
iinput (batch_size, T) or (batch_size, n_sources, T), or (batch_size, n_sources, n_mics, T)
target (batch_size, T) or (batch_size, n_sources, T) or (batch_size, n_sources, n_mics, T)
Returns:
loss (batch_size,) or (batch_size, n_sources) or (batch_size, n_sources, n_mics)
"""
n_dim = input.dim()
assert n_dim in [2, 3, 4], "Only 2D or 3D or 4D tensor is acceptable, but given {}D tensor.".format(n_dim)
loss = sisdr(input, target, eps=self.eps)
if n_dim == 3:
loss = loss.mean(dim=1)
elif n_dim == 4:
loss = loss.mean(dim=(1,2))
if batch_mean:
loss = loss.mean(dim=0)
return loss
class NegSISDR(nn.Module):
def __init__(self, eps=EPS):
super().__init__()
self.maximize = False
self.eps = eps
def forward(self, input, target, batch_mean=True):
"""
Args:
input (batch_size, T) or (batch_size, C, T)
target (batch_size, T) or (batch_size, C, T)
Returns:
loss (batch_size,)
"""
n_dim = input.dim()
assert n_dim in [2, 3, 4], "Only 2D or 3D or 4D tensor is acceptable, but given {}D tensor.".format(n_dim)
loss = - sisdr(input, target, eps=self.eps)
if n_dim == 3:
loss = loss.mean(dim=1)
elif n_dim == 4:
loss = loss.mean(dim=(1,2))
if batch_mean:
loss = loss.mean(dim=0)
return loss
|
PHP | UTF-8 | 1,474 | 2.671875 | 3 | [
"MIT"
] | permissive | <!DOCTYPE html>
<?php
include 'dbconnection.php';
// configure path to store the photo
$target_path = "flag/";
$target_path = $target_path . basename($_FILES['flag']['name']);
$idC = mysqli_real_escape_string($conn, $_POST['idCountry']);
// update the country to add the flag path
$sqlFlag = "UPDATE country SET flag='{$target_path}' WHERE idCountry={$idC}";
?>
<html>
<head>
<meta charset="UTF-8">
<?php include 'head.php'; ?>
</head>
<body>
<?php include 'banner.php' ?>
<div class="container">
<div class="well">
<?php
// if move to target path is successful and query successfully done display message
if (move_uploaded_file($_FILES["flag"]["tmp_name"], $target_path) && mysqli_query($conn,$sqlFlag)) {
?>
<h3> Flag successfully added. Check it out <a href="country.php?idC=<?php echo $idC ?>"> here </a> </h3>
<?php
} else {
?>
<h3> Oops! We are sorry, something went wrong. Please try again a bit later. <a href="index.php"> Back home </a> </h3>
<?php } ?>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js" />
<script src="js/bootstrap.min.js" />
</html>
<?php
mysqli_close($conn);
?> |
JavaScript | UTF-8 | 396 | 2.65625 | 3 | [] | no_license | /**
* Created by lekanterragon on 6/29/17.
*/
var
data1 = [
['', 'First Name', 'Last Name', 'Email'],
['2012', 10, 11, 12]
],
container1 = document.getElementById('example'),
settings1 = {
data: data1
},
hot1;
hot1 = new Handsontable(container1, settings1);
data1[0][1] = 'First Name'; // change "Kia" to "Ford" programmatically
hot1.render();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.