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
|
---|---|---|---|---|---|---|---|
TypeScript
|
UTF-8
| 573 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
export class ResultHolder {
constructor(readonly encryptedText: string, readonly keyhash: string, readonly toleranceDistance?: number, readonly salt?: Uint8Array, readonly iv?: Uint8Array) {
}
public getEncryptedText(): string {
return this.encryptedText
}
public getKeyHash(): string {
return this.keyhash
}
public getToleranceDistance(): number {
return this.toleranceDistance
}
public getSalt(): Uint8Array {
return this.salt
}
public getIV(): Uint8Array {
return this.iv
}
}
|
C++
|
GB18030
| 1,196 | 2.53125 | 3 |
[] |
no_license
|
/******************************************************************************
Ȩ (C), 2013 - 2014, Ĵʤɷ˾
ļ: wcmd.h
ߡ:
:1.0
ڡ:2013/05/22
: ҪWCmdӿ
:
******************************************************************************/
#ifndef _WCMD_H_
#define _WCMD_H_
#include "../wdllimport.h"
/**
\brief һij
\details 罫ijƶȻŴȣһϵвΪһA
AһWCmdʵԽ棬ҪʱִвAҲ͵ȼ
һϵв
ԴWCmdFactoryͨ㲻ҪԼʵWCmd࣬WCmdFactoryͿ
ɴֵWCmdĹ
\author
\date 2013/05/22
*/
class MAPAPI WCmd
{
public:
virtual ~WCmd() {}
/**
\brief exec
\Access virtual public
\retval void
\remark ִд˲
*/
virtual void exec() = 0;
};
#endif
|
Shell
|
UTF-8
| 1,357 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash -e
# Usage `./install_golang.sh && source ~/.bash_profile`
GO_VERSION=1.10.1
PECO_VERSION=v0.5.3
GO_URL=https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz
install_gvm() {
echo ""
}
install_golang() {
wget -O - ${GO_URL} | sudo tar zxC /usr/local
cp ./.bash.d/go.sh ${HOME}/.bash.d/
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
}
go_get_packages() {
go get golang.org/x/tools/cmd/godoc
# go get golang.org/x/tools/cmd/gorename
# go get golang.org/x/tools/cmd/guru
# go get github.com/golang/lint/golint
go get github.com/motemen/gore
go get github.com/motemen/ghq
echo "[ghq]" >> ~/.gitconfig
echo " root = ${HOME}/ghq" >> ~/.gitconfig
# go get github.com/nsf/gocode
# go get github.com/rogpeppe/godef
# go get github.com/jstemmer/gotags
# go get github.com/k0kubun/pp
# go get github.com/pilu/fresh
# go get github.com/github/hub
wget -O - https://github.com/peco/peco/releases/download/${PECO_VERSION}/peco_linux_amd64.tar.gz | tar zxf - -C /tmp/
cp /tmp/peco_linux_amd64/peco ${GOPATH}/bin/
}
install_vim_go() {
~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
git clone https://github.com/fatih/vim-go.git ~/.vim/plugged/vim-go
}
# install_gvm
install_golang
go_get_packages
install_vim_go
go version
|
PHP
|
UTF-8
| 2,449 | 2.53125 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: Brad
* Date: 5/22/14
* Time: 10:43 PM
*/
function getFriendBoothsSQL($pageUser, $pageNum, $howMany)
{
if ($_SESSION['username'] == $pageUser) {
$sql = "SELECT b.`fkUsername`, b.`pkNumber`, b.`blurb`, b.`datetime`, b.`imageTitle`, b.`filetype`, b.`imageHeightProp`
FROM `boothnumbers` b
WHERE b.`fkUsername` IN (
SELECT `fkFriendname` FROM `friendstbl`
WHERE lower(`fkUsername`) = '" . $pageUser . "')
AND ('" . $pageUser . "' IN (
SELECT `fkFriendname` FROM `friendstbl`
WHERE `fkUsername` = b.`fkUsername`)
OR b.`fkUsername` IN (SELECT `fkUsername` FROM `usersprivacytbl` WHERE (privacyDescriptor = 'public' OR privacyDescriptor = 'semi-public'))
)
ORDER BY b.`pkNumber` DESC LIMIT " . ($howMany * ($pageNum - 1)) . ", ".$howMany.";";
return $sql;
} else {
//select the people who are this persons friend AND either my friend OR public
$sql = "SELECT b.`fkUsername`, b.`pkNumber`, b.`blurb`, b.`datetime`, b.`imageTitle`, b.`filetype`, b.`imageHeightProp`
FROM `boothnumbers` b
WHERE b.`fkUsername` IN (SELECT `fkFriendname` FROM `friendstbl` WHERE lower(`fkUsername`) = '" . $pageUser . "')
AND '" . $pageUser . "' IN (SELECT `fkFriendname` FROM `friendstbl` WHERE `fkUsername` = b.`fkUsername`)
AND ('" . $_SESSION['username'] . "' IN (SELECT `fkFriendname` FROM `friendstbl` WHERE `fkUsername` = b.`fkUsername`)
OR (b.`fkUsername` IN (SELECT `fkUsername` FROM `userspublictbl`)
AND (b.fkUsername IN (SELECT `fkUsername` FROM `usersprivacytbl` WHERE `fkUsername` = b.`fkUsername` AND (privacyDescriptor = 'public' OR privacyDescriptor = 'semi-public') LIMIT 1)))
ORDER BY b.`pkNumber` DESC LIMIT " . ($howMany * ($pageNum - 1)) . ", ".$howMany.";";
return $sql;
}
}
|
Markdown
|
UTF-8
| 634 | 2.828125 | 3 |
[] |
no_license
|
# mi_card
A mini project that shows user's personal card. For this project, I used Educaree informartion. Educaree is a starting company which I work on, and it made me excited to its card, even though it is not an official app.
## Getting Started
To run this app, everything you have to do is to clone it, open it on an IDE (I recommend Android Studio) and get the dependencies (aka assets). Then, compile it either into your phone or into the virtual phone provided by Android Studio. That's it! Educaree's card is ready to be displayed.

|
TypeScript
|
UTF-8
| 452 | 3 | 3 |
[] |
no_license
|
export class HttpResponseError {
constructor(status? : number, errorMessage? : string, errorDescription? : string) {
this.status = status;
this.errorMessage = errorMessage;
this.errorDescription = errorDescription;
}
public status : number;
public errorMessage : string;
public errorDescription : string;
public priority : Priority;
}
enum Priority {
Top = 1,
High = 2,
Mid = 3,
Low = 4
}
|
JavaScript
|
UTF-8
| 2,355 | 2.703125 | 3 |
[] |
no_license
|
import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'
import mongoose from 'mongoose'
import listEndpoints from 'express-list-endpoints'
import designers from './data/designers.json'
dotenv.config()
// Mongoose set up
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.Promise = Promise
// Mongoose schema to match the keys from the json
const Designer = mongoose.model('Designer', {
name: {
type: String,
lowercase: true
},
surname: {
type: String,
lowercase: true
},
wasBorn: Number,
memberOfChambreSyndicaleDeLaHauteCouture: Boolean
})
// Seeding the database from the json
if (process.env.RESET_DB) {
const seedDB = async () => {
await Designer.deleteMany()
await designers.forEach(item => {
new Designer(item).save()
})
}
seedDB()
}
// Defining the port the app will run on
const port = process.env.PORT || 8080
const app = express()
// Middlewares to enable cors and json body parsing
app.use(cors())
app.use(express.json())
// Routes
// First page API page with possible endpoints
// https://designers-api.herokuapp.com/
app.get('/', (req, res) => {
res.send(listEndpoints(app))
})
// Endpoint to get all the designers
// https://designers-api.herokuapp.com/designers
app.get('/designers', async (req, res) => {
const designers = await Designer.find()
res.json(designers)
})
// Endpoint to get designer by ID
// E.g https://designers-api.herokuapp.com/designers/609fa52d1dafed06ad8dda19
app.get('/designers/:designerId', async (req, res) => {
const { designerId } = req.params
const singleDesigner = await Designer.findById(designerId)
res.json(singleDesigner)
})
// Endpoint to get designer by name
// E.g https://designers-api.herokuapp.com/designers/name/vivienne
app.get('/designers/name/:designerName', async (req, res) => {
const { designerName } = req.params
try {
const singleDesigner = await Designer.findOne({ name: designerName })
res.json(singleDesigner)
} catch (error) {
res.status(400).json({ error: 'Something went wrong', details: error })
}
})
// Starting the server
app.listen(port, () => {
// eslint-disable-next-line
console.log(`Server running on http://localhost:${port}`)
})
|
JavaScript
|
UTF-8
| 543 | 3.34375 | 3 |
[] |
no_license
|
let DateObject = new Date(),
currentDay = (DateObject.getDate() + 1 < 10)? `0${DateObject.getDate() + 1}`: DateObject.getDate() + 1,
currentMonth = (DateObject.getMonth() + 1 < 10)? `0${DateObject.getMonth() + 1}`: DateObject.getMonth() + 1,
currentYear = DateObject.getFullYear();
console.log(`${currentMonth}-${currentDay}-${currentYear}`);
console.log(`${currentMonth}/${currentDay}/${currentYear}`);
console.log(`${currentDay}-${currentMonth}-${currentYear}`);
console.log(`${currentDay}/${currentMonth}/${currentYear}`);
|
C++
|
GB18030
| 910 | 3.6875 | 4 |
[] |
no_license
|
#include<iostream>
#include<cstdio>
/*
A^Bλʾ
˵A^BĺǡABη
Input
ݰʵÿʵռһУABɣ1<=A,B<=10000A=0, B=0ʾݵĽ
Output
ÿʵA^BλʾÿռһС
Sample Input
2 3
12 6
6789 10000
0 0
Sample Output
8
984
1
*/
using namespace std;
const int mod=1000; //λȡģ1000
int QuickPower(int x,int n){
int answer = 1;
while(n!=0){
if(n%2==1){
answer*=x;
answer%=mod;
}
n/=2;
x*=x;
x%=mod;
}
return answer;
}
int main(){
int a,b;
while(scanf("%d%d",&a,&b)!=EOF){
if(a==0&&b==0)break;
printf("%d\n",QuickPower(a,b));
}
return 0;
}
|
Java
|
UTF-8
| 2,356 | 2.75 | 3 |
[] |
no_license
|
package org.geogebra.common.kernel.geos;
import org.geogebra.common.kernel.Construction;
import org.geogebra.common.media.MediaFormat;
import org.geogebra.common.media.MediaURLParser;
/**
* Class for representing playable media data.
*
* @author laszlo
*
*/
public abstract class GeoMedia extends GeoWidget {
/** Source of the media, available for subclasses too */
protected String src;
private MediaFormat format;
/**
* Constructs a new, empty media element.
*
* @param c
* the construction.
*/
public GeoMedia(Construction c) {
super(c);
app = getKernel().getApplication();
}
/**
* Constructs a new media element with given content.
*
* @param c
* the construction.
* @param url
* the media URL.
* @param format
* {@link MediaFormat}
*/
public GeoMedia(Construction c, String url, MediaFormat format) {
this(c);
setSrc(url, format);
}
@Override
public boolean showInAlgebraView() {
return false;
}
/**
*
* @return the source of the media.
*/
public String getSrc() {
return src;
}
/**
* Set the source and call changed handler.
*
* @param src
* to set.
* @param format
* {@link MediaFormat}
*/
public void setSrc(String src, MediaFormat format) {
this.format = format;
this.src = src;
onSourceChanged();
}
/**
* Set the source and call changed handler.
*
* @param src
* to set.
* @param formatStr
* format string representation.
*/
public void setSrc(final String src, String formatStr) {
MediaFormat fmt = MediaFormat.get(formatStr);
if (fmt == MediaFormat.NONE) {
fmt = MediaURLParser.checkVideo(src).getFormat();
}
setSrc(src, fmt);
}
/**
* Called after source has changed.
*/
protected abstract void onSourceChanged();
/**
* @return the duration in seconds.
*/
public abstract int getDuration();
/**
* @return the time where media play is at.
*/
public abstract int getCurrentTime();
/**
* Sets the current position to a given time in seconds.
*
* @param secs
* to set.
*/
public abstract void setCurrentTime(int secs);
/**
*
* @return the media format.
*/
public MediaFormat getFormat() {
return format;
}
@Override
public boolean isPinnable() {
return true;
}
}
|
Markdown
|
UTF-8
| 2,082 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
---
title: Agaður vilji
date: 02/08/2022
---
Einn versti óvinur vilja okkar eru tilfinningar okkar. Í síauknum mæli búum við í menningarumhverfi sem er fullt af myndum og tónlist sem geta haft bein áhrif á skynfæri okkar og vakið tilfinningar okkar – reiði, ótta eða girnd – án þess að við gerum okkur grein fyrir því. Oft hugsum við sem svo: „Hvað langar mig að borða í kvöldmat?“ „Hvað langar mig að gera í dag?“ eða „Ætti ég að kaupa þetta?“ Þannig eiga tilfinningarnar ríkan þátt í ákvörðunum okkar. Tilfinningar okkar eru ekki endilega slæmar en hvað okkur finnst um eitt eða annað kann að hafa lítið með það að gera hvort eitthvað sé rétt eða best. Reyndar geta tilfinningarnar blekkt okkur („Svikult er hjartað framar öllu öðru“ [Jer 17.9]) og skapað falska mynd af raunveruleikanum og fengið okkur til að velja eitthvað slæmt og skapað okkar eigin eldraun.
`Hvaða dæmi úr Biblíunni getur þú bent á um fólk sem valdi á grundvelli tilfinninganna fremur en orði Guðs? Hverjar voru afleiðingarnar? Sjá t.d. 1Mós 3.6; 2Sam 11.2-4 og Gal 2.11, 12.`
`Lestu 1Pét 1.13. Hverju hefur Pétur áhyggjur af og hvað vill hann að lesendur hans geri?`
Pétur skildi vel að hugurinn er stýrið sem við stjórnum líkamanum með. Ef við missum stjórn á huganum erum við á valdi hvaða tilfinninga sem upp kunna að koma í huga okkar.
Ímyndaðu þér að þú sért á leiðinni heim til hirðisins. Á leiðinni ferð þú fram hjá mörgum vegum sem liggja í ýmsar áttir. Sumir þeirra liggja til staða sem þú vilt ekki heimsækja. Aðrir eru freistandi, þeir skírskota til tilfinninga okkar, tilfinningalífs og langana. En ef við förum einhvern þeirra, hverfum við af réttri braut og förum leið sem gæti verið mjög erfitt að komast af.
`Hvaða mikilvægu ákvörðunum stendur þú frammi fyrir? Hugleiddu í einlægni hvernig þú getir vitað hvort þú byggir val þitt á tilfinningum eða löngunum í stað þess að byggja á orði Guðs?`
|
Java
|
UTF-8
| 1,857 | 1.671875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.springdoc.core;
import org.springdoc.api.ActuatorProvider;
import org.springdoc.api.MultipleOpenApiResource;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import java.util.List;
import java.util.Optional;
import static org.springdoc.core.Constants.SPRINGDOC_ENABLED;
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnBean(GroupedOpenApi.class)
@ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
public class MultipleOpenApiSupportConfiguration {
@Bean
public MultipleOpenApiResource multipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis,
ObjectFactory<OpenAPIBuilder> defaultOpenAPIBuilder, AbstractRequestBuilder requestBuilder,
AbstractResponseBuilder responseBuilder, OperationBuilder operationParser,
RequestMappingInfoHandlerMapping requestMappingHandlerMapping,
Optional<ActuatorProvider> servletContextProvider) {
return new MultipleOpenApiResource(groupedOpenApis,
defaultOpenAPIBuilder, requestBuilder,
responseBuilder, operationParser,
requestMappingHandlerMapping, servletContextProvider);
}
}
|
Java
|
UTF-8
| 826 | 2.109375 | 2 |
[] |
no_license
|
package com.wearezeta.auto.web.pages;
import com.wearezeta.auto.common.driver.DriverUtils;
import com.wearezeta.auto.common.driver.ZetaWebAppDriver;
import com.wearezeta.auto.web.locators.WebAppLocators;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.util.concurrent.Future;
public class HistoryInfoPage extends WebPage {
@FindBy(css = WebAppLocators.HistoryInfoPage.cssConfirmButton)
private WebElement confirmButton;
public HistoryInfoPage(Future<ZetaWebAppDriver> lazyDriver) throws Exception {
super(lazyDriver);
}
public boolean isConfirmButtonVisible() throws Exception {
return DriverUtils.waitUntilElementClickable(getDriver(), confirmButton);
}
public void clickConfirmButton() {
confirmButton.click();
}
}
|
Java
|
UTF-8
| 262 | 2.1875 | 2 |
[] |
no_license
|
public class Constructor_2_3_18 {
public Constructor_2_3_18 (){
System.out.println("yes constructor");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Constructor_2_3_18 obj =new Constructor_2_3_18();
}
}
|
C++
|
UTF-8
| 6,038 | 2.65625 | 3 |
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// --------------------------------------------------------------------------
// BcastClasses.cpp
// --------------------------------------------------------------------------
// this file tests functions to broadcast and serialize classes.
// --------------------------------------------------------------------------
#include <iostream>
#include <fstream>
#include <AMReX_BoxArray.H>
#include <AMReX_MultiFab.H>
#include <AMReX_ParallelDescriptor.H>
#include <AMReX_Utility.H>
using std::cout;
using std::endl;
// --------------------------------------------------------------------------
int main(int argc, char *argv[]) {
amrex::Initialize(argc, argv);
bool bIOP(amrex::ParallelDescriptor::IOProcessor());
int myProc(amrex::ParallelDescriptor::MyProc());
int ioProcNum(amrex::ParallelDescriptor::IOProcessorNumber());
amrex::Box bControl(amrex::IntVect(0,0,0), amrex::IntVect(63,63,63));
amrex::Box bBcast;
// Broadcast Bool Test -------------------------------------------
// Set bools to wrong value on all but IOProc
bool testT = false;
bool testF = true;
if(bIOP) {
testT = true;
testF = false;
}
amrex::BroadcastBool(testT, myProc, ioProcNum, amrex::ParallelDescriptor::CommunicatorAll());
amrex::BroadcastBool(testF, myProc, ioProcNum, amrex::ParallelDescriptor::CommunicatorAll());
amrex::USleep(myProc/10.0);
cout << myProc << ":: testT = " << testT << endl;
cout << myProc << ":: testF = " << testF << endl << endl;
if ((testT != true) || (testF != false)) {
cout << myProc << ":: **** Error: bad bool Bcast; testT testF = "
<< testT << " " << testF << endl;
}
// BroadcastBox Test ---------------------------------------------
amrex::Vector<int> aSB;
if(bIOP) {
aSB = amrex::SerializeBox(bControl);
}
amrex::BroadcastArray(aSB, myProc, ioProcNum, amrex::ParallelDescriptor::CommunicatorAll());
amrex::ParallelDescriptor::Barrier();
amrex::USleep(myProc/10.0);
for(int i(0); i < aSB.size(); ++i) {
cout << myProc << ":: aSB[" << i << "] = " << aSB[i] << endl;
}
amrex::Box uSB = amrex::UnSerializeBox(aSB);
amrex::ParallelDescriptor::Barrier();
amrex::USleep(myProc/10.0);
cout << myProc << ":: uSB = " << uSB << endl;
// BroadcastBoxArray Test -----------------------------------------
amrex::ParallelDescriptor::Barrier();
amrex::BoxArray baControl(bControl);
baControl.maxSize(32);
amrex::BoxArray baBcast;
if(bIOP) {
baBcast = baControl;
cout << "baBcast = " << baBcast << endl;
}
amrex::Vector<int> aBASerial;
if(bIOP) {
aBASerial = amrex::SerializeBoxArray(baControl);
for(int i(0); i < aSB.size(); ++i) {
cout << myProc << ":: aBASerial[" << i << "] = " << aBASerial[i] << endl;
}
}
amrex::ParallelDescriptor::Barrier();
amrex::BroadcastBoxArray(baBcast, myProc, ioProcNum,
amrex::ParallelDescriptor::CommunicatorAll());
amrex::ParallelDescriptor::Barrier();
amrex::USleep(myProc/10.0);
cout << myProc << ":: baBcast = " << baBcast << endl;
if(baBcast != baControl) {
cout << myProc << ":: **** Error: bad BoxArrayBroadcast: baBcast baControl = "
<< baBcast << " " << baControl << endl;
}
amrex::ParallelDescriptor::Barrier();
if(bIOP) {
cout << endl;
}
// BroadcastString Test -----------------------------------------
amrex::ParallelDescriptor::Barrier();
std::string strTest("");
std::string strControl("This is a string test.");
if(bIOP) {
strTest = strControl;
cout << "strTest = " << strTest << endl;
}
amrex::ParallelDescriptor::Barrier();
amrex::BroadcastString(strTest, myProc, ioProcNum,
amrex::ParallelDescriptor::CommunicatorAll());
amrex::ParallelDescriptor::Barrier();
amrex::USleep(myProc/10.0);
cout << myProc << ":: strTest = " << strTest << endl;
if(strTest != strControl) {
cout << myProc << ":: **** Error: bad BroadcastString: strTest strControl = "
<< strTest << " " << strControl << endl;
}
amrex::ParallelDescriptor::Barrier();
if(bIOP) {
cout << endl;
}
// BroadcastStringArray Test -----------------------------------------
amrex::ParallelDescriptor::Barrier();
amrex::Vector<std::string> strArrayTest;
amrex::Vector<std::string> strArrayControl;
strArrayControl.resize(5);
strArrayControl[0] = "This is a string array test.";
strArrayControl[1] = "Do not adjust your Linux settings.";
strArrayControl[2] = "AMReX is in control.";
strArrayControl[3] = "We are in control of the Regridding,";
strArrayControl[4] = "and the LoadBalancing.";
if(bIOP) {
strArrayTest = strArrayControl;
for(int i(0); i<strArrayTest.size(); ++i)
{
cout << strArrayTest[i] << endl;
}
}
amrex::ParallelDescriptor::Barrier();
amrex::BroadcastStringArray(strArrayTest, myProc, ioProcNum,
amrex::ParallelDescriptor::CommunicatorAll());
amrex::ParallelDescriptor::Barrier();
amrex::USleep(myProc/10.0);
for(int i(0); i<strArrayTest.size(); ++i)
{
cout << myProc << ":: strArrayTest[i] =" << strArrayTest[i] << endl;
}
if(strArrayTest != strArrayControl) {
cout << myProc << ":: **** Error: bad strArrayBroadcast: strArrayTest strArrayControl";
}
/*
if( ! fba.ok()) {
amrex::Error("BoxArray is not OK");
}
if( ! fba.isDisjoint()) {
amrex::Error("BoxArray is not disjoint");
}
fba.maxSize(32);
if(bIOP) {
std::cout << "number of grids in fba: " << fba.size() << '\n';
}
*/
amrex::Finalize();
return 0;
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
|
Python
|
UTF-8
| 58 | 3.453125 | 3 |
[] |
no_license
|
str=input("enter the string")
str1=str[1::2]
print(str1)
|
Java
|
UTF-8
| 299 | 2.453125 | 2 |
[] |
no_license
|
/**
*file driver_proj0.java
*author: Garrett Meyer
*course: CMPT 220
*assignment: project 0
*due date: September 6
*version: 1.8
*
*The file "driver_proj0" contains the words hello and world
*/
public class driver_proj0{
public static void main (String[] args){
System.out.println("Hello World!");
}
}
|
C#
|
UTF-8
| 4,912 | 2.6875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ExpenseMonitor.Helpers;
namespace ExpenseMonitor
{
public partial class frmDescription : Form
{
public frmDescription()
{
InitializeComponent();
}
private void frmCategory_Load(object sender, EventArgs e)
{
this.CenterToParent();
try
{
loadUI();
}
catch(Exception exception)
{
Helper.showMessage("Unable to load all values properly. \n\n " + exception.ToString());
}
}
private void loadUI()
{
refreshCategories();
}
private void refreshCategories()
{
try
{
datagridCategories.AutoGenerateColumns = false;
datagridCategories.DataSource = CategoryHelper.getCategories();
datagridCategories.Refresh();
}
catch (Exception ex)
{
Logger.LogException(ex);
Helper.showMessage("Categories could not retrieved from database");
}
}
private void datagridCategories_SelectionChanged(object sender, EventArgs e)
{
DataRowView row = getCurrentSelectedCategoryFromGrid();
if ( row!=null )
{
txtCategory.Text = row["description"].ToString();
}
}
private bool deleteCategory()
{
DataRowView row = getCurrentSelectedCategoryFromGrid();
if (row != null)
{
if (CategoryHelper.deleteCategory(row["description"].ToString())==0)
{
return false;
}
}
return true;
}
private DataRowView getCurrentSelectedCategoryFromGrid()
{
DataRowView row = null;
if (datagridCategories.RowCount > 0 && datagridCategories.CurrentRow != null && datagridCategories.CurrentRow.DataBoundItem != null)
{
if (datagridCategories.CurrentRow.DataBoundItem is DataRowView)
{
row = (DataRowView)datagridCategories.CurrentRow.DataBoundItem;
}
}
return row;
}
private void addCategory()
{
if (validateForm())
{
if (CategoryHelper.checkAndAddCategory(txtCategory.Text))
{
refreshCategories();
}
else
{
Helper.showMessage("Category exists already");
txtCategory.Focus();
}
}
}
private bool validateForm()
{
if (txtCategory.Text.Trim().Length < 1)
{
Helper.showMessage("Category Name is required");
txtCategory.Focus();
return false;
}
return true;
}
private void btnAddCategory_Click(object sender, EventArgs e)
{
addCategory();
}
private void btnModify_Click(object sender, EventArgs e)
{
modifyCategory();
}
private bool modifyCategory()
{
if (validateForm())
{
DataRowView row = getCurrentSelectedCategoryFromGrid();
if (row == null)
{
Helper.showMessage("Select a category to modify");
return false;
}
else
{
int id = int.Parse(row["id"].ToString());
if (CategoryHelper.modifyCategory(txtCategory.Text, id))
{
refreshCategories();
return true;
}
else
{
Helper.showMessage("Unable to modify category");
}
}
}
return false;
}
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to delete the category?", "Expense Monitor Message", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
if (!deleteCategory())
{
Helper.showMessage("Category could not be deleted as this category is used in some Expense item");
}
}
refreshCategories();
}
}
}
|
Java
|
UTF-8
| 359 | 1.976563 | 2 |
[] |
no_license
|
package com.neuedu.hismedicalsystem.model.mapper;
import com.neuedu.hismedicalsystem.model.po.Dept;
import java.util.List;
public interface DeptMapper {
public List<Dept> getDepts(Dept condition);
public void delDept(String deptcode);
public void addDept(Dept dept);
public void updateDept(Dept dept);
List<Dept> getDeptSelect();
}
|
Java
|
UTF-8
| 102 | 1.71875 | 2 |
[] |
no_license
|
package net.ilbay.listener;
public interface ConfirmationDialogListener {
public void confirmed();
}
|
SQL
|
UTF-8
| 874 | 3.078125 | 3 |
[] |
no_license
|
-- +migrate Up
CREATE TABLE IF NOT EXISTS `auto_orders` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `through` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `orders_1` (
`id` int(10) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS `orders_2` (
`id` int(10) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS `orders_3` (
`id` int(10) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
);
-- +migrate Down
DROP TABLE IF EXISTS `auto_orders`;
DROP TABLE IF EXISTS `through`;
DROP TABLE IF EXISTS `orders_1`;
DROP TABLE IF EXISTS `orders_2`;
DROP TABLE IF EXISTS `orders_3`;
|
PHP
|
UTF-8
| 2,205 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace Inkweb\ModuleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Inkweb\EleveBundle\Entity\Eleve;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Note
*
* @ORM\Table(name="note")
* @ORM\Entity(repositoryClass="Inkweb\ModuleBundle\Repository\NoteRepository")
*/
class Note
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="note", type="decimal", precision=2, scale=0)
* @Assert\Range(
* min = 0,
* max = 20,
* minMessage = "Vous devez saisir une valeur supérieur à 0",
* maxMessage = "Vous devez saisir une valeur inférieur ou égale à 20"
* )
*/
private $note;
/**
* @ORM\ManyToOne(targetEntity="Inkweb\ModuleBundle\Entity\Evaluation",inversedBy="notes",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $evaluation;
/**
* @ORM\ManyToOne(targetEntity="Inkweb\EleveBundle\Entity\Eleve",inversedBy="notes",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $eleve;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set note
*
* @param string $note
*
* @return Note
*/
public function setNote($note)
{
$this->note = $note;
return $this;
}
/**
* Get note
*
* @return string
*/
public function getNote()
{
return $this->note;
}
/**
* Set Evaluation
*/
public function setEvaluation(Evaluation $evaluation)
{
$this->evaluation = $evaluation;
return $this;
}
/**
* Get Evaluation
*/
public function getEvaluation()
{
return $this->evaluation;
}
/**
* Set Eleve
*/
public function setEleve(Eleve $eleve)
{
$this->eleve = $eleve;
return $this;
}
/**
* Get Eleve
*/
public function getEleve()
{
return $this->eleve;
}
}
|
Python
|
UTF-8
| 308 | 2.9375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
n,k = map(int, input().split())
bp = []
for i in range(30):
bp.append(1/2**i)
res = 0
for i in range(1,n+1):
if i>=k:
res += 1/n
continue
x = i
cnt = 0
while x<k:
x *= 2
cnt += 1
res += bp[cnt]/n
print("{:.12f}".format(res))
|
Java
|
UTF-8
| 3,496 | 1.804688 | 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.gridgain.poc.tasks;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.gridgain.poc.framework.worker.task.AbstractTxTask;
import org.gridgain.poc.framework.worker.task.PocTesterArguments;
import org.gridgain.poc.framework.worker.task.TaskProperties;
import org.gridgain.poc.framework.worker.task.utils.TxPair;
import org.gridgain.poc.framework.exceptions.TestFailedException;
import org.gridgain.poc.framework.model.SampleObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Runs put and get
*/
public class PutGetCacheTask extends AbstractTxTask {
/** */
private static final Logger LOG = LogManager.getLogger(PutGetCacheTask.class.getName());
/**
*
* @param args Arguments.
* @param props Task properties.
*/
public PutGetCacheTask(PocTesterArguments args, TaskProperties props){
super(args, props);
}
/** {@inheritDoc} */
@Override public void body0() throws TestFailedException {
if (!waitIfStopFlag("pauseTX"))
return;
txLenCalcMode = TxLenCalcMode.PREDEFINED;
txLenNum = 1;
List<TxPair> pairList = getPairList(putGetProbArr, false);
TxPair pair = pairList.get(0);
long key0 = pair.getKey0();
long key1 = pair.getKey1();
String cacheName0 = pair.getCacheName0();
String cacheName1 = pair.getCacheName1();
SampleObject val = (SampleObject)ignite().cache(cacheName0).get(key0);
if(val == null)
LOG.error(String.format("Failed to find value for key %d in cache %s. Make sure all data was loaded properly.",
key0, cacheName0));
try {
ignite().cache(cacheName1).put(key1, val);
}
catch (Exception e) {
LOG.error("Unexpected error occurs.", e);
try {
Thread.sleep(1000L);
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
/** {@inheritDoc} */
@Override protected void addPropsToMap(TaskProperties props) {
super.addPropsToMap(props);
Map<String, String> hdrMap = (Map<String, String>) propMap.get("headersMap");
hdrMap.put("unit", "entry");
hdrMap.put("data", "latency");
hdrMap.put("ops", "operations");
propMap.put("reportDir", "eventstore");
}
/** {@inheritDoc} */
@Override protected Object getLock() {
return PutGetCacheTask.class;
}
/** {@inheritDoc} */
@Override protected Callable<TxInfo> getTxBody() {
return null;
}
}
|
Java
|
UTF-8
| 4,068 | 2.96875 | 3 |
[] |
no_license
|
package pl;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
// Glowna klasa. Rozszerza klase Application, dlatego Java FX wie, ze ma jej uzywac.
public class GlownaKlasa extends Application {
// Musimy nadpisac metode stary z klasy Application, aby wskazac JavieFX miejsce rozpoczecia dzialania.
@Override
public void start(Stage glownaScena) {
// Ustawienie tytulu
glownaScena.setTitle("Moja aplikacja");
GridPane kratka = new GridPane();
// ustawienie parametrow kratki
kratka.setAlignment(Pos.CENTER);
kratka.setHgap(10);
kratka.setVgap(10);
kratka.setPadding(new Insets(25, 25, 25, 25));
Scene scena = new Scene(kratka, 300, 300);
glownaScena.setScene(scena);
Text glownyTekst = new Text("Witaj! Podaj nazwe i haslo!");
// Ustawienie rozmiaru czcionki.
glownyTekst.setFont(Font.font(20));
// Tutaj jest pokazane jak dzialaja indeksy: https://docs.oracle
// .com/javase/8/javafx/get-started-tutorial/img/login_gridlines_co.png
kratka.add(glownyTekst, 0, 0, 2, 1);
Label nazwaUzytkownika = new Label("Nazwa uzytkownika:");
// Dodanie "Labelu" nazwaUzytkownika do kratki. Na pierwszym miejscu (0) jest numer kolumny, na drugim (1),
// jest nazwa wiersza.
kratka.add(nazwaUzytkownika, 0, 1);
TextField tekstNazwaUzytkownika = new TextField();
// Dodanie elementu do kratki (rodzica) w odpowiednim miejscu (kolumna 1, wiersz 1).
kratka.add(tekstNazwaUzytkownika, 1, 1);
Label haslo = new Label("Haslo:");
// Dodanie "Labelu" haslo do kratki na odpowiedniej pozycji (kolumna 0, wiersz 2).
kratka.add(haslo, 0, 2);
// Stowrzenie komponentu z wpisywaniem hasla.
PasswordField poleHasla = new PasswordField();
kratka.add(poleHasla, 1, 2);
Button przyciskLogowania = new Button("Zaloguj!");
kratka.add(przyciskLogowania, 1, 4);
// Ustawinie akcji. Tutaj definiujemy co sie stanie, jak ktos kliknie na przycisk.
przyciskLogowania.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent interakcjaUzytkownika) {
if (SerwisUzytkownikow.czyUdaloSieZalogowac(tekstNazwaUzytkownika.getText(), poleHasla.getText())) {
OknoPoZalogowaniu.pokazOknoPoZalogowaniu();
} else {
Alert blad = new Alert(Alert.AlertType.ERROR, "Nie udalo sie zalogowac. Sprawdz nazwe i/lub " +
"haslo.");
// pokaz okienko z bledem
blad.show();
}
}
});
Button przyciskRejestracij = new Button("Zarejestruj");
kratka.add(przyciskRejestracij, 0, 4);
przyciskRejestracij.setOnAction(klikniecie -> OknoRejestracji.pokazOknoRejestracji());
// Tutaj zdefiniowano co sie stanie, gdy klikniemy prawym przyciskiem myszy w obszarze 'GridPane'
kratka.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent klikniecie) {
// Jezeli kliknieto prawym przyciskiem myszy
if (klikniecie.getButton().equals(MouseButton.SECONDARY)) {
MenuRozwijane.pokazMenuROzwijane(klikniecie, kratka);
}
}
});
glownaScena.show();
}
// Tutaj uruchamiamy aplikacje.
public static void main(String[] args) {
launch(args);
}
}
|
Java
|
UTF-8
| 2,568 | 2.578125 | 3 |
[] |
no_license
|
package service.impl;
import dao.impl.HibernateGameDAO;
import dao.impl.HibernateReviewDAO;
import dao.interf.GameDAO;
import dao.interf.ReviewDAO;
import dao.interf.UserDAO;
import model.Game;
import model.Review;
import model.User;
import service.interf.ServiceUser;
import java.util.ArrayList;
import java.util.stream.Collector;
import static service.TransactionRunner.run;
public class ServiceUserimpl implements ServiceUser {
private UserDAO userDAO;
private GameDAO gameDAO;
private ReviewDAO reviewDAO;
public ServiceUserimpl(UserDAO userDAO){
this.userDAO = userDAO;
this.gameDAO = new HibernateGameDAO();
this.reviewDAO = new HibernateReviewDAO();
}
@Override
public User searchUser(Long id) {
return run(()-> {return this.userDAO.recover(id);});
}
//Lo guarda en la Base
@Override
public void createUser(User user) {
run(()->{this.userDAO.save(user);});
}
@Override
public User searchByName(String name) {
return run(()->{return this.userDAO.searchByName(name);});
}
@Override
public void reviewGame(Long userID, String review, Integer stars, Long gameID, String urlImage) {
run(()->{
Review newReview = new Review();
newReview.setDescription(review);
newReview.setStar(stars);
User userRecover = userDAO.recover(userID);
userRecover.addReview(newReview);
userDAO.update(userRecover);
Game gameRecover = gameDAO.recover(gameID);
gameRecover.addReview(newReview);
gameDAO.update(gameRecover);
});
}
@Override
public void deleteReview(Long userID, Long gameID) {
run(()->{
User userRecover = userDAO.recover(userID);
Game gameRecover = gameDAO.recover(gameID);
Review review = userRecover.getMyReviews().stream().filter(review1 -> review1.getUser().equals(userRecover) && review1.getGame().equals(gameRecover))
.findAny()
.orElse(null);
userRecover.removeReview(review);
gameRecover.removeReview(review);
gameDAO.update(gameRecover);
userDAO.update(userRecover);
});
}
@Override
public void changeProfilePhoto(Long userID, String photo) {
run(()->{
User userRecover = userDAO.recover(userID);
userRecover.setPhoto(photo);
userDAO.update(userRecover);
});
}
}
|
Python
|
UTF-8
| 1,375 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
"""
created by huash06 at 2015-04-27 09:51
Sort a linked list using insertion sort.
"""
__author__ = 'huash06'
import sys
import os
import datetime
import functools
import itertools
import collections
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head:
return None
helper = ListNode(-1000000)
last = helper
node = head
maxval = -1000000
minval = 1000000
while node:
nn = node.next
if node.val <= minval:
minval = node.val
node.next = helper.next
helper.next= node
if last == helper:
last = node
maxval = node.val
elif node.val >= maxval:
maxval = node.val
node.next = None
last.next = node
last = node
else:
h = helper
while h.next and h.next.val < node.val:
h = h.next
hn = h.next
h.next = node
node.next = hn
node = nn
return helper.next
|
Ruby
|
UTF-8
| 426 | 2.828125 | 3 |
[] |
no_license
|
require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
puts "Exercise 5"
puts "----------"
# Your code goes here ...
total_rev = Store.sum(:annual_revenue)
puts total_rev
total_avg_rev = Store.average(:annual_revenue)
puts total_avg_rev
total_over_mil = Store.where("annual_revenue >= ?", 1000000).count
puts total_over_mil
|
Markdown
|
UTF-8
| 900 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
layout: blog_full_layout
title: Lori Now
category: who
image:
---
I studied painting at Pratt Institute and have worked in special effects and animation in the commercial art world. My art inspires me to create innovative lessons and techniques, teaching that art is about growing through the process, not only about producing a product. Additionally, I enjoy collaborating on projects: some recent collaborations included set design and digital art.
As a parent, I bring a unique perspective and depth of experience to my interactions with families. Being in a blended and racially mixed family, makes me sensitive to issues of diversity and students of color. I also know first hand the challenges and issues parents deal with on a daily basis. In addition to art, I have a love of nature and my family has a large garden where we raise chickens. I enjoy hiking and love visiting new places.
|
JavaScript
|
UTF-8
| 3,149 | 2.59375 | 3 |
[] |
no_license
|
import React from 'react'
import {
Text,
View,
Platform,
StatusBar,
StyleSheet,
ImageBackground,
ActivityIndicator,
KeyboardAvoidingView
} from 'react-native'
import SearchInput from './src/components/SearchInput'
import { fetchLocationId, fetchWeather } from './src/utils/api'
import getWeatherImage from './src/utils/getWeatherImage'
export default class App extends React.Component {
state = {
text: '',
location: '',
location: '',
temperature: 0,
weather: '',
loading: false,
error: false
}
componentDidMount () {
this._handleUpdateLocation("San Francisco")
}
_handleChangeText = text => this.setState({ text })
_handleSubmit = () => {
const { text } = this.state
if ( !text ) return
this._handleUpdateLocation( text )
this.setState({ text: '' })
}
_handleUpdateLocation = async city => {
try {
this.setState({ loading: true })
const locationId = await fetchLocationId( city )
const { location, temperature, weather } = await fetchWeather( locationId )
this.setState({
location,
temperature,
weather,
loading: false,
error: false
})
} catch (error) {
this.setState({
loading: false,
error: true
})
}
}
render() {
const { text, location, temperature, weather, loading, error } = this.state
return (
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
>
<StatusBar barStyle="light-content" />
<ImageBackground
source={getWeatherImage( weather )}
style={styles.imageContainer}
>
{
loading
? <ActivityIndicator color="white" size="large"/>
: (error
? <Text style={[styles.smallText, styles.textStyle]}>
Could not load weather, please try a different
city.
</Text>
: <View>
<Text style={[styles.largeText, styles.textStyle]}>
{ location }
</Text>
<Text style={[styles.smallText, styles.textStyle]}>
{ weather }
</Text>
<Text style={[styles.largeText, styles.textStyle]}>
{ Math.round(temperature) }º
</Text>
</View>
)
}
<SearchInput
placeholder="Search any city"
handleChangeText={ this._handleChangeText }
value={ text }
onSubmit={ this._handleSubmit }
/>
</ImageBackground>
</KeyboardAvoidingView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
largeText: {
fontSize: 44,
},
smallText: {
fontSize: 18
},
textStyle: {
textAlign: 'center',
fontFamily: Platform.OS === 'ios' ? 'AvenirNext-Regular' : 'Roboto',
color: 'white'
},
imageContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}
})
|
Java
|
UTF-8
| 1,813 | 2.21875 | 2 |
[] |
no_license
|
/* Copyright (C) Atos Worldline
$Id$
$Log$*/
package net.atos.odc.techforum.app.model;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SessionDto {
private long id;
private List<String> presenters;
private List<String> users;
private String name;
private String imageUrl;
private String description;
private String roomNumber;
private String timeSlot;
private List<PresenterDto> presenterDtos;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<String> getPresenters() {
return presenters;
}
public void setPresenters(List<String> presenters) {
this.presenters = presenters;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public String getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(String timeSlot) {
this.timeSlot = timeSlot;
}
public List<PresenterDto> getPresenterDtos() {
return presenterDtos;
}
public void setPresenterDtos(List<PresenterDto> presenterDtos) {
this.presenterDtos = presenterDtos;
}
}
|
Java
|
UTF-8
| 275 | 2.140625 | 2 |
[] |
no_license
|
package org.huigod.server.common;
/**
* 配置解析异常类
*/
public class ConfigurationException extends Exception{
public ConfigurationException(String msg) {
super(msg);
}
public ConfigurationException(String msg,Exception e) {
super(msg, e);
}
}
|
Java
|
UTF-8
| 11,938 | 2.0625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* Copyright 2015-2016 - CNRS (Centre National de Recherche Scientifique)
*
* 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 fr.univnantes.termsuite.test.unit.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import fr.univnantes.termsuite.engines.splitter.CompoundUtils;
import fr.univnantes.termsuite.model.Component;
import fr.univnantes.termsuite.model.Word;
import fr.univnantes.termsuite.model.WordBuilder;
public class CompoundUtilsSpec {
Word w_ab;
Word w_abcd;
Word w_abcdef;
Word w_abcdefgh;
Component ab, cd, ef, gh;
@Before
public void setUp() {
w_abcdefgh = new WordBuilder()
.setLemma("abcdefgg")
.addComponent(0, 2, "ab", "aa")
.addComponent(2, 4, "cd", "cc")
.addComponent(4, 6, "ef", "ee")
.addComponent(6, 8, "gg", "gg")
.create();
ab = w_abcdefgh.getComponents().get(0);
cd = w_abcdefgh.getComponents().get(1);
ef = w_abcdefgh.getComponents().get(2);
gh = w_abcdefgh.getComponents().get(3);
w_ab = new WordBuilder()
.setLemma("aa")
.addComponent(0, 2, "aa", "aa")
.create();
w_abcd = new WordBuilder()
.setLemma("abcc")
.addComponent(0, 2, "ab", "aa")
.addComponent(2, 4, "cc", "cc")
.create();
w_abcdef = new WordBuilder()
.setLemma("abcdee")
.addComponent(0, 2, "ab", "aa")
.addComponent(2, 4, "cd", "cc")
.addComponent(4, 6, "ee", "ee")
.create();
}
@Test
public void testMerge() {
/* nbComponents = 1*/
Component m_ab = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ab));
assertThat(m_ab.getBegin()).isEqualTo(0);
assertThat(m_ab.getEnd()).isEqualTo(2);
assertThat(m_ab.getLemma()).isEqualTo("aa");
Component m_cd = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(cd));
assertThat(m_cd.getBegin()).isEqualTo(2);
assertThat(m_cd.getEnd()).isEqualTo(4);
assertThat(m_cd.getLemma()).isEqualTo("cc");
Component m_ef = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ef));
assertThat(m_ef.getBegin()).isEqualTo(4);
assertThat(m_ef.getEnd()).isEqualTo(6);
assertThat(m_ef.getLemma()).isEqualTo("ee");
Component m_gh = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(gh));
assertThat(m_gh.getBegin()).isEqualTo(6);
assertThat(m_gh.getEnd()).isEqualTo(8);
assertThat(m_gh.getLemma()).isEqualTo("gg");
/* nbComponents = 2*/
Component m_abcd = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ab, cd));
assertThat(m_abcd.getBegin()).isEqualTo(0);
assertThat(m_abcd.getEnd()).isEqualTo(4);
assertThat(m_abcd.getLemma()).isEqualTo("abcc");
Component m_cdef = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(cd, ef));
assertThat(m_cdef.getBegin()).isEqualTo(2);
assertThat(m_cdef.getEnd()).isEqualTo(6);
assertThat(m_cdef.getLemma()).isEqualTo("cdee");
Component m_efgh = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ef, gh));
assertThat(m_efgh.getBegin()).isEqualTo(4);
assertThat(m_efgh.getEnd()).isEqualTo(8);
assertThat(m_efgh.getLemma()).isEqualTo("efgg");
/* nbComponents = 3*/
Component m_abcdef = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ab, cd, ef));
assertThat(m_abcdef.getBegin()).isEqualTo(0);
assertThat(m_abcdef.getEnd()).isEqualTo(6);
assertThat(m_abcdef.getLemma()).isEqualTo("abcdee");
Component m_cdefgh = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(cd, ef, gh));
assertThat(m_cdefgh.getBegin()).isEqualTo(2);
assertThat(m_cdefgh.getEnd()).isEqualTo(8);
assertThat(m_cdefgh.getLemma()).isEqualTo("cdefgg");
/* nbComponents = 4*/
Component m_abcdefgh = CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ab, cd, ef, gh));
assertThat(m_abcdefgh.getBegin()).isEqualTo(0);
assertThat(m_abcdefgh.getEnd()).isEqualTo(8);
assertThat(m_abcdefgh.getLemma()).isEqualTo("abcdefgg");
}
@Test
public void testHorizontalAxis() {
Word horizontalAxis = new WordBuilder()
.setLemma("horizontal-axis")
.addComponent(0, 7, "horizon", "horizon")
.addComponent(7, 10, "tal", "t")
.addComponent(11, 15, "axis", "axis")
.create();
assertThat(CompoundUtils.innerComponentPairs(horizontalAxis))
.extracting("element1.lemma", "element2.lemma")
.contains(
tuple("horizon","t"),
tuple("horizon","axis"),
tuple("t","axis"),
tuple("horizont","axis"),
tuple("horizon","tal-axis")
)
.hasSize(5)
;
}
@Test
public void testMergeWithEmptyList() {
try {
CompoundUtils.merge(w_abcdefgh, new ArrayList<Component>());
fail("Should have thrown Exception");
} catch(Exception e) {
assertThat(e)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot merge an empty set of component");
}
}
@Test
public void testMergeWithNonConsecutiveComponents() {
Word w = new WordBuilder()
.setLemma("homme-grenouille")
.addComponent(0, 5, "homme")
.addComponent(6, 16, "grenouille")
.create();
Component merged = CompoundUtils.merge(w, w.getComponents());
assertThat(merged.getBegin()).isEqualTo(0);
assertThat(merged.getEnd()).isEqualTo(16);
assertThat(merged.getLemma()).isEqualTo("homme-grenouille");
}
@Test
public void testMergeWithOverlappingComponents() {
try {
CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ab, new Component(1, 3, "titi")));
fail("Should have thrown Exception");
} catch(Exception e) {
assertThat(e)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot merge two components if they overlap. Got [0,2] followed by [1,3].");
}
}
@Test
public void testMergeWithBadComponentIndexes() {
/* Case 1, the bad component is the last one */
try {
CompoundUtils.merge(w_abcdefgh, ImmutableList.of(ef, new Component(6, 9, "tata")));
fail("Should have thrown Exception");
} catch(Exception e) {
assertThat(e)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Component tata does not belong to word Word{lemma=abcdefgg, isCompound=true} (length=8), because offsets [6,9] are too big.");
}
/* Case 2, the bad component is not the last one */
try {
CompoundUtils.merge(w_abcdefgh, ImmutableList.of(cd, new Component(4, 9, "toto", "toto"), new Component(9, 12, "tata")));
fail("Should have thrown Exception");
} catch(Exception e) {
assertThat(e)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Component toto does not belong to word Word{lemma=abcdefgg, isCompound=true} (length=8), because offsets [4,9] are too big.");
}
}
@Test
public void testAllSizeComponents() {
/* 1 component only */
assertThat(CompoundUtils.allSizeComponents(w_ab))
.hasSize(1)
.extracting("begin", "end", "lemma")
.contains(tuple(0,2,"aa"));
/* 2 components */
assertThat(CompoundUtils.allSizeComponents(w_abcd))
.hasSize(3)
.extracting("begin", "end", "lemma")
.contains(
tuple(0,2,"aa"),
tuple(2,4,"cc"),
tuple(0,4,"abcc")
);
/* 4 components */
assertThat(CompoundUtils.allSizeComponents(w_abcdefgh))
.hasSize(10)
.extracting("begin", "end", "lemma")
.contains(
tuple(0,2,"aa"),
tuple(2,4,"cc"),
tuple(4,6,"ee"),
tuple(6,8,"gg"),
tuple(0,4,"abcc"),
tuple(2,6,"cdee"),
tuple(4,8,"efgg"),
tuple(0,6,"abcdee"),
tuple(2,8,"cdefgg"),
tuple(0,8,"abcdefgg")
);
}
@Test
public void testInnerContiguousComponentPairs() {
assertThat(CompoundUtils.innerContiguousComponentPairs(w_ab))
.hasSize(0);
assertThat(CompoundUtils.innerContiguousComponentPairs(w_abcd))
.hasSize(1)
.extracting("element1.lemma", "element2.lemma")
.contains(
tuple("aa","cc"));
assertThat(CompoundUtils.innerContiguousComponentPairs(w_abcdef))
.hasSize(2)
.extracting("element1.lemma", "element2.lemma")
.contains(
tuple("aa","cdee"),
tuple("abcc","ee"));
assertThat(CompoundUtils.innerContiguousComponentPairs(w_abcdefgh))
.hasSize(3)
.extracting("element1.lemma", "element2.lemma")
.contains(
tuple("aa","cdefgg"),
tuple("abcc","efgg"),
tuple("abcdee","gg"));
}
@Test
public void testGetPossibleComponentsAt() {
/*
* ab
*/
assertThat(CompoundUtils.getPossibleComponentsAt(w_ab, 0))
.hasSize(0);
/*
* abcd
*/
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcd, 0))
.extracting("lemma")
.hasSize(1)
.contains("aa");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcd, 1))
.extracting("lemma")
.hasSize(1)
.contains("cc");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcd, 2))
.hasSize(0);
/*
* abcdef
*/
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdef, 0))
.extracting("lemma")
.hasSize(2)
.contains("aa", "abcc");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdef, 1))
.extracting("lemma")
.hasSize(3)
.contains("cc", "cdee", "ee");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdef, 2))
.extracting("lemma")
.hasSize(1)
.contains("ee");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdef, 3))
.hasSize(0);
/*
* abcdefgh
*/
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdefgh, 0))
.extracting("lemma")
.hasSize(3)
.contains("aa", "abcc", "abcdee");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdefgh, 1))
.extracting("lemma")
.hasSize(6)
.contains("cc", "cdee", "cdefgg", "ee", "efgg", "gg");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdefgh, 2))
.extracting("lemma")
.hasSize(3)
.contains("ee", "efgg", "gg");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdefgh, 3))
.extracting("lemma")
.hasSize(1)
.contains("gg");
assertThat(CompoundUtils.getPossibleComponentsAt(w_abcdefgh, 4))
.hasSize(0);
}
@Test
public void testInnerComponentPairs() {
assertThat(CompoundUtils.innerComponentPairs(w_ab))
.hasSize(0);
assertThat(CompoundUtils.innerComponentPairs(w_abcd))
.hasSize(1)
.extracting("element1.lemma", "element2.lemma")
.contains(tuple("aa","cc"));
assertThat(CompoundUtils.innerComponentPairs(w_abcdef))
.hasSize(5)
.extracting("element1.lemma", "element2.lemma")
.contains(
tuple("aa","cc"),
tuple("aa","ee"),
tuple("cc","ee"),
tuple("aa","cdee"),
tuple("abcc","ee")
);
assertThat(CompoundUtils.innerComponentPairs(w_abcdefgh))
.hasSize(15)
.extracting("element1.lemma", "element2.lemma")
.contains(
tuple("aa","cc"),
tuple("aa","ee"),
tuple("aa","gg"),
tuple("aa","cdee"),
tuple("aa","efgg"),
tuple("aa","cdefgg"),
tuple("abcc","ee"),
tuple("abcc","gg"),
tuple("abcc","efgg"),
tuple("abcdee","gg"),
tuple("cc","ee"),
tuple("cc","gg"),
tuple("cc","efgg"),
tuple("cdee","gg"),
tuple("ee","gg")
);
}
}
|
Ruby
|
UTF-8
| 4,698 | 2.9375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'date'
require 'optparse'
require 'shellwords'
class GitHubContributionsArtDrawer
class << self
def run!(args)
new(args).run!
end
end
def initialize(args)
@args = args
@input = STDIN
@output = STDOUT
@names = Deque.new
@emails = Deque.new
@messages = Deque.new
end
def run!
parse_args!
load_defaults!
read_input!
validate_input!
write_output!
end
private
def parse_args!
parser = OptionParser.new do |o|
o.banner = 'Usage:'
o.separator " #{$0} [options]"
o.separator ''
o.separator 'Options:'
w = ->(s) do
s.lstrip.lines.map.with_index do |line, idx|
idx > 0 ? ' ' * 37 + line.strip : line.strip
end.join("\n") + "\n\n"
end
h = <<-EOT
Set input file.
Default: STDIN.
EOT
o.on('-i INPUT', '--input=INPUT', w.(h)) do |v|
@input = File.open(v, 'r')
end
h = <<-EOT
Set output file.
Default: STDOUT.
EOT
o.on('-o OUTPUT', '--output=OUTPUT', w.(h)) do |v|
@output = File.open(v, 'w')
end
h = <<-EOT
Set GIT_AUTHOR_NAME & GIT_COMMITTER_NAME.
Allows multiple values.
Default: `No One`.
EOT
o.on('-n NAME', '--name=NAME', w.(h)) do |v|
@names.values << v
end
h = <<-EOT
Set email for GIT_AUTHOR_EMAIL & GIT_COMMITTER_EMAIL.
Allows multiple values.
Default: `example@example.org`.
EOT
o.on('-e EMAIL', '--email=EMAIL', w.(h)) do |v|
@emails.values << v
end
h = <<-EOT
Set commit message.
Allows multiple values.
If prefixed with @, it will threat the argument as a file.
Default: `@commit_messages.txt`.
EOT
o.on('-m MESSAGE', '--message=MESSAGE', w.(h)) do |v|
if v.start_with?('@')
@messages.values = File.read(v[1..-1]).lines.map(&:chomp)
else
@messages.values << v
end
end
o.on_tail('-h', '--help', 'Print this message and exit.') do
puts o
exit
end
end
@args = parser.parse!(@args)
rescue OptionParser::InvalidOption => e
STDERR.puts "#{$0}: #{e}"
STDERR.puts
STDERR.puts parser
exit
end
def load_defaults!
@names.values << 'No One' if @names.values.empty?
@emails.values << 'example@example.org' if @emails.values.empty?
@messages.values = File.read(File.expand_path('../commit_messages.txt', __FILE__)).lines.map(&:chomp) if @messages.values.empty?
end
def read_input!
@source = @input.read
@source = @source.lines.map{ |line| line.strip.gsub('|', '').chars }
end
def validate_input!
raise 'source should not contain more than 7 lines' if @source.length > 7
raise 'source lines differ in length' if @source.map(&:length).uniq.length != 1
raise 'source contains lines longer than 52 chars' if @source.map.any?{ |line| line.length > 54 }
rescue RuntimeError => e
STDERR.puts "#{$0}: #{e}"
exit
end
def write_output!
@output.puts '#!/bin/sh'
@output.puts
@output.puts 'git add .'
@output.puts
today = Date.today
end_of_last_week = today - today.wday
beginning_of_graph_year = end_of_last_week - 52 * 7
@source.each_with_index do |line, line_idx|
line.each_with_index do |char, char_idx|
count = char.to_i(36)
if count > 0
count.times do |minute|
name = @names.next
email = @emails.next
message = @messages.next
date = beginning_of_graph_year + char_idx * 7 + line_idx
minute = '%02d' % minute
s = []
s << "GIT_AUTHOR_DATE=#{date.to_s}\\ 10:#{minute}:00"
s << "GIT_COMMITTER_DATE=#{date.to_s}\\ 10:#{minute}:00"
s << "GIT_AUTHOR_NAME=#{Shellwords.escape(name)}"
s << "GIT_COMMITTER_NAME=#{Shellwords.escape(name)}"
s << "GIT_AUTHOR_EMAIL=#{Shellwords.escape(email)}"
s << "GIT_COMMITTER_EMAIL=#{Shellwords.escape(email)}"
s << "git commit --allow-empty --allow-empty-message -m #{Shellwords.escape(message)}"
@output.puts(s.join(' '))
end
@output.puts
end
end
end
end
class Deque
attr_accessor :values, :index
def initialize(values = [], index = 0)
@values, @index = values, index
end
def next
if @index >= @values.length
@index = 0
end
result = @values[@index]
@index += 1
result
end
end
end
if $0 == __FILE__
GitHubContributionsArtDrawer.run!(ARGV)
end
|
Java
|
UTF-8
| 383 | 2.34375 | 2 |
[] |
no_license
|
package com.example.manuel.mvptest.main;
/**
* Defines the contract between the View (MainActivity)
* and the Presenter (MainPresenter)
*/
public interface MainContract {
interface MvpView{
void showSignInScreen();
void showSignUpScreen();
}
interface Presenter{
void handleSignInButtonClick();
void handleSignUpButtonClick();
}
}
|
Java
|
UTF-8
| 605 | 1.960938 | 2 |
[] |
no_license
|
package com.cryolite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Phone phone = context.getBean(Phone.class);
phone.config();
}
}
|
Java
|
UTF-8
| 9,833 | 1.992188 | 2 |
[] |
no_license
|
/* Copyright Header Check */
/* -------------------------------------------------------------------- */
/* */
/* OCO Source Materials */
/* */
/* Product(s): PROFIT */
/* */
/* (C)Copyright IBM Corp. 2001-2004 */
/* */
/* All Rights Reserved */
/* US Government Users Restricted Rigts */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the US Copyright Office. */
/* */
/* -------------------------------------------------------------------- */
/* Please do not remove any of these commented lines 20 lines */
/* -------------------------------------------------------------------- */
/* Copyright Footer Check */
package oem.edge.ets.fe.documents.data;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Enumeration;
import java.util.ResourceBundle;
import oem.edge.common.DbConnect;
import oem.edge.common.Global;
import oem.edge.ets.fe.ETSDoc;
import oem.edge.ets.fe.ETSDocEditHistory;
import oem.edge.ets.fe.documents.common.StringUtil;
import org.apache.log4j.Logger;
/**
* This is the DATA ACCESS Class for the E&TS Documents Module
* @author v2srikau
*/
public class DocumentEJBDAO {
/** Stores the Logging object */
private Logger m_pdLog = Logger.getLogger(DocumentEJBDAO.class);
/** Stores the Connection Object */
private Connection m_pdConnection = null;
/**
* @throws Exception
*/
public void prepare() throws Exception {
Connection pdConn = getDBConnection();
setConnection(pdConn);
}
/**
* Closes and releases a connection
*/
public void cleanup() throws SQLException {
if (m_pdConnection != null && !m_pdConnection.isClosed()) {
m_pdConnection.close();
}
m_pdConnection = null;
}
/**
* @return
*/
public Connection getConnection() {
return m_pdConnection;
}
/**
* @param connection
*/
public void setConnection(Connection pdConnection) {
m_pdConnection = pdConnection;
}
/*
Gets a new connection object.
*/
public static Connection getDBConnection() throws SQLException, Exception {
Connection connection = null;
DbConnect db = null;
try {
if (!Global.loaded) {
Global.Init();
}
db = new DbConnect();
db.makeConn(getDataSource());
connection = db.conn;
} catch (SQLException e) {
if (e.getCause() != null) {
e.getCause().printStackTrace(System.err);
}
e.printStackTrace();
throw e;
} catch (Exception ex) {
if (ex.getCause() != null) {
ex.getCause().printStackTrace(System.err);
}
ex.printStackTrace();
throw ex;
}
return connection;
}
/**
* @return
* @throws Exception
*/
private static String getDataSource() throws Exception {
String sDataSource = "";
try {
ResourceBundle rb =
ResourceBundle.getBundle("oem.edge.ets.fe.ets");
if (rb == null) {
sDataSource = "etsds";
return sDataSource;
}
Enumeration e = rb.getKeys();
sDataSource = rb.getString("ets.datasource");
if (sDataSource == null || sDataSource.trim().equals("")) {
sDataSource = "etsds";
} else {
sDataSource = sDataSource.trim();
}
} catch (Exception e) {
throw e;
}
return sDataSource;
}
/**
* @param iDocID
* @param strDocFileName
* @param iDocSize
* @param pdInStream
* @return
* @throws SQLException In case of SQL Errors
*/
public synchronized boolean addDocFile(
int iDocID,
String strDocFileName,
int iDocSize,
InputStream pdInStream,
String strFileDescription,
String strFileStatus)
throws SQLException {
boolean bSuccess = false;
try {
int iNewDocFileID = getNewDocFileID(iDocID);
PreparedStatement stmtInsDocFile =
m_pdConnection.prepareStatement(
"insert into ets.ets_docfile("
+ "doc_id,docfile_id,docfile_name,docfile,"
+ "docfile_size,docfile_update_date," +
"file_description,file_status) "
+ "values(?,?,?,?,?,current timestamp,?,?)");
stmtInsDocFile.setInt(1, iDocID);
stmtInsDocFile.setInt(2, iNewDocFileID);
stmtInsDocFile.setString(3, strDocFileName);
if (pdInStream != null) {
stmtInsDocFile.setBinaryStream(4, pdInStream, iDocSize);
} else {
stmtInsDocFile.setNull(4, Types.BLOB);
}
stmtInsDocFile.setInt(5, iDocSize);
stmtInsDocFile.setString(6, strFileDescription);
stmtInsDocFile.setString(7, strFileStatus);
stmtInsDocFile.executeUpdate();
stmtInsDocFile.close();
bSuccess = true;
} catch (SQLException e) {
bSuccess = false;
m_pdLog.error("sql error in add doc file= " + e);
throw e;
}
return bSuccess;
}
/**
* @param
* @return
* @throws SQLException In case of database errors
*/
private synchronized int getNewDocFileID(int iDocID) throws SQLException {
try {
Statement stmtGetDocID = m_pdConnection.createStatement();
ResultSet rsGetDocID =
stmtGetDocID.executeQuery(
"select MAX(DOCFILE_ID) from ETS.ETS_DOCFILE WHERE DOC_ID="
+ iDocID);
int iMaxID = 0;
if (rsGetDocID.next()) {
iMaxID = rsGetDocID.getInt(1);
} else {
m_pdLog.error(
"Empty ResultSet: select MAX(DOC_ID) from ETS.ETS_DOC");
}
rsGetDocID.close();
stmtGetDocID.close();
return (iMaxID + 1);
} catch (SQLException e) {
m_pdLog.error("error= " + e);
throw e;
}
}
/**
* @param iDocId
* @param strProjectId
* @param strStatus
* @throws SQLException
*/
public synchronized void updateDocStatus(
int iDocId,
String strProjectId,
String strStatus)
throws SQLException {
PreparedStatement upDocSt = null;
upDocSt =
m_pdConnection.prepareStatement(
"UPDATE ETS.ETS_DOC "
+ "SET ITAR_UPLOAD_STATUS=? "
+ "WHERE DOC_ID=? "
+ "AND PROJECT_ID = ? "
+ "AND ITAR_UPLOAD_STATUS=?");
try {
upDocSt.setString(1, strStatus);
upDocSt.setInt(2, iDocId);
upDocSt.setString(3, strProjectId);
upDocSt.setString(4, "P");
upDocSt.executeUpdate();
upDocSt.close();
} catch (SQLException se) {
m_pdLog.error("sql error =" + se);
throw se;
}
}
/**
* @param iDocID
* @return
* @throws SQLException In case of database errors
*/
private synchronized int getSequenceNumber(int iDocID) throws SQLException {
try {
Statement stmtGetDocID = m_pdConnection.createStatement();
ResultSet rsGetDocID =
stmtGetDocID.executeQuery("SELECT MAX(SEQ_NO) FROM ETS.DOC_EDIT_HISTORY WHERE DOC_ID=" + iDocID);
int iMaxID = 0;
if (rsGetDocID.next()) {
iMaxID = rsGetDocID.getInt(1);
} else {
m_pdLog.error(
"Empty ResultSet: select MAX(SEQ_NO) from ETS.DOC_EDIT_HISTORY");
}
rsGetDocID.close();
stmtGetDocID.close();
return (iMaxID + 1);
} catch (SQLException e) {
m_pdLog.error("error= " + e);
throw e;
}
}
public synchronized boolean setEditHistory(ETSDocEditHistory pEtsDocHistory) throws SQLException, Exception {
String strQuery = StringUtil.EMPTY_STRING;
int iSeqNum = getSequenceNumber(pEtsDocHistory.getDocId());
try{
Statement stmtUpdDocResUsers = m_pdConnection.createStatement();
strQuery = "INSERT INTO ETS.DOC_EDIT_HISTORY(DOC_ID, SEQ_NO, USER_ID, "
+"ACTION, ACTION_DETAILS, LAST_TIMESTAMP) "
+ "VALUES"
+ "("+ pEtsDocHistory.getDocId() +","+ iSeqNum +",'"+ pEtsDocHistory.getUserId() +"','"
+ pEtsDocHistory.getAction() +"','"+ pEtsDocHistory.getActionDetails() +"', CURRENT TIMESTAMP )";
//m_pdLog.debug("SQL :: setEditHistory() - "+ strQuery);
stmtUpdDocResUsers.executeUpdate(strQuery);
} catch (SQLException e) {
m_pdLog.error("sql error =" + e);
throw e;
}
return true;
}
/**
* @param udDoc
* @return
* @throws SQLException
*/
public synchronized boolean updateDocProperties(ETSDoc udDoc)
throws SQLException {
boolean bSuccess = false;
PreparedStatement stmtUpdateDoc = null;
stmtUpdateDoc =
m_pdConnection.prepareStatement(
"UPDATE ETS.ETS_DOC "
+ "SET DOC_NAME=?, DOC_DESCRIPTION=?, DOC_KEYWORDS=? "
+ "WHERE DOC_ID=?");
try {
stmtUpdateDoc.setString(1, udDoc.getName());
stmtUpdateDoc.setString(2, udDoc.getDescription());
stmtUpdateDoc.setString(3, udDoc.getKeywords());
stmtUpdateDoc.setInt(4, udDoc.getId());
int iCount = stmtUpdateDoc.executeUpdate();
stmtUpdateDoc.close();
bSuccess = (iCount == 1);
} catch (SQLException se) {
m_pdLog.error("sql error =" + se);
throw se;
}
return bSuccess;
}
}
|
Markdown
|
UTF-8
| 2,172 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
comments: true
title: Noise
tags:
- Audio
---
Noise is defined as unwanted sound. Techinically its a complicated concept, but I wanna talk about the cognitive concept of noise today. And especially acoustic noise. I have noticed that noise pollution is really high in Singapore. There is so much noise around, and some of it at really high levels.
Just a few days ago, I was waiting for bus at a bus stop when another bus passed by. I was not using my MD, but my mom's CD player that day. That has some volume limiting function, so that it does not pump out the sound at levels that are harmful to our hearing. When the bus passed by, I couldn't hear anything. I turned the volume to max and still the noise from the bus drowned all the music. :( It was one of those double decker air-con bus. You probabaly wont notice then because you are used to it.
It is also very noisy inside the bus, no thanks to TV Mobile. Not only is it noisy, its annoying. But never mind about that.
All this in comparison to Denmark, where they took so much efforts to keep noise down. I was amazed by the initiative in the whole of Europe about environment, and specifically noise in Denmark. Ever person feels for conservation.Thats where Singapore lacks. A common man does not feel anything about it. And unless people feel about it nothing is gonna happen. Sigh.
Another related thing that I have noticed is this tendency pump up volume at concerts. I never get that. Good music does NOT mean loud music. Actually many times, with mediocre speakers, it actually means you probably are worst off. I agree that everyone should be able to hear the music in the location, but that does not mean you have to damage everyone's ear. Good speaker placement and proper speaker types can give out really enjoyable music without pumping up the volume.
I noticed it again today. There is some international festival thingy happening at PGP. It was so loud! And I mean not just loud, but LOUD!! I couldn't stand it for more than a few seconds. Human ears designed such that one can actually reduce their sensitivity when you encounter loud sounds.But, that another day's topic.
|
JavaScript
|
UTF-8
| 4,344 | 3.84375 | 4 |
[] |
no_license
|
// Assignment code here
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword(pass) {
var passwordText = document.querySelector("#password");
passwordText.value = pass;
}
// Add event listener to generate button
generateBtn.addEventListener("click", openModal);
function generatePassword(){
if (!validateForm()){
alert("Please check at least one Password Criteria and make sure length is between 8 - 128!")
return;
}
var specialChars = getSpecialChars()
var passLength = getPassLength()
var extraParams = getExtraParams()
var generatedPass = create(specialChars, passLength, extraParams);
var modal = document.getElementById("myModal");
modal.style.display = "none";
writePassword(generatedPass)
}
function openModal() {
// Get the modal
var modal = document.getElementById("myModal");
modal.style.display = "block";
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// get the create btn
var createBtn = document.getElementById("createBtn")
// create the password
createBtn.onclick = function() {
generatePassword()
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}
function validateForm(){
var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked');
return markedCheckbox.length;
}
function getSpecialChars(){
var markedCheckbox = document.querySelectorAll('input[name="specialChar"]:checked');
var chars = "";
if (markedCheckbox.length > 0){
for(var i=0; i < markedCheckbox.length; i++){
chars += markedCheckbox[i].value
}
}
return chars;
}
function getPassLength() {
var passwordLength = document.querySelector("#passLength");
return passwordLength.value;
}
function getExtraParams(){
var markedCheckbox = document.querySelectorAll('input[name="extraCase"]:checked');
var extraParams = {upperCase: false, lowerCase: false, includeNumbers: false};
if (markedCheckbox.length == 0){
return extraParams
}
for (let index = 0; index < markedCheckbox.length; index++) {
extraParams[markedCheckbox[index].value] = true;
}
return extraParams
}
function create(chars, length, params) {
console.log(chars, length, params)
// start with lowercase plus extra chars
var pwdChars = "";
if(chars != ""){
pwdChars += chars;
}
// if lowercase is included
if(params.lowerCase){
pwdChars += "abcdefghijklmnopqrstuvwxyz"
}
// check if numbers are included
if (params.includeNumbers) {
pwdChars += "0123456789"
}
// check if upercase is included
if (params.upperCase){
pwdChars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
}
var pwdLen = parseInt(length);
// random generator does not garantee EVERY special char is included
var randPassword = Array(pwdLen).fill(pwdChars).map(function(x) { return x[Math.floor(Math.random() * x.length)] }).join('');
return randPassword
}
function handleChange(input) {
console.log(input)
if (input.value < 8) alert("value must be greater than 8");
if (input.value > 128) alert("value must be less than 128");
}
// GIVEN I need a new, secure password
// WHEN I click the button to generate a password
// THEN I am presented with a series of prompts for password criteria
// WHEN prompted for password criteria
// THEN I select which criteria to include in the password
// WHEN prompted for the length of the password
// THEN I choose a length of at least 8 characters and no more than 128 characters
// WHEN asked for character types to include in the password
// THEN I confirm whether or not to include lowercase, uppercase, numeric, and/or special characters
// WHEN I answer each prompt
// THEN my input should be validated and at least one character type should be selected
// WHEN all prompts are answered
// THEN a password is generated that matches the selected criteria
// WHEN the password is generated
// THEN the password is either displayed in an alert or written to the page
|
Java
|
UTF-8
| 1,015 | 2.84375 | 3 |
[] |
no_license
|
package laba1.model;
public class Room extends Entity{
private String name;
private Integer size;
private Integer freePlaces;
public Room(Integer id, String name, Integer size, Integer freePlaces) {
this.size = size;
this.freePlaces = freePlaces;
this.id = id;
this.name = name;
}
public Room() {
}
public Integer getFreePlaces() {
return freePlaces;
}
public void setFreePlaces(Integer freePlaces) {
this.freePlaces = freePlaces;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
@Override
public String toString() {
return "Room{" +
"name='" + name + '\'' +
", size=" + size +
", freePlaces=" + freePlaces +
'}';
}
}
|
PHP
|
UTF-8
| 1,531 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
<?php
use App\Channel;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class ChannelsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Channel::truncate();
$title1 = 'Laravel';
$title2 = 'PHP Testing';
$title3 = 'Vue Js';
$title4 = 'JavaScript';
/*$title5 = 'CSS3';
$title6 = 'Spark';
$title7 = 'Lumen';
$title8 = 'Forge';*/
$channel1 = ['title' => $title1,'user_id' =>1 , 'slug' => Str::slug($title1,'-')];
$channel2 = ['title' => $title2,'user_id' =>2 , 'slug' => Str::slug($title2,'-')];
$channel3 = ['title' => $title3,'user_id' =>3 ,'slug' => Str::slug($title3,'-')];
$channel4 = ['title' => $title4,'user_id' =>4 , 'slug' => Str::slug($title4,'-')];
/*$channel5 = ['title' => $title5,'user_id' =>4 , 'slug' => Str::slug($title5,'-')];
$channel6 = ['title' => $title6,'user_id' =>4 , 'slug' => Str::slug($title6,'-')];
$channel7 = ['title' => $title7,'user_id' =>2 , 'slug' => Str::slug($title7,'-')];
$channel8 = ['title' => $title8,'user_id' =>2 , 'slug' => Str::slug($title8,'-')];*/
Channel::create($channel1);
Channel::create($channel2);
Channel::create($channel3);
Channel::create($channel4);
/* Channel::create($channel5);
Channel::create($channel6);
Channel::create($channel7);
Channel::create($channel8);*/
}
}
|
C++
|
UTF-8
| 6,935 | 3.453125 | 3 |
[] |
no_license
|
/*
* Implementation file for JumblePuzzle class.
* Author: Jeremy Roy
* NetId: 12jfr2
*/
#include "stdafx.h"
#include <string>
#include "jumble.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
//Exception class declaration
BadJumbleException::BadJumbleException(const string& message) : message(message) {}
string& BadJumbleException::what(){ return message; }
//JumblePuzzle Constructor
JumblePuzzle::JumblePuzzle(const string wordToHide, const string myDifficulty){
setDifficulty(myDifficulty, wordToHide);
setWord(wordToHide);
createJumble();
}//end constructor
//copy constructor
JumblePuzzle::JumblePuzzle(JumblePuzzle& old){
difficulty = old.difficulty;
hiddenWord = old.hiddenWord;
jumbleSize = old.jumbleSize;
colPos = old.colPos;
rowPos = old.rowPos;
direction = old.direction;
//and now for the jumble
jumble = cloneJumble(old.jumble);
}//end copy constructor
//destructor
JumblePuzzle::~JumblePuzzle(){
for (int row = 0; row < jumbleSize; row++){
delete jumble[row];
jumble[row] = nullptr;
}
delete jumble;
jumble = nullptr;
}//end destructor
//Assignment operator
JumblePuzzle& JumblePuzzle::operator=(const JumblePuzzle& right){
if (this != &right){
for (int row = 0; row < jumbleSize; row++){
delete jumble[row];
jumble[row] = nullptr;
}
delete jumble;
difficulty = right.difficulty;
hiddenWord = right.hiddenWord;
jumbleSize = right.jumbleSize;
colPos = right.colPos;
rowPos = right.rowPos;
direction = right.direction;
//and now for the jumble
jumble = cloneJumble(right.jumble);
}//end if
return *this;
}//end assignment operator
//creates clone of type charArrayPtr*
charArrayPtr* JumblePuzzle::cloneJumble(const charArrayPtr* old) const{
charArrayPtr* returnJumble = new charArrayPtr[jumbleSize];
for (int row = 0; row < jumbleSize; row++){
returnJumble[row] = new char[jumbleSize];
for (int col = 0; col < jumbleSize; col++)
returnJumble[row][col] = old[row][col]; //generate random lower case letter (ascii dec code)
}//end for
return returnJumble;
}//end cloneJumble
//One parameter function to set new difficulty
void JumblePuzzle::setNewDifficulty(string myDifficulty){
setDifficulty(myDifficulty, hiddenWord);
createJumble(); //remake puzzle
}//end 1-param setDifficulty
//Two-parameter function to set difficulty
void JumblePuzzle::setDifficulty(string myDifficulty, const string wordToHide){
//Transform input string to lower case
stringToLowerCase(myDifficulty);
//set difficulty and array size
if (myDifficulty == "easy"){
difficulty = EASY;
jumbleSize = wordToHide.length() * 2;
}
else if (myDifficulty == "medium"){
difficulty = MEDIUM;
jumbleSize = wordToHide.length() * 3;
}
else if (myDifficulty == "hard"){
difficulty = HARD;
jumbleSize = wordToHide.length() * 4;
}
else
throw BadJumbleException("Illegal difficulty!");
}//end 2-param setDifficulty
//Mutator to set new word
void JumblePuzzle::setNewWord(const string newWord){
setWord(newWord);
//set jumble size for new word
if (difficulty == EASY)
jumbleSize = newWord.length() * 2;
else if (difficulty == MEDIUM)
jumbleSize = newWord.length() * 3;
else if (difficulty == HARD)
jumbleSize = newWord.length() * 4;
createJumble(); //remake puzzle
}//end setNewWord()
//Set word to hide in jumble
void JumblePuzzle::setWord(string newWord){
if (newWord.length() < 3 || newWord.length() > 10)
throw BadJumbleException("Word to hide must be between 3 and 10 charcters long.");
if (isAlphabetic(newWord)){
stringToLowerCase(newWord); // <-------------------------------------------------------- PROBABLY WHAT YOU'RE LOOKING FOR
hiddenWord = newWord; // (just comment it out and you'll be able to see your upercase words)
wordSize = hiddenWord.length();
}
else
throw BadJumbleException("Word to hide must be alphabetic!");
}//end setWord()
//generate random printing direction
void JumblePuzzle::setDirection(){
srand(time(NULL));
int dir = rand() % 4;
if (dir == 0)
direction = 'n';
else if (dir == 1)
direction = 's';
else if (dir == 2)
direction = 'e';
else
direction = 'w';
}//end setDirection()
//Generates random row and column starting position
void JumblePuzzle::setPosition(){
srand(time(NULL));
colPos = rand() % (jumbleSize - 1);
rowPos = rand() % (jumbleSize - 1);
}//end setPosition()
//Creates Jumble Puzzle on heap
void JumblePuzzle::createJumble(){
jumbleInit();
while (hideWord() == 0); //keep trying to hide word until successful
}//end createJumble()
//Initialize jumble array on heap
void JumblePuzzle::jumbleInit(){
srand(time(NULL));
jumble = new charArrayPtr[jumbleSize];
for (int row = 0; row < jumbleSize; row++){
jumble[row] = new char[jumbleSize];
for (int col = 0; col < jumbleSize; col++)
jumble[row][col] = rand() % 26 + 97; //generate random lower case letter (ascii dec code)
}//end for
}//end jumbleInit()
//Write hidden word in jumble at random position in random direction. If failed, return 0. If successful, return 1.
int JumblePuzzle::hideWord(){
setPosition();
setDirection();
//write hidden word to right location
if (direction == 's'){
int row = rowPos;
for (int i = 0; i < wordSize; i++){
if (row == jumbleSize) //check if out of bounds
return 0;
jumble[row][colPos] = hiddenWord.at(i);
row++;
}
}//end south
else if (direction == 'n'){
int row = rowPos;
for (int i = 0; i < wordSize; i++){
if (row == -1) //check if out of bounds
return 0;
jumble[row][colPos] = hiddenWord.at(i);
row--;
}
}//end north
else if (direction == 'e'){
int col = colPos;
for (int i = 0; i < wordSize; i++){
if (col == jumbleSize) //check if out of bounds
return 0;
jumble[rowPos][col] = hiddenWord.at(i);
col++;
}
}//end east
else{ //must be west
int col = colPos;
for (int i = 0; i < wordSize; i++){
if (col == -1) //check if out of bounds
return 0;
jumble[rowPos][col] = hiddenWord.at(i);
col--;
}
}//end west
return 1; //if got to here, hidden word written successfully
}//end createJumbleHelper
int JumblePuzzle::getSize() const{
return jumbleSize;
}//end getSize()
int JumblePuzzle::getColPos() const{
return colPos;
}//end getColPos()
int JumblePuzzle::getRowPos() const{
return rowPos;
}//end getRowPos()
char JumblePuzzle::getDirection() const{
return direction;
}//end getDirection()
//returns 2D array of chars containing puzzle
charArrayPtr* JumblePuzzle::getJumble() const{
return cloneJumble(jumble);
}//end getJumble()
//Function to tranfrom input string to lower case
void stringToLowerCase(string& str){
for (int i = 0; i<str.length(); i++)
if (!islower(str.at(i)))
str.at(i) = tolower(str.at(i));
}//end stringToLowerCase()
//Function to check if string is alphabetic
int isAlphabetic(const string str){
for (int i = 0; i < str.length(); i++)
if (!isalpha(str.at(i)))
return 0;
return 1;
}//end isAlphabetic()
|
C++
|
UTF-8
| 2,387 | 2.890625 | 3 |
[] |
no_license
|
#include "../include/individual.h"
Individual::Individual(int *_genome,int _rating)
{
genome2.resize(100);
int *attributes[6]={&hp_points,&dmg_points,&defense_points,&speed_points,&crit_rate_points,&evasion_rate_points};
rating=_rating;
memcpy(genome,_genome,6*(sizeof (int)));
for(int r=0;r<rating;r++)
{
int p=rand()%100;
for(int i=0,p1=0;i<6;i++)
{
if(p1<=p && p<p1+genome[i])
{
(*attributes[i])++;
break;
}
p1+=genome[i];
}
}
for(int i=0,p=0;i<6;i++)
{
for(int j=0;j<genome[i];j++)
genome2[p++]=i;
}
std::random_shuffle(genome2.begin(),genome2.end());
Init_attributes();
}
const int HP_MIN=30;
const int DMG_MIN=5;
void Individual::Init_attributes()
{
hp=HP_MIN+10*hp_points;
dmg=DMG_MIN+3*dmg_points;
defense=15*std::sqrt(1.0*(defense_points+1));
speed=1.0+0.5*std::sqrt(1.0*speed_points);
crit_rate=10*std::sqrt(1.0+1.0*crit_rate_points);
evasion_rate=10*std::sqrt(1.0+1.0*evasion_rate_points);
}
void Individual::Print(int pos,FILE *out)
{
fprintf(out,"#%d {hp=%d, dmg=%d, def=%d, speed=%d, crit=%d, ev=%d}\n",pos,hp_points,dmg_points,defense_points,speed_points,crit_rate_points,evasion_rate_points);
}
bool Fight(Individual *A,Individual *B)
{
Individual a=*A;
Individual b=*B;
double action_point_a=0,action_point_b=0;
while(a.hp>0 && b.hp>0)
{
action_point_a+=a.speed;
action_point_b+=b.speed;
Attack(&a,&action_point_a,&b);
Attack(&b,&action_point_b,&a);
}
return (a.hp>b.hp);
}
void Attack(Individual *attacker,double *action_points,
Individual *attacked)
{
while(*action_points>=1)
{
(*action_points)-=1;
int p=rand()%100;
if(p<attacked->evasion_rate)
continue;
int dmg=attacker->dmg*(100.0-attacked->defense)/100.0;
p=rand()%100;
if(p<attacker->crit_rate)
dmg+=dmg/2;
attacked->hp-=dmg;
}
}
Individual Breed_individuals(Individual *A,Individual *B,int rating)
{
int p=rand()%100;
std::vector<int> genome2(100);
for(int i=0;i<p;i++)
genome2[i]=A->genome2[i];
for(int i=p;i<100;i++)
genome2[i]=B->genome2[i];
int genome[6]={0,0,0,0,0,0};
for(int i=0;i<100;i++)
genome[genome2[i]]++;
return Individual(genome,rating);
}
|
Java
|
UTF-8
| 9,338 | 2.1875 | 2 |
[] |
no_license
|
package com.secant.dcm.dump.object;
import java.io.Serializable;
import java.util.Date;
/**
* This class corresponds to the database table routing
*/
public class Routing implements Serializable {
/**
* This field corresponds to the database table routing
*
*/
private static final long serialVersionUID = 1L;
/**
* This field corresponds to the database column routing.routing_id
*
*/
private Long routingId;
/**
* This field corresponds to the database column routing.pacs_fk
*
*/
private Long pacsFk;
/**
* This field corresponds to the database column routing.ris_fk
*
*/
private Long risFk;
/**
* This field corresponds to the database column routing.total_img_to_mig
*
*/
private Long totalImgToMig;
/**
* This field corresponds to the database column routing.sent_images
*
*/
private Long sentImages;
/**
* This field corresponds to the database column routing.failed_to_snd_img
*
*/
private Long failedToSndImg;
/**
* This field corresponds to the database column routing.sender_start_time
*
*/
private Date senderStartTime;
/**
* This field corresponds to the database column routing.sender_end_time
*
*/
private Date senderEndTime;
/**
* This field corresponds to the database column routing.send_retry_count
*
*/
private Long sendRetryCount;
/**
* This field corresponds to the database column routing.sender_status
*
*/
private String senderStatus;
/**
* This field corresponds to the database column routing.cleansed_from
*
*/
private String cleansedFrom;
/**
* This field corresponds to the database column routing.source_aet
*
*/
private String sourceAet;
/**
* This field corresponds to the database column routing.mbox_aet
*
*/
private String mboxAet;
/**
* This field corresponds to the database column routing.dest_aet
*
*/
private String destAet;
/**
* Default constructor
*/
public Routing() {
}
/**
* This method returns the value of the database column routing.routing_id
*
* @return the value of routing.routing_id
*
*/
public final Long getRoutingId() {
return routingId;
}
/**
* This method sets the value of the database column routing.routing_id
*
* @param routingId the value for routing.routing_id
*
*/
public final void setRoutingId(final Long routingId) {
this.routingId = routingId;
}
/**
* This method returns the value of the database column routing.pacs_fk
*
* @return the value of routing.pacs_fk
*
*/
public final Long getPacsFk() {
return pacsFk;
}
/**
* This method sets the value of the database column routing.pacs_fk
*
* @param pacsFk the value for routing.pacs_fk
*
*/
public final void setPacsFk(final Long pacsFk) {
this.pacsFk = pacsFk;
}
/**
* This method returns the value of the database column routing.ris_fk
*
* @return the value of routing.ris_fk
*
*/
public final Long getRisFk() {
return risFk;
}
/**
* This method sets the value of the database column routing.ris_fk
*
* @param risFk the value for routing.ris_fk
*
*/
public final void setRisFk(final Long risFk) {
this.risFk = risFk;
}
/**
* This method returns the value of the database column routing.total_img_to_mig
*
* @return the value of routing.total_img_to_mig
*
*/
public final Long getTotalImgToMig() {
return totalImgToMig;
}
/**
* This method sets the value of the database column routing.total_img_to_mig
*
* @param totalImgToMig the value for routing.total_img_to_mig
*
*/
public final void setTotalImgToMig(final Long totalImgToMig) {
this.totalImgToMig = totalImgToMig;
}
/**
* This method returns the value of the database column routing.sent_images
*
* @return the value of routing.sent_images
*
*/
public final Long getSentImages() {
return sentImages;
}
/**
* This method sets the value of the database column routing.sent_images
*
* @param sentImages the value for routing.sent_images
*
*/
public final void setSentImages(final Long sentImages) {
this.sentImages = sentImages;
}
/**
* This method returns the value of the database column routing.failed_to_snd_img
*
* @return the value of routing.failed_to_snd_img
*
*/
public final Long getFailedToSndImg() {
return failedToSndImg;
}
/**
* This method sets the value of the database column routing.failed_to_snd_img
*
* @param failedToSndImg the value for routing.failed_to_snd_img
*
*/
public final void setFailedToSndImg(final Long failedToSndImg) {
this.failedToSndImg = failedToSndImg;
}
/**
* This method returns the value of the database column routing.sender_start_time
*
* @return the value of routing.sender_start_time
*
*/
public final Date getSenderStartTime() {
return senderStartTime;
}
/**
* This method sets the value of the database column routing.sender_start_time
*
* @param senderStartTime the value for routing.sender_start_time
*
*/
public final void setSenderStartTime(final Date senderStartTime) {
this.senderStartTime = senderStartTime;
}
/**
* This method returns the value of the database column routing.sender_end_time
*
* @return the value of routing.sender_end_time
*
*/
public final Date getSenderEndTime() {
return senderEndTime;
}
/**
* This method sets the value of the database column routing.sender_end_time
*
* @param senderEndTime the value for routing.sender_end_time
*
*/
public final void setSenderEndTime(final Date senderEndTime) {
this.senderEndTime = senderEndTime;
}
/**
* This method returns the value of the database column routing.send_retry_count
*
* @return the value of routing.send_retry_count
*
*/
public final Long getSendRetryCount() {
return sendRetryCount;
}
/**
* This method sets the value of the database column routing.send_retry_count
*
* @param sendRetryCount the value for routing.send_retry_count
*
*/
public final void setSendRetryCount(final Long sendRetryCount) {
this.sendRetryCount = sendRetryCount;
}
/**
* This method returns the value of the database column routing.sender_status
*
* @return the value of routing.sender_status
*
*/
public final String getSenderStatus() {
return senderStatus;
}
/**
* This method sets the value of the database column routing.sender_status
*
* @param senderStatus the value for routing.sender_status
*
*/
public final void setSenderStatus(final String senderStatus) {
this.senderStatus = senderStatus == null ? null : senderStatus.trim();
}
/**
* This method returns the value of the database column routing.cleansed_from
*
* @return the value of routing.cleansed_from
*
*/
public final String getCleansedFrom() {
return cleansedFrom;
}
/**
* This method sets the value of the database column routing.cleansed_from
*
* @param cleansedFrom the value for routing.cleansed_from
*
*/
public final void setCleansedFrom(final String cleansedFrom) {
this.cleansedFrom = cleansedFrom == null ? null : cleansedFrom.trim();
}
/**
* This method returns the value of the database column routing.source_aet
*
* @return the value of routing.source_aet
*
*/
public final String getSourceAet() {
return sourceAet;
}
/**
* This method sets the value of the database column routing.source_aet
*
* @param sourceAet the value for routing.source_aet
*
*/
public final void setSourceAet(final String sourceAet) {
this.sourceAet = sourceAet == null ? null : sourceAet.trim();
}
/**
* This method returns the value of the database column routing.mbox_aet
*
* @return the value of routing.mbox_aet
*
*/
public final String getMboxAet() {
return mboxAet;
}
/**
* This method sets the value of the database column routing.mbox_aet
*
* @param mboxAet the value for routing.mbox_aet
*
*/
public final void setMboxAet(final String mboxAet) {
this.mboxAet = mboxAet == null ? null : mboxAet.trim();
}
/**
* This method returns the value of the database column routing.dest_aet
*
* @return the value of routing.dest_aet
*
*/
public final String getDestAet() {
return destAet;
}
/**
* This method sets the value of the database column routing.dest_aet
*
* @param destAet the value for routing.dest_aet
*
*/
public final void setDestAet(final String destAet) {
this.destAet = destAet == null ? null : destAet.trim();
}
}
|
Java
|
UTF-8
| 1,159 | 2.484375 | 2 |
[] |
no_license
|
package fcu.selab.progedu.data;
import java.util.ArrayList;
import java.util.List;
public class Group {
private String groupName;
private String projectName;
private int groupId;
private String leaderUsername;
private List<String> contributorId;
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getLeaderUsername() {
return leaderUsername;
}
public void setLeaderUsername(String leaderUid) {
this.leaderUsername = leaderUid;
}
public List<String> getContributor() {
return contributorId;
}
public void setContributor(List<String> contributorId) {
this.contributorId = contributorId;
}
/**
* add contirbutor to list
*
* @param contributorId contirbutor's username
*/
public void addContributor(String contributorId) {
if (this.contributorId == null) {
this.contributorId = new ArrayList<>();
}
this.contributorId.add(contributorId);
}
}
|
Java
|
UTF-8
| 2,218 | 2.1875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* To change this template, choose Tools | Templates and open the template in the editor.
*/
package com.cybernostics.lib.resourcefinder.protocols.resloader;
import com.cybernostics.lib.resourcefinder.ResourceFinder;
import com.cybernostics.lib.resourcefinder.net.customurl.CustomURLScheme;
import com.cybernostics.lib.urlfactory.URLFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility class for resloader:// URLs
* You must call register on this class before creating any URLs with the
* "resloader:// scheme or you will get a MalformedURLException"
* By calling the create methods instead of the URL constructor directly, this
* will be done for you.
*
* @author jasonw
*/
public class ResloaderURLScheme
{
private ResloaderURLScheme()
{
}
private static final String prefix = "resloader://";
private static final String urlFmt = prefix + "%s/%s";
private static boolean resloaderRegistered = false;
public static String createString( Class< ? > objClass, String relPath )
{
String urlStr = String.format(
urlFmt,
objClass.getCanonicalName(),
relPath != null ? relPath : "" );
return urlStr;
}
public static URL create( Class< ? > objClass )
{
return create(
objClass,
"" );
}
public static URL create( Class< ? > objClass, String relPath )
{
//register();
try
{
return new URL( "resloader",
objClass.getCanonicalName(),
-1,
relPath,
Handler.get() );
}
catch (MalformedURLException ex)
{
throw new RuntimeException( ex );
}
}
public static URL create( Object objRoot )
{
return create(
objRoot.getClass(),
"" );
}
public static URL create( Object objRoot, String relPath )
{
return create(
objRoot.getClass(),
relPath );
}
public static void register()
{
if (resloaderRegistered)
{
return; // already done
}
try
{
CustomURLScheme.add(
Handler.get(),
new ResloaderChildFinder() );
resloaderRegistered = true;
}
catch (Exception ex)
{
Logger.getLogger(
ResourceFinder.class.getName() )
.log(
Level.SEVERE,
null,
ex );
}
}
}
|
Markdown
|
UTF-8
| 7,747 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
## intent:affirm
- yes
- yep
- yeah
- indeed
- that's right
- ok
- great
- right, thank you
- correct
- great choice
- sounds really good
- thanks
- true
- Cool
- Got ya
## intent:goodbye
- bye
- goodbye
- good bye
- stop
- end
- farewell
- Bye bye
- have a good one
- bbye
- ttyl
- talk to you later
- See ya
- Bbye
## intent:greet
- hey
- howdy
- hey there
- hello
- hi
- good morning
- good evening
- good afternoon
- dear sir
- what's up
- howz its going
- Hey
- Hey, whats up
## intent:restaurant_search
- i'm looking for a place to eat
- I want to grab lunch
- I am searching for a dinner spot
- I am looking for some restaurants in [Delhi](location).
- I am looking for some restaurants in [Bangalore](location)
- show me [chinese]{"entity": "cuisine", "value": "Chinese"} restaurants
- show me [chines]{"entity": "cuisine", "value": "Chinese"} restaurants in the [New Delhi]{"entity": "location", "value": "Delhi"}
- show me a [Mexican](cuisine) place in the [Nanded](location)
- i am looking for an [North Indian](cuisine) spot called olaolaolaolaolaola
- search for restaurants
- I am looking a restaurant in [294328](location)
- in [Gurgaon](location)
- [South Indian](cuisine)
- [North Indian](cuisine)
- [Italian](cuisine)
- [Chinese](cuisine)
- [chinese]{"entity": "cuisine", "value": "Chinese"}
- Oh, sorry, in [Italy](location)
- in [delhi](location)
- I am looking for some restaurants in [Mumbai](location)
- I am looking for [mexican]{"entity": "cuisine", "value": "Mexican"} food
- [Kannur](location) [American](cuisine) restaurant
- please help me to find restaurants in [Pune](location)
- Please find me a restaurantin [Bangalore](location)
- [Mumbai](location)
- show me restaurants
- please find me [Chinese](cuisine) restaurant in [Cuttak](location)
- can you find me a [Chinese](cuisine) restaurant
- [delhi]{"entity": "location", "value": "Delhi"}
- please find me a restaurant in [ahmedabad]{"entity": "location", "value": "Ahmedabad"}
- please show me a few [Italian](cuisine) restaurants in [bangalore]{"entity": "location", "value": "Bangalore"}
- Can you please help me with a [North Indian](cuisine) restaurant in [amritsar]{"entity": "location", "value": "Amritsar"}
- [bombay]{"entity": "location", "value": "Mumbai"}
- [Mexican](cuisine)
- Tell me a good [Italian](cuisine) restro in [Goa](location)
- Wanna grab [Italin](cuisine) breakfast in [kakinada]{"entity": "location", "value": "Kakinada"}
- Tell me few mouth watering [North Indian](cuisine) in [Dehradun](location)
- Show me some hygenic restaurants serving [Italian] breakfast in [Hamirpur](location)
- Restaurant serving good breakfast under 100 price bucks
- All places where I can get lunch under 200 rupees
- Hey, can you show me some nice [Italian](cuisine) restaurants in [Delhi](location)
- Hey, can you show me some nice [italian]{"entity": "cuisine", "value": "Italian"} restaurants in [Bombay]{"entity": "location", "value": "Mumbai"}
- [Ranchi](location)
- [ranchi](location)
- [Shimla](location)
- [shimla](location)
- Good [South Indian](location) in [Vellore](location)
- [Bokaro Steel City](location)
- [Vasai-Virar City](location)
- Are there any good [Italian](cuisine) restros in [Thiruvananthapuram](location) serving lunch
- We are [6](people) looking for a [North Indian](cuisine)
- Hey, We need a table of [2](people) in a posh restaurant serving [North Indian](cuisine) in [kurnool]{"entity": "location", "value": "Kurnool"}
- Can you do me a favor and tell me awesome [South Indian](cuisine) place in [belgaum](location) for [6](people) people
- Find me a restaurant in [Mumbai](location)
- [American](cuisine)
- [american]{"entity": "cuisine", "value": "American"}
- [north indian]{"entity": "cuisine", "value": "North Indian"}
- Can you search for a restaurant in [Solapur](location) serving [North Indian](cuisine) food
- Find me a restaurant serving [Italian](cuisine) food in [meerut](location)
- find me a restaurant in [Siliguri](location)
- [kurnool](location)
- Find me a restaurant
- [Bengaluru](location)
- Rs [300](min_price) to [700](max_price)
- In range of [300](min_price) and [500](max_price)
- I would say less then [500](max_price) bucks
- Anything more then [1000](min_price) bucks
- Lesser than Rs [300](max_price)
- More than [700](min_price)
- [300](min_price) to [700](max_price)
- [Yes, send](email_has_to_be_sent) the email
- [No, don't](email_has_to_be_sent) send the email
- [akhilminhas@gmail.com](email_address)
- [akhilminhas777@gmail.com](email_address)
- [anyrandomemailId@yahoo.com](email_address)
- [aakash@in.com](email_address)
- [indiaisgreat@via.in](email_address)
- [letpeaceprevail@hotmail.com](email_address)
- [543@gmail.com](email_address)
- Send email on [abc@xyx.com](email_address)
- It would be better if you send the restaurant list on [somedummyid@hotstar.com](email_address)
- Cool, send it on [someid@xyx.com](email_address)
- Search me a restaurant in [guntur](location) for [north indian]{"entity": "cuisine", "value": "North Indian"} food
- Can you find me a restaurant in [jalandhar](location) serving [american]{"entity": "cuisine", "value": "American"} food
- [minhas89@gmail.com](email_address)
- hey find me a restaurant in [rourkela](location) serving [italian]{"entity": "cuisine", "value": "Italian"} food
- [somerandomid@co.in](email_address)
- hey, find me a restaurant serving [chinese]{"entity": "cuisine", "value": "Chinese"} food around [landran]{"entity": "location", "value": "Landran"}
- hey, show me [italian]{"entity": "cuisine", "value": "Italian"} restaurants around [sangli]{"entity": "location", "value": "Sangli"}
- hey, show me [american]{"entity": "cuisine", "value": "American"} restaurants in [hajipur](location)
- find me a restaurant serving [italian]{"entity": "cuisine", "value": "Italian"} in [bombay]{"entity": "location", "value": "Mumbai"}
- hey find me a restaurant serving [italian]{"entity": "cuisine", "value": "Italian"} in [chembur](location)
- hey, find me a [north indian]{"entity": "cuisine", "value": "North Indian"} restaurant in [bengaluru]{"entity": "location", "value": "Bangalore"}
- hey, find me a restaurant in [kannur](location) serving [north indian]{"entity": "cuisine", "value": "North Indian"} food
- [xcz@amazon.in](email_address)
- hey, find me a restaurant serving [north indian]{"entity": "cuisine", "value": "North Indian"} food in [delhi]{"entity": "location", "value": "Delhi"}
- hey, can you find me a restaurant in [chennai](location)
- hey, find me a restaurant in [jalandhar](location)
- [me@checkemail.com](email_address)
- > [700](min_price)
- < [300](max_price)
- between [300](min_price) and [700](max_price)
- in range of [300](min_price) and [700](max_price)
- higher then 700[min_price]
- lower then 300[max_price]
- find me a [american]{"entity": "cuisine", "value": "American"} restaurant in [delhi]{"entity": "location", "value": "Delhi"}
- [somemailid@gmail.com](email_address)
- hey, find me a restaurant serving [italian]{"entity": "cuisine", "value": "Italian"} in [mumbai](location)
- Lesser than Rs [300](max_price)
- [No, don't](email_has_to_be_sent) send the email
## synonym:100
- hundred
## synonym:1000
- thousand
## synonym:3000
- Three thousand
## synonym:4
- four
## synonym:500
- five hundred
## synonym:Ahmedabad
- ahmedabad
## synonym:American
- american
## synonym:Amritsar
- amritsar
## synonym:Bangalore
- bangalore
- bengaluru
- Bengaluru
## synonym:Chinese
- chinese
- chines
- Chines
## synonym:Delhi
- New Delhi
- delhi
## synonym:Italian
- italian
## synonym:Kakinada
- kakinada
## synonym:Kurnool
- kurnool
## synonym:Landran
- landran
## synonym:Mexican
- mexican
## synonym:Mumbai
- bombay
- Bombay
## synonym:North Indian
- north indian
## synonym:Sangli
- sangli
## synonym:hundred
- 100
## synonym:mid
- moderate
## synonym:vegetarian
- veggie
- vegg
## regex:greet
- hey[^\s]*
## regex:pincode
- [0-9]{6}
|
Python
|
UTF-8
| 14,608 | 3.390625 | 3 |
[] |
no_license
|
from TREE import TreeNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class DLLNode(object):
def __init__(self, item):
self.val = item
self.next = None
self.prev = None
# Definition for a Node.
class RandomListNode:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
"""
LL Tricks
1. Always check Current.next for condition, you have to mostly stop one node (current) before to operate upon
2. Where you can't check Current.next for condition, maintain prev
3. Head ?? validation
"""
class LinkedList:
def __init__(self, item=0):
self.head = ListNode(item)
pass
def insert(self, item):
newNode = ListNode(item)
if self.head is None:
# 1st Node, Make it head
self.head = newNode
# Otherwise find end of list
current = self.head
while current.next is not None:
current = current.next
# We are at end of list, insert
self.insertNode_Util(current, newNode)
def insertNode_Util(self, current, newNode):
# Link changes
savedNext = current.next
current.next = newNode
newNode.next = savedNext
def insertAtPosition(self, item, position):
newNode = ListNode(item)
if position == 0:
self.head = newNode
# edge case: what happens if position is given more than what list contains
# Find the right pos to insert
current = self.head
i = 0
while i < position-1:
current = current.next
i += 1
# We are at pos, insert now
self.insertNode_Util(current, newNode)
def insertInSortedOrder(self, item):
newNode = ListNode(item)
# Head ??
if self.head.val > item:
self.insertNode_Util(self.head, newNode)
# Search for right pos
current = self.head
while current.next.val < item:
current = current.next
self.insertNode_Util(current, newNode)
def remove(self, item):
# Head ??
if self.head.val == item:
newHeadRef = self.head.next
del self.head
self.head = newHeadRef
return
self.remove_node(ListNode(item))
def remove_node(self, node):
if isinstance(type(node), Node):
return -1
# Head with no next? Delete head with next is None!
if self.head == node and self.head.next is None:
del self.head
current = self.head
prev = self.head
while current is not None and current.val != node.val:
current = current.next
prev = current
# Tail ?
if current is None:
# Not found
return -1
elif current.next is None:
# Tail node to be deleted
prev.val = current.val
prev.next = current.next
else:
# Regular node
current.val = current.next.val
current.next = current.next.next
def reverse(self):
prev = None
current = self.head
while current is not None:
savedNext = current.next
# Reverse the link
current.next = prev
# Next iteration
prev = current
current = savedNext
self.head = prev
def detect_loop(self):
slow = self.head
fast = self.head
while fast is not None and fast.next is not None:
fast = fast.next
if fast.next is not None:
fast = fast.next
slow = slow.next
if fast == slow:
break
# fast & slow are pointing at k nodes away from LoopNode
# Head is pointing at k nodes away from LoopNode
current = self.head
while current is not slow:
current = current.next
slow = slow.next
return current
def size(self, head=None):
count = 0
if head is None:
current = self.head
else:
current = head
while current is not None:
count += 1
current = current.next
return count
def size_recur_util(self, node):
if node is None:
return 0
return 1 + self.size_recur_util(node.next)
def size_recur(self):
return self.size_recur_util(self.head)
def printLL(self):
current = self.head
while current:
print current.val,
current = current.next
def printLLReversed_Util(self, node):
if node is None:
return
self.printLLReversed_Util(node.next)
print node.val
def printLLReversed(self):
return self.printLLReversed_Util(self.head)
def swap(self, item, new_item):
current = self.head
while current.val != item:
if current.next is None:
return False
current = current.next
# We are at node to swap
current.val = new_item
def middle(self):
slow = self.head
fast = self.head
while fast is not None and fast.next is not None:
fast = fast.next
if fast.next is not None:
fast = fast.next
slow = slow.next
return slow
def get_nth_from_last(self, n):
slow = self.head
fast = self.head
while n > 0 and fast is not None:
fast = fast.next
n -= 1
while fast is not None:
fast = fast.next
slow = slow.next
return slow.val if fast is not None else -1
def isPalindrom_Util(self, Left, Right):
if Right is None:
return True, Left
# Left will be traversing reverse from back
# Right will be traversing reverse from back
isp, Left = self.isPalindrom_Util(Left, Right.next)
if isp is False:
return False, Left
# Compare values of Right <-- with Left --->
isp1 = (Left.val == Right.val)
# Move Left
Left = Left.next
return isp1, Left
def isPalindrom(self):
Left = self.head
Right = self.head
return self.isPalindrom_Util(Left, Right)
"""
ADD 2 numbers represented as reversed LinkedList
https://leetcode.com/problems/add-two-numbers/description/
"""
class Solution(object):
def addTwoNumbersRecur(self, l1, l2, carry):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Base Case
# Base Case
if l1 is None and l2 is None:
if carry:
return ListNode(carry)
else:
return None
#1) Constraint for root
sumVal = carry
if l1 is not None:
sumVal += l1.val
if l2 is not None:
sumVal += l2.val
newNode = ListNode(sumVal % 10)
# 2) Same constraint for next Node (Recurssion)
newNode.next = self.addTwoNumbersRecur(l1.next if l1 is not None else None,
l2.next if l2 is not None else None,
sumVal//10)
return newNode
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummyHeadNode = ListNode(0)
current = dummyHeadNode
sumVal, carry = 0, 0
# Iterate through both lists
while l1 or l2:
sumVal = 0
if l1:
sumVal += l1.val
if l2:
sumVal += l2.val
if carry > 0:
sumVal += carry
carry = sumVal // 10
# Create a result node
current.next = ListNode(sumVal % 10)
current = current.next
# Next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
# Edge case: Remaining carry!
if carry > 0:
current.next = ListNode(carry)
return dummyHeadNode.next
def removeNthFromEnd(self, head, n):
dummyHead = ListNode(0, head)
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
slow = fast = dummyHead
for i in xrange(n):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
# Slow is pointing to pre location of node to be deleted
slow.next = slow.next.next
return dummyHead.next
def swapPairs(self, head):
dummyHead = ListNode(0, head)
pre,pre.next = dummyHead, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
# Swap a, b links
pre.next = b
a.next = b.next
b.next = a
# Next iteration
pre = a
return dummyHead.next
def findSize(self, head):
ptr = head
c = 0
while ptr:
ptr = ptr.next
c += 1
return c
def sortedListToBST(self, head):
size = self.findSize(head)
def convertRecur(l, h):
global head
# Base condition
if l > h:
return None
# if l == h:
# # Single node, let's make a TreeNode out of this
# node = TreeNode(l)
# return node
# Traversal, BST pre-order = sorted sequence, so building BST with pre-order from sorted LL
mid = (l + h) // 2
# 1) L
left = convertRecur(l, mid - 1)
# 2) C
node = TreeNode(head.val)
node.left = left # We are in LCR traversal, so earlier built node is Left of node built Now!
head = head.next # this node(head) is built in BST, keep traversing original LL
# 3) R
node.right = convertRecur(mid + 1, h)
return node
return convertRecur(0, size - 1)
def copyRandomList(self, head):
old = head
# Dict to map {oldNodeAddress -> sameNewNodeAddress}
d = {}
while old:
# Creating new Node and a dict[OldNodeAddress] = newNodeAddress
d[old] = RandomListNode(old.val, None, None)
old = old.next
# Edge case: Add last node Null!
d[None] = None
print(d)
old = head
while old:
# d[old] will give exact new node
d[old].val = old.val
d[old].next = d[old.next]
d[old].random = d[old.random]i3
old = old.next
return d[head]
def addLL_Util_Reverse(node1, node2):
# Base case
# Return node values when both lists are empty
if node1 is None and node2 is None:
return None, 0
headRef, carry = addLL_Util_Reverse(node1.next, node2.next)
sum_nodes = carry + node1.val + node2.val
newNode = ListNode(sum_nodes % 10)
carry = sum_nodes // 10
if headRef is None:
headRef = newNode
else:
newNode.next = headRef
headRef = newNode
return headRef, carry
def intersection(L1, L2):
m = L1.size()
n = L2.size()
if m > n:
fast = L1
slow = L2
else:
fast = L2
slow = L1
# Now SKIP abs(len(1)-len(2) nodes from bigger list
for i in xrange(abs(m-n)):
fast = fast.next
# Now both list are same nodes away from INTERSECTION
while slow != fast:
fast = fast.next
slow = slow.next
return slow
def addLL(L1, L2):
carry = 0
return addLL_Util(L1, L2, carry)
def addLLReversed(L1, L2, sizeL1, sizeL2):
skipNodes = abs(sizeL1 - sizeL2)
while skipNodes > 0:
L1 = L1.next
skipNodes -= 1
HeadRef, carry = addLL_Util_Reverse(L1, L2)
return HeadRef
"""
Reverses a LL and returns Head of new LL
"""
def reverse(head):
prev = None
current = head
while current is not None:
savedNext = current.next
# Reverse the link
current.next = prev
# Next iteration
prev = current
current = savedNext
return prev
def printLL(head):
while head:
print head.val,
head = head.next
def main():
# myLL = LinkedList(1)
# myLL.insert(2)
# myLL.insert(3)
# myLL.insert(4)
# myLL.insert(5)
#
# reversed_head = reverse(myLL.head)
# while reversed_head is not None:
# print reversed_head.val
# reversed_head = reversed_head.next
print "Adding 2 numbers represented by LL...."
L1 = LinkedList(3)
L1.insert(1)
L1.insert(5)
L1.insert(7)
L2 = LinkedList(5)
L2.insert(9)
L2.insert(2)
s = Solution()
result = s.addTwoNumbers(L1.head, L2.head)
printLL(result)
while result is not None:
print result.val
result = result.next
result = s.removeNthFromEnd(L1.head, 2)
printLL(result)
"""
myLL = LinkedList('k')
myLL.insert('a')
myLL.insert('y')
myLL.insert('a')
myLL.insert('k')
# myLL.printLL()
print"\nChecking palindrome"
isp, Left = myLL.isPalindrom()
print isp
myLL = None
myLL = LinkedList(1)
myLL.printLL()
print "\nChecking insertInSortedOrder"
myLL.insertInSortedOrder(4)
myLL.printLL()
print "\nChecking insertAtPosition"
myLL.insertAtPosition(5, 3)
myLL.printLL()
print "\nChecking remove"
myLL.remove(2)
myLL.printLL()
print "\nChecking remove HEAD"
myLL.remove(1)
myLL.printLL()
print "\nChecking remove NOT FOUND"
myLL.remove(15)
myLL.printLL()
print "\nChecking remove NOT FOUND"
myLL.remove_node(ListNode(1))
myLL.printLL()
print "\nChecking remove"
myLL.remove_node(ListNode(7))
myLL.printLL()
print "\nreverse"
myLL.reverse()
myLL.printLL()
print "\nsize"
print myLL.size()
print "\nsize recur"
print myLL.size_recur()
print "\nreverse print"
print myLL.printLLReversed()
print "\nswap"
myLL.swap(11, 5)
myLL.printLL()
print "\nmiddle"
print myLL.middle().val
print "get nth from last"
print myLL.get_nth_from_last(3)
"""
if __name__ == "__main__":
main()
|
Java
|
UTF-8
| 42,076 | 1.578125 | 2 |
[] |
no_license
|
package com.ningpai.m.deposit.service.impl;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.ningpai.allinpay.bean.AllinpayReg;
import com.ningpai.allinpay.service.AllinpayRegService;
import com.ningpai.allinpay.service.TLPayService;
import com.ningpai.allinpay.utils.TLPayUtil;
import com.ningpai.common.util.alipaymobile.config.AlipayConfig;
import com.ningpai.common.util.alipaymobile.util.AlipaySubmit;
import com.ningpai.m.customer.mapper.CustomerMapper;
import com.ningpai.m.customer.vo.CustomerAllInfo;
import com.ningpai.m.customer.vo.CustomerConstants;
import com.ningpai.m.deposit.bean.DepositInfo;
import com.ningpai.m.deposit.bean.DepositInfoCons;
import com.ningpai.m.deposit.bean.TradeInfo;
import com.ningpai.m.deposit.mapper.DepositInfoMapper;
import com.ningpai.m.deposit.service.DepositInfoService;
import com.ningpai.m.deposit.service.TradeInfoService;
import com.ningpai.m.order.service.OrderMService;
import com.ningpai.order.bean.Order;
import com.ningpai.system.bean.Pay;
import com.ningpai.system.bean.Receivables;
import com.ningpai.system.service.PayService;
import com.ningpai.system.service.ReceivablesService;
import com.ningpai.util.MyLogger;
import com.ningpai.util.PropertieUtil;
import com.ningpai.util.UtilDate;
import com.ningpai.utils.SecurityUtil;
import com.ningpai.wxpay.utils.GetWxOrderno;
import com.ningpai.wxpay.utils.RequestHandlerUtil;
import com.ningpai.wxpay.utils.Sha1Util;
import com.ningpai.wxpay.utils.TenpayUtil;
/**
* 预存款信息service实现
* Created by chenpeng on 2016/10/9.
*/
@Service("depositInfoServiceM")
public class DepositInfoServiceImpl implements DepositInfoService {
@Resource(name = "customerMapperM")
private CustomerMapper customerMapper;
@Resource(name = "DepositInfoMapperM")
private DepositInfoMapper depositInfoMapper;
@Resource(name = "tradeInfoServiceM")
private TradeInfoService tradeInfoService;
@Resource(name = "payService")
private PayService payService;
@Resource(name = "receivablesService")
private ReceivablesService receivablesService;
@Resource(name = "AllinpayRegService")
private AllinpayRegService allinpayRegService;
private static final String SUCCESS_RETURN_CODE = "SUCCESS";
@Resource(name = "OrderMService")
private OrderMService siteOrderService;
@Resource(name = "TLPayService")
private TLPayService tLPayService;
private static final String OUT_TRADE_NO = "out_trade_no";
private static final MyLogger LOGGER = new MyLogger(DepositInfoServiceImpl.class);
/**
* 验证手机(设置支付密码时)
*
* @param customerId 用户id
* @return true:已验证 false:未验证
*/
@Override
public boolean checkMobileValidation(Long customerId) {
CustomerAllInfo customerAllInfo = customerMapper.selectByPrimaryKey(customerId);
if (customerAllInfo != null){
if (StringUtils.isNotEmpty(customerAllInfo.getInfoMobile())
&& StringUtils.isNotEmpty(customerAllInfo.getIsMobile())){
return true;
}
}
return false;
}
/**
* 支付密码设置验证
*
* @param request
* @param code
* @return
*/
@Override
public int validatePayCode(HttpServletRequest request, String code) {
if(request.getSession().getAttribute("payCode") == null){
return 0;
}
if (code.equals((int) request.getSession().getAttribute("payCode") + "")) {
return 1;
}
return 0;
}
/**
* 支付密码设置
*
* @param request
* @param code 手机验证码
* @param password 新密码
* @return 0失败 1成功
*/
@Override
public int setPayPassword(HttpServletRequest request, String password) {
Long customerId = (Long)request.getSession().getAttribute("customerId");
CustomerAllInfo customerInfo = customerMapper.selectByPrimaryKey(customerId);
//加密处理
String securityPassword = SecurityUtil.getStoreLogpwd(customerInfo.getUniqueCode(), password, customerInfo.getSaltVal());
DepositInfo depositInfo = new DepositInfo();
depositInfo.setPayPassword(securityPassword);
depositInfo.setCustomerId(customerId);
//更新支付密码
return depositInfoMapper.updateDepositInfo(depositInfo);
}
/**
* 查询用户预付款信息
*
* @param customerId 用户id
* @return
*/
@Override
public DepositInfo queryDepositInfo(Long customerId) {
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
if(depositInfo == null){
depositInfo = new DepositInfo();
depositInfo.setCustomerId(customerId);
depositInfo.setFreezePreDeposit(BigDecimal.ZERO);
depositInfo.setPreDeposit(BigDecimal.ZERO);
depositInfo.setPasswordErrorCount(0);
depositInfoMapper.insertSelective(depositInfo);
depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
}
return depositInfo;
}
/**
* 获取getBrandWCPayRequest参数
*
* @param customerId 用户id
* @param orderPrice 交易价格
* @param orderType 交易类型
* @return getBrandWCPayRequest参数
*/
@Override
public Map<String, Object> getBrandWCPayRequest(HttpServletRequest request, HttpServletResponse response,Long customerId, BigDecimal orderPrice, String orderType) {
String payType = "0";
if(orderPrice.compareTo(new BigDecimal(1000000)) > 0){
return null;
}
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
//生成预付款交易记录
TradeInfo tradeInfo = tradeInfoService.insertSelective(customerId, orderPrice, orderType, payType, "在线充值-微信",depositInfo);
//微信支付信息
Pay pay = payService.selectWxPay();
//获取支付信息
if (tradeInfo == null){
return null;
}
//获取getBrandWCPayRequest参数
return brandWCPayRequest(request, response, tradeInfo, pay);
}
/**
* 微信参数
* @param request
* @param response
* @param tradeInfo
* @param pay
* @return
*/
private Map<String, Object> brandWCPayRequest(HttpServletRequest request, HttpServletResponse response,TradeInfo tradeInfo,Pay pay ){
// 网页授权后获取传递的参数
String userId = request.getParameter("userId");
if(request.getSession().getAttribute("openid") == null){
return null;
}
String openId = request.getSession().getAttribute("openid").toString();
// String openId = "";
// 金额转化为分为单位
String finalmoney = String.format("%.2f", tradeInfo.getOrderPrice());
finalmoney = finalmoney.replace(".", "");
int intMoney = Integer.parseInt(finalmoney);
// 总金额以分为单位,不带小数点
int totalFee = intMoney;
// 商户相关资料
String appid = pay.getApiKey();
String appsecret = pay.getSecretKey();
String partner = pay.getPartner();
String partnerkey = pay.getPartnerKey();
// 获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
String currTime = TenpayUtil.getCurrTime();
// 8位日期
String strTime = currTime.substring(8, currTime.length());
// 四位随机数
String strRandom = TenpayUtil.buildRandom(4) + "";
// 10位序列号,可以自行调整。
String strReq = strTime + strRandom;
// 随机数
String nonceStr = strReq;
// 商户号
String mchId = partner;
// 子商户号 非必输
// String sub_mch_id="";
// 商品描述
// String body = describe;
String body = "预存款充值 ";
// 附加数据
String attach = userId;
// 商户订单号
String outTradeNo = tradeInfo.getOrderCode();
// 订单生成的机器 IP
String spbillCreateIp = request.getRemoteAddr();
// String spbillCreateIp ="123.12.12.123";
// 订 单 生 成 时 间 非必输
// 订单失效时间 非必输
// 商品标记 非必输
// 这里notify_url是 支付完成后微信发给该链接信息,可以判断会员是否支付成功,改变订单状态等。
String notifyUrl = pay.getBackUrl();
notifyUrl = notifyUrl.substring(0, notifyUrl.lastIndexOf("/")) + "/wxrechargepaysuc.htm";
String tradeType = "JSAPI";
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid", appid);
packageParams.put("mch_id", mchId);
// packageParams.put("device_info", device_info); // no-required
packageParams.put("nonce_str", nonceStr);
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
// packageParams.put("attach", attach);
// 这里写的金额为1 分到时修改
packageParams.put("total_fee", String.valueOf(totalFee));
packageParams.put("spbill_create_ip", spbillCreateIp);
packageParams.put("notify_url", notifyUrl);
packageParams.put("trade_type", tradeType);
packageParams.put("openid", openId);
RequestHandlerUtil reqHandler = new RequestHandlerUtil(request, response);
reqHandler.init(appid, appsecret, partnerkey);
//签名
String sign = reqHandler.createSign(packageParams);
/*String xml = "<xml>"
+ "<appid>" + appid + "</appid>"
+ "<mch_id>" + mchId + "</mch_id>"
+ "<nonce_str>" + nonceStr + "</nonce_str>"
+ "<sign>" + sign + "</sign>"
+ "<body><![CDATA[" + body + "]]></body>"
+ "<out_trade_no>" + outTradeNo + "</out_trade_no>"
+
// 金额,这里写的1 分到时修改
"<total_fee>" + totalFee + "</total_fee>"
+
"<spbill_create_ip>" + spbillCreateIp + "</spbill_create_ip>"
+ "<notify_url>" + notifyUrl + "</notify_url>"
+ "<trade_type>" + tradeType + "</trade_type>"
+ "<openid>"+openId +"</openid>"
+ "</xml>";*/
String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>" + mchId + "</mch_id>" + "<nonce_str>" + nonceStr + "</nonce_str>" + "<sign>" + sign + "</sign>"
+ "<body><![CDATA[" + body + "]]></body>" + "<out_trade_no>" + outTradeNo + "</out_trade_no>"
+ "<total_fee>" + totalFee + "</total_fee>"
+ "<spbill_create_ip>" + spbillCreateIp + "</spbill_create_ip>" + "<notify_url>" + notifyUrl + "</notify_url>" + "<trade_type>" + tradeType + "</trade_type>"
+ "<openid>" + openId + "</openid>" + "</xml>";
String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
// String createOrderURL = "https://api.mch.weixin.qq.com/sandbox/pay/unifiedorder";
String prepayId = "";
try {
prepayId = GetWxOrderno.getPayNo(createOrderURL, xml);
if ("".equals(prepayId)) {
request.setAttribute("ErrorMsg", "统一支付接口获取预支付订单出错");
response.sendRedirect("error_page.jsp");
}
} catch (Exception e1) {
// LOGGER.info(e1);
prepayId = null;
}
SortedMap<String, String> finalpackage = new TreeMap<String, String>();
String appid2 = appid;
String timestamp = Sha1Util.getTimeStamp();
String nonceStr2 = nonceStr;
String prepayId2 = "prepay_id=" + prepayId;
String packages = prepayId2;
finalpackage.put("appId", appid2);
finalpackage.put("timeStamp", timestamp);
finalpackage.put("nonceStr", nonceStr2);
finalpackage.put("package", packages);
finalpackage.put("signType", "MD5");
String finalsign = reqHandler.createSign(finalpackage);
Map<String, Object> map = new HashMap<String, Object>();
map.put("appId", appid2);
map.put("timeStamp", timestamp);
map.put("nonceStr", nonceStr2);
map.put("package", packages);
map.put("sign", finalsign);
return map;
}
/**
* 微信充值通知处理
*
* @param outTradeNo 交易单号
* @param appId appid
* @param resultCode 返回状态码
* @param mId 商户号
* @return success:成功 fail:失败
*/
@Override
@Transactional
public boolean weixinRechargeNotify(String outTradeNo, String appId, String resultCode, String mId) {
//微信支付信息
Pay pay = payService.selectWxPay();
//交易记录
TradeInfo tradeInfo = tradeInfoService.selectByTradeNo(outTradeNo);
if (SUCCESS_RETURN_CODE.equals(resultCode) && appId.equals(pay.getApiKey()) && mId.equals(pay.getPartner())
&& "5".equals(tradeInfo.getOrderStatus())) {
tradeInfo.setOrderStatus("6");
//充值成功时,当前余额
tradeInfo.setCurrentPrice(tradeInfo.getCurrentPrice().add(tradeInfo.getOrderPrice()));
//更新交易状态
tradeInfoService.updateTradeInfo(tradeInfo);
DepositInfo depositInfo1 = depositInfoMapper.selectDepositByCustId(tradeInfo.getCustomerId());
//更新预存款信息
DepositInfo depositInfo = new DepositInfo();
depositInfo.setCustomerId(tradeInfo.getCustomerId());
depositInfo.setPreDeposit(tradeInfo.getOrderPrice().add(depositInfo1.getPreDeposit()));
depositInfoMapper.updateDepositInfo(depositInfo);
LOGGER.info("=================================微信充值回调成功 单号:"+ outTradeNo);
return true;
}
LOGGER.info("=================================微信充值回调失败 单号:"+ outTradeNo);
return false;
}
@Override
@Transactional
public boolean allinpayRechargeNotify(String orderNo) {
//处理的业务逻辑相同。
return this.zhifubaoRechargeNotify(orderNo);
}
/**
* 验证支付密码
*
* @param payPassword 支付密码
* @param customerId 用户id
* @param type 0:支付 1:提现
* @return
*/
@Override
@Transactional
public JSONObject checkPayPassword(String payPassword, Long customerId, String type,BigDecimal price) {
JSONObject resultJson = new JSONObject();
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
String password = depositInfo.getPayPassword();
int errorCount = depositInfo.getPasswordErrorCount() != null ? depositInfo.getPasswordErrorCount() :0;
//您还没有设置支付密码
if (StringUtils.isEmpty(password)){
if("0".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_SET_PAYPASSWORD0);
}else if ("1".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_SET_PAYPASSWORD1);
}
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.PASS_FAIL_CODE);
}else if(errorCount >= DepositInfoCons.ERROR_THRESHOLD){
//预存款账户锁定,无法支付
if("0".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.REACHE_ERROR_THRESHOLD_TIPS);
}else if ("1".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.REACHE_ERROR_THRESHOLD_TIPS1);
}
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.FROZEN_FAIL_CODE);
}else if(price != null && (depositInfo.getPreDeposit().compareTo(price) <0 || price.signum() <= 0)){
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.BALANCE_FAIL_CODE);
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.DEPOSIT_LESS);
}else {
CustomerAllInfo customerAllInfo = customerMapper.selectByPrimaryKey(customerId);
String encrypPassword = SecurityUtil.getStoreLogpwd(customerAllInfo.getUniqueCode(), payPassword, customerAllInfo.getSaltVal());
if (!StringUtils.equals(encrypPassword, password)){
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
errorCount++;
if (errorCount>= DepositInfoCons.ERROR_THRESHOLD){
//预存款账户锁定,无法支付
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.REACHE_ERROR_THRESHOLD_TIPS);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.FROZEN_FAIL_CODE);
}else {
int leftCount = DepositInfoCons.ERROR_THRESHOLD - errorCount;
if (leftCount > 0 ){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_REACHE_ERROR_THRESHOLD_TIPS + leftCount +"次机会");
}
}
//更新预存款错误信息
DepositInfo depositInfo1 = new DepositInfo();
depositInfo1.setCustomerId(customerId);
depositInfo1.setPasswordErrorCount(errorCount);
depositInfo1.setPasswordTime(new Date());
depositInfoMapper.updateDepositInfo(depositInfo1);
}else {
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.SUCCESS);
}
}
return resultJson;
}
/**
* 预存款支付
*
* @param order 待支付订单
* @param customerId 用户id
* @return
*/
@Override
@Transactional
public JSONObject depositPay(Order order, Long customerId,String payPassword) {
JSONObject resultJson = new JSONObject();
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
Pay depositPay = payService.selectPayByType("5");
//验证支付密码
resultJson = this.checkPayPassword(payPassword, customerId, "0", null);
if (StringUtils.equals(DepositInfoCons.FAIL, resultJson.get(DepositInfoCons.RETURN_CODE).toString())){
return resultJson;
}
//预存款金额小于支付金额
if (depositInfo.getPreDeposit().compareTo(order.getOrderPrice()) < 0){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.DEPOSIT_LESS);
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
}else {
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.SUCCESS);
//更新订单状态
Order or = siteOrderService.getPayOrderByCode(order.getOrderCode());
if (or == null){
List<Order> orders= siteOrderService.queryOrderByOrderOldCode(order.getOrderCode());
for (int i = 0; i<orders.size(); i++){
//查询订单对应的收款单
Receivables receivables = this.receivablesService.queryByOrderCode(orders.get(i).getOrderCode());
if ("0".equals(orders.get(i).getOrderStatus())) {
// 更新订单状态
int result = siteOrderService.paySuccessUpdateOrder(orders.get(i).getOrderId(),"1",order.getPayId());
// int result = siteOrderService.payOrder(orders.get(i).getOrderId());
if (null != receivables && result >0) {
//支付成功更新预存款相关信息
updateDepositInfo(depositInfo, orders.get(i), customerId);
// 修改收款单订单支付状态为支付成功
receivables.setReceivablesTime(new Date());
receivables.setPayMode(depositPay.getPayName());
this.receivablesService.updatePayStatus(receivables);
//支付成功直营店订单短信通知
siteOrderService.paySuccessSendSms(orders.get(i));
}
}
}
}else{
//查询订单对应的收款单
Receivables receivables = this.receivablesService.queryByOrderCode(or.getOrderCode());
if ("0".equals(or.getOrderStatus())) {
// 更新订单状态
int result = siteOrderService.paySuccessUpdateOrder(order.getOrderId(), "1", order.getPayId());
// int result = siteOrderService.payOrder(or.getOrderId());
if (null != receivables && result >0) {
//支付成功更新预存款相关信息
updateDepositInfo(depositInfo, order, customerId);
// 修改收款单订单支付状态为支付成功
receivables.setPayMode(depositPay.getPayName());
receivables.setReceivablesTime(new Date());
this.receivablesService.updatePayStatus(receivables);
//支付成功直营店订单短信通知
siteOrderService.paySuccessSendSms(or);
}
}
}
}
return resultJson;
}
/**
* 验证预存款是否可用
*
* @param customerId 用户id
* @return
*/
@Override
public JSONObject checkDepositPay(Long customerId,BigDecimal orderPrice,String type) {
JSONObject resultJson = new JSONObject();
DepositInfo depositInfo = this.queryDepositInfo(customerId);
// DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
if (depositInfo.getPasswordErrorCount() != null && depositInfo.getPasswordErrorCount() >= DepositInfoCons.ERROR_THRESHOLD){
//预存款账户锁定,无法支付
if("0".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.REACHE_ERROR_THRESHOLD_TIPS);
}else if("1".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.REACHE_ERROR_THRESHOLD_TIPS1);
}
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.FROZEN_FAIL_CODE);
return resultJson;
}else if(StringUtils.isEmpty(depositInfo.getPayPassword())){
//您还没有设置支付密码
if("0".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_SET_PAYPASSWORD0);
}else if("1".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_SET_PAYPASSWORD1);
}
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.PASS_FAIL_CODE);
return resultJson;
}else if(depositInfo.getPreDeposit().compareTo(orderPrice) < 0){
//预存款余额不足
if("0".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_ENOUGH_PAYPASSWORD + depositInfo.getPreDeposit());
}else if("1".equals(type)){
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_ENOUGH_PAYPASSWORD1);
}
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
resultJson.put(DepositInfoCons.FAIL_CODE, DepositInfoCons.BALANCE_FAIL_CODE);
return resultJson;
}else {
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.SUCCESS);
}
return resultJson;
}
/**
* 支付宝充值
* @param rechargePrice 充值金额
* @param customerId 用户id
* @return
*/
@Override
public String zhifubaoRecharge(BigDecimal rechargePrice,Long customerId) {
//生成预付款交易记录
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
TradeInfo tradeInfo = tradeInfoService.insertSelective(customerId, rechargePrice, "0", "0","在线充值-支付宝",depositInfo);
Pay p = payService.findByPayId(25L);
AlipayConfig.partner = p.getApiKey();
AlipayConfig.seller_id = p.getApiKey();
Properties properties = PropertieUtil.readPropertiesFile(DepositInfoServiceImpl.class.getClassLoader().getResourceAsStream("com/ningpai/web/config/alipay.properties"));
// 本地karaf路径
AlipayConfig.private_key = properties.getProperty("PRIVATE_KEY");
// 支付类型
String paymentType = "1";
// 必填,不能修改
// 服务器异步通知页面路径
String notifyUrl = p.getPayComment()+"asynrechargesucccess.htm";
// 需http://格式的完整路径,不能加?id=123这类自定义参数
// 页面跳转同步通知页面路径
String returnUrl = p.getPayComment()+"synrechargesucccess.htm";
// 需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
// 商户网站订单系统中唯一订单号,必填
// 订单名称
String subject = "充值";
// 必填
DecimalFormat df=new DecimalFormat("0.00");
// 充值金额
String totalFee = df.format(rechargePrice.doubleValue()).toString();
// 必填
// 商品展示地址
String showUrl = p.getPayUrl();
// 必填,需以http://开头的完整路径,例如:http://www.商户网址.com/myorder.html
// 订单描述
String body = "手机网购订单";
// 选填
// 超时时间
String itBPay = "";
// 选填
// 钱包token
String externToken = "";
// 选填
// ////////////////////////////////////////////////////////////////////////////////
// 把请求参数打包成数组
Map<String, String> sParaTemp = new HashMap<String, String>();
sParaTemp.put("service", "alipay.wap.create.direct.pay.by.user");
sParaTemp.put("partner", AlipayConfig.partner);
sParaTemp.put("seller_id", AlipayConfig.seller_id);
sParaTemp.put("_input_charset", AlipayConfig.input_charset);
sParaTemp.put("payment_type", paymentType);
sParaTemp.put("notify_url", notifyUrl);
sParaTemp.put("return_url", returnUrl);
sParaTemp.put("out_trade_no", tradeInfo.getOrderCode());
sParaTemp.put("subject", subject);
sParaTemp.put("total_fee", totalFee);
sParaTemp.put("show_url", showUrl);
sParaTemp.put("body", body);
sParaTemp.put("it_b_pay", itBPay);
sParaTemp.put("extern_token", externToken);
// 建立请求
return AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
}
/**
* 微信充值通知处理
*
* @param outTradeNo 交易单号
* @return success:成功 fail:失败
*/
@Override
@Transactional
public boolean zhifubaoRechargeNotify(String outTradeNo) {
TradeInfo tradeInfo = tradeInfoService.selectByTradeNo(outTradeNo);
if ("5".equals(tradeInfo.getOrderStatus())) {
tradeInfo.setOrderStatus("6");
DepositInfo depositInfo1 = depositInfoMapper.selectDepositByCustId(tradeInfo.getCustomerId());
//充值成功当前余额
tradeInfo.setCurrentPrice(depositInfo1.getFreezePreDeposit().add(depositInfo1.getPreDeposit()).add(tradeInfo.getOrderPrice()));
//更新交易状态
tradeInfoService.updateTradeInfo(tradeInfo);
//更新预存款信息
DepositInfo depositInfo = new DepositInfo();
depositInfo.setCustomerId(tradeInfo.getCustomerId());
depositInfo.setPreDeposit(tradeInfo.getOrderPrice().add(depositInfo1.getPreDeposit()));
depositInfoMapper.updateDepositInfo(depositInfo);
return true;
}
return false;
}
/**
*
* @param depositInfo
* @param order
* @param customerId
*/
private void updateDepositInfo(DepositInfo depositInfo, Order order, Long customerId){
TradeInfo tradeInfo = new TradeInfo();
tradeInfo.setDelFlag("0");
tradeInfo.setCreateTime(new Date());
tradeInfo.setCurrentPrice(depositInfo.getPreDeposit().subtract(order.getOrderPrice()).add(depositInfo.getFreezePreDeposit()));
tradeInfo.setOrderCode(order.getOrderCode());
tradeInfo.setCustomerId(customerId);
tradeInfo.setOrderPrice(order.getOrderPrice());
tradeInfo.setCreatePerson(customerId);
tradeInfo.setTradeRemark("订单编号:" + order.getOrderCode());
tradeInfo.setOrderType("3");
tradeInfoService.insertTradeInfo(tradeInfo);
//更新预存款信息
depositInfo.setPreDeposit(depositInfo.getPreDeposit().subtract(order.getOrderPrice()));
depositInfoMapper.updateDepositInfo(depositInfo);
}
/**
* 提现功能是否可用验证
*
* @param customerId 用户id
* @return
*/
@Override
public JSONObject checkWithdraw(Long customerId) {
JSONObject resultJson = new JSONObject();
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
if(StringUtils.isEmpty(depositInfo.getPayPassword())){
//您还没有设置支付密码
resultJson.put(DepositInfoCons.RETURN_MSG, DepositInfoCons.NOT_SET_PAYPASSWORD1);
resultJson.put(DepositInfoCons.RETURN_CODE, DepositInfoCons.FAIL);
}
return resultJson;
}
/**
* 通联充值 - h5快捷支付
* @param rechargePrice 充值金额
* @param customerId 用户id
* @return
* @throws IOException
*/
@Override
public void allinpayPecharge(BigDecimal rechargePrice,HttpServletRequest request,HttpServletResponse response) throws IOException {
Long customerId = (Long) request.getSession().getAttribute(CustomerConstants.CUSTOMERID);
// 生成预付款交易记录
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
TradeInfo tradeInfo = tradeInfoService.insertSelective(customerId, rechargePrice, "0", "0", "在线充值-通联H5快捷支付", depositInfo);
Pay p = payService.selectPayByType("9");
tLPayService.goTLRecharge(p, tradeInfo.getOrderCode(), customerId, rechargePrice,"H5", request, response);
// ///////////////////////////////////////////////////////////////////////
// String userId = null;
// AllinpayReg allinpayReg = allinpayRegService.queryRegInfoByCustomerId(customerId);
// if (allinpayReg == null || StringUtils.isEmpty(allinpayReg.getUserId())) {
// try {
// userId = tLPayService.goRegistCustomer(p, customerId);
// } catch (IOException e) {
// e.printStackTrace();
// }
// } else {
// userId = allinpayReg.getUserId();
// }
//
// ///////////////////////////////////////////////////////////////////////
//
// String inputCharset = "1";
// String version = "v1.0";
// String pickupUrl = p.getBackUrl() + "mobile/showmypredeposits.htm";
// String receiveUrl = p.getBackUrl() + "mobile/allinpayPechargeReceive.htm";
// String payUrl = p.getPayUrl() + "/mobilepayment/mobile/SaveMchtOrderServlet.action";
// String signType = "0";
// String merchantId = p.getPartner();
// String orderNo = tradeInfo.getOrderCode();
// String orderAmount = rechargePrice.multiply(new BigDecimal(100)).intValue()+"";
// String orderCurrency = "0";
// String orderDatetime = new SimpleDateFormat("yyyyMMddHHmmss").format(tradeInfo.getCreateTime());
// String ext1 = "<USER>" + userId + "</USER>";
// String payType = "33";
//// String tradeNature = "GOODS";
// String key = p.getSecretKey();
//
// ///////////////////////////////////////////////////////////////////////
//
// Map<String, String> params = new HashMap<String, String>();
// params.put("inputCharset", inputCharset); // 必填
// params.put("pickupUrl", pickupUrl); // 必填:前台通知回调url
// params.put("receiveUrl", receiveUrl); // 必填:服务器通知回调url
// params.put("version", version); // 必填
// // params.put("language", "1");
// params.put("signType", signType); // 必填
// params.put("merchantId", merchantId); // 必填
// // params.put("payerName", "aaa");
// // params.put("payerEmail", "aaa");
// // params.put("payerTelephone", "aaa");
// // params.put("payerIDCard", "aaa");
// // params.put("pid", "");
// params.put("orderNo", orderNo); // 必填
// params.put("orderAmount", orderAmount); // 必填
// params.put("orderCurrency", orderCurrency); // 必填
// params.put("orderDatetime", orderDatetime); // 必填
// // params.put("orderExpireDatetime", "aaa"); //
// // 订单过期时间。整形数字,单位为分钟。最大值和默认值为 180 分钟。
//
//// params.put("productName", "学费");
//// params.put("productPrice", rechargePrice.toString());
//// params.put("productNum", "1");
// // params.put("productId", "aaa");
//// params.put("productDesc", "测试通联支付所交的学费");
// params.put("ext1", ext1); // H5 版、PC 快捷需商户有会员,对接时必填
// // params.put("ext2", "aaa");
// // params.put("extTL", "aaa");
// params.put("payType", payType); // 必填
// // params.put("issuerId", "aaa");
// // params.put("pan", "33");
//// params.put("tradeNature", tradeNature);
// StringBuffer bufSignSrc = new StringBuffer();
// TLPayUtil.appendSignPara(bufSignSrc, "inputCharset", inputCharset);
// TLPayUtil.appendSignPara(bufSignSrc, "pickupUrl", pickupUrl);
// TLPayUtil.appendSignPara(bufSignSrc, "receiveUrl", receiveUrl);
// TLPayUtil.appendSignPara(bufSignSrc, "version", version);
// TLPayUtil.appendSignPara(bufSignSrc, "signType", signType);
// TLPayUtil.appendSignPara(bufSignSrc, "merchantId", merchantId);
// TLPayUtil.appendSignPara(bufSignSrc, "orderNo", orderNo);
// TLPayUtil.appendSignPara(bufSignSrc, "orderAmount", orderAmount);
// TLPayUtil.appendSignPara(bufSignSrc, "orderCurrency", orderCurrency);
// TLPayUtil.appendSignPara(bufSignSrc, "orderDatetime", orderDatetime);
// TLPayUtil.appendSignPara(bufSignSrc, "ext1", ext1);
// TLPayUtil.appendSignPara(bufSignSrc, "payType", payType);
// // TLPayUtil.appendSignPara(bufSignSrc, "tradeNature", tradeNature);
// TLPayUtil.appendLastSignPara(bufSignSrc, "key", key);
//
// String signMsg = com.allinpay.ets.client.SecurityUtil.MD5Encode(bufSignSrc.toString());
// params.put("signMsg", signMsg); // 必填
// params.put("customsExt", "aaa");
// 建立请求
// return TLPayUtil.createHtml(payUrl, params);
}
/**
* 通联充值 - 微信支付
* @param rechargePrice 充值金额
* @param customerId 用户id
* @return
* @throws IOException
*/
@Override
public Map<String, Object> allinpayWxRecharge(HttpServletRequest request, HttpServletResponse response,
Long customerId, BigDecimal orderPrice) {
String payType = "8";
if(orderPrice.compareTo(new BigDecimal(1000000)) > 0){
return null;
}
DepositInfo depositInfo = depositInfoMapper.selectDepositByCustId(customerId);
//生成预付款交易记录
TradeInfo tradeInfo = tradeInfoService.insertSelective(customerId, orderPrice, "0", payType, "在线充值-通联微信",depositInfo);
//微信支付信息
Pay pay = payService.selectPayByType(payType);
//获取支付信息
if (tradeInfo == null){
return null;
}
return brandTlWXPayRequest(request, response, tradeInfo, pay);
}
/**
* 通联微信参数
* @param request
* @param response
* @param tradeInfo
* @param pay
* @return
*/
private Map<String, Object> brandTlWXPayRequest(HttpServletRequest request, HttpServletResponse response,TradeInfo tradeInfo,Pay pay ){
Map<String, String> payInfoMap = null;// 用于存放调用通联微信公众号的统一支付接口信息
// 网页授权后获取传递的参数
String userId = request.getParameter("userId");
if(request.getSession().getAttribute("openid") == null){
return null;
}
if(tradeInfo !=null){
//获取微信参数openId
String acct = request.getSession().getAttribute("openid").toString();
//预存款的充值的金额
BigDecimal tradePrice = tradeInfo.getOrderPrice();
//预存款充值的订单的编号
String tradeInfoCode = tradeInfo.getOrderCode();
//订单的名称
String payRemark = tradeInfo.getPayRemark();
String remark = "洋鼹鼠微信公众号预存款充值订单";
String payType = "W02";
String notify_url = "/allinpaywxrechargereceive.htm";
try {
payInfoMap = tLPayService.pay(pay, tradeInfoCode, payRemark, tradePrice, remark, payType, acct, notify_url);
LOGGER.info("【微信公众号调用统一支付接口成功返回的信息】" + payInfoMap.toString());
} catch (Exception e) {
LOGGER.info("【微信公众号调用统一支付接口失败返回的信息】" + payInfoMap.toString());
e.printStackTrace();
}
}
//解析通联支付接口回调的结果参数(通联结果参数格式如下);转换成调用微信内嵌的接口所需的参数
/*{"appid":"00000006","cusid":"XXXXXXXX",
"payinfo":"{\"appId\":\"wxb3fa424b649563b5\",\"timeStamp\":\"1477356696\",
\"signType\":\"MD5\",\"package\":\"prepay_id=wx201610250851362b67f0b6570252306441\",
\"nonceStr\":\"38642\",\"paySign\":\"66FF000B739F459D093FE24AB3462170\"}",
"reqsn":"1610258923119024","retcode":"SUCCESS","sign":"9513D3ABF5983F3FACCD8161931DB1ED",
"trxid":"180681592","trxstatus":"0000"}*/
Map<String, Object> map = new HashMap<String, Object>();//存放回调微信内嵌的支付接口所需的参数信息
if (payInfoMap != null && "SUCCESS".equals(payInfoMap.get("retcode"))) {
String payinfo = payInfoMap.get("payinfo");
if (payinfo != null && payinfo.trim().length() > 0) {
LOGGER.info("【微信公众号调用统一支付接口成功返回的信息payinfo】" + payinfo);
JSONObject parseObject = JSONObject.parseObject(payinfo);
map.put("appId", parseObject.getString("appId"));
map.put("timeStamp",parseObject.getString("timeStamp"));
map.put("nonceStr", parseObject.getString("nonceStr"));
map.put("package", parseObject.getString("package"));
map.put("sign", parseObject.getString("paySign"));
} else {
LOGGER.info("【微信公众号调用统一支付接口成功返回的信息】" + payinfo);
}
}
return map;
}
/**
* 通联微信充值通知处理
*
* @param outTradeNo 交易单号
* @param appId appid
* @param resultCode 返回状态码
* @param mId 商户号
* @return success:成功 fail:失败
*/
@Override
@Transactional
public boolean allinpayWxRechargeReceive(String outTradeNo, String appId, String resultCode, String mId) {
//通联微信支付信息
Pay pay = payService.selectPayByType("8");
//交易记录
TradeInfo tradeInfo = tradeInfoService.selectByTradeNo(outTradeNo);
if ("0000".equals(resultCode) && appId.equals(pay.getApiKey()) && mId.equals(pay.getPartner())
&& "5".equals(tradeInfo.getOrderStatus())) {
tradeInfo.setOrderStatus("6");
//通联充值成功时,当前余额
tradeInfo.setCurrentPrice(tradeInfo.getCurrentPrice().add(tradeInfo.getOrderPrice()));
//更新交易状态
tradeInfoService.updateTradeInfo(tradeInfo);
DepositInfo depositInfo1 = depositInfoMapper.selectDepositByCustId(tradeInfo.getCustomerId());
//更新预存款信息
DepositInfo depositInfo = new DepositInfo();
depositInfo.setCustomerId(tradeInfo.getCustomerId());
depositInfo.setPreDeposit(tradeInfo.getOrderPrice().add(depositInfo1.getPreDeposit()));
depositInfoMapper.updateDepositInfo(depositInfo);
LOGGER.info("========allinpayWxRechargeReceive========通联微信充值回调成功 单号:"+ outTradeNo);
return true;
}
LOGGER.info("======allinpayWxRechargeReceive=======通联微信充值回调失败 单号:"+ outTradeNo);
return false;
}
}
|
Markdown
|
UTF-8
| 4,730 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
title: "常见问题"
---
### 如何快速了解 KubeSphere
1、作为新手,如何快速了解 KubeSphere 的使用?
答:我们提供了多个快速入门的示例包括工作负载和 DevOps 工程,建议从 [快速入门](../../zh-CN/quick-start/quick-start-guide) 入手,参考 **快速入门** 并实践和操作每一个示例。
### Multi-node 安装配置相关问题
2、[Multi-Node 模式](../installation/multi-node) 安装时,如果某些服务器的 **Ubuntu** 系统默认管理员用户为 `ubuntu`,若切换为 `root` 用户进行安装,应该如何配置和操作?
可通过命令 `sudo su` 切换为 root 用户后,在该节点查看是否能 ssh 连接到其他机器,如果 ssh 无法连接,则需要参考 `conf/hosts.ini` 的注释中 `non-root` 用户示例部分,如下面第二步 `hosts.ini` 配置示例所示,而最终执行安装脚本 `install.sh` 时建议以 `root` 用户执行安装。
第一步,查看是否能 ssh 连接到其他机器,若无法连接,则参考第二步配置示例。相反,如果 root 用户能够 ssh 成功连接到其它机器,则可以参考 Installer 中默认的 root 用户配置方式。
```
root@192.168.0.3 # ssh 192.168.0.2
Warning: Permanently added 'node1,192.168.0.2' (ECDSA) to the list of known hosts.
root@192.168.0.2's password:
Permission denied, please try again.
```
第二步,如下示例使用 3 台机器,参考以下示例修改主机配置文件 `hosts.ini`。
**hosts.ini 配置示例**
```ini
[all]
master ansible_connection=local ip=192.168.0.1 ansible_user=ubuntu ansible_become_pass=Qcloud@123
node1 ansible_host=192.168.0.2 ip=192.168.0.2 ansible_user=ubuntu ansible_become_pass=Qcloud@123
node2 ansible_host=192.168.0.3 ip=192.168.0.3 ansible_user=ubuntu ansible_become_pass=Qcloud@123
[kube-master]
master
[kube-node]
node1
node2
[etcd]
master
[k8s-cluster:children]
kube-node
kube-master
```
### 安装失败相关问题
3、安装过程中,如果遇到安装失败并且发现错误日志中有这类信息:`The following packages have pending transactions`,这种情况应该如何处理?

