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
|
---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 3,232 | 2.8125 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
export default class Rewards extends Component {
getItemDropDiv(itemData) {
if (!itemData) {
return <div className="reward-item--no-item">No item drop</div>;
}
return (
<div className="reward-item-parent" >
Item drop received:
{itemData.map((e, i) => {
return (
<div className="reward-item-child" key={`rewards-item-${i}`}>
{e.name}
</div>
)
})}
</div>
)
}
getLevelPercentage(levelObject, experienceObject) {
const remainder = levelObject.remainder;
const expToNextLevel = experienceObject[levelObject.level + 1];
return Math.round((remainder / expToNextLevel) * 100);
// remainder is the current exp towards next level, dividing by the exp required gives a percentage between 0-1
// multiplying by 100 gives a percentage 0-100, which we use to size our progress bar via css
// TODO remove
// probably unneccesary but I haven't fully tested the above 1-liner so this is here for now
// return (
// (remainder / expToNextLevel) // get percentage to fill progress bar, can be a long number which screws the css
// .toString() // make it a string
// .split('') // make the string an array of characters
// .map((e, i) => { // map over the characters
// if (i >= 2 && i <= 3) {
// return e
// } // ignore the characters past the second index
// })
// .filter(e => e) // filter empty responses, shouldn't be necessary but it wasn't working without
// .join('') // make the array back into a string
// )
}
fillBar(percentage) {
return {maxWidth: `${percentage}%`}
}
render() {
const { oldGold, oldExp, newGold, newExp } = this.props.propsObject.updateExperienceAndGold;
const randomItem = this.props.propsObject.getItemName;
const { experienceAndLevelObject } = this.props.propsObject;
const experienceObject = this.props.propsObject.experienceObject;
return (
<div className={"reward-highest-parent " + this.props.className } >
<div className="reward-gold-parent" >
Gold: {newGold - oldGold}
</div>
<div className="reward-experience-parent" >
<div className="reward-experience--gained-experience">
Experience Gained: {newExp - oldExp}
</div>
<div className="reward-experience--align-levels-and-bar">
<div className="reward-experience--current-level">{experienceAndLevelObject.level}</div>
<div className="reward-experience--progress-bar-parent">
<div className="reward-experience--progress-bar-child--bar width-zero"
style={this.fillBar(this.getLevelPercentage(experienceAndLevelObject, experienceObject))}/>
</div>
<div className="reward-experience--next-level">{experienceAndLevelObject.level + 1}</div>
</div>
</div>
{this.getItemDropDiv(randomItem)}
{/*<a href="/inventory">*/}
{/*Inventory*/}
{/*</a>*/}
{/*<a href="/map">*/}
{/*Map*/}
{/*</a>*/}
</div>
)
}
}
|
Go
|
UTF-8
| 24,070 | 2.671875 | 3 |
[] |
no_license
|
package compiler
import (
"fmt"
"github.com/mlmhl/compiler/gstac/compiler/ast"
"github.com/mlmhl/compiler/gstac/errors"
"github.com/mlmhl/compiler/gstac/token"
)
func (compiler *Compiler) compileUnit() {
parser := compiler.parser
logger := compiler.logger
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.FINISHED_ID {
break
}
parser.RollBack(tok)
compiler.definitionOrStatement()
}
}
func (compiler *Compiler) definitionOrStatement() {
cursor := compiler.parser.GetCursor()
function, err := compiler.functionDefinition()
if err == nil {
// This is a function definition.
err = compiler.globalContext.AddFunction(function.GetName(), function)
if err != nil {
compiler.logger.CompileError(err)
}
} else {
// rollback if failed to pass a `type` token
compiler.parser.Seek(cursor)
// This is a statement
compiler.statements = append(compiler.statements, compiler.statement())
}
compiler.parser.Commit()
}
func (compiler *Compiler) functionDefinition() (*ast.Function, errors.Error) {
parser := compiler.parser
logger := compiler.logger
var err errors.Error
var tok *token.Token
var typ ast.Type
var identifier *ast.Identifier
var paramList []*ast.Parameter
// parser return type
typ, err = compiler.typeSpecifier()
if err != nil {
return nil, err
}
// parser identifier
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.IDENTIFIER_ID {
return nil, errors.NewSyntaxError(
fmt.Sprintf("%s is invalid function identifier",
token.GetDescription(tok.GetType())),
tok.GetLocation())
}
identifier = ast.NewIdentifier(tok.GetValue(), tok.GetLocation())
// parser parameters
paramList, err = compiler.parameterList()
if err != nil {
return nil, err
}
// parser block
statements := compiler.statementListForBlock()
return ast.NewFunction(typ, identifier, paramList,
ast.NewFunctionBlock(statements)), nil
}
func (compiler *Compiler) basicTypeSpecifier() (ast.Type, errors.Error) {
parser := compiler.parser
logger := compiler.logger
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
switch tok.GetType() {
case token.BOOL_TYPE_ID:
return ast.BOOL_TYPE, nil
case token.INTEGER_TYPE_ID:
return ast.INTEGER_TYPE, nil
case token.FLOAT_TYPE_ID:
return ast.FLOAT_TYPE, nil
case token.STRING_TYPE_ID:
return ast.STRING_TYPE, nil
case token.NULL_ID:
return ast.NULL_TYPE, nil
default:
return nil, errors.NewUnsupportedTypeError(
token.GetDescription(tok.GetType()), tok.GetLocation())
}
}
// Up to now, array type specifier is the only composite type.
func (compiler *Compiler) typeSpecifier() (ast.Type, errors.Error) {
parser := compiler.parser
logger := compiler.logger
var base ast.Type
var err errors.Error
base, err = compiler.basicTypeSpecifier()
if err != nil {
return nil, err
}
var lTok *token.Token
var rTok *token.Token
deriveTags := []ast.DeriveTag{}
for {
lTok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if lTok.GetType() != token.LMP_ID {
parser.RollBack(1)
break
}
rTok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if rTok.GetType() != token.RMP_ID {
err = errors.NewParenthesesNotMatchedError(token.GetDescription(token.LMP_ID),
token.GetDescription(token.RMP_ID), lTok.GetLocation(), rTok.GetLocation())
break
}
deriveTags = append(deriveTags, ast.NewArrayDerive())
}
return ast.NewDeriveType(base, deriveTags), nil
}
func (compiler *Compiler) parameterList() ([]*ast.Parameter, errors.Error) {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.LSP_ID {
return nil, errors.NewSyntaxError(
"Function parameter list should start with "+
token.GetDescription(tok.GetType()),
tok.GetLocation())
}
parameterList := []*ast.Parameter{}
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.RSP_ID {
// empty parameter list
return parameterList, nil
} else {
parser.RollBack(1)
}
for {
location := tok.GetLocation()
typ, err := compiler.typeSpecifier()
if err != nil {
return nil, err
}
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.IDENTIFIER_ID {
return nil, errors.NewSyntaxError(
fmt.Sprintf("Can't use %s as a identifier",
token.GetDescription(tok.GetType())),
tok.GetLocation(),
)
}
parameterList = append(parameterList, ast.NewParameter(typ,
ast.NewIdentifier(tok.GetValue(), tok.GetLocation()), location))
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.RSP_ID {
break
} else if tok.GetType() != token.COMMA_ID {
return nil, errors.NewSyntaxError(
fmt.Sprintf("Can't use %s in function parameter list",
token.GetDescription(tok.GetType())),
tok.GetLocation())
}
}
return parameterList, nil
}
func (compiler *Compiler) statementListForBlock() []ast.Statement {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
var statements []ast.Statement
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.LLP_ID {
logger.CompileError(errors.NewSyntaxError(
"Block should start with "+token.GetDescription(tok.GetType()),
tok.GetLocation()))
}
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.RLP_ID {
return nil
} else {
parser.RollBack(1)
}
statements = compiler.statementList()
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.RLP_ID {
logger.CompileError(errors.NewSyntaxError(
"Block should stop with a "+token.GetDescription(tok.GetType()),
tok.GetLocation()))
}
return statements
}
func (compiler *Compiler) statementList() []ast.Statement {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
statements := []ast.Statement{}
for {
statements = append(statements, compiler.statement())
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
parser.RollBack(1)
// statement list is around by large parentheses,
// so a right large parentheses means statement list ended,
if tok.GetType() == token.RLP_ID {
break
}
}
return statements
}
func (compiler *Compiler) statement() ast.Statement {
parser := compiler.parser
logger := compiler.logger
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
parser.RollBack(1)
var statement ast.Statement
switch tok.GetType() {
case token.IF_ID:
statement = compiler.ifStatement()
case token.FOR_ID:
statement = compiler.forStatement()
case token.WHILE_ID:
statement = compiler.whileStatement()
case token.CONTINUE_ID:
statement = compiler.continueStatement()
case token.BREAK_ID:
statement = compiler.breakStatement()
case token.RETURN_ID:
statement = compiler.returnStatement()
case token.BOOL_TYPE_ID:
fallthrough
case token.INTEGER_TYPE_ID:
fallthrough
case token.FLOAT_TYPE_ID:
fallthrough
case token.STRING_TYPE_ID:
statement = compiler.declarationStatement()
default:
statement = compiler.expressionStatement()
}
// statement maybe ended with a `;`
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.SEMICOLON_ID {
parser.RollBack(tok)
}
return statement
}
func (compiler *Compiler) ifStatement() ast.Statement {
parser := compiler.parser
var tok *token.Token
// The first token's type must be IF_ID
tok, _ = parser.Next()
ifStatement := ast.NewIfStatement(tok.GetLocation())
// parse condition expression
ifStatement.SetCondition(compiler.conditionExpression())
// parse if's block
ifStatement.SetIfBlock(ast.NewIfBlock(compiler.statementListForBlock()))
// parse elif statements, if exists
ifStatement.SetElifStatements(compiler.elifStatements())
// parse else statement, if exists
ifStatement.SetElseBlock(compiler.elseStatement())
return ifStatement
}
func (compiler *Compiler) elifStatements() []*ast.ElifStatement {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
elifStatements := []*ast.ElifStatement{}
for {
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.ELIF_ID {
parser.RollBack(1)
break
}
elifStatement := ast.NewElifStatement(tok.GetLocation())
elifStatement.SetCondition(compiler.conditionExpression())
elifStatement.SetBlock(ast.NewIfBlock(compiler.statementListForBlock()))
elifStatements = append(elifStatements, elifStatement)
}
return elifStatements
}
func (compiler *Compiler) elseStatement() *ast.ElseStatement {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.ELSE_ID {
parser.RollBack(1)
return nil
}
return ast.NewElseStatement(
ast.NewIfBlock(compiler.statementListForBlock()), tok.GetLocation())
}
func (compiler *Compiler) forStatement() ast.Statement {
parser := compiler.parser
// next token's type must be FOR_ID
tok, _ := parser.Next()
forStatement := ast.NewForStatement(tok.GetLocation())
compiler.createExpressionForForStatement(forStatement)
forStatement.SetBlock(ast.NewForBlock(compiler.statementListForBlock()))
return forStatement
}
func (compiler *Compiler) createExpressionForForStatement(forStatement *ast.ForStatement) {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.LSP_ID {
logger.CompileError(errors.NewSyntaxError(
"For statement's expression should start with "+
token.GetDescription(tok.GetType()), tok.GetLocation()))
}
expressions := []ast.Expression{}
for {
expressions = append(expressions, compiler.expression())
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.RSP_ID {
break
} else if tok.GetType() != token.SEMICOLON_ID {
logger.CompileError(errors.NewSyntaxError(
fmt.Sprintf("Can't use %s in for statement's expressions",
token.GetDescription(tok.GetType())), tok.GetLocation()))
}
}
if len(expressions) != 3 {
logger.CompileError(errors.NewSyntaxError(
fmt.Sprintf("Wrong for statement's expression size: wanted 3, got %d",
len(expressions)), tok.GetLocation()))
}
forStatement.SetInit(expressions[0])
forStatement.SetCondition(expressions[1])
forStatement.SetPost(expressions[1])
}
func (compiler *Compiler) whileStatement() ast.Statement {
parser := compiler.parser
// next token's type must be WHILE_ID
tok, _ := parser.Next()
return ast.NewWhileStatement(compiler.conditionExpression(),
ast.NewWhileBlock(compiler.statementListForBlock()), tok.GetLocation())
}
func (compiler *Compiler) continueStatement() ast.Statement {
// next token's type must be CONTINUE_ID
tok, _ := compiler.parser.Next()
return ast.NewContinueStatement(tok.GetLocation())
}
func (compiler *Compiler) breakStatement() ast.Statement {
// next token's type must be BREAK_ID
tok, _ := compiler.parser.Next()
return ast.NewBreakStatement(tok.GetLocation())
}
func (compiler *Compiler) returnStatement() ast.Statement {
// next token's type must be RETURN_ID
tok, _ := compiler.parser.Next()
return ast.NewReturnStatement(compiler.expression(), tok.GetLocation())
}
func (compiler *Compiler) declarationStatement() ast.Statement {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
var typ ast.Type
var identifier *ast.Identifier
typ, err = compiler.typeSpecifier()
if err != nil {
logger.CompileError(err)
}
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType != token.IDENTIFIER_ID {
logger.CompileError(errors.NewSyntaxError(
fmt.Sprintf("Can't use %s in declaration statement",
token.GetDescription(tok.GetType())), tok.GetLocation()))
}
identifier = ast.NewIdentifier(tok.GetValue(), tok.GetLocation())
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.ASSIGN_ID {
parser.RollBack(1)
return ast.NewDeclarationStatement(ast.NewDeclaration(
typ, identifier, nil, tok.GetLocation()))
} else {
return ast.NewDeclarationStatement(ast.NewDeclaration(
typ, identifier, compiler.expression(), tok.GetLocation()))
}
}
func (compiler *Compiler) expressionStatement() ast.Statement {
return ast.NewExpressionStatement(compiler.expression())
}
func (compiler *Compiler) conditionExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.LSP_ID {
logger.CompileError(errors.NewSyntaxError(
"Condition expression should start with "+
token.GetDescription(tok.GetType()),
tok.GetLocation()))
}
expression := compiler.expression()
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.RSP_ID {
logger.CompileError(errors.NewSyntaxError(
"Condition expression should end with "+
token.GetDescription(tok.GetType()),
tok.GetLocation()))
}
return expression
}
func (compiler *Compiler) expression() ast.Expression {
parser := compiler.parser
var result ast.Expression
var err errors.Error
cursor := parser.GetCursor()
result, err = compiler.assignExpression()
if err == nil {
return result
}
parser.Seek(cursor)
return compiler.logicalOrExpression()
}
// assign expression
func (compiler *Compiler) assignExpression() (ast.Expression, errors.Error) {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
var left ast.Expression
left = compiler.primaryExpression()
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if !token.IsAssignOperator(tok.GetType()) {
return nil, errors.NewSyntaxError(fmt.Sprintf("Can't use %s in assign expression",
token.GetDescription(tok.GetType())), tok.GetLocation())
}
return ast.NewAssignExpression(tok.GetType(), left, compiler.expression())
}
func (compiler *Compiler) logicalOrExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
result := compiler.logicalAndExpression()
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.OR_ID {
parser.RollBack(1)
break
}
result = ast.NewLogicalOrExpression(result, compiler.logicalAndExpression())
}
return result
}
func (compiler *Compiler) logicalAndExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
result := compiler.equalityExpression()
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.AND_ID {
parser.RollBack(1)
break
}
result = ast.NewLogicalAndExpression(result, compiler.equalityExpression())
}
return result
}
func (compiler *Compiler) equalityExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
result := compiler.relationExpression()
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.EQUAL_ID {
result = ast.NewEqualExpression(result, compiler.relationExpression())
} else if tok.GetType() == token.UNEQUAL_ID {
result = ast.NewNotEqualExpression(result, compiler.relationExpression())
} else {
parser.RollBack(1)
break
}
}
return result
}
func (compiler *Compiler) relationExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
result := compiler.additiveExpression()
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
switch tok.GetType() {
case token.GT_ID:
result = ast.NewGreaterThanExpression(result, compiler.additiveExpression())
case token.GTE_ID:
result = ast.NewGreaterThanAndEqualExpression(result, compiler.additiveExpression())
case token.LT_ID:
result = ast.NewLessThanExpression(result, compiler.additiveExpression())
case token.LTE_ID:
result = ast.NewLessThanAndEqualExpression(result, compiler.additiveExpression())
default:
break
}
}
return result
}
func (compiler *Compiler) additiveExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
result := compiler.multiplicativeExpression()
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.ADD_ID {
result = ast.NewAddExpression(result, compiler.multiplicativeExpression())
} else if tok.GetType() == token.SUBTRACT_ID {
result = ast.NewSubtractExpression(result, compiler.multiplicativeExpression())
} else {
break
}
}
return result
}
func (compiler *Compiler) multiplicativeExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
result := compiler.unaryExpression()
for {
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
switch tok.GetType() {
case token.MULTIPLY_ID:
result = ast.NewMultiplyExpression(result, compiler.unaryExpression())
case token.DIVIDE_ID:
result = ast.NewDivideExpression(result, compiler.unaryExpression())
case token.MOD_ID:
result = ast.NewModExpression(result, compiler.unaryExpression())
default:
parser.RollBack(1)
break
}
}
return result
}
func (compiler *Compiler) unaryExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.SUBTRACT_ID {
return ast.NewMinusExpression(compiler.unaryExpression(), tok.GetLocation())
} else if tok.GetType() == token.NOT_ID {
return ast.NewLogicalNotExpression(compiler.unaryExpression(), tok.GetLocation())
} else {
return compiler.primaryExpression()
}
}
func (compiler *Compiler) primaryExpression() ast.Expression {
parser := compiler.parser
logger := compiler.logger
tok, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.NEW_ID {
return compiler.arrayCreationExpression(tok)
} else {
parser.RollBack(1)
result := compiler.primaryExpressionWithoutArrayCreation(tok)
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() == token.LMP_ID {
// array index expression
for {
result = ast.NewIndexExpression(result, compiler.dimensionExpression(tok))
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.LMP_ID {
// needn't roll back, go on process array index syntax
break
}
}
}
if tok.GetType() == token.INCREMENT_ID {
result = ast.NewIncrementExpression(result, tok.GetLocation())
} else if tok.GetType() == token.DECREMENT_ID {
result = ast.NewDecrementExpression(result, tok.GetLocation())
} else {
parser.RollBack(1)
}
return result
}
}
func (compiler *Compiler) primaryExpressionWithoutArrayCreation(first *token.Token) ast.Expression {
parser := compiler.parser
logger := compiler.logger
switch first.GetType() {
case token.LSP_ID:
return compiler.subExpression(first)
case token.NULL_ID:
return ast.NewNullExpression(first.GetLocation())
case token.TRUE_ID:
return ast.NewBoolExpression(true, first.GetLocation())
case token.FALSE_ID:
return ast.NewBoolExpression(false, first.GetLocation())
case token.INTEGER_VALUE_ID:
return ast.NewIntegerExpression(first.GetValue().(int64), first.GetLocation())
case token.FLOAT_VALUE_ID:
return ast.NewFloatExpression(first.GetValue().(float64), first.GetLocation())
case token.STRING_VALUE_ID:
return ast.NewStringExpression(first.GetValue().(string), first.GetLocation())
case token.LLP_ID:
return compiler.arrayLiteralExpression(first)
}
if first.GetType() != token.IDENTIFIER_ID {
logger.CompileError(errors.NewSyntaxError("Can't parse"+
token.GetDescription(first.GetType()), first.GetLocation()))
}
identifier := ast.NewIdentifier(first.GetValue(), first.GetLocation())
second, err := parser.Next()
if err != nil {
logger.CompileError(err)
}
if second.GetType() == token.LSP_ID {
// function call
return ast.NewFunctionCallExpression(identifier, compiler.argumentList(second))
} else {
parser.RollBack(1)
return ast.NewIdentifierExpression(identifier)
}
}
func (compiler *Compiler) subExpression(leftParentheses *token.Token) ast.Expression {
expression := compiler.expression()
tok, err := compiler.parser.Next()
if err != nil {
compiler.logger.CompileError(err)
}
if tok.GetType() != token.RSP_ID {
compiler.logger.CompileError(errors.NewParenthesesNotMatchedError(
token.GetDescription(leftParentheses.GetType()),
token.GetDescription(tok.GetType()),
leftParentheses.GetLocation(), tok.GetLocation()))
}
return expression
}
func (compiler *Compiler) arrayLiteralExpression(
leftParentheses *token.Token) *ast.ArrayLiteralExpression {
var tok *token.Token
var err errors.Error
values := []ast.Expression{}
for {
values = append(values, compiler.expression())
tok, err = compiler.parser.Next()
if err != nil {
compiler.logger.CompileError(err)
}
if tok.GetType() == token.RLP_ID {
break
} else if tok.GetType() != token.COMMA_ID {
compiler.logger.CompileError(errors.NewSyntaxError(fmt.Sprintf(
"Can't use %s in array literal expression", token.GetDescription(tok.GetType())),
tok.GetLocation()))
}
}
return ast.NewArrayLiteralExpression(values, leftParentheses.GetLocation())
}
func (compiler *Compiler) argumentList(leftParentheses *token.Token) []*ast.Argument {
var tok *token.Token
var err errors.Error
arguments := []*ast.Argument{}
for {
arguments = append(arguments, ast.NewArgument(compiler.expression()))
tok, err = compiler.parser.Next()
if err != nil {
compiler.logger.CompileError(err)
}
if tok.GetType() == token.LSP_ID {
break
} else if tok.GetType() != token.COMMA_ID {
compiler.logger.CompileError(errors.NewSyntaxError(fmt.Sprintf(
"Can't use %s in argument list", token.GetDescription(tok.GetType())), tok.GetType()))
}
}
return arguments
}
func (compiler *Compiler) arrayCreationExpression(newTok *token.Token) ast.Expression {
parser := compiler.parser
logger := compiler.logger
var tok *token.Token
var err errors.Error
var typ ast.Type
typ, err = compiler.basicTypeSpecifier()
if err != nil {
logger.CompileError(err)
}
dimensions := []ast.Expression{}
for {
tok, err = parser.Next()
if err != nil {
logger.CompileError(err)
}
if tok.GetType() != token.LMP_ID {
parser.RollBack(1)
}
dimensions = append(dimensions, compiler.dimensionExpression(tok))
}
if len(dimensions) == 0 {
logger.CompileError(errors.NewSyntaxError(
"Can't use `new` on basic type", newTok.GetLocation()))
}
return ast.NewArrayCreationExpression(typ, dimensions, newTok.GetLocation())
}
func (compiler *Compiler) dimensionExpression(leftParentheses *token.Token) ast.Expression {
expression := compiler.expression()
tok, err := compiler.parser.Next()
if err != nil {
compiler.logger.CompileError(err)
}
if tok.GetType() != token.RMP_ID {
compiler.logger.CompileError(errors.NewParenthesesNotMatchedError(
token.GetDescription(leftParentheses.GetType()),
token.GetDescription(tok.GetType()),
leftParentheses.GetLocation(), tok.GetLocation()))
}
return expression
}
|
TypeScript
|
UTF-8
| 3,888 | 2.609375 | 3 |
[] |
no_license
|
import { Item, Product } from '@app/models/item';
export interface MacchineSet {
/*
"Matnr": "SC_LINEA-FB70",
"Email": "",
"Maktx": "CATALOGO LINEA-FB70",
"Token": "",
"Langu": "IT",
"Family": "FB70",
"LoioId": ""
*/
Matnr: string,
Email: string,
Maktx: string,
Token: string,
Langu: string,
Family: string,
LoioId: string
}
export class Macchina implements MacchineSet {
Matnr: string;
Email: string;
Maktx: string;
Token: string;
Langu: string;
Family: string;
LoioId: string;
static fromMacchinaJson(macchina : any) : Item {
return this.fromJSON(macchina.Matnr,macchina.Email,macchina.Maktx, macchina.Token, macchina.Langu, macchina.Family, macchina.LoioId);
}
static fromJSON(Matnr : string, Email: string, Maktx: string, Token : string, Langu : string, Family: string, LoioId: string): Item {
const item = new Item();
item.code = Matnr;
item.description = Maktx;
item.family = Family;
item.picId=LoioId;
return item;
}
}
export class Section {
MatnrMacchina: string;
MatnrSezione: string;
Maktx: string;
Langu: string;
LoioId: string;
Email: string;
Token: string;
static fromJSON(MatnrMacchina : string, MatnrSezione: string, Maktx: string, Langu : string, LoioId: string, Email: string, Token: string): Item {
const item = new Item();
item.code = MatnrSezione;
item.description = Maktx;
item.family = MatnrMacchina;
item.picId=LoioId;
return item;
}
}
export class Materiale {
Matnr: string;
Kunnr: string;
MengeBom: string;
Maktx: string;
Maxlf: string;
Langu: string;
Minlf: string;
Matkl: string;
Pref: string;
Maktlx: string;
Prodh: string;
Prodhx: string;
Kdmat: string;
Netpr: string; // Price
Waers: string; // Currency
Labst: string;
Meins: string;
StockIndicator: string;
Email: string;
Token: string;
ItemNumBom: string;
MatnrSezione: string;
LoioId: string;
LoioId1: string;
LoioId2: string;
LoioId3: string;
LoioId4: string;
NoteCliente: string;
Documentazione: string;
NoteGenerali: string;
MatNrSub: string;
MaktxSub: string;
static fromJSON(m : Materiale): Product {
const price : number = Number(m.Netpr);
let isInStock = false;
if (price > 0) {
isInStock = true;
}
const maxQuantity = Number(m.Maxlf);
const minQuantity = Number(m.Minlf);
/* const itNumB : string = '' + Number(m.ItemNumBom); */
const product = new Product(m.Matnr,
m.Maktx,
price,
m.Waers,
isInStock,
m.Prodh,
m.Prodhx,
m.Pref,
m.Meins,
maxQuantity,
minQuantity
,m.LoioId
,m.LoioId1
,m.LoioId2
,m.LoioId3
,m.LoioId4
,m.ItemNumBom /* itNumB */
,m.StockIndicator,
m.NoteCliente,
m.Documentazione,
m.NoteGenerali,
m.MatNrSub,
m.MaktxSub
)
return product;
}
}
|
Python
|
UTF-8
| 1,690 | 3.40625 | 3 |
[] |
no_license
|
#imports
import pygame
from time import sleep
import sys
pygame.init()
#colours
WHITE = (255,255,255)
BLACK = (0,0,0)
GREEN = (0,255,127)
#functions
def char(x,y):
window.blit(cherry, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',50)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((windoww/2),(windowh/2))
window.blit(TextSurf, TextRect)
pygame.display.update()
#Set caption
pygame.display.set_caption("Sky Islands")
icon = pygame.image.load("sword.png")
pygame.display.set_icon(icon)
#Game loop
def game():
#vars
windoww = 800
windowh = 600
window = pygame.display.set_mode((windoww,windowh))
alive = True
clock = pygame.time.Clock()
#vars
x = (windoww * 0.8)
y = (windowh * 0.8)
xm = 0
cherry = pygame.image.load("pcherry.png")
while alive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
alive == False
pygame.quit()
sys.exit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xm = -5
elif event.key == pygame.K_RIGHT:
xm = 5
window.fill(GREEN)
char(x,y)
pygame.display.update()
clock.tick(60)
#intro
def intro():
window.fill(WHITE)
message_display("Sky Islands")
sleep(2)
game()
#run
intro()
|
Markdown
|
UTF-8
| 777 | 3.859375 | 4 |
[] |
no_license
|
### Channel Buffering
#### Description
By default channels are unbuffered, meaning that they will only accept sends (chan <-) if there is a corresponding receive (<- chan) ready to receive the sent value. Buffered channels accept a limited number of values without a corresponding receiver for those values.
#### Example
```go
package main
import "fmt"
func main() {
messages := make(chan string, 2)
messages <- "buffered"
messages <- "channel"
fmt.Println(<-messages)
fmt.Println(<-messages)
}
```
#### Explanation
Here we make a channel of strings buffering up to 2 values.
Because this channel is buffered, we can send these values into the channel without a corresponding concurrent receive.
Later we can receive these two values as usual.
|
Python
|
UTF-8
| 479 | 3.421875 | 3 |
[] |
no_license
|
import pandas as pd
import datetime
x = pd.date_range(start='6/15/2020', end='8/12/2020')
saturdays = [day.date() for day in x if day.weekday() == 5]
fridays = [day.date() for day in x if day.weekday() == 4]
"""
for i in saturdays:
print('Sat: {}'.format(i))
for i in fridays:
print('Fri: {}'.format(i))
"""
for i in fridays:
for j in saturdays:
print('Fri: {}'.format(i))
print('Sat: {}'.format(i))
print('\n')
|
Java
|
UTF-8
| 7,700 | 1.765625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.softonic.instamaterial.ui.locator;
import android.support.v4.app.FragmentActivity;
import com.softonic.instamaterial.data.locator.DataServiceLocator;
import com.softonic.instamaterial.domain.executor.UseCaseExecutor;
import com.softonic.instamaterial.domain.interactors.GetAuthenticatedUserUid;
import com.softonic.instamaterial.domain.interactors.GetPhoto;
import com.softonic.instamaterial.domain.interactors.GetPhotoComments;
import com.softonic.instamaterial.domain.interactors.GetPhotoLikes;
import com.softonic.instamaterial.domain.interactors.GetPhotos;
import com.softonic.instamaterial.domain.interactors.GetUser;
import com.softonic.instamaterial.domain.interactors.InteractorLocator;
import com.softonic.instamaterial.domain.interactors.LikePhoto;
import com.softonic.instamaterial.domain.interactors.PublishComment;
import com.softonic.instamaterial.domain.interactors.PublishPhoto;
import com.softonic.instamaterial.domain.interactors.UpdateUser;
import com.softonic.instamaterial.domain.interactors.UploadPhoto;
import com.softonic.instamaterial.domain.repository.RepositoryLocator;
import com.softonic.instamaterial.ui.activity.comments.CommentsPresenter;
import com.softonic.instamaterial.ui.activity.comments.CommentsPresenterLocator;
import com.softonic.instamaterial.ui.activity.main.MainPresenter;
import com.softonic.instamaterial.ui.activity.main.MainPresenterLocator;
import com.softonic.instamaterial.ui.activity.publish.PublishPresenter;
import com.softonic.instamaterial.ui.activity.publish.PublishPresenterLocator;
import com.softonic.instamaterial.ui.orchestrator.GetCommentItem;
import com.softonic.instamaterial.ui.orchestrator.GetCommentItems;
import com.softonic.instamaterial.ui.orchestrator.GetFeedItem;
import com.softonic.instamaterial.ui.orchestrator.GetFeedItems;
import com.softonic.instamaterial.ui.orchestrator.OrchestratorLocator;
public class ActivityServiceLocator
implements MainPresenterLocator, PublishPresenterLocator, CommentsPresenterLocator,
InteractorLocator, OrchestratorLocator {
private MainPresenter mainPresenter;
private PublishPresenter publishPresenter;
private CommentsPresenter commentsPresenter;
private GetPhoto getPhoto;
private GetPhotos getPhotos;
private GetUser getUser;
private UpdateUser updateUser;
private GetPhotoLikes getPhotoLikes;
private GetPhotoComments getPhotoComments;
private LikePhoto likePhoto;
private GetAuthenticatedUserUid getAuthenticatedUserUid;
private PublishPhoto publishPhoto;
private UploadPhoto uploadPhoto;
private PublishComment publishComment;
private GetFeedItem getFeedItem;
private GetFeedItems getFeedItems;
private GetCommentItems getCommentItems;
private GetCommentItem getCommentItem;
@Override public MainPresenter mainPresenter(FragmentActivity activity) {
if (mainPresenter == null) {
mainPresenter =
new MainPresenter(getLoggedUser(), getFeedItem(), getFeedItems(), likePhoto());
}
return mainPresenter;
}
@Override public PublishPresenter publishPresenter() {
if (publishPresenter == null) {
publishPresenter = new PublishPresenter(getLoggedUser(), publishPhoto());
}
return publishPresenter;
}
@Override public CommentsPresenter commentsPresenter() {
if (commentsPresenter == null) {
commentsPresenter =
new CommentsPresenter(getCommentItems(), getLoggedUser(), publishComment(),
getCommentItem());
}
return commentsPresenter;
}
@Override public GetPhoto getPhoto() {
if (getPhoto == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
getPhoto = new GetPhoto(useCaseExecutor(), repositoryLocator.photoRepository());
}
return getPhoto;
}
@Override public GetPhotos getPhotos() {
if (getPhotos == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
getPhotos = new GetPhotos(useCaseExecutor(), repositoryLocator.photoRepository());
}
return getPhotos;
}
@Override public GetUser getUser() {
if (getUser == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
getUser = new GetUser(useCaseExecutor(), repositoryLocator.userRepository());
}
return getUser;
}
@Override public UpdateUser updateUser() {
if (updateUser == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
updateUser = new UpdateUser(useCaseExecutor(), repositoryLocator.userRepository());
}
return updateUser;
}
@Override public GetPhotoLikes getPhotoLikes() {
if (getPhotoLikes == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
getPhotoLikes = new GetPhotoLikes(useCaseExecutor(), repositoryLocator.likeRepository());
}
return getPhotoLikes;
}
@Override public GetPhotoComments getPhotoComments() {
if (getPhotoComments == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
getPhotoComments =
new GetPhotoComments(useCaseExecutor(), repositoryLocator.commentRepository());
}
return getPhotoComments;
}
@Override public LikePhoto likePhoto() {
if (likePhoto == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
likePhoto = new LikePhoto(useCaseExecutor(), repositoryLocator.likeRepository());
}
return likePhoto;
}
@Override public GetAuthenticatedUserUid getLoggedUser() {
if (getAuthenticatedUserUid == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
getAuthenticatedUserUid =
new GetAuthenticatedUserUid(useCaseExecutor(), repositoryLocator.loggedUserRepository());
}
return getAuthenticatedUserUid;
}
@Override public PublishPhoto publishPhoto() {
if (publishPhoto == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
publishPhoto =
new PublishPhoto(useCaseExecutor(), uploadPhoto(), repositoryLocator.photoRepository());
}
return publishPhoto;
}
@Override public UploadPhoto uploadPhoto() {
if (uploadPhoto == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
uploadPhoto = new UploadPhoto(useCaseExecutor(), repositoryLocator.photoRepository());
}
return uploadPhoto;
}
@Override public PublishComment publishComment() {
if (publishComment == null) {
RepositoryLocator repositoryLocator = DataServiceLocator.getInstance();
publishComment = new PublishComment(useCaseExecutor(), repositoryLocator.commentRepository());
}
return publishComment;
}
@Override public GetFeedItem getFeedItem() {
if (getFeedItem == null) {
getFeedItem = new GetFeedItem(useCaseExecutor(), getPhoto(), getUser(), getPhotoLikes());
}
return getFeedItem;
}
@Override public GetFeedItems getFeedItems() {
if (getFeedItems == null) {
getFeedItems = new GetFeedItems(useCaseExecutor(), getPhotos(), getFeedItem());
}
return getFeedItems;
}
@Override public GetCommentItems getCommentItems() {
if (getCommentItems == null) {
getCommentItems = new GetCommentItems(useCaseExecutor(),
getPhotoComments(), getCommentItem());
}
return getCommentItems;
}
@Override public GetCommentItem getCommentItem() {
if (getCommentItem == null) {
getCommentItem = new GetCommentItem(useCaseExecutor(), getUser());
}
return getCommentItem;
}
private UseCaseExecutor useCaseExecutor() {
return AppServiceLocator.getInstance().useCaseExecutor();
}
}
|
PHP
|
UTF-8
| 320 | 2.71875 | 3 |
[] |
no_license
|
<?php
namespace model;
/*
* Interface: model/iMazeHazard
*
* Interface for maze hazards. All mazehazards must use iMazeHazard interface.
*/
interface iMazeHazard {
public function __construct();
public function GetName();
public function GetMazeTileCodeChar();
public function GetStepRedcution();
}
|
C
|
UTF-8
| 446 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
// main program for running the processing of the mapped files
#include <stdio.h>
int main(int argc, char *argv[]){
if (argc != 4){
fprintf(stderr, "%s: <indir> <outdir> <-r or -t>\n-t\t\ttraditional 6-column file format\n-r\t\trao format\n\nGenerate chromosome by chromosome files in the specified directory\n\n", argv[0]);
return -1;
}
// input directory, output directory, type of input files
frag_proc(argv[1], argv[2], argv[3]);
}
|
C++
|
UTF-8
| 626 | 2.8125 | 3 |
[] |
no_license
|
//
// Created by kamila on 16.03.18.
//
#include "SmartTree.h"
using namespace datastructures;
int main(){
std::unique_ptr <SmartTree> x;
std::unique_ptr <SmartTree> root= CreateLeaf(8);
std::unique_ptr <SmartTree> child= CreateLeaf(9);
x= InsertLeftChild(std::move(root),std::move(child));
std::string tree="[99 [100 [1234 [none] [none]] [4321 [none] [none]]] ";
std::string val;
for (int i=0;i<tree.size();i++){
i++;
while (tree[i] != '[' && tree[i] != ' ') {
val += tree[i];
std::cout<<val<<std::endl;
i++;
}
}
return 0;
}
|
Java
|
UTF-8
| 5,372 | 2.3125 | 2 |
[] |
no_license
|
package week1;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
//1) Go to https://www.pepperfry.com/
//2) Mouseover on Furniture and click Office Chairs under Chairs
//3) click Executive Chairs
//4) Change the minimum Height as 50 in under Dimensions
//5) Add "Poise Executive Chair in Black Colour" chair to Wishlist
//6) Mouseover on Furniture and Click Office tables
//7) Select Executive Desks
//8) Select Price between 20000 to 40000 rs
//9) Add "Executive Office Table in Brown Color" to Wishlist
//10) Verify the number of items in Wishlist
//11) Navigate to Wishlist
//12) Get the offer Price and Coupon Code for Executive Office Table in Brown Color
//13) Move Executive Office Table in Brown Color only to Cart from Wishlist
//14) Check for the availability for Pincode 600128
//15) Click on PROCEED TO PAY SECURELY from My Cart
//16) Enter the Coupon code and click Apply
//17) Click Proceed to Pay
//18) Capture the screenshot of the item under ORDER SUMMARY
//19) Close the browser
public class PepperFry {
public static void main(String[] args) throws InterruptedException, IOException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.pepperfry.com/");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
Thread.sleep(10000);
driver.switchTo().frame(driver.findElementByXPath("//iframe[@id='webklipper-publisher-widget-container-notification-frame']"));
driver.findElementByXPath("//div[@class='close']").click();
Thread.sleep(5000);
Actions builder = new Actions(driver);
WebElement closeButton = driver.findElementByXPath("//div[@id='regPopUp']/a");
builder.click(closeButton).perform();
WebElement furniture = driver.findElementByLinkText("Furniture");
Thread.sleep(3000);
builder.moveToElement(furniture).perform();
Thread.sleep(5000);
//driver.findElementByXPath("(//a[text()='Office Chairs'])[2]").click();
driver.findElementByCssSelector("div#meta-furniture>div>div:nth-of-type(3)>div:nth-of-type(2)>div:nth-of-type(12)>a").click();
Thread.sleep(2000);
driver.findElementByXPath("(//div[@class='cat-wrap-img'])[2]").click();
Thread.sleep(2000);
WebElement dimension = driver.findElementByXPath("//div[@class='clip__filter-dimension-input-holder']/input");
dimension.clear();
dimension.sendKeys("50");
Thread.sleep(5000);
driver.switchTo().frame(driver.findElementByXPath("//iframe[@id='webklipper-publisher-widget-container-notification-frame']"));
driver.findElementByXPath("//div[@class='close']").click();
Thread.sleep(5000);
driver.findElementByXPath("//a[@data-productname='Poise Executive Chair in Black Colour']").click();
Thread.sleep(3000);
WebElement furniture2 = driver.findElementByLinkText("Furniture");
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].scrollIntoView();",furniture2);
builder.moveToElement(furniture2).perform();
Thread.sleep(3000);
driver.findElementByXPath("//a[text()='Office Tables']").click();
Thread.sleep(2000);
driver.findElementByXPath("(//li[@class='clip-main-cat carousel-cell ']/a)[2]").click();
Thread.sleep(3000);
driver.findElementByXPath("//label[@for='price20000-40000']").click();
Thread.sleep(2000);
driver.findElementByXPath("//a[@data-productname='Executive Office Table in Brown Color']").click();
Thread.sleep(2000);
System.out.println("No.of items in wishlist - "+ driver.findElementByXPath("(//*[@class='wishlist_bar']/a/following::span)[1]").getText());
driver.findElementByXPath("//*[@class='wishlist_bar']/a").click();
Thread.sleep(3000);
String offerPrice = driver.findElementByXPath("//*[@class='oprice']/span[@class='txt-green']").getText();
System.out.println("Offer Price is "+offerPrice);
String couponCode = driver.findElementByXPath("//*[@class='oprice']/following::p/strong").getText();
driver.findElementByXPath("//*[@class='action_block']/a").click();
driver.findElementByXPath("//*[text()='Showing availability at']/following::input").sendKeys("600128",Keys.ENTER);
driver.findElementByXPath("//*[@class='minicart_footer']/a").click();
Thread.sleep(3000);
driver.findElementByXPath("//*[@placeholder='Enter Coupon Code']").sendKeys(couponCode,Keys.ENTER);
Thread.sleep(3000);
driver.findElementByXPath("//*[@class='ck-proceed-btn-wrap']/a").click();
Thread.sleep(3000);
driver.findElementById("ordersummary_accrodian").click();
WebElement orderDetails = driver.findElementByXPath("(//*[@class='nCheckout__accrodian open'])[2]");
File source = orderDetails.getScreenshotAs(OutputType.FILE);
File target = new File("./snaps/pepperfry.png");
FileUtils.copyFile(source, target);
driver.close();
}
}
|
C
|
UTF-8
| 554 | 3.828125 | 4 |
[] |
no_license
|
#include<stdio.h>
void sort(int*, int);
void main(){
int x[20],n, i;
puts("Enter number of elements: ");
scanf("%d",&n);
puts("Enter element");
for(i=0;i<n;i++)
scanf("%d",&x[i]);
sort(x,n); //function call
puts("Sorted array is:");
for(i=0;i<n;i++){
printf("%d",x[i]);
}
}
void sort(int *x, int n){
int i,j,t;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(x[i]>x[j]){
t=x[i];
x[i]=x[j];
x[j]=t;
}
}
|
Shell
|
UTF-8
| 1,362 | 3.265625 | 3 |
[] |
no_license
|
#!/bin/sh
#
# Istruzione di Stop del demone cupsd (non serve ai clients)
# valida per sistemi linux
#
architettura=`uname -a | awk -F" " '{print $1}'`
if [ "$architettura" = "Linux" ]; then
/sbin/service cups stop
/sbin/chkconfig cups off
fi
#
# Definisco il print server a seconda della sede
#
host=`hostname`
subnet=`host $host | perl -ni -e 'm/(\d+)\.(\d+)\.(\d+)/; print $3'`
if [ "$subnet" = "10" ] || [ "$subnet" = "12" ] || [ "$subnet" = "1" ]; then
area=i
defaultprinter=phaseribn
elif [ "$subnet" = "11" ] || [ "$subnet" = "102" ] || [ "$subnet" = "2" ]; then
area=m
defaultprinter=phaserm
else
#
# Modifica 7/8/08 D.B.
#
area=m
defaultprinter=phaserm
#
# echo "Errore nella configurazione di rete: $host\n"
# echo "Sistema il file /etc/hosts: distingui la riga di 127.0.0.1 da quella del nome-numero di rete\n"
fi
echo "ServerName prserver$area.bo.infn.it" > /etc/cups/client.conf
#
# Definisco le opzioni per le code
#
echo "Default $defaultprinter" > /etc/cups/lpoptions
cat <<EOF>>/etc/cups/lpoptions
Dest phaseribn-two number-up=2
Dest phaseribn-simplex sides=one-sided
Dest phaserm-two number-up=2
Dest phaserm-simplex sides=one-sided
Dest phaseric-two number-up=2
Dest phasermc-two number-up=2
Dest lps2-two number-up=2
Dest lpstg-two number-up=2
Dest i1color1-simplex sides=one-sided
Dest m1color1-simplex sides=one-sided
EOF
|
C#
|
UTF-8
| 1,303 | 2.796875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LoanLending.Observers;
using LoanLending.DataSets;
namespace LoanLending.Domain
{
class Client : ILoanObserver
{
private string clientId;
private string name;
private decimal debtAmount;
private List<IClientObserver> observers = new List<IClientObserver>();
public string clientIdProperty { get { return clientId; } }
public Client(string clientId, string name)
{
this.clientId = clientId;
this.name = name;
this.debtAmount = 0;
}
public void NotifyObservers()
{
ClientValues values = new ClientValues();
values.clientId = clientId;
values.name = name;
values.debtAmount = debtAmount;
foreach(IClientObserver observer in observers)
{
observer.Notify(values);
}
}
public void AddObserver(IClientObserver observer)
{
observers.Add(observer);
}
public void Notify(LoanValues loanValues)
{
debtAmount -= loanValues.amountChange;
NotifyObservers();
}
}
}
|
C#
|
UTF-8
| 1,287 | 3.078125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StudentManagemetSystem.Data;
using StudentManagemetSystem.Models;
using StudentManagemetSystem.Helpers;
namespace StudentManagemetSystem.Workflows
{
public class ListStudentWorkflow
{
/*Process for listing students
1. Get a list of students from the repository
2. Print out the students
*/
public void Execute()
{
StudentRepository repo = new StudentRepository(Settings.FilePath);
List<Student> students = repo.List();
Console.Clear();
Console.WriteLine("Student List");
ConsoleIO.PrintStudentListHeader(); //call the method from the ConsoleIO to display header
foreach (var student in students)
{
Console.WriteLine(ConsoleIO.StudentLineFormat, student.LastName + ", " + student.FirstName,
student.Major, student.GPA);
}
Console.WriteLine();
Console.WriteLine(ConsoleIO.SeparatorBar);
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
|
C++
|
UTF-8
| 9,226 | 2.546875 | 3 |
[] |
no_license
|
#include "StdAfxRegArchLib.h"
/*!
\file RegArchCompute.cpp
\brief implementation of the Simulation / Estimation procedures for general RegArchModel
\author Jean-Baptiste DURAND, Ollivier TARAMASCO
\date dec-18-2006 - last change feb-18-2011
*/
namespace RegArchLib {
/*!
* \fn void RegArchSimul(uint theNSample, const cRegArchModel& theModel, cRegArchValue& theData)
* \param uint theNSample: size of the sample
* \param const cRegArchModel& theModel: the RegArch model
* \param cRegArchValue& theData: output parameter. The Y(t) values are stored in theData.mYt
*/
void RegArchSimul(uint theNSample, const cRegArchModel& theModel, cRegArchValue& theData)
{
theData.ReAlloc(theNSample) ;
theModel.mResids->Generate(theNSample, theData.mEpst) ;
for (register uint t = 0 ; t < theNSample ; t++)
{ theData.mHt[t] = theModel.mVar->ComputeVar(t, theData) ;
if (theModel.mMean != NULL)
theData.mMt[t] = theModel.mMean->ComputeMean(t, theData) ;
theData.mUt[t] = sqrt(theData.mHt[t])*theData.mEpst[t] ;
theData.mYt[t] = theData.mMt[t] + theData.mUt[t] ;
}
}
/*!
* \fn double RegArchLLH(const cRegArchModel& theParam, cDVector* theYt, cDMatrix* theXt)
* \brief return the log-likelihood value
* \param const cRegArchModel& theParam: the model
* \param cDVector* theYt: the observations
* \param cDMatrix* theXt: the regressors matrix. Default NULL
*/
double RegArchLLH(const cRegArchModel& theParam, cDVector* theYt, cDMatrix* theXt)
{
cRegArchValue myValue(theYt, theXt) ;
return RegArchLLH(theParam, myValue) ;
}
/*!
* \fn double RegArchLLH(const cRegArchModel& theParam,cRegArchValue& theData)
* \brief return the log-likelihood value
* \param const cRegArchModel& theParam: the model
* \param cRegArchValue& theData: theData.mYt contains the observations.
*
* Inclure ici la justification de l'algorithme par un calcul en utilisant
* la syntaxe LaTeX.
*
* Exemple bidon :
* \f[
* |I_2|=\left| \int_{0}^T \psi(t)
* \left\{
* u(a,t)-
* \int_{\gamma(t)}^a
* \frac{d\theta}{k(\theta,t)}
* \int_{a}^\theta c(\xi)u_t(\xi,t)\,d\xi
* \right\} dt
* \right|
* \f]
*/
double RegArchLLH(const cRegArchModel& theParam, cRegArchValue& theData)
{
int mySize = (int)theData.mYt.GetSize() ;
double myRes = 0 ;
theData.mEpst = theData.mHt = theData.mMt = theData.mUt = 0.0 ;
for(register int t=0 ; t < mySize ; t++)
{ theData.mHt[t] = theParam.mVar->ComputeVar(t, theData) ;
if (theParam.mMean != NULL)
theData.mMt[t] = theParam.mMean->ComputeMean(t, theData) ;
theData.mUt[t] = theData.mYt[t] - theData.mMt[t] ;
theData.mEpst[t] = theData.mUt[t]/sqrt(theData.mHt[t]) ;
myRes += -0.5*log(theData.mHt[t]) + theParam.mResids->LogDensity(theData.mEpst[t]) ;
}
return myRes ;
}
/*!
* \fn void RegArchGradLt(int theDate, cRegArchModel& theParam, cRegArchValue& theValue, cRegArchGradient& theGradData, cDVector& theGradlt)
* \brief Compute the gradient of the log-likelihood, at current time theDate
* \param int theDate: time at which conditional log-density is considered
* \param const cRegArchModel& theParam: the model
* \param cRegArchValue& theValue: contains the observations. Used to stored computed residuals, standardized residuals, etc.
* \param cRegArchGradient& theGradData: contains the gradient of different components of the model, at current time theDate
* \param cDVector& theGradlt: gradient of the log-likelihood, at current time theDate
*
* Inclure ici la justification de l'algorithme par un calcul en utilisant
* la syntaxe LaTeX. Exemple : voir double RegArchLLH(const cRegArchModel& theParam,cRegArchValue& theData)
*/
void RegArchGradLt(int theDate, cRegArchModel& theParam, cRegArchValue& theValue, cRegArchGradient& theGradData, cDVector& theGradlt)
{ theGradlt = 0.0 ;
theValue.mHt[theDate] = theParam.mVar->ComputeVar(theDate, theValue) ;
if (theParam.mMean != NULL)
theValue.mMt[theDate] = theParam.mMean->ComputeMean(theDate, theValue) ;
theValue.mUt[theDate] = theValue.mYt[theDate] - theValue.mMt[theDate] ;
double mySigmat = sqrt(theValue.mHt[theDate]) ;
theValue.mEpst[theDate] = theValue.mUt[theDate]/mySigmat ;
theParam.mVar->ComputeGrad(theDate, theValue, theGradData, theParam.mResids) ;
if (theParam.mMean != NULL)
theParam.mMean->ComputeGrad(theDate, theValue, theGradData, theParam.mResids) ;
theParam.mResids->ComputeGrad(theDate, theValue, theGradData) ;
theGradData.mCurrentGradSigma = theGradData.mCurrentGradVar / (2.0 * mySigmat) ;
theGradData.mCurrentGradEps = -1.0*(theValue.mEpst[theDate] * theGradData.mCurrentGradSigma + theGradData.mCurrentGradMu)/ mySigmat ;
theGradlt = (-1.0/mySigmat) * theGradData.mCurrentGradSigma + theGradData.mCurrentGradDens[0] * theGradData.mCurrentGradEps ;
uint myNLawParam = theGradData.GetNDistrParameter() ;
uint myIndex = theGradData.GetNMeanParam() + theGradData.GetNVarParam() ;
for (register uint i = 1 ; i <= myNLawParam ; i++)
theGradlt[i+myIndex-1] += theGradData.mCurrentGradDens[i] ;
// Update
theGradData.Update() ;
}
void RegArchLtAndGradLt(int theDate, cRegArchModel& theParam, cRegArchValue& theValue, cRegArchGradient& theGradData, double& theLt, cDVector& theGradlt)
{
theGradlt = 0.0 ;
theValue.mHt[theDate] = theParam.mVar->ComputeVar(theDate, theValue) ;
if (theParam.mMean != NULL)
theValue.mMt[theDate] = theParam.mMean->ComputeMean(theDate, theValue) ;
theValue.mUt[theDate] = theValue.mYt[theDate] - theValue.mMt[theDate] ;
double mySigmat = sqrt(theValue.mHt[theDate]) ;
theValue.mEpst[theDate] = theValue.mUt[theDate]/mySigmat ;
theParam.mVar->ComputeGrad(theDate, theValue, theGradData, theParam.mResids) ;
if (theParam.mMean != NULL)
theParam.mMean->ComputeGrad(theDate, theValue, theGradData, theParam.mResids) ;
theParam.mResids->ComputeGrad(theDate, theValue, theGradData) ;
theGradData.mCurrentGradSigma = theGradData.mCurrentGradVar / (2.0 * mySigmat) ;
theGradData.mCurrentGradEps = -1.0*(theValue.mEpst[theDate] * theGradData.mCurrentGradSigma + theGradData.mCurrentGradMu)/ mySigmat ;
theGradlt = (-1.0/mySigmat) * theGradData.mCurrentGradSigma + theGradData.mCurrentGradDens[0] * theGradData.mCurrentGradEps ;
uint myNLawParam = theGradData.GetNDistrParameter() ;
uint myIndex = theGradData.GetNMeanParam() + theGradData.GetNVarParam() ;
for (register uint i = 1 ; i <= myNLawParam ; i++)
theGradlt[i+myIndex-1] += theGradData.mCurrentGradDens[i] ;
// Update
theGradData.Update() ;
theLt = -0.5*log(theValue.mHt[theDate]) + theParam.mResids->LogDensity(theValue.mEpst[theDate]) ;
}
/*!
* \brief Compute the gradient of the log-likelihood
* \fn void RegArchGradLLH(cRegArchModel& theParam, cRegArchValue& theData, cDVector& theGradLLH)
* \param const cRegArchModel& theParam: the model
* \param cRegArchValue& theData: contains the observations. Used to stored computed residuals, standardized residuals, etc.
* \param cDVector& theGradLLH: gradient of the log-likelihood
*
* Inclure ici la justification de l'algorithme par un calcul en utilisant
* la syntaxe LaTeX. Exemple : voir double RegArchLLH(const cRegArchModel& theParam,cRegArchValue& theData)
*/
void RegArchGradLLH(cRegArchModel& theParam, cRegArchValue& theData, cDVector& theGradLLH)
{
cRegArchGradient myGradData=cRegArchGradient(&theParam) ;
cDVector myGradlt(myGradData.GetNParam()) ;
theGradLLH = 0.0L ;
for (register int t = 0 ; t < (int)theData.mYt.GetSize() ; t++)
{ RegArchGradLt(t, theParam, theData, myGradData, myGradlt) ;
theGradLLH += myGradlt ;
}
}
void RegArchLLHAndGradLLH(cRegArchModel& theParam, cRegArchValue& theValue, double& theLLH, cDVector& theGradLLH)
{
cRegArchGradient myGradData(&theParam) ;
cDVector myGradlt(myGradData.GetNParam()) ;
double myLt ;
theGradLLH = 0.0L ;
theLLH = 0.0 ;
for (register int t = 0 ; t < (int)theValue.mYt.GetSize() ; t++)
{ RegArchLtAndGradLt(t, theParam, theValue, myGradData, myLt, myGradlt) ;
theGradLLH += myGradlt ;
theLLH += myLt ;
}
}
void NumericRegArchGradLLH(cRegArchModel& theModel, cRegArchValue& theValue, cDVector& theGradLLH, double theh)
{
double myLLH0 = RegArchLLH(theModel, theValue) ;
int myNParam = (int)theGradLLH.GetSize() ;
//int myNLawParam = (int)theModel.mResids->GetNParam() ;
//eCondVarEnum myVarType = theModel.mVar->GetCondVarType() ;
cDVector myVectParam(myNParam), myVect0(myNParam) ;
theModel.RegArchParamToVector(myVectParam) ;
myVect0 = myVectParam ;
for (register int i = 0 ; i < myNParam ; i++)
{
double myhh = fabs(theh * myVectParam[i]) ;
if (myhh < 1e-16)
myhh = theh ;
myVectParam[i] += myhh ;
theModel.VectorToRegArchParam(myVectParam) ;
double myLLH1 = RegArchLLH(theModel, theValue) ;
theGradLLH[i] = (myLLH1 - myLLH0)/myhh ;
myVectParam[i] -= myhh ;
}
theModel.VectorToRegArchParam(myVect0) ;
}
} //namespace
|
C#
|
UTF-8
| 1,705 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
public class TextFileCenter : IDayWorkLogStream
{
public IDayWorkLog GetTodayDayWork(string folderpath)
{
var filepath = GetFilePath(folderpath);
var enc = Encoding.GetEncoding("Shift_JIS");
if (File.Exists(filepath))
{
using (var reader = new StreamReader(filepath, enc))
{
return DayWorkLog.Parse((reader.ReadToEnd()));
}
}
return new DayWorkLog(new List<ILog>());
}
public void WritingLog(string folderpath, IReadOnlyDayWorkLog logs)
{
if (!Directory.Exists(folderpath))
{
Directory.CreateDirectory(folderpath);
}
var filepath = GetFilePath(folderpath);
var enc = Encoding.GetEncoding("Shift_JIS");
using (var writer = new StreamWriter(filepath, false, enc))
{
writer.Write(logs);
}
}
private string GetFilePath(string folderpath)
{
var Yesterdayfilepath = folderpath + @"\" + $"{DateTime.Today.AddDays(-1).ToString(Format.Day)}.txt";
if (IsUsing(Yesterdayfilepath))
{
return Yesterdayfilepath;
}
return folderpath + @"\" + $"{DateTime.Today.ToString(Format.Day)}.txt";
}
private bool IsUsing(string filepath)
{
var enc = Encoding.GetEncoding("Shift_JIS");
if (!File.Exists(filepath))
return false;
using (var reader = new StreamReader(filepath, enc))
{
var dayWorkLog = DayWorkLog.Parse(reader.ReadToEnd());
return dayWorkLog.IsUsing();
}
}
}
|
TypeScript
|
UTF-8
| 638 | 2.984375 | 3 |
[] |
no_license
|
import dayjs from 'dayjs';
import { Timestamp } from '../types';
export const parseTimestamp = (timestampMatch: string): Timestamp => {
const trimmedTimestamp = timestampMatch.trim();
if (!/\d\d:\d\d-\d\d:\d\d/.test(trimmedTimestamp)) {
return null;
}
return { start: trimmedTimestamp.split('-')[0].trim(), end: trimmedTimestamp.split('-')[1].trim() };
}
export const getDurationBasedOnTimestamp = (timestamp: Timestamp): number => {
const timestampStart = dayjs(`2000-01-01 00:${timestamp.start}`);
const timestampEnd = dayjs(`2000-01-01 00:${timestamp.end}`);
return timestampEnd.diff(timestampStart, 'seconds');
}
|
C#
|
UTF-8
| 720 | 3.109375 | 3 |
[] |
no_license
|
public static class LastEnumerator
{
public static IEnumerable<MetaEnumerableItem<T>> GetLastEnumerable<T>(this IEnumerable<T> blah)
{
bool isFirst = true;
using (var enumerator = blah.GetEnumerator())
{
if (enumerator.MoveNext())
{
bool isLast;
do
{
var current = enumerator.Current;
isLast = !enumerator.MoveNext();
yield return new MetaEnumerableItem<T>
{
Value = current,
IsLast = isLast,
IsFirst = isFirst
};
isFirst = false;
} while (!isLast);
}
}
}
}
public class MetaEnumerableItem<T>
{
public T Value { get; set; }
public bool IsLast { get; set; }
public bool IsFirst { get; set; }
}
|
Python
|
UTF-8
| 614 | 2.765625 | 3 |
[] |
no_license
|
import context
import mocks
from menu import Action
def test_init_shouldTakeName():
assert Action("myName").name() == "myName"
def test_run_doesNothing():
menu = mocks.Menu()
Action("").run(menu)
def test_lt_shouldBeTrue():
assert Action("abc") < Action("abd")
def test_lt_shouldBeFalse():
assert not Action("def") < Action("abc")
def test_lt_shouldBeFalse_forEqualName():
assert not Action("abc") < Action("abc")
def test_lt_shouldBeFalse_forLowerCase():
assert not Action("a") < Action("A")
def test_lt_shouldBeTrue_ignoring_case():
assert Action("a") < Action("B")
|
Markdown
|
UTF-8
| 2,328 | 3.5625 | 4 |
[] |
no_license
|
---
layout: post
title: programmers(78)level_3(야근지수)
categories: [algorithm]
excerpt: ' '
comments: false
share: false
tags: algorithm programmers level3
date: 2019-08-06
---
## 문제: 78. 야근지수
- 수식을 구해서 풀면 될 줄 알았는데 실패했다
```python
def solution(n, works):
total = sum(works)
cnt = len(works)
result = 0
if total <= n:
return 0
else:
total = total - n
if total % cnt == 0:
result = (((total//cnt)**2)*cnt)
return result
else:
mok = total // cnt
nam = total % cnt
result = [mok]*cnt
for i in range(nam):
result[i] = result[i]+nam
return sum(map(lambda x: x**2, result))
print(solution(1, [2, 1, 2]))
```
- 테스트 케이스만 통과한다.
* 그냥 정렬해서 쉽게 가자
```python
def solution(n, works):
answer = 0
if n > sum(works):
return answer
for i in range(n):
works.sort()
works[-1] -= 1
answer = sum(map(lambda x: x**2, works))
return answer
print(solution(1, [2, 1, 2]))
```
- 시간 초과가 뜬다. 정렬을 하지 말란 소리다.
- 매 루프마다 가장 큰 값을 새로 찾아야 한다.
- 우선순위 큐를 사용해보자.
```python
import heapq
def solution(n, works):
for i in range(len(works)):
works[i] *= -1 # maxheap을 만들기 위해 편의상 모두 -1을 곱해서 힙 정렬 해줬다.
heapq.heapify(works)
for i in range(n):
m = heapq.heappop(works)
if m >= 0:
heapq.heappush(works, m)
break
m += 1
heapq.heappush(works, m)
answer = sum(map(lambda x: x**2, works)) # 어차피 제곱하면 상관 없잖아요
return answer
print(solution(4, [4, 3, 3]))
```
- 리스트가 있어. 그리고 그 리스트 안에서 가장 큰 값을 뽑애줘야해 ?
- 그럴 때 계속 index.(max(~))를 이용해주거나, sort()를 이용해줄 수도 있지만, 우선순위 큐를 쓰면 보다 빠르다.
---
참고자료
[프로그래머스]<https://programmers.co.kr/learn/challenges>
[참고블로그]<https://blog.rajephon.dev/2018/10/14/programmers-solution-level3-no-overtime/>
[우선순위큐]<https://www.daleseo.com/python-heapq/>
|
Python
|
UTF-8
| 1,194 | 4.03125 | 4 |
[] |
no_license
|
print("Buzzfeed Quiz: Tell Us Your Style & We will Tell You What Subject You’ll Teach")
#Questions the quiz will ask:
question1 = input("On a night out do you prefer: \n A. A Dress \n B. Jeans and Blouse \n C. Romper \n D. Whatever is Clean")
question2 = input("When lounging around the house what do you wear: \n A. T-shirt and Sweatpants /n B. Nothing \n C. Bathing Suit \n D. Pajamas")
question3 = input("What are your go to shoes: \n A. Louboutins \n B. Nike \n C. Crocks \n D. UGGs")
question4 = input("WWhat is your favorite color scheme: \n A. Bright Summer Colors \n B. Black?/White \n C. Fall Colors \n D. Natural Colors ")
question5 = input("What is your typical makeup routine: \n A. All Glam \n B. Natural Look \n C. Bare Face \n D. Only Special Occasions")
question6 = input("What’s favorite type of jeans: \n A. Skinny Jeans \n B. Bootcut Jeans \n C. Boyfriend Cut Jeans \n D. Jean Shorts")
#Evaluate answers
if question1 == "A":
if question2 == "A":
if question3 =="A":
if question4 == "A":
if question5 == "A":
if question6 == "A":
print("You're A Fashionista & Would Teach English!")
|
TypeScript
|
UTF-8
| 1,398 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
import { Sprite, Game } from "phaser";
export class Swarm extends Sprite {
public static assetName = "swarm";
private enabled: boolean;
private placed: boolean;
private heightLimit = 5;
startingHeight = 0;
currentHeight = 1;
text: Phaser.Text;
constructor(game: Game, x: number, y: number, height = 0, startingHeight = 0) {
super(game, x, y, Swarm.assetName);
//TODO: use starting height
this.currentHeight = height;
this.startingHeight = startingHeight;
// this.text = this.game.add.text(x, y, height.toString() + " " + startingHeight.toString(), { font: '12px Arial', fill: '#fff' });
this.setOpacity();
}
getTotalHeight(): number {
return this.startingHeight + this.currentHeight;
}
grow(amount: number) {
this.currentHeight += amount;
if (this.currentHeight > this.heightLimit) {
this.currentHeight = this.heightLimit;
}
this.setOpacity();
}
hurt(amount: number) {
this.currentHeight -= amount;
if (this.currentHeight < 0) {
this.destroy();
return;
}
this.setOpacity();
}
setOpacity() {
this.alpha = 0.2 + (0.10 * this.currentHeight);
// this.text.text = this.currentHeight.toString() + "" + this.startingHeight.toString();
}
update() {
}
}
|
Markdown
|
UTF-8
| 444 | 2.59375 | 3 |
[] |
no_license
|
# my-first-repo
git@github.com:eagyemang21/my-first-repo.git
I am an energetic Brooklyn native who thrives off enthusiasm and new things. I am mostly excited about geting started on Marcy Lab this year and that we will
be learning new material, but also make wonderful connections and healthy bonds along the way. I hope to be seen as a ray of sunshine, not only for my cohort,
but for the program in general and paving paths for those next to come.
|
PHP
|
UTF-8
| 2,334 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
<?php declare(strict_types = 1);
namespace jschreuder\SpotDesk\Entity;
use jschreuder\SpotDesk\Value\MailTransportSecurityValue;
use Ramsey\Uuid\UuidInterface;
use DateTimeInterface;
class Mailbox
{
public function __construct(
private UuidInterface $id,
private string $name,
private ?Department $department,
private string $imapServer,
private int $imapPort,
private MailTransportSecurityValue $imapSecurity,
private string $imapUser,
private string $imapPass,
private DateTimeInterface $lastCheck
) {
}
public function getId() : UuidInterface
{
return $this->id;
}
public function getName() : string
{
return $this->name;
}
public function setName(string $name) : void
{
$this->name = $name;
}
public function getDepartment() : ?Department
{
return $this->department;
}
public function setDepartment(?Department $department) : void
{
$this->department = $department;
}
public function getImapServer() : string
{
return $this->imapServer;
}
public function setImapServer(string $imapServer) : void
{
$this->imapServer = $imapServer;
}
public function getImapPort() : int
{
return $this->imapPort;
}
public function setImapPort(int $imapPort) : void
{
$this->imapPort = $imapPort;
}
public function getImapSecurity() : MailTransportSecurityValue
{
return $this->imapSecurity;
}
public function setImapSecurity(MailTransportSecurityValue $imapSecurity) : void
{
$this->imapSecurity = $imapSecurity;
}
public function getImapUser() : string
{
return $this->imapUser;
}
public function setImapUser(string $imapUser) : void
{
$this->imapUser = $imapUser;
}
public function getImapPass() : string
{
return $this->imapPass;
}
public function setImapPass(string $imapPass) : void
{
$this->imapPass = $imapPass;
}
public function getLastCheck() : DateTimeInterface
{
return $this->lastCheck;
}
public function setLastCheck(DateTimeInterface $lastCheck) : void
{
$this->lastCheck = $lastCheck;
}
}
|
C++
|
GB18030
| 1,582 | 3.140625 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
struct Node{
int type;
int id;
double price;
double amount;
vector<int> buyer;
};
bool visited[100000];
int n;
double p,r;
vector<Node> nodes(100000);
double bfs(int now){
double sales=0;
queue<Node> q;
visited[now]=true;
q.push(nodes[now]);
Node null;
null.type=-1;
q.push(null);
double np=p;
Node newnow;
while(!q.empty()){
newnow=q.front();
q.pop();
if(newnow.type!=-1){
newnow.price=np;
if(newnow.type==2){
sales+=newnow.amount*newnow.price;
}else{
for(int i=0;i<newnow.buyer.size();i++){
if(!visited[(newnow.buyer[i])]){
q.push(nodes[newnow.buyer[i]]);
visited[(newnow.buyer[i])]=true;
}
}
}
}else{
np=np+np*r/100;
if(!q.empty()){
q.push(null);
}
}
}
return sales;
}
int main(){
/*
Ŀ⣺һļ۸ΪpȻӸ㿪ʼÿһ㣬òĻ۸ڸļ۸r%
ÿҶĻǵļ۸֮
˼·
bfsÿµһ¼۸ҶӼ۶һι
*/
scanf("%d%lf%lf",&n,&p,&r);
for(int i=0;i<n;i++){
Node tmp;
int t;
scanf("%d",&t);
if(t==0){
tmp.type=2;
scanf("%d",&t);
tmp.amount=t;
}else{
tmp.type=1;
for(int j=0;j<t;j++){
int c;
scanf("%d",&c);
tmp.buyer.push_back(c);
}
}
if(i==0){
tmp.price=p;
}
tmp.id=i;
nodes[i]=tmp;
}
double sales=bfs(0);
printf("%.1f",sales);
return 0;
}
|
C++
|
UTF-8
| 315 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <utility>
#define ASSERT_OK_AND_ASSIGN(dest, expr) \
dest = ({ \
auto __result = (expr); \
ASSERT_TRUE(__result.ok()) << __result.status(); \
std::move(*__result); \
});
|
Python
|
UTF-8
| 1,540 | 3.625 | 4 |
[] |
no_license
|
import sys
#정점의 개수, 간선의 개수, 탐색 시작할 정점의 번호
N, M, V = map(int, sys.stdin.readline().split())
#N+1을 하는 이유는 리스트의 인덱스가 0부터 시작하므로 순서상 헷갈리므로 1을 더해준다!
#즉, 1 2 3 4 5 노드에 각각 1 2 3 4 5를 넣어야 헷갈리지 않는다는 말!(원래의 리스트라면 인덱스 0 1 2 3 4에 1 2 3 4 5가 들어감)
graph_list = [set([]) for _ in range(N+1)]
#간선은 노드끼리의 연결을 의미하므로 a,b에 입력한 노드들은 서로 연결됨을 표시
for _ in range(M) :
a, b = map(int, sys.stdin.readline().split())
graph_list[a].add(b)
graph_list[b].add(a)
def DFS(graph_list, start_node) :
visit_node = []
stack = [start_node]
while stack :
node = stack.pop()
if node not in visit_node :
visit_node.append(node)
stack += sorted(list(graph_list[node] - set(visit_node)), reverse=True)
#방금 넣은 node에 연결된 다른 노드 중 방문하지 않은 것들만 스택에 역정렬해서 넣는다.
return visit_node
def BFS(graph_list, start_node) :
visit_node = []
queue = [start_node]
while queue :
node = queue.pop(0)
if node not in visit_node :
visit_node.append(node)
queue += sorted(list(graph_list[node] - set(visit_node)))
return visit_node
for i in list(DFS(graph_list, V)) :
print(i, end =" ")
print()
for j in list(BFS(graph_list, V)) :
print(j, end = " ")
|
Java
|
UTF-8
| 995 | 2.140625 | 2 |
[] |
no_license
|
/**
*
*/
package com.baomidou.springboot.config;
import org.tio.utils.time.Time;
/**
* @Description: Tio配置类
* @Author: LiHaitao
* @CreateDate: 2018/8/14 22:00
* @UpdateUser:
* @UpdateDate: 2018/8/14 22:00
* @UpdateRemark:
* @Version: 1.0.0
*/
public abstract class ServerConfig {
/**
* 协议名字(可以随便取)
*/
public static final String PROTOCOL_NAME = "showcase";
public static final String CHARSET = "utf-8";
/**
* 监听的ip
*/
public static final String SERVER_IP = null;//null表示监听所有,并不指定ip
/**
* 监听端口
*/
public static final int SERVER_PORT = 9326;
/**
* 心跳超时时间,单位:毫秒
*/
public static final int HEARTBEAT_TIMEOUT = 1000 * 60;
/**
* ip数据监控统计,时间段
*
*/
public static interface IpStatDuration {
public static final Long DURATION_1 = Time.MINUTE_1 * 5;
public static final Long[] IPSTAT_DURATIONS = new Long[] { DURATION_1 };
}
}
|
Java
|
GB18030
| 1,053 | 2.578125 | 3 |
[] |
no_license
|
package com.milkelkl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PageRedirect extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// Ҫضλ
String site=new String("http://www.baidu.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
}
}
|
JavaScript
|
UTF-8
| 1,195 | 2.59375 | 3 |
[] |
no_license
|
var express = require('express'); //require
var router = express.Router(); //新对象
router.get('/', function(req, res, next) {
var loginData; //登录变量
if (req.session.user) { //如果有登陆者
loginData = {
isLogin: true, //登录状态true
// user: {
// avatar: req.session.user.avatar, //显示头像
// username: req.session.user.username //显示名
// }
user:req.session.user
}
} else {
loginData = {
isLogin: false //否则登录状态false
}
}
res.render('index', loginData ); //发送页面,数据加模板组装起来渲染发送到页面上
});
module.exports = router; //出口
// router.get('/', function(req, res, next) {
// var data;
// if(req.session.user){
// data = {
// isLogin: true,
// user: req.session.user
// }
// }else{
// data = {
// isLogin: false
// }
// }
// console.log(data)
// res.render('index', data);
// });
|
C#
|
UTF-8
| 1,823 | 2.90625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class TimeAtTheDayDAL
{
public bool AddTimeAtTheDay(TimeAtTheDay timeAtTheDay)
{
using (PrayOnTheWayEntities DB = new PrayOnTheWayEntities())
{
DB.TimeAtTheDays.Add(timeAtTheDay);
try
{
DB.SaveChanges();
return true;
}
catch (Exception)
{
throw;
}
}
}
public List<TimeAtTheDay> GetTimeAtTheDays()
{
using (PrayOnTheWayEntities DB = new PrayOnTheWayEntities())
{
return DB.TimeAtTheDays.ToList();
}
}
public bool UpdateTimeAtTheDay(TimeAtTheDay timeAtTheDay)
{
using (PrayOnTheWayEntities DB = new PrayOnTheWayEntities())
{
DB.Entry(timeAtTheDay);
try
{
DB.SaveChanges();
return true;
}
catch (Exception)
{
throw;
}
}
}
public bool RemoveTimeAtTheDay(TimeAtTheDay TimeAtTheDay)
{
using (PrayOnTheWayEntities DB = new PrayOnTheWayEntities())
{
DB.TimeAtTheDays.Remove(TimeAtTheDay);
try
{
DB.SaveChanges();
return true;
}
catch (Exception)
{
throw;
}
}
}
}
}
|
C++
|
UTF-8
| 1,910 | 3.6875 | 4 |
[] |
no_license
|
#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
struct Complex;
typedef struct Complex *Opr;
struct Complex{
double a, b;
};
/* Should malloc in main() */
void Assign(Opr Z, double x, double y);
double GetReal(Opr Z);
double GetImage(Opr Z);
void Add(Opr X, Opr Y, Opr Z);
void Subtract(Opr X, Opr Y, Opr Z);
void Multiply(Opr X, Opr Y, Opr Z);
void Divide(Opr X, Opr Y, Opr Z);
void Destroy(Opr Z);
/* assign value */
void Assign(Opr Z, double x, double y){
Z->a = x;
Z->b = y;
return;
}
/* Get Real number */
double GetReal(Opr Z){
if(Z == NULL) return 0;
return Z->a;
}
/* Get image number */
double GetImage(Opr Z){
if(Z == NULL) return 0;
return Z->b;
}
/* Add X and Y to Z */
void Add(Opr X, Opr Y, Opr Z){
Z->a = X->a + Y->a;
Z->b = X->b + Y->b;
return ;
}
/* Subtract Y from X to Z */
void Subtract(Opr X, Opr Y, Opr Z){
Z->a = X->a - Y->a;
Z->b = X->b - Y->b;
return ;
}
/*Multiply X and Y to Z */
void Multiply(Opr X, Opr Y, Opr Z){
double a = X->a;
double b = X->b;
double c = Y->a;
double d = Y->b;
Z->a = a*c - b*d;
Z->b = b*c + a*d;
return ;
}
/*Divide Y from X to Z */
void Divide(Opr X, Opr Y, Opr Z){
double a = X->a;
double b = X->b;
double c = Y->a;
double d = Y->b;
Z->a = (a*c + b*d)/(c*c + d*d);
Z->b = (b*c - a*d)/(c*c + d*d);
return;
}
void Destroy(Opr Z){
free(Z);
return;
}
int main(void){
Opr A, B, C, D;
A = (Opr)malloc(sizeof(Complex));
B = (Opr)malloc(sizeof(Complex));
C = (Opr)malloc(sizeof(Complex));
D = (Opr)malloc(sizeof(Complex));
if (!A || !B || !C || !D) return 0;
Assign(A, 1, 1);
Assign(B, 1, 1);
Add(A, B, C);
Subtract(A, B, D);
cout << GetReal(C) << GetImage(C) <<endl;
cout << GetReal(D) << GetImage(D) <<endl;
return 0;
}
|
PHP
|
UTF-8
| 1,709 | 2.71875 | 3 |
[] |
no_license
|
<?php
include "../Includes/basedir.inc.php";
include "../Includes/config.inc.php";
//NOTE: MAKE SURE YOU DO YOUR OWN APPROPRIATE SERVERSIDE ERROR CHECKING HERE!!!
if(!empty($_POST) && isset($_POST))
{
//make variables safe to insert
$bat = mysql_real_escape_string($_POST['bat']);
$etage = mysql_real_escape_string($_POST['etage']);
$salle = mysql_real_escape_string($_POST['salle']);
if(!empty($_POST['action']) && isset($_POST['action']))
switch($_POST['action']) {
case "add" :
//query to insert topo into table
$query="INSERT INTO `topologie` (`id`, `batiment`, `etage`, `salle`) VALUES ('', '$bat', '$etage', '$salle')";
$result = mysql_query($query);
if(!$result)
{
echo "<span class=\"error\">Echec de l'enregistrement</span>";
}
else
{
echo "<span class=\"info\">Enregistrement de votre élément réussi</span>";
}
break;
case "edit" :
//query to insert topo into table
$query="UPDATE `topologie` SET `batiment` = '$bat', `etage` = '$etage', `salle` = '$salle' WHERE `salle` ='$salle'";
$result = mysql_query($query);
if(!$result)
{
echo "<span class=\"error\">Echec de la modification</span>";
}
else
{
echo "<span class=\"info\">La modification est effectuiée</span>";
}
break;
case "delete" :
$query="DELETE FROM `maint_plug`.`topologie` WHERE `topologie`.`salle` = '$salle'";
$result = mysql_query($query);
if(!$result)
{
echo "<span class=\"error\">Echec de la suppression</span>";
}
else
{
echo "<span class=\"info\">La salle <strong>$salle </strong> a été supprimée</span>";
}
break;
default:
echo "Aucune action choisie.";
break;
}
}
?>
|
Java
|
UTF-8
| 90 | 1.757813 | 2 |
[] |
no_license
|
package com.whitehat.jr.model;
public enum VehicleType {
CAR, SUV, OTHER;
}
|
Python
|
UTF-8
| 4,305 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright (c) 2023, Arm Limited or its affiliates. All rights reserved.
# SPDX-License-Identifier : Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Parse a list of perf events as used in the -e argument to 'perf stat'.
The output is a list of lists. Each item in the top-level list is a group
of events to be monitored concurrently, corresponding to the
curly braces specification in -e. If there are no groups in the input,
the output is a list of singleton lists.
This module deals only with syntax. It does not validate or resolve
the event strings against the events exposed in sysfs.
In particular, this module does not expand wildcarded event names.
Singletons in the list may become multiples after expansion.
"""
from __future__ import print_function
def perf_parse(s):
if not s:
return []
if s[0] == ',':
return perf_parse(s[1:])
if s[0] == '{':
kix = s.find('}')
assert kix >= 0, "%s: missing closing brace" % s
# we could also check that kix is followed by comma or EOS or a suffix valid for a group
group = perf_parse(s[1:kix])
suffix = ""
if s[kix+1:].startswith(':'):
# there's a suffix for the whole group: capture it and apply it to each event
cix = s[kix+1].find(",")
if cix >= 0:
suffix = s[kix+1:kix+1+cix]
kix += cix
else:
suffix = s[kix+1:]
kix += len(suffix)
assert suffix.startswith(":")
def flatten(x, suffix):
for sublist in x:
for item in sublist:
yield item + suffix
return [list(flatten(group, suffix))] + perf_parse(s[kix+1:])
cix = s.find(",")
six = s.find("/")
if six >= 0 and (cix < 0 or six < cix):
# next token has an opening slash - look for the closing slash
csix = s[six+1:].find("/")
assert csix >= 0, "%s: missing trailing slash" % s
csix += six + 1
cix = s[csix+1:].find(",")
if cix >= 0:
cix += csix + 1
if cix < 0:
# only one item left
return [[s]]
return [[s[:cix]]] + perf_parse(s[cix+1:])
"""
Unit tests
"""
def test_perf_parse(s, ls_expected):
try:
ls_got = perf_parse(s)
except Exception:
if ls_expected is not None:
print("failed: %s -> Exception" % s)
return
assert ls_got == ls_expected, "failed: %s -> %s, expected %s" % (s, ls_got, ls_expected)
perf_parse_tests = [
( "", [] ),
( "a", [["a"]] ),
( "a,", [["a"]] ),
( "a,b", [["a"], ["b"]] ),
( "{a,b}", [["a","b"]] ),
( "{cyc,cyc}", [["cyc","cyc"]] ),
( "{a,b},c", [["a","b"], ["c"]] ),
( "{a,b},{c,d}", [["a","b"], ["c","d"]] ),
( "a,,b", [["a"], ["b"]] ),
( "a,b/c,d/,e", [["a"], ["b/c,d/"], ["e"]] ),
( "a,b/cd/,e", [["a"], ["b/cd/"], ["e"]] ),
( "a,b/c,d/m,e", [["a"], ["b/c,d/m"], ["e"]] ),
( "a,b/cd/m,e", [["a"], ["b/cd/m"], ["e"]] ),
( "a:u,b:k", [["a:u"], ["b:k"]] ),
( "{a,b}:S", [["a:S", "b:S"]] ), # TBD is this the right thing to do?
# broken cases
( "{a", None ),
# ( "a}", None ),
( "a,b/c,d", None ),
]
def test():
for (s,ls) in perf_parse_tests:
test_perf_parse(s,ls)
if __name__ == "__main__":
test()
|
JavaScript
|
UTF-8
| 1,777 | 2.625 | 3 |
[] |
no_license
|
'use strict';
angular.module('ulyssesApp')
.controller('ScheduleViewCtrl', function ($scope) {
$scope.hour = 135;
$scope.schedule = null;
$scope.timeArray = [];
$scope.earlyTime = new Date('April 13, 2016, 07:00:00');
$scope.lateTime = new Date('April 13, 2016, 17:00:00');
$scope.$parent.schedule.$promise.then(function(schedule) {
$scope.schedule = schedule;
});
$scope.populateTimeArray = function(date){
var earlyTime = moment($scope.earlyTime);
$scope.timeArray.push(earlyTime.format('h:mm a'));
for(var i = 1; i<13; i++){
$scope.timeArray.push(earlyTime.add(1, 'hours').format('h:mm a'));
};
}
$scope.populateTimeArray();
$scope.duration = function(time1, time2){
return time2.getHours()-time1.getHours() + Math.abs(time2.getMinutes()-time1.getMinutes())/60;
}
$scope.borderColorCode = function(slot){
if(slot.assigned.length == 0){
return "red";
}
if(slot.assigned.length < slot.positions){
return "orange";
}
return "green";
}
$scope.colorCode = function(slot){
if(slot.assigned.length == 0){
return "#f2dede";
}
if(slot.assigned.length < slot.positions){
return "#fcf8e3";
}
return "#dff0d8";
}
$scope.calculateSlotPosition = function(slot) {
var start = new Date(slot.start)
var end = new Date(slot.end);
var offset = $scope.duration($scope.earlyTime, start);
var shiftLength = $scope.duration(start, end);
return {
left: $scope.hour * offset + 105,
width: $scope.hour * shiftLength - 5,
backgroundColor: $scope.colorCode(slot),
borderColor: $scope.borderColorCode(slot)
};
}
});
|
Python
|
UTF-8
| 81 | 2.796875 | 3 |
[] |
no_license
|
import math
def f(zxc):
q = zxc
return f'{math.pi:.{q}f}'
print(f(4))
|
Python
|
UTF-8
| 2,361 | 2.6875 | 3 |
[] |
no_license
|
import os
from cv2 import cv2
import numpy as np
import requests
import math
import random
from pathlib import Path
import time
from PIL import Image
LAT = [45.35051, 45.65]
LONG = [-122.20, -123.0]
X_SLICE = 50
Y_SLICE = 50
RAW_IMG_PATH = "C:\\Users\\harry\\Anaconda3\\envs\\gputest\\AT-Task2-DL\\TrainingData\\Satellite\\RawImg"
CROPPED_IMG_PATH = "C:\\Users\\harry\\Anaconda3\\envs\\gputest\\AT-Task2-DL\\TrainingData\\Satellite\\Cropped"
SLICED_IMG_PATH = "C:\\Users\\harry\\Anaconda3\\envs\\gputest\\AT-Task2-DL\\TrainingData\\Satellite\\SlicedImg"
def mapquest_image_request():
randLat = random.uniform(LAT[0], LAT[1])
randLon = random.uniform(LONG[0], LONG[1])
url = f"https://www.mapquestapi.com/staticmap/v4/getmap?key=MS6YUJYIiHcFHDwp0L8iUDxsuSw0G7c7&size=400, 400&zoom=18¢er={randLat},{randLon}&type=sat&imagetype=png&pois=1, {randLat}, {randLat}, {randLon}, {randLon}"
response = requests.get(url, stream=True).raw
image = np.asarray(bytearray(response.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
#cv2.imshow('URL IMG', image)
#cv2.waitKey()
return image
#return cv2.imdecode(image, cv2.IMREAD_COLOR)
def crop_img():
raw_img = mapquest_image_request()
image = raw_img[25:375, 0:400]
#image = cv2.resize(raw_img, dsize = size, interpolation=cv2.INTER_CUBIC)
#cv2.imshow("croppped", image)
#cv2.waitKey(0)
return image
def save_img():
image = crop_img()
file_name = f"{int(time.time())}.{'png'}"
cv2.imwrite(CROPPED_IMG_PATH + "\\" + file_name, image)
for x in range(1):
save_img()
X_SLICE = int(X_SLICE)
Y_SLICE = int(Y_SLICE)
def slice_image(img):
img_width, img_height = img.shape[:2]
x_tiles = math.floor(img_width / X_SLICE)
y_tiles = math.floor(img_height / Y_SLICE)
image_start_time = f"{int(time.time())}"
for y in range(y_tiles):
for x in range(x_tiles):
current_x_step = x * X_SLICE
current_y_step = y * Y_SLICE
new_img = img[current_y_step:current_y_step+Y_SLICE, current_x_step:current_x_step+X_SLICE]
file_name = f"\\{image_start_time} {x},{y}.png"
cv2.imwrite(SLICED_IMG_PATH + file_name, new_img)
for img in os.listdir(CROPPED_IMG_PATH):
img_array = cv2.imread(os.path.join(CROPPED_IMG_PATH, img), cv2.IMREAD_COLOR)
slice_image(img_array)
|
TypeScript
|
UTF-8
| 290 | 3.75 | 4 |
[] |
no_license
|
// 类的类型 将定义好的类做为类型,使用方法和接口做为类型是一样的。
/*
class Person{
name
age
constructor(name:string,age:number){
this.name = name
this.age = age
}
}
let p:Person = new Person('郭丹丹',20)
*/
|
C#
|
UTF-8
| 4,819 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Brevitee.Analytics
{
public abstract class BaseCrawler: ICrawler
{
static Dictionary<string, ICrawler> _crawlers;
static object _crawlerLock = new object();
public static Dictionary<string, ICrawler> Instances
{
get
{
return _crawlerLock.DoubleCheckLock(ref _crawlers, () => new Dictionary<string, ICrawler>());
}
}
#region ICrawler Members
public virtual string Root
{
get;
set;
}
public virtual string Name
{
get;
set;
}
public string ThreadName
{
get
{
return "Crawler_{0}"._Format(this.Name);
}
}
/// <summary>
/// When implemented by a derived class will extract
/// more targets to be processed from the specified target.
/// (Think filepath or url)
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public abstract string[] ExtractTargets(string target);
public abstract void ProcessTarget(string target);
public virtual bool WasProcessed(string target = "")
{
if (_processed != null && !string.IsNullOrEmpty(target))
{
return _processed.Contains(target);
}
return false;
}
Queue<string> _targets;
public string[] QueuedTargets
{
get
{
return _targets.ToArray();
}
}
int _maxQueue;
public int MaxQueueSize
{
get
{
return _maxQueue;
}
set
{
_maxQueue = value;
}
}
List<string> _processed;
public string[] Processed
{
get
{
return _processed.ToArray();
}
}
protected internal string Current
{
get;
set;
}
CrawlerState.Action _currentAction;
protected internal CrawlerState.Action CurrentAction
{
get
{
return _currentAction;
}
set
{
CrawlerState.Action old = _currentAction;
_currentAction = value;
OnActionChanged(old, _currentAction);
}
}
public event ActionChangedDelegate ActionChanged;
protected void OnActionChanged(CrawlerState.Action oldAction, CrawlerState.Action newAction)
{
if (ActionChanged != null)
{
ActionChanged(this, new ActionChangedEventArgs(oldAction, newAction));
}
}
public CrawlerState GetState()
{
return new CrawlerState(this);
}
public void Crawl()
{
if (string.IsNullOrEmpty(Root))
{
throw new InvalidOperationException("Root not set");
}
Crawl(Root);
}
public void Crawl(string rootTarget)
{
Exec.Start(ThreadName, () =>
{
Root = rootTarget;
_targets = new Queue<string>();
_processed = new List<string>();
_targets.Enqueue(rootTarget);
while (_targets.Count > 0)
{
Current = _targets.Dequeue();
CurrentAction = CrawlerState.Action.Extracting;
string[] more = ExtractTargets(Current);
for (int i = 0; i < more.Length; i++)
{
if (more[i] == null)
{
continue;
}
string extracted = more[i].ToLowerInvariant();
if (!WasProcessed(extracted))
{
if (MaxQueueSize == 0 || (MaxQueueSize > 0 && _targets.Count < MaxQueueSize))
{
_targets.Enqueue(extracted);
}
}
}
CurrentAction = CrawlerState.Action.Processing;
ProcessTarget(Current);
_processed.Add(Current.ToLowerInvariant());
}
CurrentAction = CrawlerState.Action.Idle;
});
}
#endregion
}
}
|
Shell
|
UTF-8
| 1,579 | 3.40625 | 3 |
[] |
no_license
|
#!/bin/sh
STRING="eHOF"
echo "Please select ..."
echo 1: Skip
echo 2: Check package $STRING
echo 3: Check package $STRING without vignette
echo 4: Checking eHOF tarball as CRAN
while :
do
read INPUT_STRING
case $INPUT_STRING in
1) break
;;
2) echo "Checking package source ..."
mv ~/.wine/drive_c/Turbowin ~/.wine/drive_c/Turbowon
cd ~/workspace/eHOF
R-devel CMD check ~/workspace/eHOF/eHOF
mv ~/.wine/drive_c/Turbowon ~/.wine/drive_c/Turbowin
break
;;
3) echo "Checking package without vignette ..."
R-devel CMD check --no-vignettes ~/workspace/eHOF/eHOF
break
;;
4) echo "Checking package tarball as-cran"
cd ~/workspace/eHOF
mv ~/.wine/drive_c/Turbowin ~/.wine/drive_c/Turbowon
R-devel CMD check --as-cran ~/eHOF*.tar.gz
mv ~/.wine/drive_c/Turbowon ~/.wine/drive_c/Turbowin
break
;;
esac
done
echo Should I build the package $STRING "?"
echo 1: Skip
echo 2: Build and install package $STRING
while :
do
read INPUT_STRING
case $INPUT_STRING in
1) break
;;
2) echo I build and install the package $STRING
cd ~
echo Uploading
# scp ~/vegdata_*.tar.gz jansen7@141.53.8.94:/srv/geobot/web/download/r_package
R-devel CMD build ~/workspace/eHOF/eHOF
R CMD INSTALL ~/workspace/eHOF/eHOF
# cd ~/R/i686-pc-linux-gnu-library/3.1/
# cat ~/eHOF_*.tar.gz | ssh jansen7@141.53.8.94 \
# "cat > /srv/geobot/web/download/r_package/eHOF.tar.gz"
# cd ~
break
;;
*) echo "invalid selection"
break
;;
esac
done
echo "\n That's all! \n"
|
Markdown
|
UTF-8
| 6,816 | 2.9375 | 3 |
[] |
no_license
|
一二〇
第二十八章 两相对质
有时逸和左北斗指路,马车很快地驰抵了楚云秋碰见梅恨天之处。
当然,梅恨天已不在这儿了。
时逸让薛空摹停住了马车,他跳下了车。
他坐在地上仔细看了一阵,然后站起来直抓头。
莫言也跳了下去,道:“怎么了,你不是精通追踪之术的吗?”
时逸皱着眉道:“足迹乱了,怎么这块地儿突然增添了这么多足迹,有另有女,不下几十个之多。”
莫言俯首往地上看去,但他却看不出什么来!
只听逍遥宫圭在车里问道:“可有什么发现吗?”
莫言回身把时逸的发现告诉了逍遥宫主。
逍遥宫主沉默了一下,道:“恐怕这是“双凤门”人留下的足迹,她们追踪而来想看个究竟。时老,增添的这些足迦是往那方向去的?”
时逸抬手一扬道:“往东去了。”
逍遥宫主道:“可看得出,走了多久了?”
时逸道:“顶多不过半个时辰。”
逍遥宫主道:“麻烦时老仔细看看,往东去的是不是也有悔恨天的足迹?”
时逸答应了一声,立即往东找了过去。
他走出几十女去,很快地又掠了回来,说道:“宫主,悔恨天的足迹跟那些人的足迦都往东去了。”
逍遥宫主道:“多半他们找悔恨天去了,二位请上车,咱们赶一阵吧!”
莫言、时逸双双跃上马车,薛空摹挥起一鞭,赶着马车往东疾驰。
时逸跟莫言两个人一直竭尽目力,凝望着车前地上的足迦,两对老眼儿,眨也没眨一下。
这些足迦并不是笔直往东,一会儿折向南,一会儿折向北,足足疾驰了近半个时辰之多。
薛空蔓忽然抬鞭往前一指,道:“三位请看!”
莫言、时速、左北斗忙抬眼往前望去。只见前面近百丈外,有一支为数几十伍在往西疾走,速度之快不下于自己这些人乘坐的疾驰马车。
莫言忙说道:“恐怕真让宫主说中了。”
逍遥宫主道:“空群!看到了什么?”
薛空摹把所见恭声禀告逍遥宫主。
莫言按着问道:“宫主,咱们该怎么办?”
时逸道:“这还用问,自然是追上去。”
逍遥宫主道:“时老说得是,追上去,先找他们也好,我要问问那位“双凤门主”,她究竟是何居心?”
薛空蔓叱喝声中猛挥了几鞭,马车驰速更快,飞也似地赶了上去。
逍遥宫主说道:“空台,叫他们停一下。”
薛空翼仰头发出一声长啸,裂石穿云,直传过去。
薛空摹这声长啸还甚管用,前头那支队伍末等啸声落,立即说道:“果然是“双凤门”的人。”
逍遥宫主冷冷地哼了一声,没说话。
马车驰行如飞,一转眼工夫之后,便已驰近“双凤门”那支队伍。
薛空摹收势停住马车,后头的马车不等拉停便分两边散开前驰,围住了“双凤门”这支队伍。
“双凤门”的人脸色微变,立即转身向外,蓄势以待。
潘朋、彭刚双双越众而出,四道锐利目光直逼车辕,潘朋震声道:“尔等何许人,这是什么意思?”
左北斗“哈”地一声,说道:“这个家伙人老眼神儿也不好了,怎么连咱们这块招牌都认不出!”
时逸冷冷地说道:“难怪,谁叫咱们三个这块招牌没人家“双凤门”的招牌大!”
彭刚冰冷一哼,道:“你们究竟是什么人?”
薛空台冷然截口道:““逍遥宫主”要见见贵门主。”
彭刚一征,说道:“你们是“逍遥宫”的人?”
薛空摹道:“不错。”
彭刚目中寒芒往后一掠,道:““逍遥宫主”现在何处?”
薛空台等纵身跃下车辕,薛空摹伸手掀起了车帘。
上彭刚往车里看了一眼,道:“老夫眼拙,哪位是“逍遥宫主”?”
逍遥宫圭冰冷道:“你跟谁称老夫?这就是你们“双凤门”的礼教了?”
只听双凤门主的话声传了过来:““双凤门”不能落人笑柄,彭护法不可失礼,闪开些。”彭刚、潘朋双双躬身退后。
双凤门主道:“小君!”
黄君抬皓腕掀起了轿帘,双凤门端坐轿内,话声微带冷意,道:““双凤门”跟“逍遥宫”素无往来,应该谈不上什么嫌隙,不知道宫主这是什么意思?”
逍遥宫主道:““逍遥宫”一向少与人来往,也从不侵人,跟谁也谈不上嫌隙,不过要是有人意图危害“逍遥宫”,那却是“逍遥宫”难以忍受的。”
双凤门主道:“宫主的意思是指“双凤门”意图危害“逍遥宫”?”
逍遥宫主道:“可以这么说!”
双凤门主突然笑了,她笑声很好转:“宫主一官之尊,“逍遥宫”在武林中,也很有点名气,宫主不应该是那莽撞孟浪的人。”
逍遥宫主道:“门主古利如刀,好不厉害,我提个人门主就明白了,楚云秋:门主知道这个人吗?”
黄君为之一忙。双凤门主也为之一征,道:“楚云秋是贵宫的人?”
逍遥宫主道:“门主既知楚云秋,当知他不是我“逍遥宫”的人,不过他跟我“逍遥宫”有极深的渊源、异常密切的关系。”
双凤门主道:“这一点我倒是真的不知道,而且我也不太明白,宫主跟我提起这个楚云秋”逍遥宫主道:“门主,楚云秋是“神手书生口楚陵霄的后人。”
黄君脸色一变。双凤门道:“我明白了,宫主敢是为我指“神手书生口楚陵霄杀害梅氏一家的事找我?”
逍遥宫主道:“正是,我要问问门主,有何谭何据指楚陵霄杀人满门?”
双凤门主道:“要是别的事我不敢说,这件事我不会不给宫主一个满意的答覆,不过我要请教,楚陵霄跟贵宫有什么渊源?有什么关系?”
逍遥宫主道:“我不满人,也周不着满人,“神手书生口楚陵霄他……他是:他是我的夫婿。”
黄君猛然一征,她脱口叫了声:“楚夫人!”
这答覆显然也大出双凤门主的意料,她忙了一忙,旋即说道:“我说楚陵霄没死跑到哪儿去了,原来他跑到“逍遥宫”招亲去了。”
逍遥宫主冷冷地说道:“门主错了,我跟楚陵霄的夫妻关系早在十几二十年前丫不是现在。”
双凤门又复一忙道:“怎么说?宫主跟楚陵霄的夫妻关系早在十几二十年前,不是现在。”
逍遥宫主道:“不错。”
|
C++
|
GB18030
| 259 | 2.90625 | 3 |
[] |
no_license
|
#include "pch.h"
// Base64ַĿ
size_t charCount(const char* str, size_t size, const char ch) {
size_t count = 0;
for (size_t i = size - 1; i > size - 4; i--) {
if (str[i] == ch)
count++;
else
break;
}
return count;
}
|
Ruby
|
UTF-8
| 369 | 3.734375 | 4 |
[] |
no_license
|
def halvsies(arr)
halfway = arr.size / 2 - 1
halfway = (arr.size / 2.0).round - 1 if arr.size.odd?
second_half = halfway + 1
arr1 = arr[0..halfway]
arr2 = arr[second_half..-1]
[arr1, arr2]
end
puts halvsies([1, 2, 3, 4]) == [[1, 2], [3, 4]]
puts halvsies([1, 5, 2, 4, 3]) == [[1, 5, 2], [4, 3]]
puts halvsies([5]) == [[5], []]
puts halvsies([]) == [[], []]
|
Java
|
UTF-8
| 672 | 3.453125 | 3 |
[] |
no_license
|
/*
53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
#this problem was discussed by Jon Bentley (Sep. 1984 Vol. 27 No. 9 Communications of the ACM P885)
the paragraph below was copied from his paper (with a little modifications)
*/
public static int maxSubArray(int[] A) {
int maxSoFar=A[0], maxEndingHere=A[0];
for (int i=1;i<A.length;++i){
maxEndingHere= Math.max(maxEndingHere+A[i],A[i]);
maxSoFar=Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
|
Ruby
|
UTF-8
| 2,392 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
module Chanko
module Helper
mattr_accessor :files
self.files = {}
def self.reset
self.files.keys.each do |path|
self.remove_old_methods_by_file_path(path)
end
end
mattr_accessor :check_to_update_interval
self.check_to_update_interval = 1.seconds
def self.included(obj)
return unless obj.instance_methods.map(&:to_s).include?('invoke')
return if obj.instance_methods.map(&:to_s).include?('invoke_without_helper')
obj.class_eval do
def invoke_with_helper(*args, &block)
options = args.extract_options!
options = options.reverse_merge(:as => :view) unless self.is_a?(ApplicationController)
args << options
invoke_without_helper(*args, &block)
end
alias_method_chain :invoke, :helper
end
end
def self.deregister(name)
line = caller.detect { |c| c =~ /(.*#{name}.*\.rb).*/ }
path = $1 || name
return remove_old_methods_by_file_path(path)
end
def self.remove_old_methods_by_file_path(path)
return unless self.files[path]
return if self.files[path][:timestamp] > Time.now - check_to_update_interval
self.files[path][:methods].each do |method|
remove_method(method)
end
self.files[path][:methods] = []
end
def self.save_new_methods(name, methods)
line = caller.detect { |c| c =~ /(.*#{name}.*\.rb).*/ }
path = $1 || name
self.files[path] ||= {}
self.files[path][:timestamp] = Time.now
self.files[path][:methods] ||= []
self.files[path][:methods].concat(methods)
end
def self.rename_new_methods(name, new_methods)
methods = []
new_methods.each do |new_method|
prefix_new_method = Chanko::Unit.unit_method_name(name, new_method)
methods << prefix_new_method
self.class_eval do
alias_method prefix_new_method, new_method
remove_method(new_method)
end
end
return methods
end
def self.register(_name, &block)
name = _name.underscore
self.deregister(name)
tmp_methods = self.instance_methods(false)
self.class_eval(&block)
new_methods = self.instance_methods(false) - tmp_methods
renamed_new_methods = self.rename_new_methods(name, new_methods)
self.save_new_methods(name, renamed_new_methods)
end
end
end
|
Java
|
UTF-8
| 517 | 1.648438 | 2 |
[] |
no_license
|
package com.leyou.item.api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @ClassName CategoryController
* @Description: xxx
* @Author ningning.chai
* @Date 2019/9/5
* @Version V1.0
**/
@RequestMapping("category")
public interface CategoryApi {
@GetMapping
public List<String> queryNamesByIds(@RequestParam("ids")List<Long> ids);
}
|
Java
|
UTF-8
| 1,111 | 2.34375 | 2 |
[] |
no_license
|
package com.anoop.iistconnectfaculty.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import com.anoop.iistconnectfaculty.R;
import in.rgpvnotes.alert.myresource.models.AttendanceModel;
import in.rgpvnotes.alert.myresource.models.StudentModel;
public class AttendanceViewHolder extends RecyclerView.ViewHolder {
public TextView studentName;
private TextView enroll;
public CheckBox checkBox;
private View mView;
public AttendanceViewHolder(View itemView) {
super(itemView);
mView = itemView;
studentName = itemView.findViewById(R.id.attendance_student_name);
enroll = itemView.findViewById(R.id.attendance_student_enrollment);
checkBox = itemView.findViewById(R.id.attendance_checkBox);
}
public void bind(AttendanceModel model){
studentName.setText(model.getStudentName());
enroll.setText(model.getEnrollmentNumber());
}
public void setCheckBox(boolean value) {
checkBox.setChecked(value);
}
}
|
C
|
UTF-8
| 9,335 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
// SPDX-License-Identifier: MIT
// Integration with Sway WM.
// Copyright (C) 2020 Artem Senichev <artemsen@gmail.com>
#include "sway.h"
#include <errno.h>
#include <json.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
/** IPC magic header value */
static const uint8_t ipc_magic[] = { 'i', '3', '-', 'i', 'p', 'c' };
/** IPC message types (used only) */
enum ipc_msg_type { IPC_COMMAND = 0, IPC_GET_WORKSPACES = 1, IPC_GET_TREE = 4 };
/** IPC header */
struct __attribute__((__packed__)) ipc_header {
uint8_t magic[sizeof(ipc_magic)];
uint32_t len;
uint32_t type;
};
/**
* Read exactly specified number of bytes from socket.
* @param fd socket descriptor
* @param buf buffer for destination data
* @param len number of bytes to read
* @return true if operation completed successfully
*/
static bool sock_read(int fd, void* buf, size_t len)
{
while (len) {
const ssize_t rcv = recv(fd, buf, len, 0);
if (rcv == 0) {
fprintf(stderr, "IPC error: no data\n");
return false;
}
if (rcv == -1) {
const int ec = errno;
fprintf(stderr, "IPC read error: [%i] %s\n", ec, strerror(ec));
return false;
}
len -= rcv;
buf = ((uint8_t*)buf) + rcv;
}
return true;
}
/**
* Write data to the socket.
* @param fd socket descriptor
* @param buf buffer of data of send
* @param len number of bytes to write
* @return true if operation completed successfully
*/
static bool sock_write(int fd, const void* buf, size_t len)
{
while (len) {
const ssize_t rcv = write(fd, buf, len);
if (rcv == -1) {
const int ec = errno;
fprintf(stderr, "IPC write error: [%i] %s\n", ec, strerror(ec));
return false;
}
len -= rcv;
buf = ((uint8_t*)buf) + rcv;
}
return true;
}
/**
* IPC message exchange.
* @param ipc IPC context (socket file descriptor)
* @param type message type
* @param payload payload data
* @return IPC response as json object, NULL on errors
*/
static struct json_object* ipc_message(int ipc, enum ipc_msg_type type,
const char* payload)
{
struct ipc_header hdr;
memcpy(hdr.magic, ipc_magic, sizeof(ipc_magic));
hdr.len = payload ? strlen(payload) : 0;
hdr.type = type;
// send request
if (!sock_write(ipc, &hdr, sizeof(hdr)) ||
!sock_write(ipc, payload, hdr.len)) {
return NULL;
}
// receive response
if (!sock_read(ipc, &hdr, sizeof(hdr))) {
return NULL;
}
char* raw = malloc(hdr.len + 1);
if (!raw) {
fprintf(stderr, "Not enough memory\n");
return NULL;
}
if (!sock_read(ipc, raw, hdr.len)) {
free(raw);
return NULL;
}
raw[hdr.len] = 0;
struct json_object* response = json_tokener_parse(raw);
if (!response) {
fprintf(stderr, "Invalid IPC response\n");
}
free(raw);
return response;
}
/**
* Send command for specified application.
* @param ipc IPC context (socket file descriptor)
* @param app application Id
* @param command command to send
* @return true if operation completed successfully
*/
static bool ipc_command(int ipc, const char* app, const char* command)
{
bool rc = false;
char cmd[128];
snprintf(cmd, sizeof(cmd), "for_window [app_id=%s] %s", app, command);
json_object* response = ipc_message(ipc, IPC_COMMAND, cmd);
if (response) {
struct json_object* val = json_object_array_get_idx(response, 0);
if (val) {
rc = json_object_object_get_ex(val, "success", &val) &&
json_object_get_boolean(val);
}
if (!rc) {
fprintf(stderr, "Bad IPC response\n");
}
json_object_put(response);
}
return rc;
}
/**
* Read numeric value from JSON node.
* @param node JSON parent node
* @param name name of the rect node
* @param value value from JSON field
* @return true if operation completed successfully
*/
static bool read_int(json_object* node, const char* name, int* value)
{
struct json_object* val;
if (!json_object_object_get_ex(node, name, &val)) {
fprintf(stderr, "JSON scheme error: field %s not found\n", name);
return false;
}
*value = json_object_get_int(val);
if (*value == 0 && errno == EINVAL) {
fprintf(stderr, "JSON scheme error: field %s not a number\n", name);
return false;
}
return true;
}
/**
* Read rectange geometry from JSON node.
* @param node JSON parent node
* @param name name of the rect node
* @param rect rectangle geometry
* @return true if operation completed successfully
*/
static bool read_rect(json_object* node, const char* name, struct rect* rect)
{
int x, y, width, height;
struct json_object* rn;
if (!json_object_object_get_ex(node, name, &rn)) {
fprintf(stderr, "Failed to read rect: node %s not found\n", name);
return false;
}
if (read_int(rn, "x", &x) && read_int(rn, "y", &y) &&
read_int(rn, "width", &width) && width > 0 &&
read_int(rn, "height", &height) && height > 0) {
rect->x = (ssize_t)x;
rect->y = (ssize_t)y;
rect->width = (size_t)width;
rect->height = (size_t)height;
return true;
}
return false;
}
/**
* Get currently focused workspace.
* @param node parent JSON node
* @return pointer to focused workspace node or NULL if not found
*/
static struct json_object* current_workspace(json_object* node)
{
int idx = json_object_array_length(node);
while (--idx >= 0) {
struct json_object* focused;
struct json_object* wks = json_object_array_get_idx(node, idx);
if (json_object_object_get_ex(wks, "focused", &focused) &&
json_object_get_boolean(focused)) {
return wks;
}
}
return NULL;
}
/**
* Get currently focused window node.
* @param node parent JSON node
* @return pointer to focused window node or NULL if not found
*/
static struct json_object* current_window(json_object* node)
{
struct json_object* focused;
if (json_object_object_get_ex(node, "focused", &focused) &&
json_object_get_boolean(focused)) {
return node;
}
struct json_object* nodes;
if (json_object_object_get_ex(node, "nodes", &nodes)) {
int idx = json_object_array_length(nodes);
while (--idx >= 0) {
struct json_object* sub = json_object_array_get_idx(nodes, idx);
struct json_object* focus = current_window(sub);
if (focus) {
return focus;
}
}
}
return NULL;
}
int sway_connect(void)
{
struct sockaddr_un sa;
memset(&sa, 0, sizeof(sa));
const char* path = getenv("SWAYSOCK");
if (!path) {
fprintf(stderr, "SWAYSOCK variable is not defined\n");
return -1;
}
size_t len = strlen(path);
if (!len || len > sizeof(sa.sun_path)) {
fprintf(stderr, "Invalid SWAYSOCK variable\n");
return -1;
}
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
const int ec = errno;
fprintf(stderr, "Failed to create IPC socket: [%i] %s\n", ec,
strerror(ec));
return -1;
}
sa.sun_family = AF_UNIX;
memcpy(sa.sun_path, path, len);
len += sizeof(sa) - sizeof(sa.sun_path);
if (connect(fd, (struct sockaddr*)&sa, len) == -1) {
const int ec = errno;
fprintf(stderr, "Failed to connect IPC socket: [%i] %s\n", ec,
strerror(ec));
close(fd);
return -1;
}
return fd;
}
void sway_disconnect(int ipc)
{
close(ipc);
}
bool sway_current(int ipc, struct rect* wnd, bool* fullscreen)
{
bool rc = false;
// get currently focused window
json_object* tree = ipc_message(ipc, IPC_GET_TREE, NULL);
if (!tree) {
return false;
}
json_object* cur_wnd = current_window(tree);
if (!cur_wnd || !read_rect(cur_wnd, "window_rect", wnd)) {
goto done;
}
// get full screen mode flag
int fs_mode;
*fullscreen = read_int(cur_wnd, "fullscreen_mode", &fs_mode) && fs_mode;
if (*fullscreen) {
rc = true;
goto done;
}
// if we are not in the full screen mode - calculate client area offset
json_object* workspaces = ipc_message(ipc, IPC_GET_WORKSPACES, NULL);
if (!workspaces) {
goto done;
}
json_object* cur_wks = current_workspace(workspaces);
if (cur_wks) {
struct rect workspace;
struct rect global;
rc = read_rect(cur_wks, "rect", &workspace) &&
read_rect(cur_wnd, "rect", &global);
if (rc) {
wnd->x += global.x - workspace.x;
wnd->y += global.y - workspace.y;
}
}
json_object_put(workspaces);
done:
json_object_put(tree);
return rc;
}
bool sway_add_rules(int ipc, const char* app, int x, int y, bool absolute)
{
char move[64];
snprintf(move, sizeof(move), "move %s position %i %i",
absolute ? "absolute" : "", x, y);
return ipc_command(ipc, app, "floating enable") &&
ipc_command(ipc, app, move);
}
|
JavaScript
|
UTF-8
| 1,338 | 2.953125 | 3 |
[] |
no_license
|
//const request = require('postman-request');
const loginForm = document.getElementById('loginform');
const emailField = document.getElementById('username');
const passwordField = document.getElementById('password');
const messageOne = document.querySelector('#message-1');
const messageTwo = document.querySelector('#message-2');
window.localStorage.clear();
loginForm.addEventListener('submit',async (event)=>{
console.log(event)
event.preventDefault();
const emailValue = emailField.value;
const passwordValue = passwordField.value;
const userDetailsJson = { email : emailValue, password: passwordValue};
try{
fetch('/validateuser',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userDetailsJson)
}).then((response)=>{
response.json().then((data)=>{
if(data.status === 500){
messageOne.textContent = data.msg;
}else{
window.localStorage.clear();
window.localStorage.setItem("loggedInUser",JSON.stringify({'ID':data.ID,'NAME':data.NAME,'EMAIL':data.EMAIL}))
window.location.replace("/home");
}
})
});
}catch(error){
messageOne.textContent = "Username or password is wrong !!"
}
});
|
TypeScript
|
UTF-8
| 404 | 2.59375 | 3 |
[] |
no_license
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'trimCreditCard'
})
export class TrimCreditCardPipe implements PipeTransform {
transform(value: string, args?: string): string {
const prefix = value.substr(0, 3);
const subfix = value.substr(13, 15);
let data = '';
for (let i = 0; i < 10; i++) {
data += args;
}
return prefix + data + subfix;
}
}
|
Shell
|
UTF-8
| 178 | 2.75 | 3 |
[] |
no_license
|
#!/bin/bash
if [[ "$#" -ne 1 ]]
then
echo "usage: ./change_pass.sh <Proxy servicio autenticacion>"
else
./src/client.py --Ice.Config=config/Client.config "changepass" "$1"
fi
|
PHP
|
UTF-8
| 2,263 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Funivan\Cs\Console;
use Funivan\Cs\Configuration\ConfigurationInterface;
use Funivan\Cs\Configuration\CsConfiguration;
use Funivan\Cs\FileProcessor\FixerProcessor;
use Funivan\Cs\Report\Report;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Ivan Shcherbak <dev@funivan.com> 2016
*/
class FixCommand extends BaseCommand {
/**
* @inheritdoc
*/
protected function configure() {
$this->setName('fix');
$this->setDescription('Fix code according your code style');
$this->addOption('save', null, InputOption::VALUE_NONE, 'By default we will show info without code modification');
parent::configure();
}
/**
* @inheritdoc
*/
protected function getResultState(InputInterface $input, OutputInterface $output, Report $report) {
$isVerbose = ($output->getVerbosity() === OutputInterface::VERBOSITY_DEBUG);
if ($report->count() === 0) {
$output->writeln('<info>✔ Looking good</info>');
return 0;
}
$output->writeln('');
foreach ($report as $message) {
$output->write('<info>');
$output->writeln('file : ' . $message->getFile()->getPath() . ':' . $message->getLine());
$output->writeln('tool : ' . $message->getTool()->getName());
if ($isVerbose) {
$output->writeln('info : ' . $message->getTool()->getDescription());
}
$output->writeln('message : ' . $message->getText());
$output->writeln('</info>');
}
if ($input->getOption('save')) {
$output->writeln('<info>✔ Fixed</info>');
} else {
$output->writeln('<comment>✔ Dry run</comment>');
}
return 0;
}
/**
* @inheritdoc
*/
protected function getFileProcessor(InputInterface $input, OutputInterface $output) {
$fixer = new FixerProcessor();
$fixer->setSaveFiles($input->getOption('save'));
return $fixer;
}
/**
* @return ConfigurationInterface
*/
protected function getDefaultConfiguration() {
return CsConfiguration::createFixerConfiguration();
}
}
|
SQL
|
UTF-8
| 11,895 | 3.453125 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.7.6
-- https://www.phpmyadmin.net/
--
-- Hôte : localhost
-- Généré le : Dim 14 jan. 2018 à 19:10
-- Version du serveur : 10.1.29-MariaDB
-- Version de PHP : 7.2.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `piscine`
--
-- --------------------------------------------------------
--
-- Structure de la table `categorie`
--
CREATE TABLE `categorie` (
`CodeCategorie` int(11) NOT NULL,
`NomCategorie` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `concerner`
--
CREATE TABLE `concerner` (
`IdConcerner` int(11) NOT NULL,
`NumReservation` int(11) NOT NULL,
`NumJeux` int(11) NOT NULL,
`NumZone` int(11) NOT NULL,
`Nombre` int(11) DEFAULT NULL,
`Recu` tinyint(1) DEFAULT NULL,
`Retour` tinyint(1) DEFAULT NULL,
`don` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `contact`
--
CREATE TABLE `contact` (
`NumContact` int(11) NOT NULL,
`NomContact` varchar(255) DEFAULT NULL,
`PrenomContact` varchar(255) DEFAULT NULL,
`NumTelContact` varchar(255) DEFAULT NULL,
`MailContact` varchar(255) DEFAULT NULL,
`NumEditeur` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `editeur`
--
CREATE TABLE `editeur` (
`NumEditeur` int(11) NOT NULL,
`NomEditeur` varchar(255) DEFAULT NULL,
`VilleEditeur` varchar(255) DEFAULT NULL,
`RueEditeur` varchar(255) DEFAULT NULL,
`CodePostaleEditeur` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `editeur`
--
INSERT INTO `editeur` (`NumEditeur`, `NomEditeur`, `VilleEditeur`, `RueEditeur`, `CodePostaleEditeur`) VALUES
(1, 'nathan', 'sucy', 'carnot', '94370');
-- --------------------------------------------------------
--
-- Structure de la table `Festival`
--
CREATE TABLE `Festival` (
`AnneeFestival` int(11) NOT NULL,
`DateFestival` date DEFAULT NULL,
`NombreTables` int(11) DEFAULT NULL,
`PrixPlaceStandard` double DEFAULT NULL,
`Courant` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `Festival`
--
INSERT INTO `Festival` (`AnneeFestival`, `DateFestival`, `NombreTables`, `PrixPlaceStandard`, `Courant`) VALUES
(2015, '2018-01-23', 25, 263, 1),
(2016, '0000-00-00', 25, 23, 0);
-- --------------------------------------------------------
--
-- Structure de la table `jeux`
--
CREATE TABLE `jeux` (
`NumJeux` int(11) NOT NULL,
`FestivalJeux` int(11) DEFAULT NULL,
`NomJeux` varchar(255) DEFAULT NULL,
`NombreJoueur` int(11) DEFAULT NULL,
`DateSortie` date DEFAULT NULL,
`DureePartie` int(11) DEFAULT NULL,
`NumEditeur` int(11) NOT NULL,
`CodeCategorie` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `jeux`
--
INSERT INTO `jeux` (`NumJeux`, `FestivalJeux`, `NomJeux`, `NombreJoueur`, `DateSortie`, `DureePartie`, `NumEditeur`, `CodeCategorie`) VALUES
(1, 2015, 'de', 41, '2018-01-10', 41, 1, 4),
(2, 2015, 'ded', 45, '2018-01-11', 25, 1, 3),
(3, 2015, 'fr', 12, '2018-01-10', 23, 1, 3);
-- --------------------------------------------------------
--
-- Structure de la table `localiser`
--
CREATE TABLE `localiser` (
`IdLocaliser` int(11) NOT NULL,
`NumReservation` int(11) NOT NULL,
`NumZone` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `logement`
--
CREATE TABLE `logement` (
`NumLogement` int(11) NOT NULL,
`NomLogement` varchar(255) DEFAULT NULL,
`VilleLogement` varchar(255) DEFAULT NULL,
`RueLogement` varchar(255) DEFAULT NULL,
`CodePostaleLogement` varchar(255) DEFAULT NULL,
`NombreChambres` int(11) DEFAULT NULL,
`CoutLongementNuit` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `logement`
--
INSERT INTO `logement` (`NumLogement`, `NomLogement`, `VilleLogement`, `RueLogement`, `CodePostaleLogement`, `NombreChambres`, `CoutLongementNuit`) VALUES
(1, 'def', 'de', 'de', 'de', 15, 12),
(2, 's', 'cs', 'sc', 'sc', 14, 14),
(3, 'bonjour', 'sucy', 'dz', '6598', 2, 21);
-- --------------------------------------------------------
--
-- Structure de la table `loger`
--
CREATE TABLE `loger` (
`IdLoger` int(11) NOT NULL,
`NumLogement` int(11) NOT NULL,
`NumReservation` int(11) NOT NULL,
`PlacesFrais` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `organiser`
--
CREATE TABLE `organiser` (
`IdOrganiser` int(11) NOT NULL,
`NumZone` int(11) NOT NULL,
`CodeCategorie` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `regrouper`
--
CREATE TABLE `regrouper` (
`IdRegrouper` int(11) NOT NULL,
`NumEditeur` int(11) NOT NULL,
`NumZone` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `reservation`
--
CREATE TABLE `reservation` (
`NumReservation` int(11) NOT NULL,
`FestivalReservation` int(11) NOT NULL,
`NumEditeurReservation` int(11) NOT NULL,
`DateReservation` date DEFAULT NULL,
`Commentaire` char(255) DEFAULT NULL,
`PrixEspace` double DEFAULT NULL,
`Statut` bit(1) DEFAULT NULL,
`EtatFacture` bit(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `reservation`
--
INSERT INTO `reservation` (`NumReservation`, `FestivalReservation`, `NumEditeurReservation`, `DateReservation`, `Commentaire`, `PrixEspace`, `Statut`, `EtatFacture`) VALUES
(1, 2015, 0, '0000-00-00', '', 0, b'0', b'0'),
(2, 2015, 0, '0000-00-00', '', 0, b'1', b'0'),
(3, 2015, 0, '0000-00-00', '', 0, b'1', b'0'),
(4, 2015, 0, '0000-00-00', '', 0, b'1', b'0'),
(5, 2015, 1, '2018-01-18', '14', 14, b'1', b'0'),
(6, 2016, 1, '2018-01-18', 'fdfd', 25, b'1', b'1'),
(7, 2015, 1, '2018-01-11', 'xqxq', 25, b'1', b'1'),
(8, 2015, 1, '2018-01-18', 'sf', 25, b'1', b'1'),
(9, 2015, 1, '2018-01-18', 'assasa', 25, b'1', b'1'),
(10, 2015, 1, '2018-01-10', 'dzzdzd', 25, b'1', b'1'),
(11, 2015, 1, '2018-01-25', 'gukg', 52, b'1', b'1'),
(12, 2015, 1, '2018-01-25', 'wsh', 23, b'1', b'1');
-- --------------------------------------------------------
--
-- Structure de la table `suivi`
--
CREATE TABLE `suivi` (
`RefSuivi` int(11) NOT NULL,
`FestivalSuivi` int(11) NOT NULL,
`PremierContact` int(11) DEFAULT NULL,
`Relance` bit(1) DEFAULT NULL,
`Reponse` bit(1) DEFAULT NULL,
`NumEditeur` int(11) NOT NULL,
`AnneeSuivi` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `zone`
--
CREATE TABLE `zone` (
`NumZone` int(11) NOT NULL,
`NomZone` varchar(255) DEFAULT NULL,
`AnneeZone` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `categorie`
--
ALTER TABLE `categorie`
ADD PRIMARY KEY (`CodeCategorie`),
ADD UNIQUE KEY `CodeCategorie` (`CodeCategorie`);
--
-- Index pour la table `concerner`
--
ALTER TABLE `concerner`
ADD PRIMARY KEY (`IdConcerner`),
ADD UNIQUE KEY `IdConcerner` (`IdConcerner`),
ADD UNIQUE KEY `NumReservation` (`NumReservation`),
ADD UNIQUE KEY `NumJeux` (`NumJeux`);
--
-- Index pour la table `contact`
--
ALTER TABLE `contact`
ADD PRIMARY KEY (`NumContact`),
ADD UNIQUE KEY `NumContact` (`NumContact`);
--
-- Index pour la table `editeur`
--
ALTER TABLE `editeur`
ADD PRIMARY KEY (`NumEditeur`),
ADD UNIQUE KEY `NumEditeur` (`NumEditeur`);
--
-- Index pour la table `Festival`
--
ALTER TABLE `Festival`
ADD PRIMARY KEY (`AnneeFestival`),
ADD UNIQUE KEY `AnneeFestival` (`AnneeFestival`);
--
-- Index pour la table `jeux`
--
ALTER TABLE `jeux`
ADD PRIMARY KEY (`NumJeux`),
ADD UNIQUE KEY `NumJeux` (`NumJeux`);
--
-- Index pour la table `localiser`
--
ALTER TABLE `localiser`
ADD PRIMARY KEY (`IdLocaliser`),
ADD UNIQUE KEY `IdLocaliser` (`IdLocaliser`),
ADD UNIQUE KEY `NumReservation` (`NumReservation`),
ADD UNIQUE KEY `NumZone` (`NumZone`);
--
-- Index pour la table `logement`
--
ALTER TABLE `logement`
ADD PRIMARY KEY (`NumLogement`),
ADD UNIQUE KEY `NumLogement` (`NumLogement`);
--
-- Index pour la table `loger`
--
ALTER TABLE `loger`
ADD PRIMARY KEY (`IdLoger`),
ADD UNIQUE KEY `IdLoger` (`IdLoger`);
--
-- Index pour la table `organiser`
--
ALTER TABLE `organiser`
ADD PRIMARY KEY (`IdOrganiser`),
ADD UNIQUE KEY `IdOrganiser` (`IdOrganiser`),
ADD UNIQUE KEY `NumZone` (`NumZone`),
ADD UNIQUE KEY `CodeCategorie` (`CodeCategorie`);
--
-- Index pour la table `regrouper`
--
ALTER TABLE `regrouper`
ADD PRIMARY KEY (`IdRegrouper`),
ADD UNIQUE KEY `IdRegrouper` (`IdRegrouper`);
--
-- Index pour la table `reservation`
--
ALTER TABLE `reservation`
ADD PRIMARY KEY (`NumReservation`),
ADD UNIQUE KEY `NumReservation` (`NumReservation`);
--
-- Index pour la table `suivi`
--
ALTER TABLE `suivi`
ADD PRIMARY KEY (`RefSuivi`),
ADD UNIQUE KEY `RefSuivi` (`RefSuivi`);
--
-- Index pour la table `zone`
--
ALTER TABLE `zone`
ADD PRIMARY KEY (`NumZone`),
ADD UNIQUE KEY `NumZone` (`NumZone`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `categorie`
--
ALTER TABLE `categorie`
MODIFY `CodeCategorie` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `concerner`
--
ALTER TABLE `concerner`
MODIFY `IdConcerner` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `contact`
--
ALTER TABLE `contact`
MODIFY `NumContact` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `editeur`
--
ALTER TABLE `editeur`
MODIFY `NumEditeur` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT pour la table `jeux`
--
ALTER TABLE `jeux`
MODIFY `NumJeux` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `localiser`
--
ALTER TABLE `localiser`
MODIFY `IdLocaliser` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `logement`
--
ALTER TABLE `logement`
MODIFY `NumLogement` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `loger`
--
ALTER TABLE `loger`
MODIFY `IdLoger` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `organiser`
--
ALTER TABLE `organiser`
MODIFY `IdOrganiser` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `regrouper`
--
ALTER TABLE `regrouper`
MODIFY `IdRegrouper` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `reservation`
--
ALTER TABLE `reservation`
MODIFY `NumReservation` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT pour la table `suivi`
--
ALTER TABLE `suivi`
MODIFY `RefSuivi` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `zone`
--
ALTER TABLE `zone`
MODIFY `NumZone` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Ruby
|
UTF-8
| 2,264 | 3.328125 | 3 |
[] |
no_license
|
require 'world'
require 'cell'
require 'renderer/console'
require 'rules/conway'
class GolEngine
def initialize(options = {})
@renderer = get_renderer(options.fetch(:renderer, :console))
@width = options.fetch(:width, @renderer.width)
@height = options.fetch(:height, @renderer.height)
include_rule options.fetch(:rule, :conway)
@world = World.new(@width, @height)
@world.populate Cell.new
end
def read_pattern(file, translate_x = 0, translate_y = 0)
raise "The file #{file} does not exist!" unless File.exists? file
x = translate_x
y = translate_y
pattern = []
File.open(file, 'r') do |f|
f.each_line do |line|
line.strip.chars.each do |char|
pattern << [x, y] unless char.eql? '.'
x += 1
end
x = translate_x
y += 1
end
end
initial_pattern pattern
end
def initial_pattern(coordinates)
coordinates.each do |x, y|
cell = @world.get(x, y)
cell.state = :alive
end
end
def run(rounds)
render @world
rounds.times do
calculate_cycle
apply
render @world
end
@renderer.shutdown
end
private
def get_renderer(renderer)
get_constant(renderer, 'Renderer').new
end
def include_rule(rule)
rule_module = get_constant(rule, 'Rules')
extend rule_module
end
def get_constant(type, ns)
klazz = type.to_s.split('_').map{ |p| p.capitalize }.join
[ns, klazz].inject(Object) { |o, c| o.const_get c}
rescue
puts "Unknown constant #{ns}::#{klazz}. Try to include it before running the Game-of-Live-Engine."
exit
end
def calculate_cycle
neighbours = []
@world.each do |cell|
next if cell.is_dead?
calculate_cell cell
neighbours.concat cell.neighbours
end
neighbours.uniq.each do |c|
calculate_cell c
end
end
def calculate_cell(cell)
alive_neighbours = cell.neighbours.reduce(0) { |count, neighbour| count += 1 if neighbour.is_alive?; count }
execute_rule(cell, alive_neighbours)
end
def apply
@world.each do |cell|
cell.apply
end
end
def render(world)
@renderer.render world
end
end
|
Java
|
UTF-8
| 1,078 | 2.9375 | 3 |
[] |
no_license
|
package Dec25;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import java.nio.file.Paths;
public class Tanpopo extends ImageView {
static Image tanpopoImage = new
Image(Paths.get("images/tanpopo.png").toUri().toString());
static Image flowerImg = new
Image(Paths.get("images/flower.png").toUri().toString());
//x座標
int x=500;
int y=400;
//コンストラクタ
Tanpopo(){
super(tanpopoImage);
setTranslateY(y);
setTranslateX(x);
}
//moveメソッド ※矢印キー、スペースキーを調べて、タンポポを動かす
public void move(KeyCode key){
if(key==KeyCode.RIGHT&&x<770) x+=5;
if(key==KeyCode.LEFT&&x>-80) x-=5;
if(key==KeyCode.UP&&y>-770) y-=5;
if(key==KeyCode.DOWN&&y<400) y+=5;
setTranslateX(x);
setTranslateY(y);
}
public void changeImage( ){
if(getImage()==flowerImg) setImage(tanpopoImage);
else setImage(flowerImg);
}
}
|
Java
|
UTF-8
| 702 | 2.640625 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.ucundinamarca.figurasgeometricas;
/**
* Clase encargada de establecer la estructura que tendrán todas las figuras geométricas
* @author Miguel Ángel Manrique Téllez
* @since 1.0.0
* @version 1.0.0
*/
public abstract class FiguraGeometrica implements Informacion {
/**
* Retorna el área de la figura
* @return area
*/
public abstract float calcularArea();
/**
* Retorna el perímetro de la figura
* @return perimetro
*/
public abstract float calcularPerimetro();
}
|
Java
|
UTF-8
| 2,987 | 2.390625 | 2 |
[] |
no_license
|
package cs.uga.edu.finalproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
TextView welcomeText;
Button signoutButton;
Button shoppingListButton;
Button recentPurchase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
signoutButton = findViewById(R.id.signoutButton);
welcomeText = findViewById(R.id.welcomeText);
shoppingListButton = findViewById(R.id.shoppingListButton);
recentPurchase = findViewById(R.id.recentPurchaseButton);
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
// User is signed in
Log.d("Main", "onAuthStateChanged:signed_in:" + currentUser.getUid());
String username;
if(currentUser.getDisplayName() == null) {
Intent intent = getIntent();
username = intent.getStringExtra("username");
}
else
username = currentUser.getDisplayName();
//Gets the username before @ sign
welcomeText.setText("Welcome, " + username+ "!");
} else {
// User is signed out
Log.d("Main", "onAuthStateChanged:signed_out");
}
shoppingListButton.setOnClickListener(new ShoppingListButtonClickListener());
signoutButton.setOnClickListener(new SignoutButtonClickListener());
recentPurchase.setOnClickListener(new RecentlyPurchasedButtonClickListener());
}
private class SignoutButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
//Sign out
FirebaseAuth.getInstance().signOut();
Log.d("Main", "onAuthStateChanged:signed_out");
//Call next page
Intent intent = new Intent(MainActivity.this, SignoutActivity.class);
startActivity(intent);
}
}
private class RecentlyPurchasedButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RecentlyPurchasedActivity.class);
startActivity(intent);
}
}
private class ShoppingListButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ShoppingListActivity.class);
v.getContext().startActivity(intent);
}
}
}
|
Java
|
UTF-8
| 2,554 | 2.09375 | 2 |
[] |
no_license
|
package nvminecraftbros.minecraftaddons.rosegold.items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraftforge.registries.IForgeRegistry;
import nvminecraftbros.minecraftaddons.MinecraftAddonMod;
public class RoseGoldItems {
public static ItemBase rose_gold_ingot = new ItemBase("rose_gold_ingot");
public static ItemPickaxe rose_gold_pickaxe = new ItemPickaxe(MinecraftAddonMod.rosegoldmaterial, "rose_gold_pickaxe");
public static ItemSword rose_gold_sword = new ItemSword(MinecraftAddonMod.rosegoldmaterial, "rose_gold_sword");
public static ItemAxe rose_gold_axe = new ItemAxe(MinecraftAddonMod.rosegoldmaterial, "rose_gold_axe");
public static ItemShovel rose_gold_shovel = new ItemShovel(MinecraftAddonMod.rosegoldmaterial, "rose_gold_shovel");
public static ItemHoe rose_gold_hoe = new ItemHoe(MinecraftAddonMod.rosegoldmaterial, "rose_gold_hoe");
public static ItemArmor rose_gold_helmet = new ItemArmor(MinecraftAddonMod.rosegoldarmor, EntityEquipmentSlot.HEAD, "rose_gold_helmet");
public static ItemArmor rose_gold_chestplate = new ItemArmor(MinecraftAddonMod.rosegoldarmor, EntityEquipmentSlot.CHEST, "rose_gold_chestplate");
public static ItemArmor rose_gold_leggings = new ItemArmor(MinecraftAddonMod.rosegoldarmor, EntityEquipmentSlot.LEGS, "rose_gold_leggings");
public static ItemArmor rose_gold_boots = new ItemArmor(MinecraftAddonMod.rosegoldarmor, EntityEquipmentSlot.FEET, "rose_gold_boots");
public static void register(IForgeRegistry<Item> registry) {
registry.registerAll(rose_gold_ingot);
registry.registerAll(rose_gold_pickaxe);
registry.registerAll(rose_gold_sword);
registry.registerAll(rose_gold_axe);
registry.registerAll(rose_gold_shovel);
registry.registerAll(rose_gold_hoe);
registry.registerAll(rose_gold_helmet);
registry.registerAll(rose_gold_chestplate);
registry.registerAll(rose_gold_leggings);
registry.registerAll(rose_gold_boots);
}
public static void registerModels() {
rose_gold_ingot.registerItemModel();
rose_gold_pickaxe.registerItemModel(rose_gold_pickaxe);
rose_gold_sword.registerItemModel(rose_gold_sword);
rose_gold_axe.registerItemModel(rose_gold_axe);
rose_gold_shovel.registerItemModel(rose_gold_shovel);
rose_gold_hoe.registerItemModel(rose_gold_hoe);
rose_gold_helmet.registerItemModel(rose_gold_helmet);
rose_gold_chestplate.registerItemModel(rose_gold_chestplate);
rose_gold_leggings.registerItemModel(rose_gold_leggings);
rose_gold_boots.registerItemModel(rose_gold_boots);
}
}
|
Java
|
UTF-8
| 150 | 2.1875 | 2 |
[] |
no_license
|
public class Person {
int h;
int k;
public Person(int height, int peopleAhead)
{
h = height;
k = peopleAhead;
}
}
|
C++
|
UTF-8
| 1,692 | 3.15625 | 3 |
[] |
no_license
|
#include "string.h"
//#include <cstring>
void String::copy_from(const String& x)
{
if (x.sz <= short_max) {
memcpy(this, &x, sizeof(x));
ptr = ch;
}
else {
ptr = expand(x.ptr, x.sz+1);
sz = x.sz;
space = 0;
}
}
void String::move_from(String& x)
{
if (x.sz <= short_max) {
memcpy(this, &x, sizeof(x));
ptr = ch;
}
else {
ptr = x.ptr;
sz = x.sz;
space = x.space;
x.ptr = x.ch;
x.sz = 0;
x.ch[0] = 0;
}
}
String::String()
:sz{0}, ptr{ch}
{
ch[0] = 0;
}
String::String(const char* p):
sz{strlen(p)},
ptr{(sz<=short_max)?ch:new char[sz+1]},
space{0}
{
std::cout << "String(const char* p)\n";
strcpy(ptr, p);
}
String::String(const String& x)
{
std::cout << "String(const String& x)\n";
copy_from(x);
}
String::String(String&& x)
{
std::cout << "String(String&& x)\n";
move_from(x);
}
String& String::operator=(const String& x)
{
std::cout << "operator=(const String& x)\n";
if (this==&x) return *this;
char* p = (short_max<sz)?ptr:0;
copy_from(x);
delete[] p;
return *this;
}
String& String::operator=(String&& x)
{
std::cout << "operator=(String&& x)\n";
if (this==&x) return *this;
if (short_max<sz) delete[] ptr;
move_from(x);
return *this;
}
String& String::operator+=(char c)
{
if (sz == short_max) {
int n = sz+sz+2;
ptr = expand(ptr, n);
space = n-sz-2;
}
else if (short_max < sz) {
if (space == 0) {
int n = sz+sz+2;
char* p = expand(ptr, n);
delete[] ptr;
ptr = p;
space = n-sz-2;
}
else {
--space;
}
}
ptr[sz] = c;
ptr[++sz] = 0;
return *this;
}
|
Java
|
UTF-8
| 377 | 2.015625 | 2 |
[] |
no_license
|
package apache;
import org.apache.commons.io.FileUtils;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Collection;
/**
* Created by Administrator on 12/8/2016.
*/
public class FileUtilsTest {
@Test
public void testListFile() {
Collection collection = FileUtils.listFiles(new File("E:/tmp"), new String[]{"java"}, true);
}
}
|
Java
|
UTF-8
| 778 | 1.835938 | 2 |
[] |
no_license
|
package com.wyc.draw.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wyc.draw.domain.QuestionOption;
import com.wyc.draw.repositories.QuestionOptionRepository;
@Service
public class QuestionOptionService {
@Autowired
private QuestionOptionRepository questionOptionRepository;
public List<QuestionOption> findAllByQuestionId(String id) {
return questionOptionRepository.findAllByQuestionId(id);
}
public QuestionOption findOne(String optinId) {
return questionOptionRepository.findOne(optinId);
}
public List<QuestionOption> findAllByPaperIdOrderBySeqAsc(String paperId) {
return questionOptionRepository.findAllByPaperIdOrderBySeqAsc(paperId);
}
}
|
Python
|
UTF-8
| 5,527 | 3.46875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import numpy as np
"""
Created on Thu Feb 08 09:59:53 2018
@author: Pascal Raux
quicksave generates a formated str array from a list of variables and
saves this array inside a txt file (one column for each variable)
each variable in the array must be a one dimensional vector, of the same size
variables = [var1,var2,var3,var4,etc...] is an array of variables (each one is a list)
header=str, or list of str allow to add custom headers to the file
nosave allow to skip the saving in order to recover only the str array generated
column = False allow to create line arranged variable instead of column arranged variables
colwidth is the width of each column (without the delimiter)
floatfmt sets precision and format for float numbers as collength+fmt (default='16.5g')
alignment define how to aligne the variables ('<' left, '>' right or '^' center)
for format details see https://pyformat.info/ or https://docs.python.org/3/library/string.html#string-formatting
"""
def quicksave(variables, name='quicksave_TEMP', root='./', header=[], nosave=False, column=True,
colwidth=16, alignment='<', floatfmt='.5g', signed=' ', # format options
delimiter='\t'): # np.savetxt options
# define saving path:
if name[-4:]=='.txt': name=root+name
else: name=root+name+'.txt'
# determine data type:
datatype=[]
for variable in variables:
datatype.append(type(variable[0]))
# # initialize format for each variable
formatstr = []
for k, dtype in enumerate(datatype):
if np.issubdtype(dtype,str):
formatstr.append('{:'+alignment+str(colwidth)+'}')
elif np.issubdtype(dtype, int):
formatstr.append('{:'+alignment+signed+str(colwidth)+'d}') # ' ' signed, ie: ' ' for positive, '-' for negative
elif np.issubdtype(dtype, float):
formatstr.append('{:'+alignment+signed+str(colwidth)+floatfmt+'}')
else:
print("data type unsuported in quicksave: "+str(dtype)+
" in variable nb "+str(k)+"... -> replaced by float")
datatype[k] = float
formatstr.append('{:'+alignment+str(colwidth)+'}')
# define header if not given by user:
if not header:
headerstr=''
for k, dtype in enumerate(datatype):
headerfmt = '{:'+alignment+str(colwidth)+'}'
headerstr=headerstr+headerfmt.format(str(dtype)[6:-1]+' #'+str(k))+delimiter+' '
# elif type(header)==str: # if str, header is kept as defined by the user
elif type(header)==list: # expecting an array of str
headerstr=''
for string in header:
headerfmt = '{:'+alignment+str(colwidth)+'}'
headerstr=headerstr+headerfmt.format(string)+delimiter+' '
else:
headerstr=header
# initialize data array
savedata=np.empty((len(variables[0]),len(variables)), dtype='S'+str(colwidth))
for i, var in enumerate(variables):# assign each variable
for k in range(len(var)):
savedata[k,i] = formatstr[i].format(var[k])
if not column:
savedata = savedata.swapaxes(0,1) #linewise array
# save as string:
if not nosave:
np.savetxt(name, savedata, fmt='%s', delimiter=delimiter,
header= headerstr)
else:
return savedata
#%% example 1: basics
#data:
a,b,c,d = np.arange(1,4), np.arange(11,14), np.arange(21,24), np.arange(31,34)
#save it:
quicksave([a,b,c,d])
#returns the following table: (default is in ./quicksave_TEMP.txt)
# 'numpy.int32' #0 'numpy.int32' #1 'numpy.int32' #2 'numpy.int32' #3
# 1 11 21 31
# 2 12 22 32
# 3 13 23 33
# NB : for this simple task (always the same type of data), a simpler method is to use swapaxes:
#a,b,c,d = np.arange(1,4), np.arange(11,14), np.arange(21,24), np.arange(31,34)
#savedata=[a,b,c,d] # in lines
#savedata= np.swapaxes(savedata,0,1) # swap to columns
#np.savetxt(root+name,savedata, fmt='%-16s', delimiter='\t')
#%% example 2: various types
#data:
a= ['pommes', 'bananes', 'oranges']
b= [10, 20, 30]
c = [4.5, 2.5e2, 42]
#save it:
quicksave([a,b,c], header=['fruit','number (%)','price ($)'])
#returns the following table in ./quicksave_TEMP.txt:
## fruit name number (%) price ($)
#pommes 10 4.5
#bananes 20 250
#oranges 30 42
#%% example 3: change format
#save it:
quicksave([a,b,c], header=['fruit','nb (%)','price ($)'], alignment='^', colwidth=9)
# returns a centered table:
## fruit nb (%) price ($)
# pommes 1 4.5
# bananes 2 250
# oranges 3 -42
#
# recover the corresponding str array:
abc = quicksave([a,b,c], nosave=True, alignment='^', colwidth=9)
abc
#%% example 4: line display
a= ['pommes', 'bananes', 'oranges']
b= [1, 2, 3]
c = [4.5, 2.5e2, -42]
abc = quicksave([a,b,c], name='quicksave_myfavoritename', column=False, nosave = True, header='in lines: a then b and c')
#returns the following table in ./quicksave_myfavoritename.txt, with a line display:
## in line: a then b and c
#pommes 1 4.5
#bananes 2 250
#oranges 3 -42
|
C++
|
UTF-8
| 4,683 | 2.6875 | 3 |
[] |
no_license
|
//////////////////////////////////////////////////////////////////////////
// CachedParameterisation
// ======================
// High fidelity parameterised geometry in GEANT4 described by data
//
// Author: Christopher M Poole <mail@christopherpoole.net>
// Source: http://github.com/christopherpoole/CachedParameterisation
//
// License & Copyright
// ===================
//
// Copyright 2013 Christopher M Poole <mail@christopherpoole.net>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////////////
#ifndef Cache_h
#define Cache_h 1
// GEANT4 //
#include "globals.hh"
// USER //
#include "Helpers.hh"
template<class K, class V>
class CacheBase
{
public:
CacheBase(unsigned int max_size) {
this->max_size = max_size;
this->verbose = false;
index = new std::list<K>();
cache = new std::map<K, V>();
};
~CacheBase() {
delete index;
delete cache;
};
virtual void push(K key, V value) {
if (verbose)
G4cout << "Cache::push " << key << G4endl;
// Remove if K:V exists
pop(key);
// Put K:V at the top of the list
cache->insert(std::make_pair(key, value));
index->push_front(key);
// If the cache is oversize, remove the least used K:V
if (index->size() > max_size) {
pop(index->back());
}
};
virtual V pull(K key) {
if (verbose)
G4cout << "Cache::pull " << key << G4endl;
if (exists(key)) {
return cache->at(key);
} else {
return NULL;
}
};
virtual void pop(K key) {
if (verbose)
G4cout << "Cache::pop " << key << G4endl;
if (exists(key)) {
cache->erase(key);
index->remove(key);
}
};
bool exists(K key) {
if (verbose)
G4cout << "Cache::exists " << key << G4endl;
return cache->find(key) != cache->end();
};
void SetSize(unsigned int size) {
this->max_size = size;
};
void SetVerbosity(bool verbose) {
this->verbose = verbose;
}
protected:
unsigned int max_size;
bool verbose;
std::list<K>* index;
std::map<K, V>* cache;
};
#include <limits>
#include "CachedParameterisation.hh"
class Cache : public CacheBase<G4ThreeVector, CachedParameterisation*>
{
public:
Cache(unsigned int max_size, double threshold) : CacheBase(max_size) {
this->threshold = threshold;
};
CachedParameterisation* pull(G4ThreeVector key) {
G4ThreeVector nearest = nearest_key(key);
CachedParameterisation* param;
if (nearest == key) {
param = NULL;
} else {
param = CacheBase::pull(nearest);
}
return param;
};
G4ThreeVector nearest_key(G4ThreeVector key) {
// TODO: use a KD-tree instead of testing each key.
// Find the closest key that is within this->threshold
double distance = std::numeric_limits<double>::infinity();
G4ThreeVector nearest = G4ThreeVector();
for (std::list<G4ThreeVector>::iterator it=index->begin();
it!=index->end(); ++it) {
double d = (key - *it).mag();
if (d <= threshold) {
nearest = *it;
distance = d;
break;
}
}
if (distance <= threshold) {
return nearest;
} else {
return key;
}
};
void dump() {
for (std::list<G4ThreeVector>::iterator it=index->begin();
it!=index->end(); ++it) {
G4cout << "Entry: " << *it << G4endl;
CachedParameterisation* param = CacheBase::pull(*it);
for (unsigned int i=0; i<param->GetSize(); i++) {
G4cout << " " << param->GetPosition(i) << G4endl;
}
}
};
private:
double threshold;
};
#endif
|
PHP
|
UTF-8
| 892 | 2.671875 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace App\Library\Api\Request\Mapper;
use App\Library\Api\Exception\InvalidRequestException;
trait JsonRequestTrait
{
protected function validateContentType($contentType)
{
if (strtolower($contentType) !== 'application/json') {
throw new InvalidRequestException('Only application/json request is supported');
}
}
protected function bodyToArray($requestBody)
{
if ($requestBody) {
$array = json_decode($requestBody, true);
if (!$array) {
if (preg_replace('/[\s\n\r\t]+/', '', $requestBody) !== '{}') {
throw new InvalidRequestException('Malformed json request');
} else {
$array = [];
}
}
} else {
$array = [];
}
return $array;
}
}
|
Java
|
UTF-8
| 2,642 | 1.945313 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 1996-2014 FoxBPM ORG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author kenshin
*/
package org.foxbpm.engine.impl.task.cmd;
import org.foxbpm.engine.impl.entity.ProcessInstanceEntity;
import org.foxbpm.engine.impl.entity.TaskEntity;
import org.foxbpm.engine.impl.identity.Authentication;
import org.foxbpm.engine.impl.interceptor.CommandContext;
import org.foxbpm.engine.impl.task.command.SubmitTaskCommand;
import org.foxbpm.engine.task.TaskCommand;
import org.foxbpm.kernel.runtime.FlowNodeExecutionContext;
/**
* @author kenshin
*
*/
public class SubmitTaskCmd extends AbstractExpandTaskCmd<SubmitTaskCommand, Void> {
private static final long serialVersionUID = 1L;
public SubmitTaskCmd(SubmitTaskCommand abstractCustomExpandTaskCommand) {
super(abstractCustomExpandTaskCommand);
}
protected Void execute(CommandContext commandContext, TaskEntity task) {
if(this.initiator == null){
this.initiator = Authentication.getAuthenticatedUserId();
}
// 获取任务命令
TaskCommand taskCommand = getTaskCommand(task);
// 获取流程内容执行器
FlowNodeExecutionContext executionContext = getExecutionContext(task);
// 任务命令的执行表达式变量
taskCommand.getExpressionValue(executionContext);
// 设置任务处理者
task.setAssignee(Authentication.getAuthenticatedUserId());
// 设置任务上点击的处理命令
task.setCommandId(taskCommand.getId());
// 设置任务上点击的处理命令类型
task.setCommandType(taskCommand.getTaskCommandType());
// 设置任务上点击的处理命令文本
task.setCommandMessage(taskCommand.getName());
// 处理意见
task.setTaskComment(taskComment);
// 设置流程提交人
task.setProcessInitiator(this.initiator);
ProcessInstanceEntity processInstance = commandContext.getProcessInstanceManager().findProcessInstanceById(task.getProcessInstanceId());
if (businessKey != null) {
processInstance.setBizKey(this.businessKey);
}
if (initiator != null) {
processInstance.setInitiator(this.initiator);
}
task.complete();
return null;
}
}
|
Java
|
UTF-8
| 1,414 | 2.125 | 2 |
[
"MIT"
] |
permissive
|
package com.secure.secure_back_end.configuration.insert_on_startup;
import com.secure.secure_back_end.repositories.AuthorityRepository;
import com.secure.secure_back_end.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DemoData
{
private final static String PASSWORD_1234 = "$2a$10$N84ugQMjD25QvdyIOBWEpeZLAQOwzjFAQdaIGLQkQY.2JGIMr06C6";
private final AuthorityRepository authorityRepository;
private final UserRepository userRepository;
@Autowired
public DemoData(AuthorityRepository authorityRepository, UserRepository userRepository)
{
this.authorityRepository = authorityRepository;
this.userRepository = userRepository;
}
// @EventListener
// public void appReady(ApplicationReadyEvent event)
// {
// Set<Authority> authorities = new HashSet<>();
// authorities.add(new Authority("ROLE_SUBMITTER", 1));
// authorities.add(new Authority("ROLE_DEVELOPER", 2));
// authorities.add(new Authority("ROLE_PROJECT_MANAGER", 3));
// authorities.add(new Authority("ROLE_ADMIN", 4));
// this.authorityRepository.saveAll(authorities);
//
// Authority developer = this.authorityRepository.findById(2L).orElse(null);
//
// Set<User> users = new HashSet<>();
// users.add(new User("sasho", PASSWORD_1234, true, new Date()));
//
// }
}
|
C
|
UTF-8
| 401 | 3.703125 | 4 |
[] |
no_license
|
#include <stdio.h>
int main(int argc, char *argv[]){
printf("Command Line Arguments\n\n\n");
printf("Total no of arguments: %d\n\n", argc);
int i;
// We can use argv[1] to get entered words in command line and argv[0] is command to start program
printf("Arguments: \n");
for(i=0; i<argc; i++){
printf("%s\n", argv[i]);
}
return 0;
}
|
C#
|
UTF-8
| 1,678 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
using Loria.Core;
using Loria.Core.Actions.Activities;
using Loria.Core.Modules;
using System.Globalization;
namespace Loria.Modules.DateTime
{
public class DateTimeModule : Module, IActivity
{
public override string Name => "Date and time module";
public override string Description => "It allows me to give you current date and time";
public override string Keywords => "date time";
public string Action => "datetime";
public string[] SupportedIntents => new[] { DateIntent, TimeIntent };
public string[] Samples => new[]
{
"datetime date",
"datetime time"
};
public const string DateIntent = "date";
public const string TimeIntent = "time";
public DateTimeModule(Engine engine)
: base(engine)
{
}
public override void Configure()
{
// Nothing to configure yet
Activate();
}
public void Perform(ActivityCommand command, IModule sender)
{
switch (command.Intent)
{
case DateIntent:
var todayDate = System.DateTime.Now.ToString("D", CultureInfo.CurrentUICulture);
Engine.Propagator.PropagateMessenger(todayDate, sender);
break;
case TimeIntent:
var todayTime = System.DateTime.Now.ToString("t", CultureInfo.CurrentUICulture);
Engine.Propagator.PropagateMessenger(todayTime, sender);
break;
default:
break;
}
}
}
}
|
C++
|
UTF-8
| 2,299 | 2.96875 | 3 |
[] |
no_license
|
/**
* \file arch/semaphore.hpp
* \brief System-dependant Part of afl/sys/semaphore.cpp
*/
#ifndef AFL_ARCH_SEMAPHORE_HPP
#define AFL_ARCH_SEMAPHORE_HPP
#include "afl/sys/semaphore.hpp"
#if TARGET_OS_POSIX
/*
* POSIX
*/
# include <semaphore.h>
# include <time.h>
class afl::sys::Semaphore::Impl {
public:
Impl(int value)
{
sem_init(&m_sem, 0, value);
}
~Impl()
{
sem_destroy(&m_sem);
}
void post()
{
sem_post(&m_sem);
}
void wait()
{
sem_wait(&m_sem);
}
bool wait(Timeout_t t)
{
if (t == 0) {
return sem_trywait(&m_sem) == 0;
} else if (t == INFINITE_TIMEOUT) {
wait();
return true;
} else {
// Obtain the time (zero-initialize so it is not uninitialized if anything fails)
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 0;
clock_gettime(CLOCK_REALTIME, &ts);
// Add timeout. sem_timedwait wants an absolute timeout. D'ooh.
ts.tv_sec += t / 1000;
ts.tv_nsec += (t % 1000) * 1000000L;
if (ts.tv_nsec > 1000000000L) {
ts.tv_nsec -= 1000000000L;
++ts.tv_sec;
}
// Do it.
return sem_timedwait(&m_sem, &ts) == 0;
}
}
private:
sem_t m_sem;
};
#elif TARGET_OS_WIN32
/*
* Win32
*/
# include <windows.h>
class afl::sys::Semaphore::Impl {
public:
Impl(int value)
: m_hSem(CreateSemaphore(0, value, 0x7FFFFFFF, 0))
{
// FIXME: handle error return
}
~Impl()
{
CloseHandle(m_hSem);
}
void post()
{
ReleaseSemaphore(m_hSem, 1, 0);
}
void wait()
{
WaitForSingleObject(m_hSem, INFINITE);
}
bool wait(Timeout_t t)
{
DWORD timeout = (t == INFINITE_TIMEOUT ? INFINITE : t);
return WaitForSingleObject(m_hSem, timeout) == WAIT_OBJECT_0;
}
private:
HANDLE m_hSem;
};
#else
# error Teach me about semaphores
#endif
#endif
|
C++
|
UTF-8
| 3,103 | 2.546875 | 3 |
[] |
no_license
|
/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ROTE_BTAS_ELEMSCAL_HPP
#define ROTE_BTAS_ELEMSCAL_HPP
namespace rote{
////////////////////////////////////
// Workhorse routines
////////////////////////////////////
template<typename T>
inline void
ElemScal_fast(T const * const src1Buf, T const * const src2Buf, T * const dstBuf, const ElemScalData& data ){
const std::vector<Unsigned> loopEnd = data.loopShape;
const std::vector<Unsigned> src1BufStrides = data.src1Strides;
const std::vector<Unsigned> src2BufStrides = data.src2Strides;
const std::vector<Unsigned> dstBufStrides = data.dstStrides;
Unsigned src1BufPtr = 0;
Unsigned src2BufPtr = 0;
Unsigned dstBufPtr = 0;
Unsigned order = loopEnd.size();
Location curLoc(order, 0);
Unsigned ptr = 0;
if(loopEnd.size() == 0){
dstBuf[0] = src1Buf[0] * src2Buf[0];
return;
}
bool done = !ElemwiseLessThan(curLoc, loopEnd);
while(!done){
dstBuf[dstBufPtr] = src1Buf[src1BufPtr] * src2Buf[src2BufPtr];
//Update
curLoc[ptr]++;
dstBufPtr += dstBufStrides[ptr];
src1BufPtr += src1BufStrides[ptr];
src2BufPtr += src2BufStrides[ptr];
while(ptr < order && curLoc[ptr] >= loopEnd[ptr]){
curLoc[ptr] = 0;
dstBufPtr -= dstBufStrides[ptr] * (loopEnd[ptr]);
src1BufPtr -= src1BufStrides[ptr] * (loopEnd[ptr]);
src2BufPtr -= src2BufStrides[ptr] * (loopEnd[ptr]);
ptr++;
if(ptr >= order){
done = true;
break;
}else{
curLoc[ptr]++;
dstBufPtr += dstBufStrides[ptr];
src1BufPtr += src1BufStrides[ptr];
src2BufPtr += src2BufStrides[ptr];
}
}
if(done)
break;
ptr = 0;
}
}
////////////////////////////////////
// Local interfaces
////////////////////////////////////
//NOTE: Add checks for conforming shapes
//NOTE: Convert to incorporate blocked tensors.
template <typename T>
void ElemScal(const Tensor<T>& A, const Tensor<T>& B, Tensor<T>& C){
ElemScalData data;
data.loopShape = C.Shape();
data.src1Strides = A.Strides();
data.src2Strides = B.Strides();
data.dstStrides = C.Strides();
const T* src1Buf = A.LockedBuffer();
const T* src2Buf = B.LockedBuffer();
T* dstBuf = C.Buffer();
ElemScal_fast(src1Buf, src2Buf, dstBuf, data);
std::cout << "done\n";
}
////////////////////////////////////
// Global interfaces
////////////////////////////////////
//NOTE: Add checks for conforming dists and shapes
template<typename T>
void ElemScal(const DistTensor<T>& A, const DistTensor<T>& B, DistTensor<T>& C){
ElemScal(A.LockedTensor(), B.LockedTensor(), C.Tensor());
}
} // namespace rote
#endif // ifndef ROTE_BTAS_ELEMSCAL_HPP
|
PHP
|
UTF-8
| 649 | 3.46875 | 3 |
[] |
no_license
|
<?php
namespace Wordtest;
use Evenement\EventEmitterTrait;
/**
* Emit a 'sequence' event for every 4 letters
* in a given word when calling analyzeWord()
*/
class Sequencer {
use EventEmitterTrait;
/**
* Shoot off word in 4 letter groups
* If word length is less than 4 letters, skip
*/
public function analyzeWord($w) {
$len = strlen($w);
if ($len < 4) {
return;
}
//chop up word into 4 letter sequences
//start at the end and go backwards to reduce
//number of counter variables.
while ($len >=4) {
$seq = strtolower(substr( $w, ($len-4), 4));
$this->emit('sequence', array($seq, $w));
$len--;
}
}
}
|
Markdown
|
UTF-8
| 338 | 2.53125 | 3 |
[] |
no_license
|
# Structures
Cappuccino relies on what are known as `structures` to verify whether a member is allowed to use a certain command or not. If your server is registered, you can build your own structures. Otherwise, there are two base structures that Cappuccino comes with:
- ADM
- Member
## [ADM Docs](./adm.md)
## [Member Docs](./member.md)
|
C++
|
UTF-8
| 890 | 3.09375 | 3 |
[] |
no_license
|
#include <vector>
#include "data.h"
using namespace std;
Transaction::Transaction(const Transaction &tr)
{
length = tr.length;
t = new int[tr.length];
for(int i=0; i< length; i++) t[i] = tr.t[i];
}
Data::Data(char *filename)
{
fn = filename;
current=0;
in = fopen(fn,"rt");
}
Data::~Data()
{
if(in) fclose(in);
}
Transaction *Data::getNext()
{
vector<int> list;
char c;
// read row by row, push in list
do {
int item=0, pos=0;
c = getc(in);
while((c >= '0') && (c <= '9')) {
item *=10;
item += int(c)-int('0');
c = getc(in);
pos++;
}
if(pos) list.push_back(item);
}while(c != '\n' && !feof(in));
// if end of file is reached, rewind to beginning for next pass
if(feof(in)){
rewind(in);
return 0;
}
// put items in *t
Transaction *t = new Transaction(list.size());
for(int i=0; i<int(list.size()); i++)
t->t[i] = list[i];
return t;
}
|
Python
|
UTF-8
| 1,406 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
from unittest.mock import Mock, call
from pyviews.core.rendering import Node, NodeGlobals, RenderingContext
from pyviews.presenter import Presenter, PresenterNode, add_presenter_to_globals, add_reference, call_on_rendered
class TestPresenter(Presenter):
@property
def one(self):
return self._references['one']
class PresenterTests:
@staticmethod
def test_add_reference():
"""should add reference"""
presenter = TestPresenter()
node = Mock()
presenter.add_reference('one', node)
assert presenter.one == node
def test_add_presenter_to_globals():
"""should add presenter to node globals"""
presenter = Mock()
node = PresenterNode(presenter, Mock())
add_presenter_to_globals(node, RenderingContext())
assert node.node_globals['presenter'] == presenter
def test_call_on_rendered():
"""should call on_rendered method of presenter"""
presenter = Mock()
node = PresenterNode(presenter, Mock())
call_on_rendered(node, RenderingContext())
assert presenter.on_rendered.called
def test_add_reference():
"""should add reference to node to presenter by passed key"""
presenter = Mock(add_reference = Mock())
node = Node(Mock(), node_globals = NodeGlobals({'presenter': presenter}))
add_reference(node, '', 'key')
assert presenter.add_reference.call_args == call('key', node)
|
Markdown
|
UTF-8
| 642 | 2.515625 | 3 |
[] |
no_license
|
# spellCheck
Install python 3
Install virtual environemnt package
In ubuntu(linux) : sudo apt-get install python3-venv
Set up a virtual environment.
python3 -m venv DIR
source DIR/bin/activate
set DIR="venv"
This is to ensure that the following packages are available:
1. pandas
2. numpy
------
Python spell checker using a DP edit distance algo.
To run the recursive version:
python3 recursive_ed.py
To run the Top down version:
python3 topDown_ed.py
To run the Bottom up version:
python3 bottomUp_ed.py
To run all cases in the cases.csv file :
python3 exec.py
|
Java
|
UTF-8
| 350 | 1.960938 | 2 |
[] |
no_license
|
package com.futurehealth.repository;
import com.futurehealth.domain.Doctor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface DoctorRepository extends JpaRepository<Doctor, Long> {
Optional<Doctor> findByEmail(String email);
}
|
C++
|
UTF-8
| 3,055 | 2.671875 | 3 |
[] |
no_license
|
#ifndef VISITOR_TEST_HPP
#define VISITOR_TEST_HPP
#include "gtest/gtest.h"
#include "iterator.hpp"
#include "visitor.hpp"
#include "op.hpp"
#include "rand.hpp"
#include "mult.hpp"
#include "div.hpp"
#include "sub.hpp"
#include "pow.hpp"
#include "add.hpp"
#include "abs.hpp"
#include "trunc.hpp"
#include "paren.hpp"
#include "ceil.hpp"
#include "floor.hpp"
TEST(VisitorTest, singles) {
Base* o1 = new Op(1);
Base* o2 = new Op(1);
Base* r1 = new Rand();
Base* r2 = new Rand();
Base* a1 = new Add(1,1);
Base* s1 = new Sub(1,1);
Base* m1 = new Mult(1,11);
Base* d1 = new Div(1,1);
Base* p1 = new Pow(1,1);
CountVisitor* v = new CountVisitor();
o1->accept(v);
o2->accept(v);
r1->accept(v);
r2->accept(v);
a1->accept(v);
s1->accept(v);
m1->accept(v);
d1->accept(v);
p1->accept(v);
EXPECT_EQ(v->op_count(), 2);
EXPECT_EQ(v->rand_count(), 2);
EXPECT_EQ(v->add_count(), 1);
EXPECT_EQ(v->mult_count(), 1);
EXPECT_EQ(v->sub_count(), 1);
EXPECT_EQ(v->div_count(), 1);
EXPECT_EQ(v->pow_count(), 1);
}
TEST(VisitorTest, xpTree) {
Base* PnewA = new Paren(new Add(new Rand(),1.0));
Base* FCnewP = new Floor(new Ceil(new Pow(PnewA,2)));
Base* DnewS = new Abs(new Sub(FCnewP,190));
Base* DnewD = new Abs(new Div(4,-2));
Base* test = new Paren(new Trunc(new Mult(DnewS, DnewD)));
Iterator* it = new PreorderIterator(test);
CountVisitor* v = new CountVisitor();
it->first();
while(!it->is_done()){
Base* temp = it->current();
temp->accept(v);
it->next();
}
EXPECT_EQ(v->op_count(), 5);
EXPECT_EQ(v->rand_count(), 1);
EXPECT_EQ(v->add_count(), 1);
EXPECT_EQ(v->mult_count(), 1);
EXPECT_EQ(v->sub_count(), 1);
EXPECT_EQ(v->div_count(), 1);
EXPECT_EQ(v->pow_count(), 1);
EXPECT_EQ(v->ceil_count(), 1);
EXPECT_EQ(v->trunc_count(), 1);
EXPECT_EQ(v->paren_count(), 1);
EXPECT_EQ(v->floor_count(), 1);
EXPECT_EQ(v->abs_count(), 2);
}
TEST(VisitorTest, xpTree2) {
Base* CnewA = new Ceil(new Add(9.5,1.2));
Base* PTnewP = new Paren(new Trunc(new Pow(CnewA,2)));
Base* AnewS = new Abs(new Sub(PTnewP,190));
Base* FAnewD = new Floor(new Abs(new Div(4.5,-2.2)));
Base* test = new Paren(new Mult(AnewS, FAnewD));
Iterator* it = new PreorderIterator(test);
CountVisitor* v = new CountVisitor();
it->first();
while(!it->is_done()){
Base* temp = it->current();
temp->accept(v);
it->next();
}
EXPECT_EQ(test->evaluate(), 138);
EXPECT_EQ(test->stringify(), "((((121.000000) - 190.000000) * (4.500000 / -2.200000)))");
EXPECT_EQ(v->op_count(), 6);
EXPECT_EQ(v->rand_count(), 0);
EXPECT_EQ(v->add_count(), 1);
EXPECT_EQ(v->mult_count(), 1);
EXPECT_EQ(v->sub_count(), 1);
EXPECT_EQ(v->div_count(), 1);
EXPECT_EQ(v->pow_count(), 1);
EXPECT_EQ(v->ceil_count(), 1);
EXPECT_EQ(v->trunc_count(), 1);
EXPECT_EQ(v->paren_count(), 1);
EXPECT_EQ(v->floor_count(), 1);
EXPECT_EQ(v->abs_count(), 2);
}
#endif
|
Markdown
|
UTF-8
| 870 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
# Homework-3
## My Task
From the provided code I gathered that my task was to introduce logic that would make the website function as a random password generator. I must construct a code using javascript and Html to ask for prompts such as wheather or not the user wanted a password containing any upper case letters, special characters, or numbers. The provided code contained an event listener that would start the program.
## Logic
I wrote two functions that would first begin the code on a clickI and it began by applying prompts to gather string variables from the user. After gathering data, then a password is generated using if, else if, else. The logic would also alert the user when they entered something outside the parameters given. For instance the password must contain between 8 and 128 characters. Also they must enter 'y/Y' for yes and 'n/N' for no.
|
Java
|
UTF-8
| 16,118 | 2.015625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.schulcloud.mobile.data;
import android.util.Log;
import org.schulcloud.mobile.data.local.DatabaseHelper;
import org.schulcloud.mobile.data.local.PreferencesHelper;
import org.schulcloud.mobile.data.model.AccessToken;
import org.schulcloud.mobile.data.model.Contents;
import org.schulcloud.mobile.data.model.Course;
import org.schulcloud.mobile.data.model.CurrentUser;
import org.schulcloud.mobile.data.model.Device;
import org.schulcloud.mobile.data.model.Directory;
import org.schulcloud.mobile.data.model.Event;
import org.schulcloud.mobile.data.model.File;
import org.schulcloud.mobile.data.model.Homework;
import org.schulcloud.mobile.data.model.Submission;
import org.schulcloud.mobile.data.model.Topic;
import org.schulcloud.mobile.data.model.User;
import org.schulcloud.mobile.data.model.requestBodies.AddHomeworkRequest;
import org.schulcloud.mobile.data.model.requestBodies.CallbackRequest;
import org.schulcloud.mobile.data.model.requestBodies.Credentials;
import org.schulcloud.mobile.data.model.requestBodies.DeviceRequest;
import org.schulcloud.mobile.data.model.requestBodies.FeedbackRequest;
import org.schulcloud.mobile.data.model.requestBodies.SignedUrlRequest;
import org.schulcloud.mobile.data.model.responseBodies.AddHomeworkResponse;
import org.schulcloud.mobile.data.model.responseBodies.DeviceResponse;
import org.schulcloud.mobile.data.model.responseBodies.FeathersResponse;
import org.schulcloud.mobile.data.model.responseBodies.FeedbackResponse;
import org.schulcloud.mobile.data.model.responseBodies.FilesResponse;
import org.schulcloud.mobile.data.model.responseBodies.SignedUrlResponse;
import org.schulcloud.mobile.data.remote.RestService;
import org.schulcloud.mobile.util.crypt.JWTUtil;
import org.schulcloud.mobile.util.Pair;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Observable;
import rx.functions.Func1;
@Singleton
public class DataManager {
private final RestService mRestService;
private final DatabaseHelper mDatabaseHelper;
private final PreferencesHelper mPreferencesHelper;
@Inject
public DataManager(RestService restService, PreferencesHelper preferencesHelper,
DatabaseHelper databaseHelper) {
mRestService = restService;
mPreferencesHelper = preferencesHelper;
mDatabaseHelper = databaseHelper;
}
public PreferencesHelper getPreferencesHelper() {
return mPreferencesHelper;
}
/**** User ****/
public Observable<User> syncUsers() {
return mRestService.getUsers(getAccessToken())
.concatMap(new Func1<List<User>, Observable<User>>() {
@Override
public Observable<User> call(List<User> users) {
return mDatabaseHelper.setUsers(users);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<User>> getUsers() {
return mDatabaseHelper.getUsers().distinct();
}
public String getAccessToken() {
return mPreferencesHelper.getAccessToken();
}
public Observable<CurrentUser> signIn(String username, String password) {
return mRestService.signIn(new Credentials(username, password))
.concatMap(new Func1<AccessToken, Observable<CurrentUser>>() {
@Override
public Observable<CurrentUser> call(AccessToken accessToken) {
// save current user data
String jwt = mPreferencesHelper.saveAccessToken(accessToken);
String currentUser = JWTUtil.decodeToCurrentUser(jwt);
mPreferencesHelper.saveCurrentUserId(currentUser);
return syncCurrentUser(currentUser);
}
});
}
public void signOut() {
mDatabaseHelper.clearAll();
mPreferencesHelper.clear();
}
public Observable<CurrentUser> syncCurrentUser(String userId) {
return mRestService.getUser(getAccessToken(), userId).concatMap(new Func1<CurrentUser, Observable<CurrentUser>>() {
@Override
public Observable<CurrentUser> call(CurrentUser currentUser) {
mPreferencesHelper.saveCurrentUsername(currentUser.displayName);
mPreferencesHelper.saveCurrentSchoolId(currentUser.schoolId);
return mDatabaseHelper.setCurrentUser(currentUser);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<CurrentUser> getCurrentUser() {
return mDatabaseHelper.getCurrentUser().distinct();
}
public String getCurrentUserId() {
return mPreferencesHelper.getCurrentUserId();
}
/**** FileStorage ****/
public Observable<File> syncFiles(String path) {
return mRestService.getFiles(getAccessToken(), path)
.concatMap(new Func1<FilesResponse, Observable<File>>() {
@Override
public Observable<File> call(FilesResponse filesResponse) {
// clear old files
mDatabaseHelper.clearTable(File.class);
List<File> files = new ArrayList<>();
// set fullPath for every file
for (File file : filesResponse.files) {
file.fullPath = file.key.substring(0, file.key.lastIndexOf(java.io.File.separator));
files.add(file);
}
return mDatabaseHelper.setFiles(files);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<File>> getFiles() {
return mDatabaseHelper.getFiles().distinct().concatMap(files -> {
List<File> filteredFiles = new ArrayList<File>();
String currentContext = getCurrentStorageContext();
// remove last trailing slash
if (!currentContext.equals("/") && currentContext.endsWith("/")) {
currentContext = currentContext.substring(0, currentContext.length() - 1);
}
for (File f : files) {
if (f.fullPath.equals(currentContext)) filteredFiles.add(f);
}
return Observable.just(filteredFiles);
});
}
public Observable<Directory> syncDirectories(String path) {
return mRestService.getFiles(getAccessToken(), path)
.concatMap(new Func1<FilesResponse, Observable<Directory>>() {
@Override
public Observable<Directory> call(FilesResponse filesResponse) {
// clear old directories
mDatabaseHelper.clearTable(Directory.class);
List<Directory> improvedDirs = new ArrayList<Directory>();
for(Directory d : filesResponse.directories) {
d.path = getCurrentStorageContext();
improvedDirs.add(d);
}
return mDatabaseHelper.setDirectories(improvedDirs);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<Directory>> getDirectories() {
return mDatabaseHelper.getDirectories().distinct().concatMap(directories -> {
List<Directory> filteredDirectories = new ArrayList<Directory>();
for (Directory d : directories) {
if (d.path.equals(getCurrentStorageContext())) filteredDirectories.add(d);
}
return Observable.just(filteredDirectories);
});
}
public Observable<ResponseBody> deleteDirectory(String path) {
return mRestService.deleteDirectory(this.getAccessToken(), path);
}
public Observable<SignedUrlResponse> getFileUrl(SignedUrlRequest signedUrlRequest) {
return mRestService.generateSignedUrl(this.getAccessToken(), signedUrlRequest);
}
public Observable<ResponseBody> downloadFile(String url) {
return mRestService.downloadFile(url);
}
public Observable<ResponseBody> uploadFile(java.io.File file, SignedUrlResponse signedUrlResponse) {
RequestBody requestBody = RequestBody.create(MediaType.parse("file/*"), file);
return mRestService.uploadFile(
signedUrlResponse.url,
signedUrlResponse.header.getContentType(),
signedUrlResponse.header.getMetaPath(),
signedUrlResponse.header.getMetaName(),
signedUrlResponse.header.getMetaThumbnail(),
requestBody
);
}
public Observable<ResponseBody> deleteFile(String path) {
return mRestService.deleteFile(this.getAccessToken(), path);
}
public String getCurrentStorageContext() {
String storageContext = mPreferencesHelper.getCurrentStorageContext();
// personal files are default
return storageContext.equals("null") ? "users/" + this.getCurrentUserId() + "/" : storageContext + "/";
}
public void setCurrentStorageContext(String newStorageContext) {
mPreferencesHelper.saveCurrentStorageContext(newStorageContext);
}
/**** NotificationService ****/
public Observable<DeviceResponse> createDevice(DeviceRequest deviceRequest, String token) {
return mRestService.createDevice(
getAccessToken(),
deviceRequest)
.concatMap(new Func1<DeviceResponse, Observable<DeviceResponse>>() {
@Override
public Observable<DeviceResponse> call(DeviceResponse deviceResponse) {
Log.i("[DEVICE]", deviceResponse.id);
mPreferencesHelper.saveMessagingToken(token);
return Observable.just(deviceResponse);
}
});
}
public Observable<Device> syncDevices() {
return mRestService.getDevices(getAccessToken())
.concatMap(new Func1<List<Device>, Observable<Device>>() {
@Override
public Observable<Device> call(List<Device> devices) {
// clear old devices
mDatabaseHelper.clearTable(Device.class);
return mDatabaseHelper.setDevices(devices);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<Device>> getDevices() {
return mDatabaseHelper.getDevices().distinct();
}
public Observable<Response<Void>> sendCallback(CallbackRequest callbackRequest) {
return mRestService.sendCallback(getAccessToken(), callbackRequest);
}
public Observable<Response<Void>> deleteDevice(String deviceId) {
return mRestService.deleteDevice(getAccessToken(), deviceId);
}
/**** Events ****/
public Observable<Event> syncEvents() {
return mRestService.getEvents(
getAccessToken())
.concatMap(new Func1<List<Event>, Observable<Event>>() {
@Override
public Observable<Event> call(List<Event> events) {
// clear old events
mDatabaseHelper.clearTable(Event.class);
return mDatabaseHelper.setEvents(events);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<Event>> getEvents() {
return mDatabaseHelper.getEvents().distinct();
}
public List<Event> getEventsForDay() {
return mDatabaseHelper.getEventsForDay();
}
/**** Homework ****/
public Observable<Homework> syncHomework() {
return mRestService.getHomework(getAccessToken())
.concatMap(new Func1<List<Homework>, Observable<Homework>>() {
@Override
public Observable<Homework> call(List<Homework> homeworks) {
// clear old devices
mDatabaseHelper.clearTable(Homework.class);
return mDatabaseHelper.setHomework(homeworks);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<Homework>> getHomework() {
return mDatabaseHelper.getHomework().distinct();
}
public Homework getHomeworkForId(String homeworkId) {
return mDatabaseHelper.getHomeworkForId(homeworkId);
}
public Pair<String, String> getOpenHomeworks() {
return mDatabaseHelper.getOpenHomeworks();
}
public Observable<AddHomeworkResponse> addHomework(AddHomeworkRequest addHomeworkRequest) {
return mRestService.addHomework(getAccessToken(), addHomeworkRequest);
}
/**** Submissions ****/
public Observable<Submission> syncSubmissions() {
return mRestService.getSubmissions(getAccessToken())
.concatMap(new Func1<List<Submission>, Observable<Submission>>() {
@Override
public Observable<Submission> call(List<Submission> submissions) {
// clear old devices
mDatabaseHelper.clearTable(Submission.class);
return mDatabaseHelper.setSubmissions(submissions);
}
}).doOnError(Throwable::printStackTrace);
}
public Observable<List<Submission>> getSubmissions() {
return mDatabaseHelper.getSubmissions().distinct();
}
public Submission getSubmissionForId(String homeworkId) {
return mDatabaseHelper.getSubmissionForId(homeworkId);
}
/**** Courses ****/
public Observable<Course> syncCourses() {
return mRestService.getCourses(getAccessToken())
.concatMap(new Func1<FeathersResponse<Course>, Observable<Course>>() {
@Override
public Observable<Course> call(FeathersResponse<Course> courses) {
mDatabaseHelper.clearTable(Course.class);
return mDatabaseHelper.setCourses(courses.data);
}
})
.doOnError(Throwable::printStackTrace);
}
public Observable<List<Course>> getCourses() {
return mDatabaseHelper.getCourses().distinct();
}
public Course getCourseForId(String courseId) {
return mDatabaseHelper.getCourseForId(courseId);
}
/**** Topics ****/
public Observable<Topic> syncTopics(String courseId) {
return mRestService.getTopics(getAccessToken(), courseId)
.concatMap(new Func1<FeathersResponse<Topic>, Observable<Topic>>() {
@Override
public Observable<Topic> call(FeathersResponse<Topic> topics) {
mDatabaseHelper.clearTable(Topic.class);
return mDatabaseHelper.setTopics(topics.data);
}
})
.doOnError(Throwable::printStackTrace);
}
public Observable<List<Topic>> getTopics() {
return mDatabaseHelper.getTopics().distinct();
}
public List<Contents> getContents(String topicId) {
return mDatabaseHelper.getContents(topicId).contents;
}
/**** Feedback ****/
public Observable<FeedbackResponse> sendFeedback(FeedbackRequest feedbackRequest) {
return mRestService.sendFeedback(
getAccessToken(),
feedbackRequest)
.concatMap(new Func1<FeedbackResponse, Observable<FeedbackResponse>>() {
@Override
public Observable<FeedbackResponse> call(FeedbackResponse feedbackResponse) {
return Observable.just(feedbackResponse);
}
});
}
}
|
C++
|
UTF-8
| 1,518 | 2.578125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
template<typename T = int> vector<T> create(size_t n){ return vector<T>(n); }
template<typename T, typename... Args> auto create(size_t n, Args... args){ return vector<decltype(create<T>(args...))>(n, create<T>(args...)); }
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
for(int _ = 1; _ <= t; _++){
cout << "Case #" << _ << ":";
using ll = long long;
ll x, y;
cin >> y >> x;
int rx = 0, ry = 0;
if(x < 0) rx = 1, x = -x;
if(y < 0) ry = 1, y = -y;
if((x + y) % 2 == 0){
cout << " IMPOSSIBLE\n";
continue;
}
auto covers = [&](ll x, ll y, int b){
return abs(x) + abs(y) <= ((1ll<<(b + 1)) - 1);
};
string res;
for(int i = 0; i <= 40 && res.empty(); i++){
if(covers(x, y, i)){
for(int j = i; j >= 0; j--){
long long delta = 1ll<<j;
if(covers(x - delta, y, j - 1)){
x -= delta;
res.push_back('N');
} else if(covers(x + delta, y, j - 1)){
x += delta;
res.push_back('S');
} else if(covers(x, y - delta, j - 1)){
y -= delta;
res.push_back('E');
} else if(covers(x, y + delta, j - 1)){
y += delta;
res.push_back('W');
} else assert(0);
}
}
}
reverse(res.begin(), res.end());
if(rx){
for(auto & c : res){
if(c == 'N') c = 'S';
else if(c == 'S') c = 'N';
}
}
if(ry){
for(auto & c : res){
if(c == 'E') c = 'W';
else if(c == 'W') c = 'E';
}
}
cout << " " << res << '\n';
}
return 0;
}
|
PHP
|
UTF-8
| 2,939 | 2.625 | 3 |
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
<?php
namespace BackendBundle\Entity;
/**
* Presupuesto
*/
class Presupuesto
{
/**
* @var integer
*/
private $id;
/**
* @var \DateTime
*/
private $fechaIngreso;
/**
* @var float
*/
private $valor;
/**
* @var \DateTime
*/
private $fechaPago;
/**
* @var string
*/
private $item;
/**
* @var string
*/
private $comentario;
/**
* @var \BackendBundle\Entity\Empresa
*/
private $empresa;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fechaIngreso
*
* @param \DateTime $fechaIngreso
*
* @return Presupuesto
*/
public function setFechaIngreso($fechaIngreso)
{
$this->fechaIngreso = $fechaIngreso;
return $this;
}
/**
* Get fechaIngreso
*
* @return \DateTime
*/
public function getFechaIngreso()
{
return $this->fechaIngreso;
}
/**
* Set valor
*
* @param float $valor
*
* @return Presupuesto
*/
public function setValor($valor)
{
$this->valor = $valor;
return $this;
}
/**
* Get valor
*
* @return float
*/
public function getValor()
{
return $this->valor;
}
/**
* Set fechaPago
*
* @param \DateTime $fechaPago
*
* @return Presupuesto
*/
public function setFechaPago($fechaPago)
{
$this->fechaPago = $fechaPago;
return $this;
}
/**
* Get fechaPago
*
* @return \DateTime
*/
public function getFechaPago()
{
return $this->fechaPago;
}
/**
* Set item
*
* @param string $item
*
* @return Presupuesto
*/
public function setItem($item)
{
$this->item = $item;
return $this;
}
/**
* Get item
*
* @return string
*/
public function getItem()
{
return $this->item;
}
/**
* Set comentario
*
* @param string $comentario
*
* @return Presupuesto
*/
public function setComentario($comentario)
{
$this->comentario = $comentario;
return $this;
}
/**
* Get comentario
*
* @return string
*/
public function getComentario()
{
return $this->comentario;
}
/**
* Set empresa
*
* @param \BackendBundle\Entity\Empresa $empresa
*
* @return Presupuesto
*/
public function setEmpresa(\BackendBundle\Entity\Empresa $empresa = null)
{
$this->empresa = $empresa;
return $this;
}
/**
* Get empresa
*
* @return \BackendBundle\Entity\Empresa
*/
public function getEmpresa()
{
return $this->empresa;
}
}
|
Python
|
UTF-8
| 17,848 | 2.90625 | 3 |
[] |
no_license
|
from typing import Tuple, List, Dict, Set, Any
from functools import wraps
import re
from collections import Counter
import numpy as np
import pandas as pd
import torch
from sklearn.feature_extraction import stop_words
# Identify constants for vocabulary operations.
DELIMITERS = re.compile(r' |\\n|\|')
PUNCTUATION = re.compile(r'[.:;,?!\"|#()-_•]|^\'|\'$')
STOP_WORDS = stop_words.ENGLISH_STOP_WORDS
STOP_PATTERN = re.compile(r'http|www|^\s*$')
UNK = '<unk>'
PAD = '<pad>'
DEFAULT_KWARGS = {
'tokenize_pattern': DELIMITERS,
'clean_pattern': PUNCTUATION,
'stop_words': STOP_WORDS,
'drop_pattern': STOP_PATTERN
}
# Write a decorator to add default keyword arguments.
def include_default_kwargs(**default_kwargs):
def decorator(f):
@wraps(f)
def g(*args, **kwargs):
default_kwargs.update(kwargs)
return f(*args, **default_kwargs)
return g
return decorator
class TorchTextLike():
'''
Represent a label, sentence pair in a container that handles like an
Example object from the torchtext.data library. These attributes are
those expected in train_eval.py.
'''
# Identify the device on which to put tensors.
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def __init__(self, label: torch.Tensor, text: torch.Tensor):
self.label = label.to(device=TorchTextLike.DEVICE)
self.text = text.to(device=TorchTextLike.DEVICE)
def get_labels_and_corpus(
data: pd.DataFrame,
idx_labels: int,
idx_corpus: List[int],
label_target: Any = None,
labels_other: List[Any] = None,
silent: bool = False
) -> Tuple[np.ndarray, np.ndarray]:
'''
Extract the labels and corpus identified in a dataframe. Concatenate the
columns given for the corpus, keep only observations with select labels if
any indicated, and binarize on the target label.
data (pd.DataFrame): original data to parse.
idx_labels (int): index at which to find labels.
idx_corpus (list of ints): indices at which to find the corpus.
label_target (Any): the positive class on which to binarize labels.
labels_other (list of Any): any other classes to include with labels.
Return labels and corpus (tuple of np.ndarray).
'''
# Identify observations that belong to either the target or other classes.
if labels_other:
keep = [label_target] + labels_other if label_target else labels_other
idx_keep = data.index[data.iloc[:, idx_labels].isin(keep)]
else:
idx_keep = np.arange(data.shape[0])
# Extract the labels and corpus from the data.
labels = data.iloc[idx_keep, idx_labels]
corpus = data.iloc[idx_keep, idx_corpus]
# Concatenate text features in the corpus.
if len(idx_corpus) > 1:
corpus = corpus.astype(str).agg(' '.join, axis=1)
# Binarize on the target label if requested.
if label_target:
labels = labels.apply(lambda y: 1 if y == label_target else 0)
# Report on the data.
if not silent:
__show_label_stats(labels)
# Return the labels and corpus.
return labels.to_numpy(), corpus.to_numpy()
@include_default_kwargs(**DEFAULT_KWARGS)
def get_vocab_and_batches(
labels: np.ndarray,
corpus: np.ndarray,
splits: Tuple[float, float, float],
ngram_size: int,
vocab_size: int,
batch_size: int,
cbow: bool = False,
silent: bool = False,
**kwargs: dict
) -> Tuple[Tuple[Dict[str, int], Dict[int, str]], List[List[TorchTextLike]]]:
'''
Preprocess the data for modeling with a neural network. Split the data into
training, validation, and testing sets; get the vocabulary of n-grams from
the training set; get batches of sentence vectors in each set, represented
as either simple padded numericizations or continuous bags of words.
labels (np.ndarray): 1-d array of labels.
corpus (np.ndarray): 1-d array of sentences to parse.
splits (tuple of floats): proportional allocations of each respective set.
ngram_size (int): length of n-gram, i.e. number of words in one token.
vocab_size (int): number of most frequent words to keep.
batch_size (int): number of sentences with each batch.
cbow (bool): whether to represent sentences as continuous bags of words.
kwargs (dict): keyword arguments to pass to __make_sentence().
Return vocab (tuple of dicts), batches (list of lists of TorchTextLike).
'''
# Split the data into training, validation, and testing sets.
datasets = get_splits(labels, corpus, splits)
# Get the vocabulary from the training set.
_, train_corpus = datasets[0]
vocab = get_vocab(train_corpus, ngram_size, vocab_size, **kwargs)
# Get batches for each dataset.
dataset_batches = []
for labels, corpus in datasets:
batches = get_batches(
vocab[0], labels, corpus, ngram_size, batch_size, cbow, **kwargs)
dataset_batches.append(batches)
# Report on the vocabulary and batches.
if not silent:
__show_vocab_stats(vocab[0])
__show_batch_stats(dataset_batches)
# Return the vocabulary and batches.
return vocab, dataset_batches
def get_splits(
labels: np.ndarray,
corpus: np.ndarray,
splits: Tuple[float]
) -> List[Tuple[np.ndarray, np.ndarray]]:
'''
Split the data into training, validation, and testing sets.
labels, corpus (np.ndarray): data to split.
splits (tuple of floats): proportional allocations of each respective set.
Return training, validation, testing sets (list of tuples of np.ndarray).
'''
datasets = []
# Ensure the size of the labels and corpus match.
len_corpus = corpus.shape[0]
assert labels.shape[0] == corpus.shape[0]
# Slice and copy the data with indices that allocate each set exclusively.
for idx in __make_splits(len_corpus, *splits):
dataset = np.copy(labels[idx]), np.copy(corpus[idx])
datasets.append(dataset)
# Return the training, validation, testing sets.
return datasets
@include_default_kwargs(**DEFAULT_KWARGS)
def get_vocab(
corpus: np.ndarray,
n: int,
k: int,
**kwargs: dict
) -> Tuple[Dict[str, int], Dict[int, str]]:
'''
Get the k most frequent words in the vocabulary of n-grams as mappings of
words to indices and indices to words.
corpus (np.ndarray): 1-d array of sentences to parse.
n (int): length of n-gram, i.e. number of words to represent with one token.
k (int): number of most frequent words to keep.
kwargs (dict): keyword arguments to pass to __make_sentence().
Return mappings of the vocabulary (tuple of dicts).
'''
# Collect the vocabulary in the corpus.
vocab = __make_vocab(corpus, n, **kwargs)
# Collect the mapping of the k most frequent words to their indices.
word_to_idx = __make_index(vocab, k)
idx_to_word = {i: w for w, i in word_to_idx.items()}
return word_to_idx, idx_to_word
@include_default_kwargs(**DEFAULT_KWARGS)
def get_batches(
vocab: Dict[str, int],
labels: np.ndarray,
corpus: np.ndarray,
n: int,
k: int,
cbow: bool = False,
**kwargs: dict
) -> List[TorchTextLike]:
'''
Get k batches of sentences in the corpus as their vector representations,
either simple padded numericizations or continuous bags of words.
vocab (dict): mapping of words to indices.
labels (np.ndarray): 1-d array of labels.
corpus (np.ndarray): 1-d array of sentences to parse.
n (int): length of n-gram, i.e. number of words to represent with one token.
k (int): number of sentences with each batch.
cbow (bool): whether to represent sentences as continuous bags of words.
kwargs (dict): keyword arguments to pass to get_vectorization().
Return batches of label, sentence pairs (list of tuples).
'''
batches = []
# Ensure the size of the labels and corpus match.
len_corpus = corpus.shape[0]
assert len_corpus == labels.shape[0]
# Vectorize sentences.
sentences = [
__make_vector(vocab, corpus[idx], n, cbow, **kwargs)
for idx in range(len_corpus)
]
# Sort sentences by length, descending, to minimize padding in each batch.
sentences.sort(key=lambda x: x.shape[0], reverse=True)
# Get the type of which to make the batches; embeddings require long type.
dtype = torch.float if cbow else torch.long
# Calculate the number of batches to create.
len_batches = (len_corpus + k - 1) // k
# Create each batch.
for i in range(len_batches):
# Identify the indices in the data that correspond to this batch.
idx_min = i * k
idx_max = min(idx_min + k, len_corpus)
# Batch sentences and labels.
batch_X = __make_batch(sentences[idx_min:idx_max], vocab[UNK], dtype)
batch_y = torch.as_tensor(
labels[idx_min:idx_max], dtype=torch.float).squeeze()
# Ensure the text and label tensors have the same length.
assert batch_X.shape[1] == batch_y.shape[0]
# Include this batch with all batches.
batches.append(TorchTextLike(batch_y, batch_X))
# Return the batches.
return batches
def __make_splits(
n: int,
train: float,
valid: float,
test: float
) -> Tuple[np.ndarray]:
'''
Get the indices that proportionally allocate training, validation, and
testing sets.
n (int): length of the data.
train, valid, test (float): proportional allocations of each respective set.
Return indices of each split (tuple of np.ndarray).
'''
# Ensure the proportions sum to one.
assert sum([train, valid, test]) == 1
# Allocate a random permutation of row indices proportionally.
idx = np.random.permutation(n)
idx_train = idx[:int(n * train)]
idx_valid = idx[int(n * train):int(n * (train + valid))]
idx_testg = idx[int(n * (train + valid)):]
# Return the subsets of data.
return idx_train, idx_valid, idx_testg
def __make_vocab(
corpus: np.ndarray,
n: int,
**kwargs: dict
) -> Dict[str, int]:
'''
Collect the vocabulary in the corpus and tally the frequency of each word.
Identify words on the delimiter and clean them with a regular expression.
corpus (np.ndarray): 1-d array of sentences to parse.
n (int): length of n-gram, i.e. number of words to represent with one token.
kwargs (dict): keyword arguments to pass to __make_sentence().
Return mapping of words to frequencies (dict).
'''
vocab = {}
# Consider each sentence in the corpus.
for sentence in corpus:
# Preprocess the sentence, i.e. tokenize, clean, drop, pad.
sentence = __make_sentence(sentence, n, **kwargs)
# Consider each word, or possibly n-gram, in the sentence.
for w in range(len(sentence) - n):
# Collect this word or n-gram.
word = ' '.join(sentence[w:w + n])
# Update the frequency of this word or n-gram in the vocabulary.
if word not in vocab:
vocab[word] = 0
vocab[word] += 1
# Return the mapping of words to frequencies.
return vocab
def __make_sentence(
sentence: str,
n: int,
tokenize_pattern: re.Pattern = DELIMITERS,
clean_pattern: re.Pattern = PUNCTUATION,
stop_words: Set[str] = STOP_WORDS,
drop_pattern: re.Pattern = STOP_PATTERN
) -> List[str]:
'''
Preprocess the sentence by tokenizing, cleaning, dropping stop words, and
including any padding.
sentence (str): collection of words to process.
n (int): length of n-gram, i.e. number of words to represent with one token.
tokenize_pattern (re.Pattern): regular expression for delimiters.
clean_pattern (re.Pattern): regular expression for substrings to remove.
stop_words (set): words to remove, i.e. articles, prepositions.
drop_pattern (re.Pattern): regular expression for words to remove.
Return processed sentence (list).
'''
# Tokenize the sentence on the delimiter.
sentence = __tokenize_words(sentence, tokenize_pattern)
# Clean words in the sentence.
sentence = [__clean_words(word, clean_pattern) for word in sentence]
# Drop any stop words in the sentence.
sentence = __drop_words(sentence, stop_words, drop_pattern)
# Pad both sides of the sentence.
sentence = [PAD] * (n - 1) + sentence + [PAD] * (n - 1)
# Return the sentence.
return sentence
def __tokenize_words(text: str, pattern: re.Pattern) -> List[str]:
'''
Tokenize text on the delimiter.
text (str): collection of characters to tokenize.
pattern (re.Pattern): regular expression for delimiters.
Return tokenized text (list).
'''
return re.split(pattern, text)
def __clean_words(text: str, pattern: re.Pattern) -> str:
'''
Clean text of substrings.
text (str): collection of characters to clean.
pattern (re.Pattern): regular expression for substrings to remove.
Return cleaned text (str).
'''
return re.sub(pattern, '', text.lower())
def __drop_words(
words: List[str],
stop_words: Set[str],
pattern: re.Pattern
) -> List[str]:
'''
Remove words that are among the stop words or match a regular expression.
words (list): collection of words, i.e. a sentence.
stop_words (set): words to remove.
pattern (re.Pattern): regular expression for words to remove.
Return words (list).
'''
return [
word for word in words
if word not in stop_words and not re.search(pattern, word)
]
def __make_index(vocab: Dict[str, int], k: int) -> Dict[str, int]:
'''
Collect indices for the k most frequent words in the vocabulary. Include
tokens for unknown words and padding.
vocab (dict): mapping of words to frequencies.
k (int): number of most frequent words to keep.
Return mapping of most frequent words to indices (dict).
'''
# Collect most the frequent words into a set.
vocab = {word for word, _ in Counter(vocab).most_common(k)}
# Include tokens for unknown words and padding.
vocab.update([UNK, PAD])
# Return the mapping of words to indices.
return {word: i for i, word in enumerate(vocab)}
def __make_numeric(
vocab: Dict[str, int],
sentence: str,
n: int,
**kwargs: dict
) -> List[int]:
'''
Represent each word in the sentence with its index in the vocabulary.
vocab (dict): mapping of words to indices.
sentence (str): collection of words to process.
n (int): length of n-gram, i.e. number of words to represent with one token.
kwargs (dict): keyword arguments to pass to __make_sentence().
Return the numericized sentence (list).
'''
new_sentence = []
# Preprocess the sentence, i.e. tokenize, clean, drop, pad.
sentence = __make_sentence(sentence, n, **kwargs)
# Consider each word, or possibly n-gram, in the sentence.
for w in range(len(sentence) - n):
# Collect this word or n-gram.
word = ' '.join(sentence[w:w + n])
# Add the index of this word or n-gram to the new sentence.
new_sentence.append(vocab.get(word, vocab[UNK]))
# Return the numericized sentence.
return new_sentence
def __make_vector(
vocab: Dict[str, int],
sentence: str,
n: int,
cbow: bool,
**kwargs: dict
) -> torch.Tensor:
'''
Map words in a sentence to their indices in the vocabulary into either a
simple numericization or a continuous bag of words.
vocab (dict): mapping of words to indices.
sentence (str): collection of words to process.
n (int): length of n-gram, i.e. number of words to represent with one token.
cbow (bool): whether to represent the sentence as a continuous bag of words.
kwargs (dict): keyword arguments to pass to __make_sentence().
Return the vectorization (torch.Tensor)
'''
# Numericize the sentence.
sentence = __make_numeric(vocab, sentence, n, **kwargs)
# Return the continuous bag of words.
if cbow:
# Count each word in the vocabulary that appears in the sentence.
bag = torch.zeros(len(vocab))
for idx in sentence:
bag[idx] += 1
return bag
# Return the simple numericization otherwise.
return torch.as_tensor(sentence)
def __make_batch(
sentences: List[torch.Tensor],
idx_padding: int,
dtype: type
) -> torch.Tensor:
'''
Collect sentences into a batch with the length of the longest sentence.
sentences (list): vectorized sentences sorted by length, descending.
idx_padding (int): default value that pads shorter sentences.
dtype (type): type of the values in the batch.
Return the batch (torch.Tensor)
'''
# Initialize the batch; sentences are sorted, so the first is the longest.
p = sentences[0].shape[0]
q = len(sentences)
batch = torch.full(size=(p, q), fill_value=idx_padding, dtype=dtype)
# Load the batch with each sentence; unfilled cells have the padding value.
for i, sentence in enumerate(sentences):
batch[:sentence.shape[0], i] = sentence
# Return the batch of sentences.
return batch
def __show_label_stats(labels: np.ndarray) -> None:
n = labels.shape[0]
baseline = labels[labels == 1].shape[0] / n * 100
print('Size of these data: %d' % n)
print('Baseline precision: %7.4f' % baseline)
def __show_vocab_stats(vocab: Dict[str, int]) -> None:
n = len(vocab)
print('Size of the vocabulary: %d' % n)
def __show_batch_stats(dataset_batches: List[List[TorchTextLike]]) -> None:
labels = ['training', 'validation', 'testing']
for i, label in enumerate(labels):
n = sum(batch.text.shape[1] for batch in dataset_batches[i])
print('Size of the %s data: %d' % (label, n))
|
C#
|
UTF-8
| 7,119 | 2.59375 | 3 |
[] |
no_license
|
using System;
using UnityEngine;
using static SimpleDice.Utils.SimpleDiceUtils;
namespace SimpleDice
{
public struct Face
{
public Face(int id, string value, Vector3 orientation)
{
faceID = id;
faceValue = value;
faceOrientation = orientation;
}
public int faceID { get; }
public string faceValue { get; }
public Vector3 faceOrientation { get; }
}
// All dice must have rigidbodies to be usable
[RequireComponent(typeof(Rigidbody))]
public abstract class Die : MonoBehaviour
{
protected Face[] dieFaces;
// User Inputs
[SerializeField] protected float allowedSlant;
public bool showRotationGizmos;
public bool showStateGizmos;
public static string faceValueWhenInvalid = "Invalid";
// Set up an immutable value for invalid faces, based on user input
[HideInInspector] public readonly Face invalidFace = new Face(0, faceValueWhenInvalid, new Vector3(0, 0, 0));
[HideInInspector] public bool selected;
// Let only this class change the rolled face, but anyone access it
protected Face _faceRolled;
[HideInInspector] public Face faceRolled
{
get { return _faceRolled; }
}
public bool rolledFaceValid
{
get
{
return _faceRolled.faceValue != Die.faceValueWhenInvalid;
}
}
protected Rigidbody _rb;
private bool _wasRBSleepingLastTick = false;
// Events broadcast by Die
public event EventHandler<Face> DieStopped;
public event EventHandler<Face> DieStarted;
// Start is called before the first frame update
void Start()
{
}
void FixedUpdate()
{
ManageRBSleep();
}
private void ManageRBSleep()
{
// Makes up for lack of events in Unity when RigidBodies start and stop sleeping
// If this is the first tick after the die's rigidbody started sleeping
if (!_wasRBSleepingLastTick && _rb.IsSleeping())
{
_wasRBSleepingLastTick = true;
OnDieRBSleep();
}
// If this is the first tick after the rigidbody stopped sleeping
else if (_wasRBSleepingLastTick && !_rb.IsSleeping())
{
_wasRBSleepingLastTick = false;
OnDieRBAwaken();
}
}
protected void OnDieRBSleep()
{
// First tick after the Rigidbody starts sleeping
// Not actually an event
_faceRolled = DetectRolledFace();
// Invoke the event DieStopped if it's not null, and send all subscribers the current value of the die
DieStopped?.Invoke(this, _faceRolled);
}
protected void OnDieRBAwaken()
{
// First tick after the Rigidbody stops sleeping
// Not actually an event
// Invoke the event DieStarted if it's not null
DieStarted?.Invoke(this, _faceRolled);
// Set the face value to default
_faceRolled = invalidFace;
}
public virtual void SelectDie()
{
//Debug.Log(transform.rotation.eulerAngles);
Debug.Log(transform.rotation);
selected = true;
}
public virtual void UnselectDie()
{
selected = false;
}
protected virtual Face DetectRolledFace()
{
Vector3 eulers = transform.rotation.eulerAngles;
// Check every face
foreach(Face face in dieFaces)
{
// Check rotations about the X and Z axis only. Y-rotation doesn't change the result
// AngleWithinError is a utility function
if(VectorWithinError(transform.TransformDirection(face.faceOrientation), Vector3.up, allowedSlant))
{
return face;
}
}
// If none of the faces match the current die rotation, it's invalid
return invalidFace;
}
public void RollDie(Vector3 velocity, Vector3 angularVelocity)
{
//If the die was selected before rolling, we now unselect it
UnselectDie();
_rb.velocity = velocity;
_rb.angularVelocity = angularVelocity;
}
public void RollDie()
{
// Velocity
float baseUpVelocity = 5;
float extraUpVelocityMax = 2;
Vector3 velocity = Vector3.up * (baseUpVelocity + UnityEngine.Random.Range(0, extraUpVelocityMax))
+ transform.TransformDirection(Vector3.right) * RandomFloatRandomSign(0.1f, 0.2f)
+ transform.TransformDirection(Vector3.forward) * RandomFloatRandomSign(0.1f, 0.2f);
// Angular Velocity
// Decide how much the die rotates around each axis proportionately
Vector3 angularVelocityAxis =
(transform.TransformDirection(Vector3.right) * RandomFloatRandomSign(0.5f, 1)
+ (transform.TransformDirection(Vector3.back) * RandomFloatRandomSign(0.5f, 1))
+ (transform.TransformDirection(Vector3.up) * RandomFloatRandomSign(0.5f, 1)));
//Normalize and multiply with a scalar to always get a similar speed of rotation, just in slightly different directions
angularVelocityAxis.Normalize();
float angularVelocityScalar = UnityEngine.Random.Range(5, 20);
Vector3 angularVelocity = angularVelocityAxis * angularVelocityScalar;
RollDie(velocity, angularVelocity);
}
protected void OnDrawGizmos()
{
/* Status gizmoz */
if(showStateGizmos)
{
// Yellow wire cube when rigidbody is active
if (!_rb.IsSleeping())
{
Gizmos.color = Color.yellow;
Collider col = GetComponent<Collider>();
Gizmos.DrawWireCube(col.bounds.center, col.bounds.size);
}
// Red wire cube when the rigidbody is sleeping, but the rolled face is invalid
if (_rb.IsSleeping() && _faceRolled.faceValue == invalidFace.faceValue)
{
Gizmos.color = Color.red;
Collider col = GetComponent<Collider>();
//Gizmos.DrawCube(col.bounds.center, col.bounds.size);
Gizmos.DrawWireCube(col.bounds.center, col.bounds.size);
}
// Green wire cube when die is selected
if (selected == true)
{
Gizmos.color = Color.green;
Collider col = GetComponent<Collider>();
Gizmos.DrawWireCube(col.bounds.center, col.bounds.size);
}
}
}
}
}
|
Python
|
UTF-8
| 203 | 2.78125 | 3 |
[] |
no_license
|
import sys
#System Module provides function and module -- Python Runtime Emvironmment
print(sys.path) # Module Directory
#sys.exit() -- Exit interms exception
print("Ashish")
print(sys.version_info)
|
Java
|
UTF-8
| 12,691 | 2.34375 | 2 |
[
"MIT"
] |
permissive
|
package com.builtbroken.ishihara;
import com.builtbroken.ishihara.api.UncorrectedGui;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.shader.ShaderManager;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;
/**
* The overlay gui for Ishihara. Used to render the color wheels and names of the deficiencies.
*
* @author Wyn Price
*/
public class IshiharaGui extends GuiScreen implements UncorrectedGui
{
/**
* The number of entries per page
*/
private static final int PER_PAGE = 7;
/**
* The shader manager used to hold the color wheel shader
*/
private static ShaderManager shaderManager;
/**
* The list of deficiencies to display and choose from
*/
private final List<Deficiency> deficiencies = Lists.newArrayList();
/**
* The parent gui, that this gui was opened from. Can be null if it were from in game.
*/
@Nullable
private final GuiScreen parent;
/**
* Used to keep track of if this is the first time {@link #initGui()} has been called. <br>
* If it is not the first time, then the screen has been changed and therefore the parent screen should also be changed.
*/
private boolean firstRun = true;
private GuiButton nextPage;
private GuiButton backPage;
/**
* The current page that the gui is on
*/
private int page;
public IshiharaGui()
{
this.parent = Minecraft.getMinecraft().currentScreen;
//Setup the shader manager
if (shaderManager == null)
{
try
{
shaderManager = new ShaderManager(Minecraft.getMinecraft().getResourceManager(), Ishihara.MODID + ":colorwheel");
}
catch (IOException e)
{
e.printStackTrace();
}
}
//Get all the deficiencies
Ishihara.getDeficiencies((name, matrix) -> this.deficiencies.add(new Deficiency(this.deficiencies.size(), name, matrix)));
}
@Override
public void initGui()
{
super.initGui();
//If this isnt the first run, and the parent isn't null, meaning that the screen has changed and needs refreshing.
if (!this.firstRun && this.parent != null)
{
this.parent.initGui();
}
this.firstRun = false;
this.addButton(new GuiButton(5, this.width / 4 - 50, this.height - 40, 100, 20, I18n.format("gui.back")));
//Only show the next/back page buttons if there is more than one page
if (this.deficiencies.size() / PER_PAGE > 1)
{
int width = MathHelper.clamp(IshiharaGui.this.width / 4, 25, 75);
int centerX = (int) (11 / 16F * IshiharaGui.this.width);
this.nextPage = this.addButton(new GuiButton(6, centerX + width + 40 - 10, this.height / 2 - 10, 20, 20, ">"));
this.backPage = this.addButton(new GuiButton(7, centerX - width - 40 - 10, this.height / 2 - 10, 20, 20, "<"));
this.backPage.enabled = false;
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
//Render the deficiencies. Renders everything except the color wheel
for (Deficiency deficiency : this.deficiencies)
{
deficiency.render(false, mouseX, mouseY);
}
int centerX = this.width / 4;
int centerY = this.height / 2;
int radii = Math.min(centerX, centerY) / 2;
//Render the large color wheel on the left of the screen
if (shaderManager != null)
{
shaderManager.useShader();
BufferBuilder buff = Tessellator.getInstance().getBuffer();
buff.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
buff.pos(centerX - radii, centerY - radii, 0).tex(0, 0).endVertex();
buff.pos(centerX - radii, centerY + radii, 0).tex(0, 1).endVertex();
buff.pos(centerX + radii, centerY + radii, 0).tex(1, 1).endVertex();
buff.pos(centerX + radii, centerY - radii, 0).tex(1, 0).endVertex();
Tessellator.getInstance().draw();
shaderManager.endShader();
}
}
/**
* Gets once per frame after {@link net.minecraft.client.gui.GuiScreen#drawScreen(int, int, float)}.
* Anything rendered on this will be excluded from the color correcting
*/
@Override
public void drawUncoloredScreen(int mouseX, int mouseY, float partialTicks)
{
//Render all the color wheels on the deficiency entries
for (Deficiency deficiency : this.deficiencies)
{
deficiency.render(true, mouseX, mouseY);
}
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
//If the escape key has been pressed instead of doing the close that would run `initScreen`
//on the parent screen, just quietly display the parent screen. Means anything typed or
//selected stays the same. Makes this screen act like an overlay.
if (keyCode == Keyboard.KEY_ESCAPE)
{
Ishihara.setScreenQuietly(false, this.parent);
}
}
@Override
protected void actionPerformed(GuiButton button) throws IOException
{
//exit button
if (button.id == 5)
{
Ishihara.setScreenQuietly(false, IshiharaGui.this.parent);
}
//next page button
if (button.id == 6)
{
this.page = Math.min(this.page + 1, this.deficiencies.size() / PER_PAGE);
if (this.page == this.deficiencies.size() / PER_PAGE)
{
button.enabled = false;
}
this.backPage.enabled = true;
}
//previous page button
if (button.id == 7)
{
this.page = Math.max(this.page - 1, 0);
if (this.page == 0)
{
button.enabled = false;
}
this.nextPage.enabled = true;
}
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
//Go through the deficiency. If the mouse is over it (deficiency.selected), then set that as the active deficiency
for (Deficiency deficiency : this.deficiencies)
{
if (deficiency.selected)
{
IshiharaRenderer.matrix.put(deficiency.matrix);
break;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
/**
* Contains information about a deficiency.
*/
public class Deficiency
{
/**
* The index of which this deficiency is at in {@link IshiharaGui#deficiencies}'s list
*/
private final int index;
/**
* The name of this deficiency, as defined in the json file
*/
private final String name;
/**
* The matrix of this deficiency, as defined in the json file
*/
private final float[] matrix;
/**
* Whether the mouse is over this entry or not. Used to determine what deficiency has been clicked.
*/
private boolean selected;
public Deficiency(int index, String name, float[] matrix)
{
this.index = index;
this.name = name;
this.matrix = matrix;
}
/**
* Renders the entry
*
* @param wheel If true, then the wheel is rendered. If false then the background + text is rendered. <br>
* Used to render the wheel with color correction off, and the rest with color correction on.
* @param mouseX The mouse x
* @param mouseY The mouse y
*/
private void render(boolean wheel, int mouseX, int mouseY)
{
//If it is in the current page. Takes advantage of integer division
if (this.index / IshiharaGui.PER_PAGE == IshiharaGui.this.page)
{
int centerX = (int) (11 / 16F * IshiharaGui.this.width);
int hWidth = MathHelper.clamp(IshiharaGui.this.width / 4, 25, 100);
int height = 30;
//Total deficiencies to show on this page
int total = Math.min(IshiharaGui.this.deficiencies.size() - IshiharaGui.PER_PAGE * IshiharaGui.this.page, IshiharaGui.PER_PAGE);
//The y start of this entry
int start = (IshiharaGui.this.height / 2) - (total * height) / 2 + (this.index % IshiharaGui.PER_PAGE) * height;
//If we should draw the wheel only. Used for uncorrected rendering
if (wheel)
{
int radii = 10;
int wheelx = centerX - hWidth + height / 2;
int wheely = start + height / 2;
//Set the shader to use the deficiency and set the deficiencies matrix values.
shaderManager.getShaderUniformOrDefault("UseDeficiency").set(1);
shaderManager.getShaderUniformOrDefault("Deficiency0").set(this.matrix[0], this.matrix[1], this.matrix[2]);
shaderManager.getShaderUniformOrDefault("Deficiency1").set(this.matrix[3], this.matrix[4], this.matrix[5]);
shaderManager.getShaderUniformOrDefault("Deficiency2").set(this.matrix[6], this.matrix[7], this.matrix[8]);
shaderManager.useShader();
BufferBuilder buff = Tessellator.getInstance().getBuffer();
buff.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
buff.pos(wheelx - radii, wheely - radii, 0).tex(0, 0).endVertex();
buff.pos(wheelx - radii, wheely + radii, 0).tex(0, 1).endVertex();
buff.pos(wheelx + radii, wheely + radii, 0).tex(1, 1).endVertex();
buff.pos(wheelx + radii, wheely - radii, 0).tex(1, 0).endVertex();
Tessellator.getInstance().draw();
shaderManager.getShaderUniformOrDefault("UseDeficiency").set(0);
shaderManager.endShader();
}
else
{
//Draw the text + background color.
int color = 0xFFAAAAAA;
if (mouseX > centerX - hWidth && mouseY > start && mouseX < centerX + hWidth && mouseY < start + height)
{
color = 0xFFAAAAEE;
this.selected = true;
}
else
{
this.selected = false;
}
Gui.drawRect(centerX - hWidth, start, centerX + hWidth, start + height, color);
//top
Gui.drawRect(centerX - hWidth, start - 1, centerX + hWidth, start + 1, 0xFF555555);
//bottom
Gui.drawRect(centerX - hWidth, start + height - 1, centerX + hWidth, start + height + 1, 0xFF555555);
//left
Gui.drawRect(centerX - hWidth - 1, start - 1, centerX - hWidth + 1, start + height + 1, 0xFF555555);
//right
Gui.drawRect(centerX + hWidth - 1, start - 1, centerX + hWidth + 1, start + height + 1, 0xFF555555);
int wheely = start + height / 2;
//Only translate the name if there is a key for it.
String text = Ishihara.MODID + "." + this.name;
if (I18n.hasKey(text))
{
text = I18n.format(text);
}
else
{
text = this.name;
}
mc.fontRenderer.drawString(text, centerX - (int) (mc.fontRenderer.getStringWidth(text) / 2F - height / 2F), wheely - 3, 0xFF676767, false);
}
}
}
}
}
|
Java
|
UTF-8
| 1,482 | 2.171875 | 2 |
[] |
no_license
|
package com.icetea.manager.pagodiario.api.dto;
public abstract class PersonDto extends BasicDto {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String documentType = "DNI";
private Long documentNumber;
private String phone;
private String address;
private String nearStreets;
private String city;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
public Long getDocumentNumber() {
return documentNumber;
}
public void setDocumentNumber(Long documentNumber) {
this.documentNumber = documentNumber;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNearStreets() {
return nearStreets;
}
public void setNearStreets(String nearStreets) {
this.nearStreets = nearStreets;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
Markdown
|
UTF-8
| 3,360 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
# [chai](https://github.com/chaijs/chai)
## Registration
```js
// using ES6 modules
import { registerAssertions } from 'redux-actions-assertions/chai';
// using CommonJS modules
var registerAssertions = require('redux-actions-assertions/chai').registerAssertions;
// registration
registerAssertions();
```
## Usage
### .to.dispatch.actions or assert.isDispatching
> `expect(action).to.dispatch.actions(expectedActions, callback)`
> `action.should.dispatch.actions(expectedActions, callback)`
> `assert.isDispatching(action, expectedActions, callback)`
Asserts that when given `action` is dispatched it will dispatch `expectedActions`. `action` can be plain object (action) or function (action creator). `expectedActions` can be can be plain object (action) or function (action creator) or array of objects/functions.
```js
expect(myActionCreator())
.to.dispatch.actions({ type: 'MY_ACTION_START' }, callback);
myActionCreator()
.should.dispatch.actions({ type: 'MY_ACTION_START' }, callback);
assert.isDispatching(
myActionCreator(),
{ type: 'MY_ACTION_START' },
callback
);
```
### .not.to.dispatch.actions or .to.not.dispatch.actions or assert.isNotDispatching
> `expect(action).not.to.dispatch.actions(expectedActions, callback)`
> `expect(action).to.not.dispatch.actions(expectedActions, callback)`
> `action.should.not.dispatch.actions(expectedActions, callback)`
> `assert.isNotDispatching(action, expectedActions, callback)`
Asserts that when given `action` is dispatched it will not dispatch `expectedActions`. `action` can be plain object (action) or function (action creator). `expectedActions` can be can be plain object (action) or function (action creator) or array of objects/functions.
```js
expect(myActionCreator())
.not.to.dispatch.actions({ type: 'MY_ACTION_START' }, callback);
myActionCreator()
.should.not.dispatch.actions({ type: 'MY_ACTION_START' }, callback);
assert.isNotDispatching(
myActionCreator(),
{ type: 'MY_ACTION_START' },
callback
);
```
### .with.state or assert.isDispatchingWithState and assert.isNotDispatchingWithState
> `expect(action).with.state(state).to.dispatch.actions(expectedActions, callback)`
> `expect(action).with.state(state).not.to.dispatch.actions(expectedActions, callback)`
> `expect(action).with.state(state).to.not.dispatch.actions(expectedActions, callback)`
> `action.should.with.state(state).dispatch.actions(expectedActions, callback)`
> `action.should.with.state(state).not.dispatch.actions(expectedActions, callback)`
> `assert.isDispatchingWithState(action, expectedActions, state, callback)`
> `assert.isNotDispatchingWithState(action, expectedActions, state, callback)`
Asserts that store initialised with `state` before `action` is dispatched.
```js
expect(myActionCreator())
.with.state({ property: 'value' })
.to.dispatch.actions([{ type: 'MY_ACTION_START' }, finishActionCreator()], callback);
myActionCreator()
.should.with.({ property: 'value' })
.dispatch.actions([{ type: 'MY_ACTION_START' }, finishActionCreator()], callback);
assert.isDispatchingWithState(
myActionCreator(),
[{ type: 'MY_ACTION_START' }, finishActionCreator()],
{ property: 'value' }
callback
);
assert.isNotDispatchingWithState(
myActionCreator(),
[{ type: 'MY_ACTION_START' }, finishActionCreator()],
{ property: 'value' }
callback
);
```
|
Python
|
UTF-8
| 155 | 3.40625 | 3 |
[] |
no_license
|
IDADE = FLOAT(INPUT('QUAL A SUA IDADE?'))
IF IDADE <= 11
PRINT ("CRIANCA)
ELIF IDADE >= 12 AND IDADE < 18
PRINT ("ADOLESCENTE")
ELSE:
PRINT ("ADULTO")
|
C++
|
UTF-8
| 692 | 2.78125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int power(int x,int y)
{
int i;
int n=1;
for(i=0;i<y;i++)
{
n*=x;
}
return n;
}
int main()
{
int i,j;
int x;
scanf("%d",&x);
vector<int>keep;
int t=0;
for(i=20;!(x>>i)&1;i--);
for(;i>0;i--)
{
if(!((x>>(i-1)&1)))
{
keep.push_back(i);
t++;
x^=(power(2,i)-1);
if((x&(power(2,i)-1))==(power(2,i)-1))
{
break;
}
x+=1;
t++;
}
}
printf("%d\n",t);
for(auto it:keep)
{
printf("%d ",it);
}
printf("\n");
return 0;
}
|
Shell
|
UTF-8
| 2,729 | 2.6875 | 3 |
[] |
no_license
|
#!/usr/bin/env sh
# To setup the development environment
set -e
cp bash_profile ~/.bash_profile
cp agignore ~/.agignore
cp ./ctags ~/.ctags.d/default.ctags
#cp bash_profile ~/.bash_profile
cp vimrc ~/.vimrc
cp coc-settings.json ~/.vim/coc-settings.json
# Install homebrew
if ! brew -v &> /dev/null
then
curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh
fi
# Install softwares
brew install --cask macvim
brew install fzf autojump the_silver_searcher vim bash bash-completion yarn ctags watchman wget readline rbenv ruby-build postgresql node diff-so-fancy antigen
# git config
cat << EOF >> ~/.gitconfig
[http]
postBuffer = 524288000
[pull]
rebase = false
[core]
pager = diff-so-fancy | less --tabs=4 -RFX
[interactive]
diffFilter = diff-so-fancy --patch
[color]
ui = true
[color "diff-highlight"]
oldNormal = red bold
oldHighlight = red reverse
newNormal = green bold
newHighlight = green bold 22
[color "diff"]
new = green bold
[alias]
d = difftool
[difftool]
prompt = false
[difftool "mvimdiff"]
cmd = mvim -f -d \"\$LOCAL\" \"\$REMOTE\"
EOF
# zsh alternative, run command zsh manually
brew install zsh
curl -L git.io/antigen > ~/.antigen.zsh
cp zshrc ~/.zshrc
# Whitelist the new bash for login shells
sudo echo /usr/local/bin/bash >> /etc/shells
# change the default shell to new bash
chsh -s /usr/local/bin/bash
# Fetch git-completion.bash
curl https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash > ~/.git-completion.bash
#curl https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.zsh > ~/.git-completion.zsh
#To install useful keybindings and fuzzy completion
/usr/local/opt/fzf/install
# Install latest Ruby
rbenv install $(rbenv install -l | grep -v - | tail -1)
rbenv rehash
# For ruby language server
gem install solargraph
# Install gem-ctags and run ctags to generate tags for each gems
gem install gem-ctags
gem ctags
# Switched to coc-nvim documentation function
# Generate ri documentation for pressing K in vim
#gem rdoc --ri --all --overwrite
# Switched to fzf.vim
#mkdir .vim/autoload/ctrlp
#cp vim/autoload/ctrlp/tag.vim .vim/autoload/ctrlp/tag.vim
# Install vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# Install plugins and install coc extension in vim
vim -S snapshot.vim -c 'CocInstall -sync coc-snippets coc-tag coc-json coc-pairs coc-syntax coc-css coc-html coc-solargraph coc-tsserver coc-translator coc-sh coc-yank coc-tabnine'
#vim -c 'CocInstall -sync coc-snippets coc-tag coc-json coc-pairs coc-syntax coc-css coc-html coc-solargraph coc-tsserver coc-translator coc-sh coc-yank|q'
|
Markdown
|
UTF-8
| 4,037 | 3.5 | 4 |
[] |
no_license
|
悟空传
今何在
2012-12
========序 在路上========
我总在想人的一生要追求什么,功名利禄?得到这一切之后呢?当你老去的时候,回想一生,你会不会遗憾?似乎不论如何去苦苦追求,总有一些你必须放弃,总有一些你只能怀念,还有一些永远只在梦想中。我们永远在计算成败、取舍与得失,却没有人能找到正确答案。
佛是什么,佛就是虚无,四大皆空,什么都没有了,没有感情没有欲望没有思想,当你放弃这些,你就不会痛苦了。但问题是,放弃了这些,人还剩下什么?什么都没了,直接就死了。所以成佛就是消亡,西天就是寂灭
每个人都有一条自己的西游路,我们都在向西走,到了西天,大家就虚无了,就同归来处了,所有人都不可避免要奔向那个归宿,你没办法选择,没办法回头,那怎么办呢?你只有在这条路上,尽量走得精彩一些,走得抬头挺胸一些,多经历一些,多想一些,多看一些,去做好你想做的事,最后,你能说,这个世界我来过,我爱过,我战斗过,我不后悔。
成败,其实并不是最重要的。因为你去追求理想时你就会明白,你很可能不会成功。最关键就在于,当你深知这一点时,你还要不要去追求。
我没有答案。也不需要答案。
========正文部分========
“因为我想活着,我不能掩藏我心中的本欲,正如我心中爱你美丽,又怎能嘴上装四大皆空。”
五百年,很漫长吗?
失去的一切
都无处寻找了吗?
骂着骂着,猪八戒突然仰天喊:“为什么!这一切是为什么呀……”
“呜呜呜呜……”他竟已泣不成声。
那天上,有一轮那么蓝的月亮。满天的银河,把光辉静静照在一只哭泣的猪身上。
我是一个和你一样不肯忘记前世而宁愿承受痛苦的人
是不是选择任何一个方向,都会游向同一个宿命呢?
我要这天,再遮不住我眼,要这地,再埋不了我心,要这众生,都明白我意,要那诸佛,都烟消云散
因为生命随时都会终止,命运是大海,当你能够畅游时,你就要纵情游向你的所爱,因为你不知道狂流什么会到来,卷走一切希望与梦想
也许每个人出生时都以为这天地是为他一个人而存在的,当他发现自己错的时候,他便开始长大了。
“你知道吗,这天空就是一片荒漠。”紫霞说,“它用精美的东西镶砌,但它们在成为天宫的一部分时,就已被剥夺了灵魂。你知道吗?”
也许,在每个人的心里都会有一个天宫,有一片黑暗,在那边黑暗的深处,会有一片水面,里面映出他心的影子,灵魂就居住在那里,可是当一个人决定变成一个神,他就必须抛弃这些,他要让那水面里什么也没有,什么也看不见,一片空寂之时,他就成仙了,可是心里是空空的,那是什么滋味?你知道么?你……”
生我何用?不能欢笑,灭我何用,不减狂骄
可我将忘记所有的事……我……将失去了一切……因为……我不肯放弃
“你为你发现了自己而恐惧?”一个声音说。
那世上有那么多不能做到的事,你岂不是总是不能快乐?”
……我真想能象你们一样吃果子。”
“有时候你没有选择的。”一个声音说。
“你可以不做自己不想做的事情。我想那可以。”
你是从石头中蹦出来的吧,你总是忧虑,因为几万年来沉寂的你还在害怕着那林间飞速的跳跃,千百万扑面而来的事物,而你知道你能如此自由的掌握自己的时间是极短暂,你能这样感受到自己自由的思考的时间是极短暂,为了这短暂的时光你要尽力的去抓住你所遇见的。要知你生命中所出现的,都是在漫长的时光中来到你的面前,去珍惜它们,孩子。”
|
PHP
|
UTF-8
| 318 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace Nassau\CartoonBattle\Services\Farming\LootExtractor;
class GiggitywattsExtractor implements LootHandler
{
/**
* @param mixed $data
* @return \Generator|string[]
*/
public function formatLoot($data)
{
yield $data ? sprintf("%d GiggityWatts", $data) : null;
}
}
|
Java
|
UTF-8
| 2,161 | 3.125 | 3 |
[] |
no_license
|
package sii.maroc;
import static org.hamcrest.CoreMatchers.nullValue;
import java.util.PrimitiveIterator.OfDouble;
public class Vehicles {
private String moteur;
enum typeVehiculeEnum {
CAR,TRUCK,MOTORCYCLE
};
public Vehicles(String moteur) {
super();
this.moteur = moteur;
}
public int consomationMoteur(String moteur) {
int consomation=0;
String moteurType[] = this.moteur.split(",");
for (String m: moteurType) {
if(m.contains(moteur)) {
String consomationSplit[] = m.split(":");
String cnsomationPerCent[] = consomationSplit[1].split("%");
consomation=Integer.parseInt(cnsomationPerCent[0]);
}
}
return consomation;
}
public int distance(String distance) {
String distanceSplit[]=distance.split(" KM");
int distanceInteger=Integer.parseInt(distanceSplit[0]);
return distanceInteger;
}
public String move(String typeVehicles,String moteur,String doors,String distance) {
String result = null;
typeVehiculeEnum typeVehicule = null;
if (typeVehicles.equals("CAR"))
typeVehicule = typeVehiculeEnum.CAR;
else if (typeVehicles.equals("TRUCK")) typeVehicule = typeVehiculeEnum.TRUCK;
else typeVehicule = typeVehiculeEnum.MOTORCYCLE;
switch (typeVehicule) {
case CAR:
if (doors.equals("1 2 3 4")) {
result = "DOORS OK, MOVING. The CAR will consume "+distance(distance)*consomationMoteur(moteur)/100+".00 L";
}
else if(doors.equals("1 3 4")) {
result="DOORS KO, BLOCKED \n"+
" _\n"+
" | \\\n"+
" |_|";
}
else if (doors.equals("1 2 4")) {
result="DOORS KO, BLOCKED \n"+
" _\n"+
" | |\n"+
" /_|";
}
break;
case TRUCK:
if (doors.equals("1 2")) {
result = "DOORS OK, MOVING. The TRUCK will consume "+distance(distance)*consomationMoteur(moteur)/100+".00 L";
}
break;
case MOTORCYCLE:
if (doors.equals("")) {
result = "DOORS OK, MOVING. The MOTORCYCLE will consume "+distance(distance)*consomationMoteur(moteur)/100+".00 L";
}
break;
}
return result;
}
}
|
C++
|
UTF-8
| 8,735 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
#include "messagecoder.h"
#include "bitcoinunits.h"
#include <boost/lexical_cast.hpp>
CMessageCoder::CMessageCoder() :
terminator('.'), maxSymbolsPerCodeWord(7)
{
// Contains the min and max value for each character
characterRanges = createCharacterRanges();
}
QList<qint64> CMessageCoder::encode(const QString &message) const
{
// The actual number of characters that can be encoded into 8 decimal places can vary based on the characters.
// Therefore, encoding starts by trying to encode 7 characters and encodes 1 character less each time the
// resulting encoded value exceeds 8 decimal places. This helps ensure maximum information density.
// The part of the message encoded is paired with the encoded value
QList<qint64> result;
for (int i = 0, chunkLength = maxSymbolsPerCodeWord; i < message.length(); i += chunkLength, chunkLength = maxSymbolsPerCodeWord)
{
QString chunk = message.mid(i, chunkLength);
qint64 encodedChunk;
// Check for chunkLength > 0 to avoid any infinite loops caused by errors in the encoding algorithm
while (chunkLength > 0 && !tryEncode(chunk + terminator, &encodedChunk))
{
// Reduce the size of the chunk by 1 and try again
chunkLength--;
chunk = message.mid(i, chunkLength);
}
// This should never happen but, if it does, there is a major error in the encoding algorithm
if (chunkLength <= 0)
{
result.clear();
return result;
}
result.append(encodedChunk);
}
return result;
}
QString CMessageCoder::decode(const QList<qint64> &encodedMessage) const
{
QString message;
qint64 chunk;
// Decode each encoded chunk to form the entire message
foreach (chunk, encodedMessage)
{
message.append(decodeChunk(BitcoinUnits::format(BitcoinUnits::BTC, chunk).toDouble()));
}
return message;
}
QMap<QChar, QPair<double, double> > CMessageCoder::createCharacterRanges() const
{
QMap<QChar, QPair<double, double> > results;
QVector<QPair<QChar, double> > frequencies = createFrequencyMap();
double low = 0;
QPair<QChar, double> i;
foreach (i, frequencies)
{
// The high value of this character is the cumulative sum of this character's and
// previous character's relative frequencies
double high = i.second + low;
results[i.first] = QPair<double, double>(low, high);
// The low value of the next character is the high value of this character
low = high;
}
return results;
}
QVector<QPair<QChar, double> > CMessageCoder::createFrequencyMap() const
{
QVector<QPair<QChar, double> > frequencies;
// The relative frequencies of all the valid characters
frequencies.append(QPair<QChar, double>('a', 0.0609));
frequencies.append(QPair<QChar, double>('b', 0.0105));
frequencies.append(QPair<QChar, double>('c', 0.0284));
frequencies.append(QPair<QChar, double>('d', 0.0292));
frequencies.append(QPair<QChar, double>('e', 0.1136));
frequencies.append(QPair<QChar, double>('f', 0.0179));
frequencies.append(QPair<QChar, double>('g', 0.0138));
frequencies.append(QPair<QChar, double>('h', 0.0341));
frequencies.append(QPair<QChar, double>('i', 0.0544));
frequencies.append(QPair<QChar, double>('j', 0.0024));
frequencies.append(QPair<QChar, double>('k', 0.0041));
frequencies.append(QPair<QChar, double>('l', 0.0292));
frequencies.append(QPair<QChar, double>('m', 0.0276));
frequencies.append(QPair<QChar, double>('n', 0.0544));
frequencies.append(QPair<QChar, double>('o', 0.0600));
frequencies.append(QPair<QChar, double>('p', 0.0195));
frequencies.append(QPair<QChar, double>('q', 0.0024));
frequencies.append(QPair<QChar, double>('r', 0.0495));
frequencies.append(QPair<QChar, double>('s', 0.0568));
frequencies.append(QPair<QChar, double>('t', 0.0803));
frequencies.append(QPair<QChar, double>('u', 0.0243));
frequencies.append(QPair<QChar, double>('v', 0.0097));
frequencies.append(QPair<QChar, double>('w', 0.0138));
frequencies.append(QPair<QChar, double>('x', 0.0024));
frequencies.append(QPair<QChar, double>('y', 0.0130));
frequencies.append(QPair<QChar, double>('z', 0.0003));
frequencies.append(QPair<QChar, double>(' ', 0.1217));
frequencies.append(QPair<QChar, double>(terminator, 0.0658));
return frequencies;
}
bool CMessageCoder::tryEncode(const QString &text, qint64 *result) const
{
// Arithmetic Coding algorithm
long double low = 0.0, high = 1.0;
for (int i = 0; i < text.length(); i++)
{
long double range = high - low;
long double previousLow = low;
low = previousLow + range * characterRanges[text[i]].first;
high = previousLow + range * characterRanges[text[i]].second;
}
// Note: Currently, low can never be 0 and high can never be 1 nor can either be >= 1.
// Low can never be 0 because that would require a string of only a's. All a's is not possible
// because the terminator character is always appended to the message.
// High can never be 1 because that would require a string of only .'s. All .'s is not possible
// because the user cannot enter in .'s nor can the user enter in a blank message.
// If low could be 0 or high could be 1, the following code would not work.
// Since the Arithmetic Coding algorithm results in a valid range for the encoded message, we
// can select a value that has the fewest number of digits. This is done by keeping all the
// digits that are the same between the low and high values until we reach a digit that is
// different. At this point, we can likely take the high value's digit. However, if doing so
// would make the code word equal to the high value then we must, instead, find the value with
// the fewest digits that is greater than or equal to the low value.
QString lowString = QString::fromStdString(boost::lexical_cast<std::string, long double>(low));
QString highString = QString::fromStdString(boost::lexical_cast<std::string, long double>(high));
QString output = "0.";
for (int i = 2; i < lowString.length() && i < highString.length(); i++)
{
if (lowString[i] == highString[i])
{
output.append(lowString[i]);
}
else if ((output + highString[i]).toDouble() == high)
{
// The code word cannot be equal to the high value. Therefore, we must find the
// shortest value that is >= the low value
output.append(lowString[i]);
// Find the first digit that is not a 9, increment it, and that is the final code word.
// If the low value only contains 9's beyond this point then the code word will equal
// the low value.
for (i++; i < lowString.length(); i++)
{
int digit = QString(lowString[i]).toInt();
if (digit == 9)
{
output.append(lowString[i]);
}
else
{
output.append(QString::number(digit + 1));
break;
}
}
break;
}
else
{
output.append(highString[i]);
break;
}
}
// Use the existing bitcoin parsing function to validate the result
return BitcoinUnits::parse(BitcoinUnits::BTC, output, result);
}
QString CMessageCoder::decodeChunk(long double value) const
{
// Arithmetic Decoding algorithm
QString decodedMessage;
QChar symbol;
while (true)
{
long double low = 0.0, high = 0.0;
// Search for the range that the value falls within to
// determine the next character
foreach (symbol, characterRanges.keys())
{
low = characterRanges[symbol].first;
high = characterRanges[symbol].second;
if (value >= low && value < high)
{
break;
}
}
if (symbol == terminator)
{
break;
}
decodedMessage.append(symbol);
// Stop if we've decoded more than the max number of symbols per code word
// (Prevents infinite loops if attempting to decode an invalid code word).
if (decodedMessage.length() > maxSymbolsPerCodeWord)
{
decodedMessage.clear();
break;
}
value = (value - low) / (high - low);
}
return decodedMessage;
}
|
Java
|
UTF-8
| 777 | 2.4375 | 2 |
[] |
no_license
|
package com.practice.bankadvisor.core.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@Mapper
public interface LocalDateMapper {
LocalDateMapper INSTANCE = Mappers.getMapper( LocalDateMapper.class );
default LocalDate toLocalDate(String date) {
if(date == null || StringUtils.isEmpty(date)) {
return null;
}
return LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
}
default String toString(LocalDate date) {
if(date == null) {
return null;
}
return date.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
|
C
|
UTF-8
| 851 | 3.953125 | 4 |
[] |
no_license
|
#include<stdio.h>
int main(){
int i;
int a[5];
printf("Enter the numbers to sort");
for (i=0; i<5; i=++i){
printf("Enter the numbers %d ",i + 1);
scanf("%d", &a[i]);
}
//assign the array's first address to variable p
int *p = a;
int q = *a;
int *r = &a[0];
printf("\n p value %d q value %d r value %d ", p, q, r);
printf("\n The numbers in the array are : ");
for (i=0; i<5; i=++i){
//printf("The numbers i is in first format %d \n", i + 1, a[i]);
//printf("The numbers i is in second format %d \n", i + 1, *(a+i));
printf("The numbers i is in third format %d \n", i + 1, p);
printf("The numbers i is in fourth format %d \n", i + 1, q);
printf("The numbers i is in fifth format %d \n", i + 1, r);
}
//bubble_sort(a);
return 0;
}
|
TypeScript
|
UTF-8
| 715 | 2.640625 | 3 |
[] |
no_license
|
import { Entity, Column, ManyToOne } from 'typeorm';
import { MinLength, MaxLength, IsDefined } from 'class-validator';
import ResearchCategory from './ResearchCategory';
import AbstractEntity from './AbsrtactEntity';
@Entity('paperTypes')
export default class PaperType extends AbstractEntity {
@MinLength(5, PaperType.getMessage('minLength'))
@MaxLength(50, PaperType.getMessage('maxLength'))
@IsDefined(PaperType.getMessage('required'))
@Column({ type: 'varchar', unique: true, length: 50 })
paperType?: string;
@Column({ type: 'uuid' })
researchCategoryId!: string;
@ManyToOne(() => ResearchCategory, researchCategory => researchCategory.paperTypes)
researchCategory!: ResearchCategory;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.