答:这是因为有些 transactions 操作没有完成,可以连接到安装失败的节点上,依次执行下列命令,并重新执行 `install.sh` 脚本:
```shell
$ yum install yum-utils -y
$ yum-complete-transaction
$ yum-complete-transaction --cleanup-only
```
<!-- 3、如果在操作 [示例六](../../devops/jenkinsfile-in-scm) 运行流水线时,遇到 `Could not resolve host: github.com` 这类情况造成流水线运行失败了,应该如何处理?

答:可能是由于主机环境对 GitHub 域名解析配置的问题,可以在后台编辑配置文件 `/etc/resolv.conf`,将其中的 `search domain` 这一行命令注释掉,流水线即可正常运行。如下所示注释了第二行 `search pek3.qingcloud.com`。
```
# Generated by NetworkManager
# search pek3.qingcloud.com
nameserver 100.64.9.5
···
``` -->
### 流水线运行报错相关问题
4、创建 Jenkins 流水线后,运行时报错怎么处理?

答:最快定位问题的方法即查看日志,点击 **查看日志**,具体查看出错的阶段 (stage) 输出的日志。比如,在 **push image** 这个阶段报错了,如下图中查看日志提示可能是 DockerHub 的用户名或密码错误。

5、运行流水线失败时,查看日志发现是 Docker 镜像 push 到 DockerHub 超时问题 (Timeout),比如以下情况,要怎么处理?

答:可能由于网络问题造成,建议尝试再次运行该流水线。
### 如何查看 kubeconfig 文件
6、如何查看 Kubeconfig 文件?
用户可以通过打开 Kubectl UI 查看 Kubeconfig 文件,仅管理员或拥有 Kubectl UI 权限的用户有权限。

### 如何访问 Jenkins 服务端
7、如何访问和登录 Jenkins 服务端?
Installer 安装将会同时部署 Jenkins Dashboard,该服务暴露的端口 (NodePort) 为 `30180`,确保外网流量能够正常通过该端口,然后访问公网 IP 和端口号 (${EIP}:${NODEPORT}) 即可。Jenkins 已对接了 KubeSphere 的 LDAP,因此可使用用户名 `admin` 和 KubeSphere 集群管理员的密码登录 Jenkins Dashboard。
> 说明:
> 若您在使用中遇到任何产品相关的问题,欢迎在 [GitHub Issue](https://github.com/kubesphere/docs.kubesphere.io/issues) 提问。
|
JavaScript
|
UTF-8
| 2,487 | 2.625 | 3 |
[] |
no_license
|
import { useReducer, useEffect } from "react";
import axios from "axios";
const BASE_URL =
"https://api.allorigins.win/raw?url=https://jobs.github.com/positions.json";
const ACTIONS = {
MAKE_REQUEST: "make-request",
GET_DATA: "get-data",
ERROR: "error",
UPDATE_HAS_NEXT_PAGE: "update_has_next_page",
};
const reducer = (currstate, action) => {
switch (action.type) {
case ACTIONS.MAKE_REQUEST:
return { jobs: [], loading: true };
case ACTIONS.GET_DATA:
return {
...currstate,
jobs: action.payload.jobs,
loading: false,
};
case ACTIONS.ERROR:
return { ...currstate, jobs: [], error: action.payload.error };
case ACTIONS.UPDATE_HAS_NEXT_PAGE:
return { ...currstate, hasNextPage: action.payload.hasNextPage };
default:
return currstate;
}
};
export const useFetchJobs = (params, page) => {
const [state, dispatch] = useReducer(reducer, {
jobs: [],
loading: true,
});
// console.log(state);
useEffect(() => {
const cancelToken1 = axios.CancelToken.source();
const cancelToken2 = axios.CancelToken.source();
dispatch({ type: ACTIONS.MAKE_REQUEST });
axios
.get(BASE_URL, {
cancelToken: cancelToken1.token,
params: { markdown: true, page: page, ...params },
})
.then((res) => {
// console.log(res.data);
dispatch({ type: ACTIONS.GET_DATA, payload: { jobs: res.data } });
})
.catch((e) => {
if (axios.isCancel(e)) return;
dispatch({ type: ACTIONS.ERROR, payload: { error: e } });
});
// checking if there is another page for pagination
axios
.get(BASE_URL, {
cancelToken: cancelToken2.token,
params: { markdown: true, page: page + 1, ...params },
})
.then((res) => {
// console.log(res.data);
dispatch({
type: ACTIONS.UPDATE_HAS_NEXT_PAGE,
payload: { hasNextPage: res.data.length !== 0 },
});
})
.catch((e) => {
if (axios.isCancel(e)) return;
dispatch({ type: ACTIONS.ERROR, payload: { error: e } });
});
return () => {
cancelToken1.cancel();
cancelToken2.cancel();
};
}, [params, page]);
return state;
};
// for too many requests. i do not know how this works
// add before api call just like heroku
// https://api.allorigins.win/raw?url=
|
C#
|
UTF-8
| 1,947 | 3.96875 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
namespace Questions
{
public class SearchInOrderedArray
{
public int Search(int[] array, int searchFor)
{
if(array == null || array.Length == 0)
throw new ArgumentException("Invalid input", nameof(array));
var lower = 0;
var upper = array.Length -1;
while (lower <= upper)
{
var index = (lower + upper) / 2;
if (array[index] == searchFor)
{
return array[index];
}
else if (array[index] < searchFor)
{
lower = index+1;
}
else
{
upper = index-1;
}
}
throw new KeyNotFoundException();
}
public int SearchRecursive(int[] array, int searchFor)
{
if (array == null || array.Length == 0)
throw new ArgumentException("Invalid input", nameof(array));
return SearchRecursive(array, 0, array.Length - 1, searchFor);
}
private int SearchRecursive(int[] array,int lower,int upper, int searchFor)
{
if (lower <= upper)
{
var index = (lower + upper) / 2;
if (array[index] == searchFor)
{
return array[index];
}
else if (array[index] < searchFor)
{
lower = index + 1;
return SearchRecursive(array, lower, upper, searchFor);
}
else
{
upper = index - 1;
return SearchRecursive(array, lower, upper, searchFor);
}
}
throw new KeyNotFoundException();
}
}
}
|
Markdown
|
UTF-8
| 4,082 | 2.515625 | 3 |
[] |
no_license
|
# Algoritmi
Colectie de algoritmi elementari, scrisi in C++
## [Cautare Binara](https://github.com/ExplodingInsanity/Algoritmi/tree/master/cautare%20binara)
Algoritm de cautare intr-un sir ordonat. Complexitate logaritmica
Algoritmi scrisi pentru:
* Cautare binara - Iterativa
* Cautare binara - Recursiva
* Cautarea binara recursiva, fara parametri de stanga si dreapta
* Partea Intreaga a radicalului unui numar natural
[Wikipedia - Cautare Binara](https://ro.wikipedia.org/wiki/C%C4%83utare_binar%C4%83)
## [Cel mai mare divizor](https://github.com/ExplodingInsanity/Algoritmi/tree/master/cmmdc)
Algoritmi scrisi pentru:
* cmmdc prin algoritmul lui Euclid - Iterativ
* cmmdc prin algoritmul lui Euclid - Recursiv
* cmmdc prin scaderi repetate
[Infoarena - Algoritmul lui Euclid](https://infoarena.ro/algoritmul-lui-euclid)
[Wikipedia - Algoritmul lui Euclid](https://ro.wikipedia.org/wiki/Algoritmul_lui_Euclid)
## Conversii baze
Algoritmi scrisi pentru
* Conversia unui numar din baza b in baza 10 iterativ, returnat ca numar, b < 10
* Conversia unui numar din baza b in baza 10 recursiv, returnat ca numar, b < 10
* Conversia unui numar din baza 10 in baza b iterativ, returnat ca numar, b < 10
* Conversia unui numar din baza 10 in baza b recursiv, returnat ca numar, b < 10
* Conversia unui numar din baza 10 in baza b recursiv, returnat ca sir de caractere, b < 10
* Conversia unui sir de caractere din baza b in baza 10 iterativ, returnat ca numar, b < 37
* Conversia unui sir de caractere din baza b in baza 10 recursiv, returnat ca numar, b < 37
## [Flood Fill](https://github.com/ExplodingInsanity/Algoritmi/tree/master/flood%20fill)
Algoritm de determinare a zonelor dintr-o matrice cu o anumita proprietate,
Algoritmi scrisi pentru:
* Aflarea numarului de camere dintr-o matrice unde se dau locatiile peretilor
[Tutoriale-pe-net - Algoritmul de fill](https://tutoriale-pe.net/algoritmul-de-fill-de-umplere-in-c/)
[Wikipedia - Flood fill](https://en.wikipedia.org/wiki/Flood_fill)
## [Interclasare](https://github.com/ExplodingInsanity/Algoritmi/tree/master/interclasare)
Reuniunea a doi vectori sortati crescator. Se foloseste la Merge Sort.
Algoritmi scrisi pentru:
* Reuniunea a doi vectori, fara repetitie
[Tutoriale-pe-net - Interclasarea a doi vectori in C++](https://tutoriale-pe.net/interclasarea-a-doi-vectori-in-c/)
## [Numarul de cifre 1 din reprezentarea binara](https://github.com/ExplodingInsanity/Algoritmi/tree/master/flood%20fill)
Nu e neaparat algoritm elementar, dar sunt mai multe metode de aflare a numarului de cifre 1 din reprezentarea binara a unui numar.
Algoritmi scrisi pentru:
* Aflarea numarului de cifre '1' prin impartiri repetate si modulo
* Aflarea numarului de cifre '1' prin 'and' logic intre n si 1, si shift pe biti
* Aflarea numarului de cifre '1' prin 'and' logic repetat intre n si n-1
* Aflarea numarului de cifre '1' prin preprocesare si verificarea a cate 4 biti odata
[Tutoriale-pe-net - Algoritmul de fill](https://tutoriale-pe.net/algoritmul-de-fill-de-umplere-in-c/)
[Wikipedia - Flood fill](https://en.wikipedia.org/wiki/Flood_fill)
## [Permutari - asta probabil nu-i bine ¯\\_(ツ)_/¯](https://github.com/ExplodingInsanity/Algoritmi/tree/master/permutari)
Generarea permutarilor unui sir, prin backtracking. Probabil o sa schimb folderul asta si o sa pun in schimb unul cu backtracking
Algoritmi scrisi pentru:
* Afisarea tuturor permutarilor
## Recursivitate
Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion Is this recursion???????????
Algoritmi scrisi pentru:
* Conversie dintr-o baza (<10) in baza 10
* Al n-lea termen din sirul lui Fibonacci
* Elementul de pe linia l, coloana c din triunghiul lui Pascal
* Suma cifrelor unui numar
* Numarul format din cifrele impare ale unui numar, si cel format din cifrele pare
* Valoarea unui polinom intr-un anumit punct
# TODO:
* Conversie din baza 10 in baza b
* Hanoi
* Interclasare
* Sort (bubble sort, merge sort, etc)
|
TypeScript
|
UTF-8
| 1,199 | 2.640625 | 3 |
[] |
no_license
|
import { ChangeDetectionStrategy
, Component
, EventEmitter
, Input
, OnInit
, Output
} from '@angular/core'
import { Tile } from '../../world/model'
import { TILE_WIDTH
, TILE_HEIGHT
} from '../../world/constants/visual'
@Component(
{ selector: 'game-tile'
, templateUrl: './game-tile.component.html'
, styleUrls: [ './game-tile.component.css' ]
, changeDetection: ChangeDetectionStrategy.OnPush
}
)
class GameTile {
width: number = TILE_WIDTH
height: number = TILE_HEIGHT
@Input() shouldAnimate
@Input() tile: Tile
@Input() marked: Tile[]
@Input() zIndex: number
@Output() mark = new EventEmitter()
// Emits a MARK_TILE event loaded with a tile, only if it is open.
onClick (): void {
if (this.tile.isOpen) {
this.mark.emit(this.tile)
}
}
// Is this tile marked?
isMarked (): boolean {
const [ i0, j0, k0 ] = this.tile.address
return this.marked.some(
({ address: [ i, j, k ] }: Tile) => i === i0
&& j === j0
&& k === k0
)
}
}
export default GameTile
|
Markdown
|
UTF-8
| 853 | 3.125 | 3 |
[] |
no_license
|
# Introduction To Flutter Workshop
> A workshop to serve as an introduction to Flutter, Dart and how to go about building your first application.
## Table of Contents
* [🎯 Goals](#goals)
* [⚡ Get Started](#get-started)
* [🚀 How To Use This Workshop](#how-to-use-this-workshop)
## 🎯 Goals
- Learn what Flutter is
- Learn what Dart is
- Learn why we should be using Flutter
- Learn how to create a new Flutter project
- Demonstrate what [pub.dev](https://pub.dev/) is
- Demonstrate how to add a package to your application
- Learn what widgets are
- Learn what the widget tree is
- Learn what the element tree is
- Learn the difference between stateful and stateless widgets
## ⚡ Get Started
### Clone Repo
```
# clone the repo
$ git clone git@github.com:askharley/introduction_to_flutter_workshop.git
```
## 🚀 How To Use This Workshop
|
JavaScript
|
UTF-8
| 463 | 2.875 | 3 |
[] |
no_license
|
export const loadstate = () => {
try{
const localdata = localStorage.getItem('state');
if(localdata == null){
return undefined;
}
return JSON.parse(localdata);
}
catch(err){
return undefined;
}
}
export const savestate = state => {
try {
const savedata = JSON.stringify(state);
localStorage.setItem('state', savedata);
}
catch(err){
console.log(err);
}
}
|
PHP
|
UTF-8
| 377 | 2.59375 | 3 |
[] |
no_license
|
<?php
function check_username_not_unique($user_name = '')
{
$sql = "SELECT COUNT(username) as num FROM the_user WHERE username='".trim($user_name)."'";
$query = mysql_query($sql) or die("ERROR : ".mysql_error()."$sql<br>");
$row = mysql_fetch_assoc($query);
$total = $row['num'];
if($total > 0)
{
return FALSE;
}
else
{
return TRUE;
}
}
?>
|
TypeScript
|
UTF-8
| 1,329 | 2.515625 | 3 |
[] |
no_license
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http:HttpClient) {
}
httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*'
})
}
post(urlName,data):Observable<any>{
return this.http.post(this.apiGetUrl(urlName), data, this.httpOptions);/*.pipe(
retry(1),
catchError(this.errorHandl)
);*/
}
// Error handling
errorHandl(error) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
baseUrl = "http://localhost/learnangular/";
apiGetUrl(istek): string{
let secim:string = "";
switch(istek)
{
case "login":
secim = this.baseUrl+"login.php";
break;
}
return secim;
}
}
|
Java
|
UTF-8
| 388 | 2.015625 | 2 |
[] |
no_license
|
package com.Federico.ProyectoFinal.Model;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface DaoOrdenRepuesto extends CrudRepository<OrdenRepuesto, Long>{
List<OrdenRepuesto> findByOrden(Orden orden);
OrdenRepuesto findByOrdenAndRepuesto(Orden orden, Repuesto repuesto);
}
|
TypeScript
|
UTF-8
| 202 | 2.59375 | 3 |
[] |
no_license
|
import { FormControl } from "./form-control.decorator"
export class Person {
id: number;
@FormControl({ type: 'text' })
name: string
@FormControl({ type: 'number' })
age: number
}
|
JavaScript
|
UTF-8
| 393 | 3.125 | 3 |
[] |
no_license
|
var cities = [
{ name: 'Los Angeles', temperature: 60.0, windSpeed: 4 },
{ name: 'Atlanta', temperature: 52.0, windSpeed: 7 },
{ name: 'Detroit', temperature: 48.0, windSpeed: 8},
{ name: 'New York', temperature: 80.0, windSpeed: 6}
];
var newCities = cities.filter(function(element) {
return element.temperature > 50 && element.windSpeed > 6;
});
console.log(newCities);
|
Java
|
UTF-8
| 7,861 | 2.1875 | 2 |
[] |
no_license
|
package com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.fragments;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.R;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.adapters.AlbumAdapter;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.api.ApiClient;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.model.Album;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.model.IAlbum;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.model.Image;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.model.TopAlbumsHolder;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.realm.AlbumRealmModel;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.utils.Constants;
import com.lastfmseach.stanislavsikorsyi.lastfmartistalbums.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Fragment to show albums of certain artist in list
*/
public class AlbumsFragment extends Fragment {
private final String TAG = "AlbumsFragment";
private ListView albumListView;
private AlbumAdapter albumAdapter;
private boolean isDownloadInProgress = false;
private List<IAlbum> albumList = new ArrayList<IAlbum>();
public String artistName = "Cher";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_album_search, container, false);
albumListView = (ListView) rootView.findViewById(R.id.listView_of_albums);
return rootView;
}
/**
* This method will only be called once when the retained
* Fragment is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initListView();
if(Utils.isOnline(getActivity())) {
downloadAlbumData();
} else {
Toast.makeText(getActivity(), R.string.no_connection, Toast.LENGTH_SHORT).show();
getAlbumsFromRealmStorage();
}
}
/**
* Initialization of adapter and listView itself
*/
private void initListView() {
albumAdapter = new AlbumAdapter(getActivity(), albumList, this);
albumListView.setAdapter(albumAdapter);
albumListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onClickItem(position);
}
});
}
/**
* Click on file item
* @param position Position of item in list
*/
private void onClickItem(int position) {
if(Utils.isOnline(getActivity())) {
TracksFragment newFragment = new TracksFragment();
Bundle args = new Bundle();
args.putString(Constants.ALBUM_NAME, albumList.get(position).getName());
args.putString(Constants.ARTIST_NAME, artistName);
Log.d(TAG, "album:" + albumList.get(position).getName());
newFragment.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack("Album");
transaction.commit();
} else {
Toast.makeText(getActivity(), R.string.no_connection, Toast.LENGTH_SHORT).show();
}
}
/**
* Download data from server in separate thread
*/
public void downloadAlbumData() {
if (!isDownloadInProgress) {
isDownloadInProgress = true;
ApiClient.getAlbumsByArtist().pullAlbums(Constants.METHOD_GET_ALBUMS,
artistName,
getResources().getString(R.string.api_key),
Constants.JSON,
new Callback<TopAlbumsHolder>() {
@Override
public void success(TopAlbumsHolder albums, Response response) {
consumeApiData(albums.getTopAlbums().getAlbum());
}
@Override
public void failure(RetrofitError retrofitError) {
consumeApiData(null);
Log.d(TAG, "failure downloading: " + retrofitError.getMessage());
}
});
}
}
/**
* Consume and render data.
* @param albumsFromServer
*/
private void consumeApiData(List<Album> albumsFromServer) {
if (albumsFromServer != null) {
albumList.clear();
// Add the found albums to list to render
albumList.addAll(albumsFromServer);
// Tell the adapter that it needs to rerender
albumAdapter.notifyDataSetChanged();
//Save cache
addObjectsToRealmStorage(albumsFromServer);
}
isDownloadInProgress = false;
}
/**
* Adding these objects to the cache in nosql storage
* @param albumsFromServer List of albums from server
*/
private void addObjectsToRealmStorage(List<Album> albumsFromServer) {
Realm realm = Realm.getInstance(getActivity());
realm.beginTransaction();
//Delete previously saved objects from search results
RealmQuery<AlbumRealmModel> query = realm.where(AlbumRealmModel.class);
RealmResults<AlbumRealmModel> result = query.findAll();
result.clear();
//Write new objects of current search results
for(Album album : albumsFromServer) {
AlbumRealmModel albumRealm = realm.createObject(AlbumRealmModel.class); // Create a new object
albumRealm.setName(album.getName());
albumRealm.setPlaycount(album.getPlaycount());
albumRealm.setImageUrl(album.getImage().get(Constants.IMAGE_SIZE_SMALL).getText());
}
realm.commitTransaction();
realm.close();
}
public void getAlbumsFromRealmStorage() {
Realm realm = Realm.getInstance(getActivity());
realm.beginTransaction();
//Query previously saved objects from search results
RealmQuery<AlbumRealmModel> query = realm.where(AlbumRealmModel.class);
RealmResults<AlbumRealmModel> result = query.findAll();
List<Album> albumsFromCache = new ArrayList<Album>();
for(AlbumRealmModel albumRealm : result) {
Album album = new Album();
album.setName(albumRealm.getName());
album.setPlaycount(albumRealm.getPlaycount());
Image image = new Image();
image.setText(albumRealm.getImageUrl());
List<Image> imageList = new ArrayList<Image>();
imageList.add(image);
album.setImage(imageList);
albumsFromCache.add(album);
}
realm.commitTransaction();
realm.close();
albumList.clear();
albumList.addAll(albumsFromCache);
}
}
|
Python
|
UTF-8
| 2,266 | 2.96875 | 3 |
[] |
no_license
|
import pymongo
from nltk.data import LazyLoader
from nltk.tokenize import TreebankWordTokenizer
from nltk.util import AbstractLazySequence, LazyMap, LazyConcatenation
class MongoDBLazySequence(AbstractLazySequence):
def __init__(self, host = "localhost", port = 27017, db = "test",
collection = "corpus", field = "text"):
self.conn = pymongo.MongoClient(host, port)
self.collection = self.conn[db][collection]
self.field = field
def __len__(self):
return self.collection.count()
def iterate_from(self, start):
f = lambda d: d.get(self.field, "")
return iter(LazyMap(f, self.collection.find(fields = [self.field], skip = start)))
class MongoDBCorpusReader(object):
def __init__(self, word_tokenizer = TreebankWordTokenizer(),
sent_tokenizer = LazyLoader("tokenizers/punkt/PY3/english.pickle"),
**kwargs):
self._seq = MongoDBLazySequence(**kwargs)
self._word_tokenize = word_tokenizer.tokenize
self._sent_tokenize = sent_tokenizer.tokenize
def text(self):
return self._seq
def words(self):
return LazyConcatenation(LazyMap(self._word_tokenize, self.text()))
def sents(self):
return LazyConcatenation(LazyMap(self._sent_tokenize, self.text()))
## hypothetical example
reader = MongoDBCorpusReader(db = "website", collection = "comments", field = "comment")
import lockfile, tempfile, shutil
def append_line(fname, line):
with lockfile.FileLock(fname):
fp = open(fname, "a+")
fp.write(line)
fp.write("\n")
fp.close()
def remove_line(fname, line):
with lockfile.FileLock(fname):
tmp = tempfile.TemporaryFile()
fp = open(fname, "w+")
# write all lines from orig file, except if matches given line
for l in fp:
if l.strip() != line:
tmp.write(l)
# reset file pointers so entire files are copied
fp.seek(0)
tmp.seek(0)
# copy tmp into fp, then truncate to remove trailing line(s)
shutil.copyfileobj(tmp, fp)
fp.truncate()
fp.close()
tmp.close()
append_line("test.txt", "foo")
remove_line("test.txt", "foo")
|
C#
|
UTF-8
| 3,899 | 2.75 | 3 |
[] |
no_license
|
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using CodeGuru.Exercises;
using Microsoft.CSharp;
using NUnit.Core;
namespace NUnitExercises
{
public abstract class NUnitChallenge
{
public string Instructions { get; set; }
public List<CodeFile> CodeFiles { get; set; }
public int CourseId { get; set; }
public int LevelNo { get; set; }
public int ChallengeNo { get; set; }
/// <summary>
/// Default Constructor
/// </summary>
protected NUnitChallenge()
{
//inject dependencies for NUnit to run successfully
CoreExtensions.Host.InstallBuiltins();
CodeFiles = new List<CodeFile>();
}
/// <summary>
/// Validates whether the code files are valid inputs for this challenge
/// </summary>
/// <param name="codefiles"></param>
/// <returns></returns>
public TestResult RunTests(List<string> codefiles)
{
var assembly = BuildAssembly(codefiles.ToArray());
//to avoid NullReferenceException - don't know why this is needed!
TestExecutionContext.CurrentContext.TestPackage = new TestPackage(assembly.GetName().FullName);
var suite = GetTestSuiteFromAssembly(assembly);
return suite.Run(new NullListener(), TestFilter.Empty);
}
/// <summary>
/// Converts a given assembly containing tests to a runnable TestSuite
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
protected static TestSuite GetTestSuiteFromAssembly(Assembly assembly)
{
var treeBuilder = new NamespaceTreeBuilder(new TestAssembly(assembly, assembly.GetName().FullName));
treeBuilder.Add(GetFixtures(assembly));
return treeBuilder.RootSuite;
}
/// <summary>
/// Builds an assembly
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
protected static Assembly BuildAssembly(string[] code)
{
var compilerparams = new CompilerParameters()
{
GenerateExecutable = false,
GenerateInMemory = true
};
//need to reference nunit framework
compilerparams.ReferencedAssemblies.Add(typeof (NUnit.Framework.TestCaseAttribute).Assembly.Location);
var results = new CSharpCodeProvider()
.CompileAssemblyFromSource(compilerparams, code);
if (!results.Errors.HasErrors) return results.CompiledAssembly;
throw new Exception(GetErrors(results));
}
/// <summary>
/// Gets Errors from the Compiler results
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
protected static String GetErrors(CompilerResults results)
{
var errors = new StringBuilder("Compiler Errors :\r\n");
foreach (CompilerError error in results.Errors)
{
errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
}
return errors.ToString();
}
/// <summary>
/// Creates a tree of fixtures and containing TestCases from the given assembly
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
protected static IList GetFixtures(Assembly assembly)
{
return assembly.GetTypes()
.Where(TestFixtureBuilder.CanBuildFrom)
.Select(TestFixtureBuilder.BuildFrom).ToList();
}
}
}
|
Java
|
UTF-8
| 284 | 2.203125 | 2 |
[] |
no_license
|
package com.github.ompc.dragoon.cmd;
/**
* 延时命令
* @author vlinux
*
*/
public class DelayCmd extends Cmd {
/*
* 延时毫秒数
*/
private final long delay;
public DelayCmd(long delay) {
this.delay = delay;
}
public long getDelay() {
return delay;
}
}
|
Markdown
|
UTF-8
| 1,920 | 2.765625 | 3 |
[] |
no_license
|
# Title: Plotkin and Griffin accidentally showed us their cards in the hearing 🃏🃏🃏
# Author: fatedMercy
# Post URL: [https://www.reddit.com/r/GME/comments/lpa0s3/plotkin_and_griffin_accidentally_showed_us_their/](https://www.reddit.com/r/GME/comments/lpa0s3/plotkin_and_griffin_accidentally_showed_us_their/)
Plotkin’s written testimony had a part that stuck out to me, and it finally clicked. Along with GameStop, he mentioned having positions in AutoZone and Expedia.
For a supposed brilliant investor, “one of the best money managers of his time” as Griffin put it, why would those holdings be something to brag about?
They’re not.
In actuality, he’s just accidentally admitting that he “covered” his GME positions by focusing his attention on XRT. How would he effectively help manipulate the price of GME while using XRT? By holding long positions in other companies that XRT contains. Like, say, AutoZone and Expedia.
Griffin told us something very important also.
We couldn’t figure out how they effectively traded volume back and forth to short on such low volume without buying countering it. Even though on many of these days, the buy/sell ratio was well above 50%, some days as high as 65-75%.
If someone has a link to the exact part, I’ll edit my post to include it. But Griffin talks about trading to a whole cent.
Retail only has the ability to trade in whole cents. $10.00 or $10.01. HF’s and MM’s have the ability to trade to the 3rd decimal point.
Griffin kept dodging the questions about trade executions, and here’s why. They can trade amongst each other at $10.005, $10.015, and they know who they are trading with.
SIR, I THINK WE’VE GOT ‘EM
Friday close: [3rd decimal point](https://ibb.co/Jz7M4zQ)
[Plotkin’s written testimony ](https://docs.house.gov/meetings/BA/BA00/20210218/111207/HHRG-117-BA00-Wstate-PlotkinG-20210218.pdf)
|
Java
|
ISO-8859-1
| 3,226 | 2 | 2 |
[] |
no_license
|
package org.test;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import com.payu.sdk.PayU;
import com.payu.sdk.PayUPayments;
import com.payu.sdk.exceptions.ConnectionException;
import com.payu.sdk.exceptions.InvalidParametersException;
import com.payu.sdk.exceptions.PayUException;
import com.payu.sdk.model.Currency;
import com.payu.sdk.model.Language;
import com.payu.sdk.model.PaymentCountry;
import com.payu.sdk.model.PaymentMethod;
import com.payu.sdk.model.TransactionResponse;
public class Cash {
public static void main(String[] args) {
payuInit("6u39nqhq8ftd0hlvnjfs66eh8c", "11959c415b33d0c", "500238",
false); // Test
String reference = "comprame_java_test_00000005";
String value = "10000";
Map<String, String> parameters = new HashMap<String, String>();
// Enter the accounts identifier here.
parameters.put(PayU.PARAMETERS.ACCOUNT_ID, "500538");
// Enter the reference code here.
parameters.put(PayU.PARAMETERS.REFERENCE_CODE, reference);
// Enter the description here.
parameters.put(PayU.PARAMETERS.DESCRIPTION, "payment test");
// Enter the transaction language here.
parameters.put(PayU.PARAMETERS.LANGUAGE, Language.es.name());
// -- Values --
// Enter the value here.
parameters.put(PayU.PARAMETERS.VALUE, value);
// Enter the currency here.
parameters.put(PayU.PARAMETERS.CURRENCY, Currency.COP.name());
// Enter the buyer's email here.
parameters.put(PayU.PARAMETERS.BUYER_EMAIL, "nick@comprame.com");
// Enter the payer's name here.
parameters.put(PayU.PARAMETERS.PAYER_NAME, "nick wu");
// Enter the cash payment method name here.
parameters.put(PayU.PARAMETERS.PAYMENT_METHOD, PaymentMethod.BALOTO
.name());
parameters.put(PayU.PARAMETERS.PAYER_DNI, "1111111111111");
// Enter the name of the country here.
parameters.put(PayU.PARAMETERS.COUNTRY, PaymentCountry.CO.name());
// Enter the expiration date here.
parameters.put(PayU.PARAMETERS.EXPIRATION_DATE, "2015-12-23T00:00:00");
// Payer IP
parameters.put(PayU.PARAMETERS.IP_ADDRESS, "127.0.0.1");
parameters.put(PayU.PARAMETERS.COOKIE, "pt1t38347bs6jc9ruv2ecpv7o2");
// "Authorization and capture" request
try {
TransactionResponse response = PayUPayments
.doAuthorizationAndCapture(parameters);
String string = JSONObject.fromObject(response).toString();
System.out.println(string);
} catch (PayUException e) {
e.printStackTrace();
} catch (InvalidParametersException e) {
e.printStackTrace();
} catch (ConnectionException e) {
e.printStackTrace();
}
}
public static void payuInit(String apiKey, String apiLogin,
String merchartId, Boolean isTest) {
PayU.apiKey = apiKey; // Enter your ApiKey here.
PayU.apiLogin = apiLogin; // Enter your apiLogin here.
PayU.language = Language.en; // Enter the language you prefer here
PayU.isTest = isTest; // Leave it true when
// testing..
PayU.merchantId = merchartId;
PayU.paymentsUrl = "https://stg.api.payulatam.com/payments-api/";
PayU.reportsUrl = "https://stg.api.payulatam.com/reports-api/";
// PayU.paymentsUrl = "https://api.payulatam.com/payments-api/";
// PayU.reportsUrl = "https://api.payulatam.com/reports-api/";
}
}
|
Markdown
|
UTF-8
| 4,404 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
---
title: How to Write a Reference Guide
---
## What is a Reference Guide?
A Reference Guide is a nitty-gritty technical description of how some piece of Gatsby works. Reference Guides are most useful when you need detailed information about Gatsby's APIs or internals.
Reference Guides contain information that many developers would expect to find in technical documentation: function descriptions, parameters and default values, component properties. The Reference Guides section of the docs also includes the [Release Notes](/docs/reference/release-notes/) for each version of Gatsby.
Reference Guides work well for describing the nuts and bolts of how to use a Gatsby feature. You can think of a Reference Guide as an encyclopedia article about a specific plant. It lists details like the plant's defining characteristics, where it can be found, how it can be used. It might also include warnings about potential side effects.
A Reference Guide isn't meant to be read from start to finish. Rather, it's meant to be used by developers who are actively working on a project and need to look up some details about how a particular Gatsby feature works. It might include code examples to show how to use a feature in context, but it doesn't provide a full step-by-step process like what you'd expect from a [How-To Guide](/contributing/docs-contributions/how-to-write-a-how-to-guide) or [Tutorial](/contributing/docs-contributions/how-to-write-a-tutorial)
> For more information on Reference Guides, check out the [Diátaxis documentation system](https://diataxis.fr/reference-guides/), which the Gatsby docs are based on.
## A near-perfect example of a Reference Guide
Want to see what a good Reference Guide looks like? Check out the [Reference Guide: Gatsby Image plugin](/docs/reference/built-in-components/gatsby-plugin-image/).
## Reference Guide template
The structure of each Reference Guide will be slightly different, but they should have at least the following sections:
- **Introduction:** The first section. Provide some quick background information to help readers understand 1) what this feature is (at a high level) and 2) why it's useful.
- **Additional Resources:** The last section. Links to other docs or content that might be useful next steps for readers. Also, any resources that helped you write the Reference Guide.
The sections in between the Introduction and Additional Resources should be broken down in a way that best fits the feature you're describing.
You can copy and paste the markdown text below and fill it in with your own information. See the docs contributions guide for information about [structuring accessible headings](/contributing/docs-contributions#headings).
```markdown
---
title: Feature Name
---
## Introduction
In 2-3 sentences, give a high-level description of what this feature does,
why it's important, and when it might be helpful for users.
## Feature Name
Break up this section into multiple headings, as needed.
Here are some general tips for helpful things to include:
- Diagrams or other visuals, to show key processes or architectures.
- Make sure to include alt text for accessibility! For
help writing great alt text, refer to the W3C alt decision
tree: https://www.w3.org/WAI/tutorials/images/decision-tree/
- Code examples, to show how to use the feature in practice.
- Be sure to include all the necessary imports!
- Introduce the code snippet with a sentence describing what the code does
and which parts the reader should pay particular attention to.
- Code snippets should be as close to real-world examples as possible.
Avoid using "foobar" examples.
- Lists of parameters, including:
- A description of what it does
- The expected data type
- The default value
- Tips for troubleshooting.
- Are there any edge cases that readers should be aware of?
- What common error messages might readers encounter? How can they
resolve the problem?
## Additional Resources
Include other resources you think readers would benefit from or next steps
they might want to take after reading your Reference Guide. You can also
mention any resources that helped you write the article (blog posts, outside
tutorials, etc.).
- Link to a blog post
- Link to a YouTube tutorial
- Link to an example site
- Link to source code for a live site
- Links to relevant plugins
- Links to starters
```
|
TypeScript
|
UTF-8
| 3,460 | 4.0625 | 4 |
[] |
no_license
|
{
/** 基础*/
let x = 3;
// 凡是和x 有关(运算 赋值 等)的类型都会推断为number 类型
// 相当于
let x1: number = 3;
}
{
/**
* 最佳通用类型
* 当需要从几个表达式中推断类型时候,会使用这些表达式的类型来推断出一个最合适的通用类型.
* */
let x = [0, 1, null];
// 为了推断x的类型,我们必须考虑所有元素的类型。 这里有两种选择: number和null。 计算通用类型算法会考虑所有的候选类型,并给出一个兼容所有候选类型的类型。
// 所以相当于
let x1: Array<null | number> = [0, 1, null];
class Animal {}
class Rhino extends Animal {}
class Elephant extends Animal {}
class Snake extends Animal {}
let zoo = [new Rhino(), new Elephant(), new Snake()];
// 默认推断为
let zoo1: Array<Rhino | Elephant | Snake> = [
new Rhino(),
new Elephant(),
new Snake(),
];
// 如果想要重新推断为 父类就要重新声明类型 (可能导致 类型问题 具体可以查看协变(covariance) 和 抗变(contravariance).md)
let zoo2: Array<Animal> = [new Rhino(), new Elephant(), new Snake()];
// 如果没有 父类声明 这里依然是 联合类型
function createZoo(): Animal[] {
return [new Rhino(), new Elephant(), new Snake()];
}
}
{
/** 上下文类型 */
window.onmousedown = function (mouseEvent: MouseEvent) {
// 3.5 版本 还不需要:MouseEvent 3.6 又需要了 vscode 不能检查出问题 但是编译报错 webstorm 在检查时就能知道问题
// 已经推断了为mouse的Event类型
console.log(mouseEvent.button);
};
/**
* */
document.getElementById("test")!.addEventListener("keydown", function (e) {
// 推断为 按键的Event类型
console.log(e.altKey);
});
}
/**
* From 2.4
* 返回类型作为推断目标
* */
{
function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[] {
return (a) => a.map(f);
}
const lengths: (a: string[]) => number[] = arrayMap((s) => s.length);
// 等同于
}
{
// 推断类型为 arrayMap(f: (x: T) => U): (a: T[]) => U[] 同上
function arrayMap<T, U>(f: (x: T) => U) {
return (a: T[]) => a.map(f);
}
// 推断为 lengths: (a: string[]) => number[] 同上
// 相当于 将T 设为 string 同时 由 T 推断了 S 为 number
const lengths = arrayMap((s: string) => s.length);
}
/**
* From 2.7
* 更智能的对象字面量推断
* */
{
let someTest!: boolean;
let foo = someTest ? { value: 42 } : {}; // foo 在ide 显示的类型为 {}
// 实际类型 为 { value: number } | { value?: undefined } 保留类 value number 的 可能性
if (foo.value) {
const a = foo.value.toFixed(1); // 正确推断为 number 类型
}
let a = someTest ? { a: 1 } : { a: "string" }; // a 正确推断的类型为 {a:string} | {a:number}
let b = someTest ? { a: 1 } : { b: 2 }; // a 正确推断的类型为 {a:string} | {b:number}
}
/**
* From 4.1
* unknown 和 any 在类型推断时被认为是 falsy类型
* 修复这个类型判断的方法 就是强制转成 boolean 类型
* */
{
let foo!: unknown;
let somethingElse!: { someProp: string };
let x = foo && somethingElse; // unknown
let y = !!foo && somethingElse; // false | somethingElse
}
{
let foo!: any;
let somethingElse!: { someProp: string };
let x = foo && somethingElse; // any
let y = !!foo && somethingElse; // false | somethingElse
}
export {};
|
Swift
|
UTF-8
| 1,450 | 2.875 | 3 |
[] |
no_license
|
//
// Ticket.swift
// Agile Suite
//
// Created by CS3714 on 12/2/20.
// Copyright © 2020 Nathan Moeliono, Tommy Phan, Mariam Naseem. All rights reserved.
//
import Foundation
import CoreData
/*
🔴 Set Current Product Module:
In xcdatamodeld editor, select Ticket and
select Current Product Module from Module menu.
🔴 Turn off Auto Code Generation:
In xcdatamodeld editor, select Ticket and
select Manual/None from Codegen menu.
*/
// ❎ CoreData Ticket entity public class
public class Ticket: NSManagedObject, Identifiable {
@NSManaged public var title: String?
@NSManaged public var d_escription: String?
@NSManaged public var dueDate: String?
@NSManaged public var dateCreated: String?
@NSManaged public var completed: NSNumber?
}
/*
Swift type Double cannot be used for @NSManaged Core Data attributes because the type
Double cannot be represented in Objective-C, which is internally used for Core Data.
Therefore, we must use the Objective-C type NSNumber instead for latitude and longitude.
*/
extension Ticket {
static func allTicketsFetchRequest() -> NSFetchRequest<Ticket> {
let request: NSFetchRequest<Ticket> = Ticket.fetchRequest() as! NSFetchRequest<Ticket>
request.sortDescriptors = [
NSSortDescriptor(key: "dueDate", ascending: true),
NSSortDescriptor(key: "dateCreated", ascending: true)
]
return request
}
}
|
Java
|
UTF-8
| 826 | 3.296875 | 3 |
[] |
no_license
|
package com.DA.SynchronizedSample;
/**
* <类详细说明:多线程下的线程同步关键字synchronized>
*
* @Author: HuangHai
* @Version: 2017-03-22
**/
public class SynchronizedCounter {
private static int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
//测试
public static void main(String[] args) throws Exception {
RunnableDemo r1 = new RunnableDemo("thread1");
Thread thread1 = new Thread(r1);
thread1.start();
RunnableDemo r2 = new RunnableDemo("thread2");
Thread thread2 = new Thread(r2);
thread2.start();
thread2.join();
System.out.println("c: "+SynchronizedCounter.c);
}
}
|
Shell
|
UTF-8
| 245 | 2.984375 | 3 |
[] |
no_license
|
#!/bin/bash
TITLE=$1
DOUBLE_LINE="\n\n"
COMPLETE_PATH="${HOME}/Notes/${TITLE}.md"
touch "${COMPLETE_PATH}" || exit 1
printf "# ${TITLE}${DOUBLE_LINE}Tags: ${DOUBLE_LINE}\n" \
>> "${COMPLETE_PATH}" || exit 2
nvim "${COMPLETE_PATH}"
exit 0
|
Markdown
|
UTF-8
| 2,663 | 3.0625 | 3 |
[] |
no_license
|
# DescribeUsagePlanEnvironments
## 接口描述
用户在绑定了某个使用计划到环境后,可用此接口查询这个使用计划绑定的所有服务的环境
## 1、输入参数
以下请求参数列表仅列出了接口请求参数,其它参数可参考[公共请求参数](/document/api/213/6976)。
| 参数名称 | 是否必选 | 类型 | 描述 |
| ----------- | ---- | ------ | ------------------------------- |
| usagePlanId | 是 | String | 待查询的使用计划唯一ID。 |
| limit | 否 | Int | 返回数量。当绑定多个服务的环境时,返回的数量若不配置则默认20 |
| offset | 否 | Int | 当有多个返回值时,从此偏移量开始查询。 |
## 2、输出参数
| 参数名称 | 类型 | 描述 |
| --------------- | ------------- | ---------------------------------------- |
| code | Int | 公共错误码, 0表示成功,其他值表示失败。详见错误码页面的<a href="https://www.qcloud.com/doc/api/372/%E9%94%99%E8%AF%AF%E7%A0%81#1.E3.80.81.E5.85.AC.E5.85.B1.E9.94.99.E8.AF.AF.E7.A0.81" title="公共错误码">公共错误码</a>。 |
| codeDesc | String | 业务侧错误码。成功时返回Success,错误时返回具体业务错误原因。 |
| message | String | 模块错误信息描述,与接口相关。 |
| totalCount | Int | 绑定的服务的环境数。 |
| environmentList | List of Array | 使用计划已经绑定的各个服务的环境状态。 |
其中environmentList表示了该服务是否绑定到各个环境,environmentList是由environment组成的数组,environment的构成如下:
| 参数名称 | 类型 | 描述 |
| --------------- | ------ | --------- |
| seviceId | String | 绑定的服务唯一Id |
| serviceName | String | 绑定的服务名称 |
| environmentName | String | 已经绑定的环境名称 |
## 3、示例
```
https://apigateway.api.qcloud.com/v2/index.php?
&<公共请求参数>
&Action=DescribeUsagePlanEnvironments
&usagePlanId=usagePlan-XX
```
返回示例如下:
```
{
"code":"0",
"message":"",
"codeDesc":"Success",
"totalCount":2,
"environmentList":[
{
"seviceId":"sevice-XX",
"serviceName":"xxx",
"environmentName":"Test",
},
{
"seviceId":"sevice-XXXX",
"serviceName":"xxx",
"environmentName":"release"
}
],
}
```
|
Java
|
UTF-8
| 1,110 | 1.90625 | 2 |
[] |
no_license
|
package by.feedblog.api.configuration;
import by.feedblog.api.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private TokenInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor)
.addPathPatterns("/post/**")
.addPathPatterns("/tag/**")
.addPathPatterns("/category/**")
.addPathPatterns("/reaction/**")
.addPathPatterns("/like/**")
.addPathPatterns("/dislike/**")
.addPathPatterns("/comment/**")
.addPathPatterns("/bookmark/**");
}
}
|
Java
|
UTF-8
| 282 | 1.757813 | 2 |
[] |
no_license
|
package com.dpplabs.project.cermatigithubuser.presentation.util;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class NormalViewHolder extends RecyclerView.ViewHolder {
public NormalViewHolder(View itemView) {
super(itemView);
}
}
|
Markdown
|
UTF-8
| 668 | 2.984375 | 3 |
[] |
no_license
|
# Employee-Summary
## Description
This is the homework for week ten. The goal is to create a command line application that generates an HTML page after taking in information about team managers and members. It will basically create a roster with basic information, such as email, identification, and other specific information.
## Installation
In the terminal, run the following commands:
* `npm install`
* `npm install inquirer`
## Usage
In the terminal, run the following command: `node index.js`
## Demonstration
* https://drive.google.com/file/d/1cUfID_uc3TqgRi6Qa-rAWanuaXbMu8RJ/view
## Links
* https://github.com/LostandConfusedStudent/Employee-Summary
|
PHP
|
UTF-8
| 4,056 | 2.671875 | 3 |
[] |
no_license
|
<?php
class roster {
public function get_classInfo ($classNum) {
switch ($classNum) {
case 1:
$className = 'Warrior';
$classColor = '#C79C6E';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-warrior.png';
break;
case 2:
$className = 'Paladin';
$classColor = '#F58CBA';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-paladin.png';
break;
case 3:
$className = 'Hunter';
$classColor = '#ABD473';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-hunter.png';
break;
case 4:
$className = 'Rogue';
$classColor = '#FFF569';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-rogue.png';
break;
case 5:
$className = 'Priest';
$classColor = '#FFFFFF';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-priest.png';
break;
case 6:
$className = 'Death Knight';
$classColor = '#C41F3B';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-deathknight.png';
break;
case 7:
$className = 'Shaman';
$classColor = '#0070DE';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-shaman.png';
break;
case 8:
$className = 'Mage';
$classColor = '#69CCF0';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-mage.png';
break;
case 9:
$className = 'Warlock';
$classColor = '#9482C9';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-warlock.png';
break;
case 10:
$className = 'Monk';
$classColor = '#00FF96';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-monk.png';
break;
case 11:
$className = 'Druid';
$classColor = '#FF7D0A';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-druid.png';
break;
case 12:
$className = 'Demon Hunter';
$classColor = '#A330C9';
$classIcon = 'http://wow.zamimg.com/images/classes/symbols/icon-demonhunter.png';
break;
default:
break;
}
$classInfo = array($className, $classColor, $classIcon, $classNum);
return $classInfo;
}
public function get_guildRank ($rankNum) {
switch ($rankNum) {
case 0:
$rankName = 'Guild Master';
break;
case 2:
$rankName = 'Officer';
break;
case 4:
$rankName = 'Veteran Raider';
break;
case 6:
$rankName = 'Raider';
break;
}
return $rankName;
}
public function get_classResult ($classInfo) {
include_once $_SERVER['DOCUMENT_ROOT'].'/assets/php/class/database.php';
$db = new Database();
$sql = "SELECT * FROM stormguild.guild_roster WHERE class = {$classInfo[3]} order by rank asc, name asc";
$result = $db -> readResults($sql);
return $result;
}
public function get_classList () {
include_once $_SERVER['DOCUMENT_ROOT'].'/assets/php/class/database.php';
$db = new Database();
$results = $db -> readResults("SELECT DISTINCT class, count(*) as class_count from stormguild.guild_roster group by class order by class asc");
$classList = array();
foreach ($results as $result) {
$classInfo = $this -> get_classInfo($result['class']);
array_push($classInfo,$result['class_count']);
array_push($classList,$classInfo);
}
sort($classList);
return $classList;
}
}
?>
|
Markdown
|
UTF-8
| 1,035 | 3.109375 | 3 |
[] |
no_license
|
# itsTiny
**A simple URL shrinker in Flask and Postgresql**
### [Demo](https://itstiny.herokuapp.com): https://itstiny.herokuapp.com
## Features
* Shortens any valid URL
* Stores the URL and Code pair in database to avoid repeating process
* Displays click count
* Admin panel for editing and adding custom parameters
Made with:
- Flask
- PostgreSQL
To run this;
- Clone the repo
`git clone https://github.com/anorebel/itsTiny.git`
- Enter the directory
`cd itsTiny`
- Create environment and install dependencies
`pipenv install`
- Rename `.env.example` to `.env` and add your postgres connection string
- Initialize database and run:
- In development:
```bash
export FLASK_ENV=development
export FLASK_APP=app
flask db upgrade
flask run
```
- In production:
```bash
export FLASK_APP=app
flask db upgrade
flask run
```
- Run create_admin.py and follow prompts to create admin user then visit https://URL/admin
`python3 create_admin.py`
|
Markdown
|
UTF-8
| 895 | 3.25 | 3 |
[] |
no_license
|
# Lab: React Game Guess Who - Harry Potter
### Learning Objectives
- Be able to update state via a callback
- Be able to update the screen on user input
- Be able to integrate game logic into a React app
## Brief
Your task is to build a single player game of Guess Who. The computer will choose a random character, and the user has to ask questions to guess which is the winning character.

There is a character data set and character images provided.
### MVP
- The computer should select a secret character.
- The player should be able to ask questions about the secret character and recieve a yes/no answer.
### Extensions
- A player should be able to make a guess as to which is the secret character, and see it their guess was correct.
### Planning
Draw a component diagram that details and state and props before you begin.
|
Markdown
|
UTF-8
| 10,711 | 2.6875 | 3 |
[] |
no_license
|
## Project: Behavioral Cloning Project [](http://www.udacity.com/drive)
Model Architecture
---
I used Nvidia's end-to-end Self-Driving Deep Learning network for the Behavioral Cloning project. The network has 5 convolutional layers and 3 fully connected (dense) layers. To prevent overfitting, as suggested by the project rubric, I inserted dropouts between the first two dense (fully-connected) layers for regularization with dropout probability of 0.3. Determining a good network architecture to solve a given problem appears to be more of an art than a science, and involves extensive experimentation. For this project, I relied on existing literature to find a good starting point for my network architecture. So I chose to start with the Nvidia architecutre, which has shown very promising results. It turned out that this architecture was sufficient for successfully achieving the objectives of this project, so I did not have to evaluate variations of the architecture. However, I did explore changing the dropout probability to 0.5 (the performance was worse with this on that dataset I had) before settling on a value of 0.3 which appeared to work better. It is possible that with a more complex problem (like on the challenge track) requiring more extensive training data, a dropout probability of 0.5 may work better to avoid overfitting, but this is still under investigating. As a preprocessing/normalization step, as recommended in the Project videos, I normalized the images so the pixel values are between [-0.5,+0.5], and cropped the images to exclude 70 pixel-rows from the top, and 25-pixel rows from the bottom of each image.

The following the output of Keras' model.summary() method. As the print out shows, this network has approx. 350K training parameters.
```text
Layer (type) Output Shape Param # Connected to
====================================================================================================
lambda_1 (Lambda) (None, 160, 320, 3) 0 lambda_input_1[0][0]
____________________________________________________________________________________________________
cropping2d_1 (Cropping2D) (None, 65, 320, 3) 0 lambda_1[0][0]
____________________________________________________________________________________________________
convolution2d_1 (Convolution2D) (None, 31, 158, 24) 1824 cropping2d_1[0][0]
____________________________________________________________________________________________________
activation_1 (Activation) (None, 31, 158, 24) 0 convolution2d_1[0][0]
____________________________________________________________________________________________________
convolution2d_2 (Convolution2D) (None, 14, 77, 36) 21636 activation_1[0][0]
____________________________________________________________________________________________________
activation_2 (Activation) (None, 14, 77, 36) 0 convolution2d_2[0][0]
____________________________________________________________________________________________________
convolution2d_3 (Convolution2D) (None, 5, 37, 48) 43248 activation_2[0][0]
____________________________________________________________________________________________________
activation_3 (Activation) (None, 5, 37, 48) 0 convolution2d_3[0][0]
____________________________________________________________________________________________________
convolution2d_4 (Convolution2D) (None, 3, 35, 64) 27712 activation_3[0][0]
____________________________________________________________________________________________________
activation_4 (Activation) (None, 3, 35, 64) 0 convolution2d_4[0][0]
____________________________________________________________________________________________________
convolution2d_5 (Convolution2D) (None, 1, 33, 64) 36928 activation_4[0][0]
____________________________________________________________________________________________________
activation_5 (Activation) (None, 1, 33, 64) 0 convolution2d_5[0][0]
____________________________________________________________________________________________________
flatten_1 (Flatten) (None, 2112) 0 activation_5[0][0]
____________________________________________________________________________________________________
dense_1 (Dense) (None, 100) 211300 flatten_1[0][0]
____________________________________________________________________________________________________
activation_6 (Activation) (None, 100) 0 dense_1[0][0]
____________________________________________________________________________________________________
dropout_1 (Dropout) (None, 100) 0 activation_6[0][0]
____________________________________________________________________________________________________
dense_2 (Dense) (None, 50) 5050 dropout_1[0][0]
____________________________________________________________________________________________________
activation_7 (Activation) (None, 50) 0 dense_2[0][0]
____________________________________________________________________________________________________
dropout_2 (Dropout) (None, 50) 0 activation_7[0][0]
____________________________________________________________________________________________________
dense_3 (Dense) (None, 10) 510 dropout_2[0][0]
____________________________________________________________________________________________________
activation_8 (Activation) (None, 10) 0 dense_3[0][0]
____________________________________________________________________________________________________
dense_4 (Dense) (None, 1) 11 activation_8[0][0]
====================================================================================================
Total params: 348,219Trainable params: 348,219
Non-trainable params: 0
____________________________________________________________________________________________________
```
Training, Validation and Testing
---
I started out by splitting the dataset which was included with the Udacity project using an 80/20 ratio into training and validation sets. I used the center image as well as the left and right camera images from this dataset with a correction of -/+ 0.1 respectively. I initially tried a correction value of -/+ 0.2, but that did not work well. In order to augment my dataset, I also flipped these three images horizontally (using the negative of the steering angle as the corresponding training output). I used the Adam optimizer with a batch size of 32 samples, and experimented with training for upto 20 epochs. After observing the performance of the network I collected additional data on stretches of the track where the car was veering off course, and included the center/left/right images from this data as well in my training and validation. I've included a video of this dataset below where I drive over two particularly troublesome stretches of the track where the car repeatedly went off track.
[](https://youtu.be/RFD8soBKVxM)
In addition, I also included one additional dataset by going over the track for 3 full laps with smooth turns. With all of this data used for training and validation (again with an 80/20 split), the car was able to go completely around the track without going off course. My final training dataset was ~62K image samples, and my validation set was ~14K image samples. After observing the training and validation loss metrics, I settled on 7 epochs as the proper balance for the network weights to converge, without overfitting.
```text
62328/62328 [==============================] - 139s - loss: 0.0132 - val_loss: 0.0111
Epoch 2/20
62328/62328 [==============================] - 128s - loss: 0.0117 - val_loss: 0.0108
Epoch 3/20
62328/62328 [==============================] - 127s - loss: 0.0111 - val_loss: 0.0104
Epoch 4/20
62328/62328 [==============================] - 128s - loss: 0.0107 - val_loss: 0.0102
Epoch 5/20
62328/62328 [==============================] - 127s - loss: 0.0104 - val_loss: 0.0105
Epoch 6/20
62328/62328 [==============================] - 127s - loss: 0.0100 - val_loss: 0.0104
Epoch 7/20
62328/62328 [==============================] - 127s - loss: 0.0096 - val_loss: 0.0102
Epoch 8/20
62328/62328 [==============================] - 127s - loss: 0.0090 - val_loss: 0.0103
Epoch 9/20
62328/62328 [==============================] - 127s - loss: 0.0086 - val_loss: 0.0104
Epoch 10/20
62328/62328 [==============================] - 127s - loss: 0.0082 - val_loss: 0.0105
Epoch 11/20
62328/62328 [==============================] - 127s - loss: 0.0078 - val_loss: 0.0108
Epoch 12/20
62328/62328 [==============================] - 127s - loss: 0.0074 - val_loss: 0.0109
Epoch 13/20
62328/62328 [==============================] - 127s - loss: 0.0071 - val_loss: 0.0106
Epoch 14/20
62328/62328 [==============================] - 127s - loss: 0.0069 - val_loss: 0.0107
Epoch 15/20
62328/62328 [==============================] - 127s - loss: 0.0065 - val_loss: 0.0107
Epoch 16/20
62328/62328 [==============================] - 127s - loss: 0.0063 - val_loss: 0.0107
Epoch 17/20
62328/62328 [==============================] - 127s - loss: 0.0061 - val_loss: 0.0107
Epoch 18/20
62328/62328 [==============================] - 127s - loss: 0.0058 - val_loss: 0.0108
Epoch 19/20
62328/62328 [==============================] - 127s - loss: 0.0055 - val_loss: 0.0108
Epoch 20/20
62328/62328 [==============================] - 127s - loss: 0.0053 - val_loss: 0.0111
```

Future improvements
---
I plan to experiment using more data from the challenge track so the car successfully completes the challenge course as well. Currently the car makes it way through roughly 10% of the challenge course before veering off track. The training and validation losses are still fairly high after 20 epochs of training, indicating that the network weights have not yet converged. I am currently testing by increasing the number of epochs as well as collecting more data on the challenge track.
|
Swift
|
UTF-8
| 2,848 | 2.734375 | 3 |
[] |
no_license
|
//
// HeartIcon.swift
//
//
// Created by Matěj Jirásek on 3/04/16.
//
//
import UIKit
@IBDesignable
public class HeartIcon: AnimatedIcon {
// MARK: - Inspectable properties
@IBInspectable public var strokeColor: UIColor = .iconRedColor {
didSet {
layer.setNeedsDisplay()
}
}
@IBInspectable public var fillColor: UIColor = .iconRedColor {
didSet {
layer.setNeedsDisplay()
}
}
@IBInspectable public var twoLines: Bool = true {
didSet {
layer.setNeedsDisplay()
}
}
@IBInspectable public var visible: Bool {
get {
return Bool(value)
}
set {
value = CGFloat(newValue)
}
}
// MARK: - Drawing methods
override func draw(time: CGFloat = 0) {
guard time > 0, let context = UIGraphicsGetCurrentContext() else {
return
}
context.clear(CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
// Variable Declarations
let dash: CGFloat = time * (twoLines ? 82 : 164)
let gap: CGFloat = -5 + (1 - time) * (twoLines ? 82 : 164)
let phase: CGFloat = -0.5
context.scaleBy(x: scale, y: scale)
// Bezier Drawing
context.saveGState()
context.translateBy(x: 50, y: 75)
context.rotate(by: -45 * .pi / 180)
let bezierPath = UIBezierPath(style: self)
bezierPath.move(to: CGPoint(x: 30, y: -30.19))
bezierPath.addLine(to: CGPoint(x: 30, y: -30))
bezierPath.addCurve(to: CGPoint(x: 45, y: -15), controlPoint1: CGPoint(x: 38.28, y: -30), controlPoint2: CGPoint(x: 45, y: -23.28))
bezierPath.addCurve(to: CGPoint(x: 30, y: 0), controlPoint1: CGPoint(x: 45, y: -6.72), controlPoint2: CGPoint(x: 38.28, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: -30))
bezierPath.addCurve(to: CGPoint(x: 5.94, y: -41.95), controlPoint1: CGPoint(x: 0, y: -34.88), controlPoint2: CGPoint(x: 2.33, y: -39.21))
bezierPath.addLine(to: CGPoint(x: 6.03, y: -42.02))
bezierPath.addCurve(to: CGPoint(x: 15, y: -45), controlPoint1: CGPoint(x: 8.53, y: -43.89), controlPoint2: CGPoint(x: 11.64, y: -45))
bezierPath.addCurve(to: CGPoint(x: 30, y: -30.19), controlPoint1: CGPoint(x: 23.22, y: -45), controlPoint2: CGPoint(x: 29.9, y: -38.39))
bezierPath.close()
strokeColor.setStroke()
fillColor.withAlphaComponent(time * fillAlpha).setFill()
context.saveGState()
if time < 1 {
context.setLineDash(phase: phase, lengths: [dash < 0 ? 0 : dash, gap < 0 ? 0 : gap])
}
bezierPath.fill()
bezierPath.stroke()
context.restoreGState()
context.restoreGState()
}
}
|
SQL
|
UTF-8
| 1,132 | 3.84375 | 4 |
[] |
no_license
|
use ecommerce;
-- TAREFAS
-- 1. TRAGA EM UMA CONSULTA TODOS OS CLIENTES E OS ENDEREÇOS QUE ELES POSSUEM
SELECT * FROM tb_cliente
LEFT JOIN tb_cliente_endereco
ON tb_cliente.ID_CLIENTE = tb_cliente_endereco.ID_CLIENTE;
-- 2. TRAGA OS 5 PRIMEIROS PRODUTOS DA CADASTRADOS COM O NOME DE SEUS FORNECEDORES
SELECT * FROM tb_produto prod
INNER JOIN tb_fornecedor forn
ON prod.ID_FORNECEDOR = forn.ID_FORNECEDOR
LIMIT 5;
-- 3. TRAGA TODOS OS FORNECEDORES QUE POSSUEM A CATEGORIA COMO A (Sem usar o ID_FORNECEDOR_CATEGORIA no WHERE)
SELECT * FROM tb_fornecedor f
INNER JOIN tb_fornecedor_categoria fc
ON f.ID_FORNECEDOR_CATEGORIA = fc.ID_FORNECEDOR_CATEGORIA
WHERE fc.ds_nome = "a";
-- 4. TRAGA OS 3 PRIMEIROS PEDIDOS CADASTRADOS E O NOME DE SEUS RESPECTIVOS PRODUTOS
SELECT * FROM tb_pedido pe
INNER JOIN tb_pedido_detalhe pd
ON pe.ID_PEDIDO = pd.ID_PEDIDO
INNER JOIN tb_produto pr
ON pd.ID_PRODUTO = pr.ID_PRODUTO
-- WHERE pe.ID_PEDIDO <= 3
;
-- 5. TRAZER OS NOMES DE TODOS OS PRODUTOS COMPRADOS POR 5 CLIENTES
-- SELECT * FROM tb_pedido
-- INNER JOIN tb_cliente;
|
Java
|
UTF-8
| 1,498 | 3.171875 | 3 |
[] |
no_license
|
import java.util.Scanner;
public class ABM {
public static Scanner scn= new Scanner(System.in);
public static int multiOfsingle(int n,int d,int b){
int pow=1;
int finalans=0;
int carry=0;
while(n!=0 || carry!=0)
{
int s=n%10;
int ans=s*d+carry;
finalans+=(ans%b)*pow;
carry= carry/b;
n/=10;
pow*=10;
}
return finalans;
}
public static int anybaseAddition(int n1,int n2,int b)
{
int carry=0;
int pow=1;
int finalanswer=0;
while(n1>0 || n2>0 || carry>0)
{
int d1=n1%10;
int d2=n2%10;
int ans=d1+d2+carry;
finalanswer=finalanswer+(ans%b)*pow;
carry=ans/b;
pow=pow*10;
n1/=10;
n2/=10;
}
return finalanswer;
}
public static int multiOfanybase(int n,int m,int b)
{ int d=0;
int finalanswer=0;
int pow=1;
while(m!=0)
{
d=m%10;
m/=10;
int ans= multiOfsingle(n,d,b);
ans=ans*pow;
finalanswer=anybaseAddition(finalanswer, ans, b);
pow=pow*10;
}
return finalanswer;
}
public static void main(String[] args) {
int n=scn.nextInt();
int m=scn.nextInt();
int b=scn.nextInt();
int ans= multiOfanybase(n,m,b);
System.out.print(ans);
}
}
|
Ruby
|
UTF-8
| 384 | 2.65625 | 3 |
[] |
no_license
|
module AnswersHelper
ANSWER_HINTS = YAML.load_file("#{Rails.root}/config/one_maths_hints.yml")['hints']
def print_hint(hint)
if hint_index?(hint)
ANSWER_HINTS[hint.to_i]
else
hint
end
end
protected
def load_hints
YAML.load_file("#{Rails.root}/config/one_maths_hints.yml")['hints']
end
def hint_index?(hint)
/^\d+$/ === hint
end
end
|
C++
|
UTF-8
| 5,403 | 3.921875 | 4 |
[] |
no_license
|
//Nate Wood
#include "proj05_functions.h"
#include<iostream>
using std::cout; using std::skipws; using std::endl;
#include<string>
#include<cmath>
using std::pow;
string lower_case(const string& s){ //takes all alphabetical characters in a string and makes them lowercase
cout << skipws;
string result = "";//string after making characters lowercase
for (auto c : s){
if (c != ' ')
c = tolower(c);
result += c;
}
return result;
}
string to_binary(char c){//turns a character into a five character binary based on the index of the letter in the alphabet
string result = "";//string of the 5 character binary
if (isalpha(c) == false){//if the character is not a letter an empty string is returned
return result;
}
else{
if (isupper(c)){
return result;
}
else{
int index = c - 'a';//finds the index of the letter
for (int i = 4; i >= 0; i--){
if (index >= pow(2, i)){
index -= pow(2, i);
result += "1";
}
else{
result += "0";
}
}
return result;
}
}
}
char from_binary(const string& bit_str){//takes a 5 character binary and finds the ltter associated with the index
int num = 0;
for (int i = 4; i >= 0; i--){//adds up all of the binary characters to get the index of the letter
if (bit_str[4-i] == '1'){
num += pow(2, i);
}
}
char c = static_cast<char>(num + 97);//turns the index of the letter into the letter, returns 0 if the character is not a letter
if (isalpha(c))
return c;
else
return 0;
}
bool check_message(const string& plaintext, const string& message){//checks to make sure the binary of the secret messgage can fit in the plaintext
cout << skipws;
int num1 = 0;
for (auto c : plaintext){//finds the amount of letters in the plaintext
if (isalpha(c)){
num1 += 1;
}
}
int num2 = 0;
for (auto c : message){//finds the amount of letters in the secret message and adds 5 for each because the binary would be 5 times the length
if (isalpha(c)){
num2 += 5;
}
}
if (num1 >= num2){//returns a boolean based on if the message would fit in the plaintext
return true;
}
else{
return false;
}
}
string encode(const string& plaintext, const string& message){//encodes a message by capitalizing each letter that would have to same index as a 1 in the binary secret message
cout << skipws;
string new1 = lower_case(plaintext);
string new2 = lower_case(message);
bool ans = check_message(new1, new2);
if (ans == false){//tests if the encoding would be possible, returns "Error" if it is not
return "Error";
}
else{
string binary = "";
for (auto c : message){//turns the secret message into a binary
if (isalpha(c)){
binary += to_binary(c);
}
else
binary += c;
}
int index = 0;
for (int i = 0; i < binary.length(); i++){//capitalizes each letter corresponding with a 1 in the binary message
bool test = true;
while (test){
if (isalpha(new1[index]) == false){
index += 1;
}
else{
test = false;
}
}
if (binary[i] == '1'){
new1[index] = toupper(new1[index]);
}
index += 1;
}
return new1;
}
}
string decode(const string& to_decode){//takes a plaintext and decodes the message by finding the capital letters and making a binary code from them to decode
string message = "";
string binary = "";
int num = 0;
for (auto c : to_decode){//finds the number of letters in the string
if (isalpha(c)){
num += 1;
}
}
int remainder = num % 5;//finds the amount of letters that can not be a part of a binary if the number of letters is not divisible by 5
int count = num - remainder;//makes the count by subtracting the number of remaining letters from the total number of letters
int index = 0;
for (int i = 0; i < count; i++){
if (isalpha(to_decode[index]) == false){//tests if the character is a letter, if not then the character is skipped
index += 1;
}
if (isupper(to_decode[index])){//tests for capital letters to add 1's to the binary, if they are not capital a 0 is added instead
binary += "1";
}
else{
binary += "0";
}
index += 1;
}
for (int i = 0; i < (count/5); i++){//decodes the binary by splitting it into segments of 5 characters and calculating the total of each to get the index of each letter
int total = 0;
string sub = binary.substr(i*5, 5);//splits the binary into segments of 5 characters
int power = 4;
for (auto c : sub){
if (c == '1'){
total += pow(2, power);
}
power -= 1;
}
message += static_cast<char>(total + 97);//adds the letters to the message once decoded from the binary
}
return message;
}
|
Python
|
UTF-8
| 476 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import pymongo
# 指定数据库
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test
# 指定集合
collection = db.students
# 即将插入的数据
student1 = {
'id' : '20180104',
'name' : '陈志远',
'age' : '24',
'gender' : 'male'
}
student2 = {
'id' : '20180105',
'name' : '陈志远',
'age' : '24',
'gender' : 'male'
}
result = collection.insert_many([student1,student2])
print(result)
print(result.inserted_ids)
|
Ruby
|
UTF-8
| 490 | 3.375 | 3 |
[] |
no_license
|
class TextAnalyzer
def initialize(filepath)
@text = File.read(filepath)
end
def process
operation = yield
result = self.send(operation)
puts "#{result} #{operation.to_s}"
end
def paragraphs
@text.scan(/\n\n/).size + 1
end
def lines
@text.scan(/$/).size
end
def words
@text.scan(/\b\w+\b/).size
end
end
analyzer = TextAnalyzer.new('sample_text.txt')
analyzer.process { :paragraphs }
analyzer.process { :lines }
analyzer.process { :words }
|
Shell
|
UTF-8
| 1,397 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
# Entrypoint for utilizing as a worker pool instead of a web server
# Based on configuration, can run multiple instances of a single worker process
SUPERVISOR_CONF=/etc/supervisor/conf.d/worker.conf
SERVICES_D=/etc/services.d
# Signal to init processes to avoid any webserver startup
export CONTAINER_ROLE='worker'
# Begin startup sequence
/init.sh
STATUS=$? # Captures exit code from script that was run
# TODO this exit code detection is also present in run.sh, needs to be combined
if [[ $STATUS == $SIGNAL_BUILD_STOP ]]
then
echo "[worker] container exit requested"
exit # Exit cleanly
fi
if [[ $STATUS != 0 ]]
then
echo "[worker] failed to init"
exit $STATUS
fi
WORKER_QUANTITY=$1
# Rebuild worker command as properly escaped parameters from shifted input args
# @see http://stackoverflow.com/questions/7535677/bash-passing-paths-with-spaces-as-parameters
shift
WORKER_COMMAND="$@"
if [ -z "$WORKER_COMMAND" ]
then
echo "[worker] command is required, exiting"
exit 1
fi
echo "[worker] command: '${WORKER_COMMAND}' quantity: ${WORKER_QUANTITY}"
for i in `seq 1 $WORKER_QUANTITY`;
do
SERVICE_FOLDER="${SERVICES_D}/worker-${i}"
mkdir $SERVICE_FOLDER
echo "\
#!/usr/bin/execlineb -P
with-contenv
s6-setuidgid ${NOT_ROOT_USER}
${WORKER_COMMAND}" > "${SERVICE_FOLDER}/run"
done
# Start process manager
echo "[run] starting process manager"
exec /init
|
C++
|
UTF-8
| 811 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef HW1_KEY_GEN_H_
#define HW1_KEY_GEN_H_
#include <stdint.h>
#include "common/p_box.h"
namespace hw1 {
// Generates subkeys for each round.
class KeyGen {
public:
// Args:
// start_key: The initial 10-bit key, in an array of two uint8_ts.
KeyGen(const uint8_t *start_key);
// Resets the state of the key generator with a new starting key.
// Args:
// key: The new starting key, as a 2-length byte array.
void Reset(const uint8_t *key);
// Generates the next subkey.
// Returns:
// The next 8-bit subkey.
uint8_t GenNext();
private:
// Current ten-bit state. This is implemented as an array of 2 uint8_ts.
uint8_t state_[2];
// Initial permutation.
PBox initial_perm_;
// Final permutation.
PBox final_perm_;
};
} // namespace hw1
#endif // HW1_KEY_GEN_H_
|
PHP
|
UTF-8
| 3,681 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
<?php declare(strict_types=1);
namespace Torr\MenuBundle\Item;
use Symfony\Contracts\Translation\TranslatableInterface;
use Torr\Rad\Route\LinkableInterface;
class MenuItem
{
// region Fields
/**
* The children of the menu item.
*
* @var self[]
*/
private array $children = [];
/**
* Whether the item is visible (= should be included in the tree but never rendered).
*/
private readonly bool $visible;
//endregion
/**
*/
public function __construct (
/**
* The label to display.
* Will be translated using the translation domain given in the renderer.
*/
private readonly TranslatableInterface|string|null $label = null,
/**
* The parent menu item.
*/
private ?self $parent = null,
/**
* The target of this item.
*
* LinkableInterface -> route
* string -> direct URI
* null -> no link
*/
private readonly LinkableInterface|string|null $target = null,
/**
* Whether the item is the currently selected menu item.
*/
private readonly bool $current = false,
/**
* The extra attributes on the menu item.
*/
private array $extras = [],
bool $visible = true,
)
{
$this->parent?->addChild($this);
$this->visible = $visible && null !== $this->label;
}
//region Accessors
/**
*/
public function getParent () : ?self
{
return $this->parent;
}
/**
*/
public function getLabel () : TranslatableInterface|string|null
{
return $this->label;
}
/**
*
*/
public function setParent (?self $parent) : self
{
// remove child from previous parent
$this->parent?->removeChild($this);
// update parent
$this->parent = $parent;
// add to parent children, if parent is not null
$parent?->addChild($this);
return $this;
}
/**
*/
public function getTarget () : LinkableInterface|string|null
{
return $this->target;
}
/**
*/
public function setExtra (string $name, mixed $value) : self
{
$this->extras[$name] = $value;
return $this;
}
/**
*/
public function getExtra (string $name, mixed $defaultValue = null) : mixed
{
return $this->extras[$name] ?? $defaultValue;
}
/**
*/
public function isVisible () : bool
{
return $this->visible;
}
/**
*/
public function isCurrent () : bool
{
return true === $this->current;
}
/**
* @return self[]
*/
public function getChildren () : array
{
return $this->children;
}
/**
*
*/
public function addChild (self $child) : self
{
$child->parent?->removeChild($child);
$child->parent = $this;
$this->children[] = $child;
return $this;
}
/**
*
*/
public function removeChild (self $childToRemove) : self
{
$newChildren = [];
foreach ($this->children as $child)
{
if ($child === $childToRemove)
{
$child->parent = null;
continue;
}
$newChildren[] = $child;
}
$this->children = $newChildren;
return $this;
}
/**
*
*/
public function __clone ()
{
// Remove the parent link when cloning, as it wouldn't even be in the list of children.
// If the user wants to add it to the same parent, they can do it themselves.
// This has the added bonus that if used with `find()` and rendering, that it will reset
// the level calculation on this node.
$this->parent = null;
// Explicitly deep clone children.
$oldChildren = $this->children;
$this->children = [];
foreach ($oldChildren as $child)
{
$this->addChild(clone $child);
}
}
/**
* @return self[]
*/
public function getVisibleChildren () : array
{
$filtered = [];
foreach ($this->children as $child)
{
if ($child->isVisible())
{
$filtered[] = $child;
}
}
return $filtered;
}
}
|
Go
|
UTF-8
| 30,684 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
package genetic
import (
. "gopkg.in/check.v1" // https://labix.org/gocheck
"math/rand"
"time"
)
// Create a suite.
type NeatNeuralNetSuite struct{}
var _ = Suite(&NeatNeuralNetSuite{})
// Add the tests.
func (s *NeatNeuralNetSuite) Test_NewNeatNeuralNet(c *C) {
setMaxGeneId(0)
c.Skip("This test has been verified but is unpredictable so should be manually reviewed.")
// Get the randomness rolling.
rand.Seed(time.Now().UnixNano())
// Create an interface of inputs and outputs for the neural net.
var inOut NeuralNetInOut = NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
}
// Make a new neural net.
var neuralNet NeatNeuralNet = newNeatNeuralNet(inOut)
// The contents are random. Just inspect it with a test.
c.Assert(neuralNet, Equals, "unpredictable")
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_AddConnection(c *C) {
var ok bool
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
}
// Set the max gene id.
setMaxGeneId(0)
c.Assert(_maxGeneId, Equals, uint64(0))
// The genome is empty at the moment.
c.Assert(neuralNet.Genome, DeepEquals, neatGenome{})
// Add a connection.
ok = neuralNet.addConnection("i1", "o1", 0.5)
c.Assert(ok, Equals, true)
c.Check(neuralNet.Genome, DeepEquals, neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 0.5},
}})
c.Check(_maxGeneId, Equals, uint64(1))
// Add a different connection.
ok = neuralNet.addConnection("i2", "o2", 0.3)
c.Assert(ok, Equals, true)
c.Check(neuralNet.Genome, DeepEquals, neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 0.5},
neatGene{GeneId: 2, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 0.3},
}})
c.Check(_maxGeneId, Equals, uint64(2))
// Attempt to add the same connection again.
ok = neuralNet.addConnection("i2", "o2", 0.5)
c.Assert(ok, Equals, false) // Wasn't added.
c.Check(neuralNet.Genome, DeepEquals, neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 0.5},
neatGene{GeneId: 2, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 0.3},
}})
c.Check(_maxGeneId, Equals, uint64(2)) // GeneId not incremented.
// Attempt to add a connection with a input as the sink.
c.Assert(func() { neuralNet.addConnection("i1", "i2", 0.88888) }, Panics, `Cannot use input as sink: 'i2'`)
c.Check(_maxGeneId, Equals, uint64(2)) // GeneId not incremented.
// Attempt to add a connection with a input as the sink.
c.Assert(func() { neuralNet.addConnection("i1", "b", 0.88888) }, Panics, `Cannot use bias as sink: 'b'`)
c.Check(_maxGeneId, Equals, uint64(2)) // GeneId not incremented.
// Attempt to add a connection with an output as the source.
c.Assert(func() { neuralNet.addConnection("o1", "o2", 0.88888) }, Panics, `Cannot use output as source: 'o1'`)
c.Check(_maxGeneId, Equals, uint64(2)) // GeneId not incremented.
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_AddConnection_HiddenNodes(c *C) {
var ok bool
// Build a neural net we can test challenging connections on.
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1"},
Outputs: []string{"o1"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 2, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_SINE},
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_RAMP},
neatGene{GeneId: 4, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "b", To: "o1", Weight: 0.1},
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "1", Weight: 0.2},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "1", To: "2", Weight: 0.3},
neatGene{GeneId: 7, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "2", To: "3", Weight: 0.4},
neatGene{GeneId: 8, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "3", To: "o1", Weight: 0.5},
neatGene{GeneId: 9, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 0.6}, // Disabled!
},
},
}
// Set the max gene id.
setMaxGeneId(9)
c.Assert(_maxGeneId, Equals, uint64(9))
// Attempt to add a circular dependency
ok = neuralNet.addConnection("1", "1", 0.88888)
c.Assert(ok, Equals, false) // Wasn't added.
c.Assert(len(neuralNet.Genome.Genes), Equals, 9) // Unchanged.
c.Assert(_maxGeneId, Equals, uint64(9)) // GeneId not incremented.
// Attempt to add a circular dependency
ok = neuralNet.addConnection("2", "1", 0.88888)
c.Assert(ok, Equals, false) // Wasn't added.
c.Assert(len(neuralNet.Genome.Genes), Equals, 9) // Unchanged.
c.Assert(_maxGeneId, Equals, uint64(9)) // GeneId not incremented.
// Attempt to add a circular dependency
ok = neuralNet.addConnection("3", "1", 0.88888)
c.Assert(ok, Equals, false) // Wasn't added.
c.Assert(len(neuralNet.Genome.Genes), Equals, 9) // Unchanged.
c.Assert(_maxGeneId, Equals, uint64(9)) // GeneId not incremented.
// Unknown nodes.
c.Assert(func() { neuralNet.addConnection("unknown", "3", 0.88888) }, Panics, `Unknown from node: 'unknown'`)
c.Assert(func() { neuralNet.addConnection("3", "unknown", 0.88888) }, Panics, `Unknown to node: 'unknown'`)
c.Assert(_maxGeneId, Equals, uint64(9)) // GeneId not incremented.
// Make some valid connection to hidden nodes.
// Connect an input to a hidden node.
ok = neuralNet.addConnection("i1", "2", 0.12)
c.Assert(ok, Equals, true) // Wasn't added.
c.Check(neuralNet.Genome.Genes[9], DeepEquals, neatGene{GeneId: 10, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "2", Weight: 0.12})
c.Check(_maxGeneId, Equals, uint64(10)) // Gene id incremented.
// Connect a hidden node to a hidden node.
ok = neuralNet.addConnection("1", "3", 0.13)
c.Assert(ok, Equals, true) // Wasn't added.
c.Check(neuralNet.Genome.Genes[10], DeepEquals, neatGene{GeneId: 11, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "1", To: "3", Weight: 0.13})
c.Check(_maxGeneId, Equals, uint64(11)) // Gene id incremented.
// Connect a hidden node to an output.
ok = neuralNet.addConnection("2", "o1", 0.14)
c.Assert(ok, Equals, true) // Wasn't added.
c.Check(neuralNet.Genome.Genes[11], DeepEquals, neatGene{GeneId: 12, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "2", To: "o1", Weight: 0.14})
c.Check(_maxGeneId, Equals, uint64(12)) // Gene id incremented.
// Connect the bias to a hidden node.
ok = neuralNet.addConnection("b", "1", 0.15)
c.Assert(ok, Equals, true) // Wasn't added.
c.Check(neuralNet.Genome.Genes[12], DeepEquals, neatGene{GeneId: 13, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "b", To: "1", Weight: 0.15})
c.Check(_maxGeneId, Equals, uint64(13)) // Gene id incremented.
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_AddNode(c *C) {
var neuralNet NeatNeuralNet
// Make a new neural net (avoiding randomness).
neuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Add a node to the first gene.
setMaxGeneId(345)
c.Assert(_maxGeneId, Equals, uint64(345))
neuralNet.addNode(0, ACTIVATION_SIGMOID)
c.Check(neuralNet.Genome.Genes, DeepEquals, []neatGene{
neatGene{GeneId: 1, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Disable the original connection.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2},
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3},
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4},
neatGene{GeneId: 346, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_SIGMOID}, // Node added to genome.
neatGene{GeneId: 347, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "346", Weight: 1.1}, // First half of original connection.
neatGene{GeneId: 348, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "346", To: "o1", Weight: 1.1}, // First half of original connection.
})
// Make a new neural net (avoiding randomness).
neuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Add a node to the second gene.
setMaxGeneId(345)
c.Assert(_maxGeneId, Equals, uint64(345))
c.Check(func() { neuralNet.addNode(1, ACTIVATION_SIGMOID) }, Panics, `Disabled genes cannot be split with a new node.`)
// Make a new neural net (avoiding randomness).
neuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Add a node to the third gene.
setMaxGeneId(345)
c.Assert(_maxGeneId, Equals, uint64(345))
neuralNet.addNode(2, ACTIVATION_SIGMOID)
c.Check(neuralNet.Genome.Genes, DeepEquals, []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1},
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2},
neatGene{GeneId: 3, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Disable the original connection.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4},
neatGene{GeneId: 346, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_SIGMOID}, // Node added to genome.
neatGene{GeneId: 347, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "346", Weight: 1.3}, // First half of original connection.
neatGene{GeneId: 348, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "346", To: "o1", Weight: 1.3}, // First half of original connection.
})
// Make a new neural net (avoiding randomness).
neuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Add a node to the forth gene.
setMaxGeneId(345)
c.Assert(_maxGeneId, Equals, uint64(345))
c.Check(func() { neuralNet.addNode(3, ACTIVATION_SIGMOID) }, Panics, `Only genes of type 'connection' can have nodes added, not type: 'SOMETHING_ELSE'`)
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_MutateAddNode(c *C) {
setMaxGeneId(0)
c.Skip("This test has been verified but is unpredictable so should be manually reviewed.")
// Get the randomness rolling.
rand.Seed(time.Now().UnixNano())
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Mutate the neural net.
neuralNet.mutateAddNode([]string{ACTIVATION_BIPOLAR_SIGMOID, ACTIVATION_INVERSE, ACTIVATION_SINE})
// The contents are random. Just inspect it with a test.
c.Assert(neuralNet, Equals, "unpredictable")
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_MutateAddNode_NoActivationFunctions(c *C) {
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Invalid parameters.
c.Check(func() { neuralNet.mutateAddNode(nil) }, Panics, `Available functions must be defined to mutetate add node.`)
c.Check(func() { neuralNet.mutateAddNode([]string{}) }, Panics, `Available functions must be defined to mutetate add node.`)
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_MutateAddConnection(c *C) {
c.Skip("This test has been verified but is unpredictable so should be manually reviewed.")
// Get the randomness rolling.
rand.Seed(time.Now().UnixNano())
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
}},
}
setMaxGeneId(6)
// Mutate the neural net.
var wasAdded bool = neuralNet.mutateAddConnection(1)
// The contents are random. Just inspect it with a test.
c.Assert(wasAdded, Equals, true)
c.Assert(neuralNet, Equals, "unpredictable")
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_MutateChangeConnectionWeight(c *C) {
c.Skip("This test has been verified but is unpredictable so should be manually reviewed.")
// Get the randomness rolling.
rand.Seed(time.Now().UnixNano())
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
}},
}
// Mutate the neural net.
neuralNet.mutateChangeConnectionWeight()
// The contents are random. Just inspect it with a test.
c.Assert(neuralNet, Equals, "unpredictable")
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_MutateAddConnection_NoMaxAttempts(c *C) {
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Invalid parameters.
c.Check(func() { neuralNet.mutateAddConnection(0) }, Panics, `Must have a 1 or more max attempts to mutate add connection, not: 0`)
c.Check(func() { neuralNet.mutateAddConnection(-1) }, Panics, `Must have a 1 or more max attempts to mutate add connection, not: -1`)
}
func (s *NeatNeuralNetSuite) Test_Mate(c *C) {
c.Skip("This test has been verified but is unpredictable so should be manually reviewed.")
// Get the randomness rolling.
rand.Seed(time.Now().UnixNano())
// Make a neural net (avoiding randomness).
var fitterNeuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 8, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i4", To: "o1", Weight: 1.5}, // Gene in just this neural net.
}},
}
// Make another neural net (avoiding randomness).
var otherNeuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 2.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 2.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 2.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 2.4}, // Pick weight that can never be randomized to.
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 7, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE}, // Gene in just this neural net.
}},
}
// Mutate the neural net.
var child NeatNeuralNet = mate(fitterNeuralNet, otherNeuralNet)
// The contents are random. Just inspect it with a test.
c.Assert(child, Equals, "unpredictable")
}
func (s *NeatNeuralNetSuite) Test_Mate_UnorderedGenes(c *C) {
// Make a neural net with properly ordered genes.
var orderedNeuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
}},
}
// Make a neural net with improperly ordered genes.
var unorderedNeuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
}},
}
// Invalid parameters.
c.Check(func() { mate(orderedNeuralNet, unorderedNeuralNet) }, Panics, `genome not sorted correctly by gene id: [{GeneId:2 IsEnabled:false Type:connection From:i2 To:o2 Weight:1.2 Function:} {GeneId:1 IsEnabled:true Type:connection From:i1 To:o1 Weight:1.1 Function:}]`)
c.Check(func() { mate(unorderedNeuralNet, orderedNeuralNet) }, Panics, `genome not sorted correctly by gene id: [{GeneId:2 IsEnabled:false Type:connection From:i2 To:o2 Weight:1.2 Function:} {GeneId:1 IsEnabled:true Type:connection From:i1 To:o1 Weight:1.1 Function:}]`)
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_RandomizedClone(c *C) {
// Get the randomness rolling.
rand.Seed(time.Now().UnixNano())
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2", "i3", "i4"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 1.1}, // Pick weight that can never be randomized to.
neatGene{GeneId: 2, IsEnabled: false, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "o2", Weight: 1.2}, // Pick weight that can never be randomized to.
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i3", To: "o1", Weight: 1.3}, // Pick weight that can never be randomized to.
neatGene{GeneId: 4, IsEnabled: true, Type: "SOMETHING_ELSE", From: "i4", To: "o2", Weight: 1.4}, // Pick weight that can never be randomized to.
}},
}
// Create a randomized clone.
var clone NeatNeuralNet = neuralNet.randomizedClone()
// The clone and original share the same inputs and outputs.
c.Assert(clone.InOut, DeepEquals, neuralNet.InOut)
// The clone and original share the same number of genes.
c.Assert(len(clone.Genome.Genes), Equals, len(neuralNet.Genome.Genes))
// The original neuralNet is unchanged.
c.Check(neuralNet.Genome.Genes[0].Weight, Equals, 1.1)
c.Check(neuralNet.Genome.Genes[1].Weight, Equals, 1.2)
c.Check(neuralNet.Genome.Genes[2].Weight, Equals, 1.3)
c.Check(neuralNet.Genome.Genes[3].Weight, Equals, 1.4)
// For the clone, some genes have been given new weights.
// The first gene should have a new weight.
c.Check(clone.Genome.Genes[0].Weight, Not(Equals), 1.1)
// The second gene should be unchanged, it was disabled.
c.Check(clone.Genome.Genes[1].Weight, Equals, 1.2)
// The third gene should have a new weight.
c.Check(clone.Genome.Genes[2].Weight, Not(Equals), 1.3)
// The forth gene should be unchanged, it was not a connection.
c.Check(clone.Genome.Genes[3].Weight, Equals, 1.4)
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_Compute(c *C) {
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 0.1},
neatGene{GeneId: 2, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "2", Weight: 0.25},
neatGene{GeneId: 4, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "2", To: "o1", Weight: 0.4},
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "b", To: "2", Weight: 0.5},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "b", To: "o2", Weight: 0.5},
}},
}
// Compute and get the expected outputs.
//
// i1 = 10.0
// i2 = 100.0
// b = 1.0
// h2 = -1.0 * (100.0 * 0.25 + 1.0 * 0.5) = -25.5
// o1 = (10.0 * 0.1 - 25.5 * 0.4) = 1 - 10.2 = -9.2
// o2 = (1.0 * 0.5) = 0.5
var expectedOutputs map[string]float64 = map[string]float64{
"o1": (10.0*0.1 + ((100.0*0.25+1.0*0.5)*-1.0)*0.4),
"o2": (1.0 * 0.5),
}
var outputs map[string]float64 = neuralNet.Compute(map[string]float64{"i1": 10.0, "i2": 100.0})
c.Assert(len(outputs), Equals, len(expectedOutputs))
c.Assert(int64(outputs["o1"]*10000.0), Equals, int64(expectedOutputs["o1"]*10000.0)) // Round with typecast.
c.Assert(int64(outputs["o2"]*10000.0), Equals, int64(expectedOutputs["o2"]*10000.0)) // Round with typecast.
// Attempt to compute missing an input.
c.Check(func() { neuralNet.Compute(map[string]float64{"i1": 10.0}) }, Panics, `Missing input: 'i2'`)
// Attempt to compute with unknown input.
c.Check(func() { neuralNet.Compute(map[string]float64{"i1": 10.0, "i2": 100.0, "i3": 100.0}) }, Panics, `Unknown input: 'i3'`)
}
func (s *NeatNeuralNetSuite) Test_NeatNeuralNet_PrepareComputeTopology_CircularDependency(c *C) {
// Make a new neural net (avoiding randomness).
var neuralNet NeatNeuralNet = NeatNeuralNet{
InOut: NeuralNetInOut{
Inputs: []string{"i1", "i2"},
Outputs: []string{"o1", "o2"},
},
Genome: neatGenome{Genes: []neatGene{
neatGene{GeneId: 1, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i1", To: "o1", Weight: 0.1},
neatGene{GeneId: 2, IsEnabled: true, Type: _GENE_TYPE_NODE, Function: ACTIVATION_INVERSE},
neatGene{GeneId: 3, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "i2", To: "2", Weight: 0.25},
neatGene{GeneId: 4, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "2", To: "o1", Weight: 0.4},
neatGene{GeneId: 5, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "b", To: "2", Weight: 0.5},
neatGene{GeneId: 6, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "b", To: "o2", Weight: 0.5},
neatGene{GeneId: 7, IsEnabled: true, Type: _GENE_TYPE_CONNECTION, From: "2", To: "2", Weight: 0.5}, // Circular dependency.
}},
}
// Attempting to compute before preparing compute topology will fail.
c.Check(func() { neuralNet.prepareComputeTopology() }, Panics, `Neural net has a circular dependency in Genome: [{GeneId:1 IsEnabled:true Type:connection From:i1 To:o1 Weight:0.1 Function:} {GeneId:2 IsEnabled:true Type:node From: To: Weight:0 Function:inverse} {GeneId:3 IsEnabled:true Type:connection From:i2 To:2 Weight:0.25 Function:} {GeneId:4 IsEnabled:true Type:connection From:2 To:o1 Weight:0.4 Function:} {GeneId:5 IsEnabled:true Type:connection From:b To:2 Weight:0.5 Function:} {GeneId:6 IsEnabled:true Type:connection From:b To:o2 Weight:0.5 Function:} {GeneId:7 IsEnabled:true Type:connection From:2 To:2 Weight:0.5 Function:}]`)
}
|
Markdown
|
UTF-8
| 3,887 | 2.71875 | 3 |
[] |
no_license
|
---
description: "La Recette Pas à Pas Gaufres"
title: "La Recette Pas à Pas Gaufres"
slug: 288-la-recette-pas-a-pas-gaufres
date: 2020-08-30T20:38:04.292Z
image: https://img-global.cpcdn.com/recipes/6f92b93d65cfa456/751x532cq70/gaufres-photo-principale-de-la-recette.jpg
thumbnail: https://img-global.cpcdn.com/recipes/6f92b93d65cfa456/751x532cq70/gaufres-photo-principale-de-la-recette.jpg
cover: https://img-global.cpcdn.com/recipes/6f92b93d65cfa456/751x532cq70/gaufres-photo-principale-de-la-recette.jpg
author: Francis Stokes
ratingvalue: 4.7
reviewcount: 10
recipeingredient:
- "8 ufs entiers"
- "500 gr farine"
- "100 gr sucre"
- "1 sachet de sucre vanill"
- "1 sachet de levure chimique"
- "600 ml lait"
- "100 gr beurre"
recipeinstructions:
- "Mettre dans votre robot l'ultra blade et votre beurre programmez Vit5/90°/3min"
- "Ajoutez le sucre, sucre vanillé et le lait pendant 1min/vit10"
- "Puis ajoutez la farine et la levure en Vit10/2min"
- "Incorporez les œufs et battre 2min/Vit5 pendant ce temps faites chauffez votre gaufrier et quand c'est bon faites vos gaufres."
categories:
- Resep
tags:
- gaufres
katakunci: gaufres
nutrition: 103 calories
recipecuisine: Indonesian
preptime: "PT40M"
cooktime: "PT50M"
recipeyield: "4"
recipecategory: Dessert
---

La cuisine est une sorte d'art et il existe différentes sortes de cuisine que vous pouvez découvrir. Vous pouvez devenir un chef gastronomique ou simplement essayer de maîtriser l'art de cuisiner de bons plats dans votre maison. Plusieurs tâches au bureau font appel à des cuisiniers, des préparateurs et des superviseurs qui supervisent également les chefs. Nous espérons que cette <strong> Gaufres </strong> recette pourra vous aider à devenir un meilleur cuisinier.
<!--inarticleads1-->
Vous pouvez avoir gaufres en utilisant 7 Ingrédients et 4 pas. Voici comment vous atteindre cette.
##### Ingrédients de gaufres :
1. Utilisation 8 œufs entiers
1. Fournir 500 gr farine
1. Vous devez vous préparer 100 gr sucre
1. Fournir 1 sachet de sucre vanillé
1. Vous avez besoin 1 sachet de levure chimique
1. Préparer 600 ml lait
1. Vous avez besoin 100 gr beurre
In France we have mainly two ways of preparing waffles. The most classic one is a mix of flour, sugar, butter, milk, whole eggs with baking powder. It needs to rest for at least one hour. Gaufre definition is - a very thin crisp wafer baked with a wafer iron.
<!--inarticleads2-->
##### Gaufres pas à pas :
1. Mettre dans votre robot l'ultra blade et votre beurre programmez Vit5/90°/3min
1. Ajoutez le sucre, sucre vanillé et le lait pendant 1min/vit10
1. Puis ajoutez la farine et la levure en Vit10/2min
1. Incorporez les œufs et battre 2min/Vit5 pendant ce temps faites chauffez votre gaufrier et quand c'est bon faites vos gaufres.
A typical Western confectionery made by Kobe Fugetsudo. It has a small size that makes it easy to enjoy a Western-style rice cracker Gaufres with sandwiches of crispy and fragrant thin baked Vanilla, Strawberry, and Chocolate cream. It is also a product that will be appreciated by customers who invite you. Gaufres & Waffles reinvents one of the most gastronomic treasures in Brussels culture - the Brussels Waffle (available in a savoury version). At Gaufres & Waffles, the waffle is no longer seen as a dessert or a snack, but as a real meal.
<!--inarticleads1-->
<p>
Maintenant que vous avez terminé cette recette de Gaufres, explorez actuellement les recettes, appliquez-la et appréciez également. Vous ne le reconnaissez jamais - vous avez peut-être découvert une toute nouvelle vocation.
</p>
<p>
<i>Si vous trouvez cette Gaufres recette précieuse, partagez-la avec vos amis proches ou votre famille, merci et bonne chance.</i>
</p>
|
C++
|
UTF-8
| 16,932 | 2.96875 | 3 |
[] |
no_license
|
const int ledPin = 8;
const int buzzPin = 5;
const int buzzFreq = 443;
char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '.', '?', ' '};
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void execMorse(String codetype, int ledpin, int buzzerpin, int delaytime, int freq) {
int switchState;
if (codetype == "dot") {
switchState = 0;
} else if (codetype == "stripe") {
switchState = 1;
}
switch (switchState) {
case 0:
digitalWrite(ledpin, HIGH);
tone(buzzerpin, freq);
delay(delaytime);
digitalWrite(ledpin, LOW);
noTone(buzzerpin);
break;
case 1:
digitalWrite(ledpin, HIGH);
tone(buzzerpin, freq);
delay(delaytime * 3);
digitalWrite(ledpin, LOW);
noTone(buzzerpin);
break;
default:
break;
}
}
void morseDelay(String delaytype, int delaytime) {
int switchState;
if (delaytype == "element") {
switchState = 0;
} else if (delaytype == "letter") {
switchState = 1;
} else if (delaytype == "word") {
switchState = 2;
}
switch (switchState) {
case 0:
delay(delaytime);
break;
case 1:
delay(delaytime * 3);
break;
case 2:
delay(delaytime * 7);
break;
default:
break;
}
}
void morse(char letter, int ledpin, int buzzerpin, int delaytime, int freq) {
int index;
for (int i = 0; i < sizeof(alphabet); i++) {
if (alphabet[i] == letter) {
index = i;
}
}
switch (index) {
case 0:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 1:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 2:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 3:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 4:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 5:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 6:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 7:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 8:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 9:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 10:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 11:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 12:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 13:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 14:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 15:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 16:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 17:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 18:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 19:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 20:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 21:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 22:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 23:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 24:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 25:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 26:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 27:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 28:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 29:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 30:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 31:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 32:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 33:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 34:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 35:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 36:
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 37:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
break;
case 38:
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("stripe", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
morseDelay("element", delaytime);
execMorse("dot", ledpin, buzzerpin, delaytime, freq);
break;
case 39:
morseDelay("word", delaytime);
break;
default:
break;
}
}
void loop() {
String incoming;
if (Serial.available() > 0) {
// Read a byte from the serial buffer.
char inchar = (char)Serial.read();
if ((' ' <= inchar) && (inchar <= '~')) {
incoming += inchar;
}
char inc_array[sizeof(incoming)];
incoming.toLowerCase();
incoming.toCharArray(inc_array,sizeof(incoming));
for(int i = 0;i<sizeof(inc_array);i++){
morse(inc_array[i], ledPin, buzzPin, 100, 443);
if(inc_array[i] != " "){
morseDelay("letter", 100);
}
}
}
}
|
Java
|
UTF-8
| 2,312 | 2.890625 | 3 |
[] |
no_license
|
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Board extends JFrame implements MouseListener, WindowListener, KeyListener {
public Board() {
this.setTitle("Kevelson Math Challenge");
BoardPanel panel = new BoardPanel();
this.add(panel);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(600,600);
this.setVisible(true);
}
public static void main(String args[]) {
Board board = new Board();
}
@Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
|
C#
|
UTF-8
| 1,462 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace EasyGameServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static EasyGameServer server = null;
private static Thread serverThread = null;
private void bu_server_start_Click(object sender, EventArgs e)
{
if (server == null)
{
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.RealTime;
server = new EasyGameServer();
serverThread = new Thread(server.Run);
serverThread.Start();
}
}
private void bu_test_Click(object sender, EventArgs e)
{
DB.DBHelper dbHelper = new DB.DBHelper();
if( dbHelper.Initialize() )
{
Console.WriteLine("DB INIT OK");
dbHelper.TestSP();
}
else
{
Console.WriteLine("DB INIT FAIL");
}
}
private void bu_console_clear_Click(object sender, EventArgs e)
{
Console.Clear();
}
}
}
|
Java
|
UTF-8
| 1,466 | 2.109375 | 2 |
[] |
no_license
|
package br.com.lbr.beerApi.controller;
import br.com.lbr.beerApi.dto.BreweryDTO;
import br.com.lbr.beerApi.exception.BreweryAlreadyRegisteredException;
import br.com.lbr.beerApi.exception.BreweryNotFoundException;
import br.com.lbr.beerApi.service.BreweryService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/api/v1/breweries")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class BreweryController implements BreweryControllerDocs {
private final BreweryService breweryService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BreweryDTO createBrewery(@RequestBody @Valid BreweryDTO breweryDTO) throws BreweryAlreadyRegisteredException {
return breweryService.createBrewery(breweryDTO);
}
@GetMapping("/{name}")
public BreweryDTO findByName(@PathVariable String name) throws BreweryNotFoundException {
return breweryService.findByName(name);
}
@GetMapping
public List<BreweryDTO> listBreweries() {
return breweryService.listAll();
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteById(@PathVariable Long id) throws BreweryNotFoundException {
breweryService.deleteById(id);
}
}
|
Java
|
UTF-8
| 258 | 1.890625 | 2 |
[] |
no_license
|
package ru.otus.bookapp.domain;
import lombok.Data;
import lombok.RequiredArgsConstructor;
/**
* @author Aleksey.Potekhin
* @date 23.06.2021
*/
@Data
@RequiredArgsConstructor
public class Author {
private final long id;
private final String name;
}
|
C++
|
UTF-8
| 1,437 | 2.859375 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
bool in[51];
bool out[51];
bool p[51][51];
void pAns(int n, fstream& coutf){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(p[i][j])
coutf << "Y";
else
coutf << "N";
}
coutf << endl;
}
}
int main(){
fstream cinf;
cinf.open("travel_restrictions_input.txt");
fstream coutf;
coutf.open("output.txt", fstream::out);
int t;
cinf >> t;
int count = 0;
while(t--){
count++;
int n;
cinf >> n;
char ch;
for(int i=1;i<=n;i++) fill(p[i], p[i]+n+1, false);
fill(in, in+n+1, false);
fill(out, out+n+1, false);
for(int i=1;i<=n;i++){
cinf >> ch;
if(ch=='Y') in[i]=true;
else in[i]=false;
}
for(int i=1;i<=n;i++){
cinf >> ch;
if(ch=='Y') out[i]=true;
else out[i]=false;
}
for(int i=1;i<=n;i++){
int curr = i;
p[i][i]=true;
while(curr!=n && out[curr] && in[curr+1]) {p[i][curr+1]=true; curr++;}
curr=i;
while(curr!=1 && out[curr] && in[curr-1]) {p[i][curr-1]=true; curr--;}
}
coutf << "Case #" << count << ": " << endl;
pAns(n, coutf);
}
return 0;
}
|
Markdown
|
UTF-8
| 884 | 2.6875 | 3 |
[] |
no_license
|
# Warpath Hack iOS Cheats gift code gold redemption that work with mod
Warpath Hack iOS Cheats gift code gold redemption that work with mod - Different Warpath gift code for redemption gold will affect different types of followers. For example, frost and graupel will change the attack power of all Warpath melee cards (except hero cards) to 1, while fog will affect long-range followers. The Warpath hack iOS is very interesting. Its attack power will be calculated on the opposite side, but it can let you draw two more gold in each stage. For the game of Warpath Cheats, which has extremely limited resources, the significance of making up cards is self-evident. In order to offset the negative effects of Warpath mod apk, you can use higher combat power to press the opposite end, or use weather cards to restrict, or simply give up the game.
Here https://fundanemt.org/warpath
|
JavaScript
|
UTF-8
| 4,517 | 2.96875 | 3 |
[
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
/*
Any copyright to this file is released to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
If you like this, you should donate
to Peter O. (original author of
the Public Domain HTML 3D Library) at:
http://peteroupc.github.io/
*/
/**
* Contains constants for assigning semantics
* to vertex attributes found in mesh buffers and
* to data that is uniform throughout a particular
* geometry draw call.
* @constructor
* @readonly
*/
export const Semantic = {};
/** Attribute semantic for a vertex position.
* In general, vertex positions are 2-dimensional or 3-dimensional.
* @const
* @static
*/
Semantic.POSITION = 0;
/** Attribute semantic for a vertex normal.<p>
* For 3D graphics libraries to calculate a mesh buffer's lighting and shading correctly, that mesh buffer must specify normals for all its vertices.<p>
* <b>What are normals?</b> A normal is a set of numbers (usually three numbers) describing a particular direction. Generally, a normal's direction is perpendicular to a surface's edges, and points up and
* away from the surface.<p>
* Normals are important in the lighting and shading model. When light hits an object's surface, how brightly the surface will be lit depends on how directly the light points to the surface. It will be lit the most brightly if the light is directly opposite to its normal, and not at all if the light is perpendicular to the normal or in the same direction as the normal.<p>
* In general, vertex normals are 3-dimensional
* and are defined for a mesh buffer only if it
* also contains vertex positions.
* @const
* @static
*/
Semantic.NORMAL = 1;
/** Attribute semantic for a tuple of texture coordinates.<p>
* If a texture (array of memory units) will be applied to a mesh buffer's geometry, then texture coordinates need to be specified for each vertex in that mesh buffer. In general, a texture coordinate is one of two numbers, called U and V, that map to a specific point in the texture. Each texture coordinate ranges from 0 to 1.<p>
* In most 3D graphics pipelines, U coordinates start at the left of the texture (0) and increase to the right (1). In some graphics pipelines, such as OpenGL, V coordinates start by default at the bottom of the texture (0) and increase to the top (1), while in others, such as WebGL, Vulkan, Metal, and DirectX, V coordinates start by default at the top of the texture and increase to the bottom. Thus, for example, in OpenGL by default, texture coordinates (0, 1) indicate the top left corner of the texture, and texture coordinates (0.5, 0.5) indicate the center of the texture.<p>
* In general, texture coordinates describe 2-dimensional points.
* However, for such texturing tasks as mapping
* a square to a trapezoid, trios of 3-dimensional texture coordinates (U, V, and Z)
* are useful to ensure the texturing remains perspective-correct.
* In this case, the 3-D texture coordinates are converted
* to 2-D by dividing the U and V components by the Z component.
* In a fragment shader or pixel shader, this can look like
* the following
* code: <code>texCoord.xy/texCoord.z</code>.
* @const
* @static
*/
Semantic.TEXCOORD = 2;
/** Attribute semantic for a color.
* In general, each color consists of three components.
* @const
* @static
*/
Semantic.COLOR = 3;
/** Attribute semantic for a skinning joint.
* @const
* @static
*/
Semantic.JOINT = 4;
/** Attribute semantic for a skinning weight.
* @const
* @static
*/
Semantic.WEIGHT = 5;
/** Attribute semantic for a tangent vector.
* @const
* @static
*/
Semantic.TANGENT = 6;
/** Attribute semantic for a bitangent vector.
* @const
* @static
*/
Semantic.BITANGENT = 7;
/** Attribute semantic for custom attributes.
* @const
* @static
*/
Semantic.CUSTOM = 8;
/** Uniform semantic for a model matrix.
* @const */
Semantic.MODEL = 101;
/** Uniform semantic for a view matrix.
* @const */
Semantic.VIEW = 102;
/** Uniform semantic for a projection matrix.
* @const */
Semantic.PROJECTION = 103;
/** Uniform semantic for a model-view matrix.
* @const */
Semantic.MODELVIEW = 104;
/** Uniform semantic for a model-view-projection matrix.
* @const */
Semantic.MODELVIEWPROJECTION = 105;
/** Uniform semantic for the inverse of the 3x3 transpose of the model-view matrix.
* @const */
Semantic.MODELVIEWINVERSETRANSPOSE = 106;
/** Uniform semantic for an inverse view matrix.
* @const */
Semantic.VIEWINVERSE = 107;
/** Uniform semantic for a joint matrix.
* @const */
Semantic.JOINTMATRIX = 108;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.