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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 2,185 | 2.0625 | 2 | [] | no_license | /***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.sopremo.cleansing;
import eu.stratosphere.sopremo.EvaluationContext;
import eu.stratosphere.sopremo.base.ArraySplit;
import eu.stratosphere.sopremo.base.Difference;
import eu.stratosphere.sopremo.base.UnionAll;
import eu.stratosphere.sopremo.operator.CompositeOperator;
import eu.stratosphere.sopremo.operator.InputCardinality;
import eu.stratosphere.sopremo.operator.OutputCardinality;
import eu.stratosphere.sopremo.operator.SopremoModule;
/**
* Detects duplicates, fuses them, and combines the non-duplicates the the fused records.
*
* @author Arvid Heise
*/
@InputCardinality(1)
@OutputCardinality(1)
public class DuplicateRemoval extends CompositeOperator<DuplicateRemoval> {
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.operator.CompositeOperator#asModule(eu.stratosphere.sopremo.EvaluationContext)
*/
@Override
public void addImplementation(SopremoModule module, EvaluationContext context) {
DuplicateDetection duplicates = new DuplicateDetection().withInputs(module.getInput(0));
Fusion fusedDuplicates = new Fusion().withInputs(duplicates);
Difference nonDuplicates =
new Difference().withInputs(module.getInput(0), new ArraySplit().withInputs(duplicates));
module.getOutput(0).setInputs(new UnionAll().withInputs(fusedDuplicates, nonDuplicates));
}
}
|
Python | UTF-8 | 5,754 | 2.609375 | 3 | [] | no_license | """
----------------------------------
Smolfin - a numerical solver of the Smoluchowski equation for interesting geometries
Copyright (C) 2012 Peter Kekenes-Huskey, Ph.D., huskeypm@gmail.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
----------------------------------------------------------------------------
"""
#
# Revisions
# 10.08.10 inception
#
from dolfin import *
from homogutil import *
import numpy as np
EPS = 1.e-10
#
# Solve homogenized diff. eqn based on vector field
#
## solv. homog cell
# See notetaker notes from 2012-04-19 (pg 11)
# Using first-order representation from Higgins paper ()
# type - scalar is valid only for certain cases
# solverMode - gmres/mumps
def solveHomog(domain,solver="gmres"):
solverMode = solver
# mesh
problem = domain.problem
mesh = problem.mesh
V = problem.V
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
## LHS terms
# Diffusion constant
Dbulk = problem.d # set diffusion coefficient
nDims = problem.nDims
Dii = Constant(Dbulk*np.ones(nDims))
Aij = diag(Dii) # for now, but could be anisotropic
Atilde = Aij
# Identity matrix
Delta = Identity( mesh.ufl_cell().geometric_dimension()) #
# LHS.
# dot (A grad u + I )) =0
form = inner(Atilde*(grad(u) + Delta), grad(v))*dx
# note: we are mixing linear and bilinear forms, so we need to split
# these up for assembler
LHS = lhs(form)
RHS = rhs(form)
a = LHS
## RHS terms
# add in RHS from earlier
L = RHS
## Compute solution
# We can use different solver types, depending on the convergence properies of the system
#solverType="original"
solverType="krylov"
#solve(a == L, x, problem.bcs)
if solverType=="original":
lvproblem = LinearVariationalProblem(a,L, x, bcs=problem.bcs)
solver = LinearVariationalSolver(lvproblem)
solver.parameters["linear_solver"] = "gmres"
#solver.parameters["preconditioner"] = "ilu"
#print "Using amg preconditioner instead of ilu"
solver.parameters["preconditioner"] = "amg"
#solver.parameters["newton_solver"]["linear_solver"] = "mumps"
x = Function(V)
solver.solve(x.vector())
elif solverType=="krylov":
#print "NOW USING KRYLOV SOLVER (from stokes-iterative example)"
#print "WARNING: made a random qguess as to what to use for the preconditioner [used basic diff eqn, no delta term]"
# Form for use in constructing preconditioner matrix
#b = inner(Atilde*(grad(u) + Delta), grad(v))*dx
b = inner(Atilde*(grad(u)), grad(v))*dx
# Assemble system
A, bb = assemble_system(a, L, problem.bcs)
# Assemble preconditioner system
P, btmp = assemble_system(b, L, problem.bcs)
# Create Krylov solver and AMG preconditioner
solver = KrylovSolver("minres", "amg")
# Associate operator (A) and preconditioner matrix (P)
solver.set_operators(A, P)
x = Function(V)
solver.solve(x.vector(),bb)
#print solver.parameters
## Store solution
problem.x = x
# save unprojected soln instead
fileName = problem.outpath + problem.name+"_unit.pvd"
if MPI.rank(mpi_comm_world())==0:
print("Writing ",fileName)
#File(fileName) << problem.x
File(fileName) << problem.x
return problem
# Computes effective diffusion constant based on solution from solveHomog
def compute_eff_diff(domain):
problem = domain.problem
mesh = problem.mesh
dim = mesh.ufl_cell().geometric_dimension()
dx_int = dx(domain=mesh)
Vscalar = FunctionSpace(mesh,"CG",1)
us = TrialFunction(Vscalar)
vs = TestFunction(Vscalar)
## get omega (e.g. integration term below)
# deff = 1/volUnitCell int( grad u + 1 dx )
# treating each component independtly, following Goel's example in sec 2.7
import numpy as np
omegas = np.zeros(dim)
x = problem.x
# I iterate only over the diagonal, since my original diffusion constant is diagonal
for i in range(dim):
## This is used for evaluating grad(x)+1
# x[i].dx(i) is the gradient of the ith component of our solution
# along the ith direction
grad_Xi_component = x[i].dx(i)+Constant(1)
form = grad_Xi_component * dx_int
omegas[i] = assemble(form)
# for visualizing intermediate results
#D_eff_project = Function(Vscalar)
#outname = "diff%d.pvd" % i
#solve(us*vs*dx_int==grad_Xi_component*vs*dx_int, D_eff_project)
#File(outname)<<D_eff_project
if MPI.rank(mpi_comm_world())==0:
print("omegasO ",omegas)
# normalize by volumeUnitCell to get deff
d_eff = problem.d*omegas
d_eff /= problem.volUnitCell
if MPI.rank(mpi_comm_world())==0:
if(dim==3):
print("d_eff= [%4.2f,%4.2f,%4.2f] for d=%4.2f"%\
(d_eff[0],d_eff[1],d_eff[2],problem.d))
else:
print("d_eff= [%4.2f,%4.2f] for d=%4.2f"%\
(d_eff[0],d_eff[1],problem.d))
print("problem.volUnitCell", problem.volUnitCell)
# report volume frac for validation purposes
vol = assemble( Constant(1)*dx_int)#, mesh=mesh )
problem.volFrac = vol / problem.volUnitCell
# store
problem.d_eff = d_eff
return d_eff
|
Python | UTF-8 | 736 | 2.921875 | 3 | [] | no_license | GlowScript 3.1 VPython
g = 9.8
r = 0.2
v0 = 10
theta0 = 80
bola_de_basquete = sphere(pos=vector(0,0,0), radius=2*r, color=color.orange, make_trail=True)
bola_de_basquete.v = vector(v0*cos(radians(theta0)), v0*sin(radians(theta0)), 0)
bola_de_basquete.a = vector(0, -g, 0)
chao = box(pos = vector(5, 0, 0), width = 8, length = 20, height = 0.05, color = color.white)
t = 0
dt = 0.01
while t <= 5:
rate(100)
bola_de_basquete.v = bola_de_basquete.v + bola_de_basquete.a * dt
bola_de_basquete.pos = bola_de_basquete.pos + bola_de_basquete.v * dt
if bola_de_basquete.pos.y <= r:
bola_de_basquete.v.y = - 0.8*bola_de_basquete.v.y
bola_de_basquete.pos.y = r
t = t + dt
print(t)
|
Java | UTF-8 | 946 | 1.953125 | 2 | [] | no_license | package com.feri.shop.newretail.msg.controller;
import com.feri.shop.newretail.common.vo.R;
import com.feri.shop.newretail.msg.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @program: NewRetail
* @description:
* @author: Feri
* @create: 2019-08-12 17:22
*/
@RestController
public class SmsMsgController {
@Autowired
private SmsService smsService;
@GetMapping("nr/provider/sms/sendvc.do")
public R sendSms(@RequestParam("phone") String phone){
return smsService.sendValidateCode(phone);
}
@GetMapping("nr/provider/sms/checkvc.do")
public R checkVC(@RequestParam("phone") String phone,@RequestParam("code") String code){
return smsService.checkCode(phone, code);
}
}
|
Java | UTF-8 | 10,063 | 2.5 | 2 | [] | no_license | package net.thumbtack.school.file;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Random;
import net.thumbtack.school.colors.v3.Color;
import net.thumbtack.school.colors.v3.ColorException;
import net.thumbtack.school.figures.v3.ColoredRectangle;
import net.thumbtack.school.figures.v3.Rectangle;
import net.thumbtack.school.ttschool.Trainee;
import net.thumbtack.school.ttschool.TrainingException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class TestFileService {
@TempDir
public Path tempDir;
@Test
public void testFileReadWriteByteArray1() throws IOException {
byte[] arrayToWrite = {0, 1, 5, -34, 67, -123};
File file = Files.createFile(tempDir.resolve("test.dat")).toFile();
FileService.writeByteArrayToBinaryFile(file, arrayToWrite);
assertTrue(file.exists());
assertEquals(arrayToWrite.length, file.length());
byte[] arrayRead = FileService.readByteArrayFromBinaryFile(file);
assertArrayEquals(arrayToWrite, arrayRead);
}
@Test
public void testFileReadWriteByteArray2() throws IOException {
byte[] arrayToWrite = {0, 1, 5, -34, 67, -123};
String fileName = Files.createFile(tempDir.resolve("test.dat")).toFile().getAbsolutePath();
FileService.writeByteArrayToBinaryFile(fileName, arrayToWrite);
File file = new File(fileName);
assertTrue(file.exists());
assertEquals(arrayToWrite.length, file.length());
byte[] arrayRead = FileService.readByteArrayFromBinaryFile(fileName);
assertArrayEquals(arrayToWrite, arrayRead);
}
@Test
public void testByteStreamReadWriteByteArray() throws IOException {
byte[] arrayToWrite = {0, 1, 5, -34, 67, -123};
byte[] result = FileService.writeAndReadByteArrayUsingByteStream(arrayToWrite);
assertArrayEquals(new byte[]{0, 5, 67}, result);
}
@Test
public void testFileReadWriteByteArray1Buffered() throws IOException {
byte[] arrayToWrite = {0, 1, 5, -34, 67, -123};
File file = Files.createFile(tempDir.resolve("test.dat")).toFile();
FileService.writeByteArrayToBinaryFileBuffered(file, arrayToWrite);
assertTrue(file.exists());
assertEquals(arrayToWrite.length, file.length());
byte[] arrayRead = FileService.readByteArrayFromBinaryFileBuffered(file);
assertArrayEquals(arrayToWrite, arrayRead);
}
@Test
public void testFileReadWriteByteArray2Buffered() throws IOException {
byte[] arrayToWrite = {0, 1, 5, -34, 67, -123};
String fileName = Files.createFile(tempDir.resolve("test.dat")).toFile().getAbsolutePath();
FileService.writeByteArrayToBinaryFileBuffered(fileName, arrayToWrite);
File file = new File(fileName);
assertTrue(file.exists());
assertEquals(arrayToWrite.length, file.length());
byte[] arrayRead = FileService.readByteArrayFromBinaryFileBuffered(fileName);
assertArrayEquals(arrayToWrite, arrayRead);
}
@Test
public void testFileReadWriteRectangleBinary() throws IOException {
Rectangle rectToWrite = new Rectangle(10000, 10000, 20000, 20000);
File file = Files.createFile(tempDir.resolve("test.dat")).toFile();
FileService.writeRectangleToBinaryFile(file, rectToWrite);
assertTrue(file.exists());
assertEquals(16, file.length());
Rectangle rectRead = FileService.readRectangleFromBinaryFile(file);
assertEquals(rectToWrite, rectRead);
}
@Test
public void testFileReadWriteColoredRectangleBinary() throws ColorException, IOException {
ColoredRectangle rectToWrite = new ColoredRectangle(10000, 10000, 20000, 20000, Color.RED);
File file = Files.createFile(tempDir.resolve("test.dat")).toFile();
FileService.writeColoredRectangleToBinaryFile(file, rectToWrite);
assertTrue(file.exists());
assertEquals(21, file.length());
ColoredRectangle rectRead = FileService.readColoredRectangleFromBinaryFile(file);
assertEquals(rectToWrite, rectRead);
}
@Test
public void testFileReadRectangleArrayBinary() throws IOException {
int count = 5;
Rectangle[] rectsToWrite = new Rectangle[count];
Random random = new Random();
for (int i = 0; i < count; i++) {
rectsToWrite[i] = new Rectangle(random.nextInt(), random.nextInt(), random.nextInt(), random.nextInt());
}
File file = Files.createFile(tempDir.resolve("test.dat")).toFile();
FileService.writeRectangleArrayToBinaryFile(file, rectsToWrite);
assertTrue(file.exists());
assertEquals(count * 16, file.length());
Rectangle[] rectsRead = FileService.readRectangleArrayFromBinaryFileReverse(file);
for (int i = 0; i < rectsRead.length / 2; i++) {
Rectangle temp = rectsRead[i];
rectsRead[i] = rectsRead[rectsRead.length - i - 1];
rectsRead[rectsRead.length - i - 1] = temp;
}
assertArrayEquals(rectsToWrite, rectsRead);
}
@Test
public void testFileReadWriteRectangleTextOneLine() throws IOException {
Rectangle rectToWrite = new Rectangle(10000, 10000, 20000, 20000);
File file = Files.createFile(tempDir.resolve("test.txt")).toFile();
FileService.writeRectangleToTextFileOneLine(file, rectToWrite);
assertTrue(file.exists());
assertEquals(1, Files.readAllLines(file.toPath()).size());
Rectangle rectRead = FileService.readRectangleFromTextFileOneLine(file);
assertEquals(rectToWrite, rectRead);
}
@Test
public void testFileReadWriteRectangleTextFourLines() throws IOException {
Rectangle rectToWrite = new Rectangle(10000, 10000, 20000, 20000);
File file = Files.createFile(tempDir.resolve("test.txt")).toFile();
FileService.writeRectangleToTextFileFourLines(file, rectToWrite);
assertTrue(file.exists());
assertEquals(4, Files.readAllLines(file.toPath()).size());
Rectangle rectRead = FileService.readRectangleFromTextFileFourLines(file);
assertEquals(rectToWrite, rectRead);
}
@Test
public void testFileReadWriteTraineeTextOneLine() throws NumberFormatException, TrainingException, IOException {
Trainee traineeToWrite = new Trainee("Иван", "Иванов", 2);
File file = Files.createFile(tempDir.resolve("test.txt")).toFile();
FileService.writeTraineeToTextFileOneLine(file, traineeToWrite);
assertTrue(file.exists());
assertEquals(1, Files.readAllLines(file.toPath()).size());
Trainee traineeRead = FileService.readTraineeFromTextFileOneLine(file);
assertEquals(traineeToWrite, traineeRead);
}
@Test
public void testFileReadWriteTraineeTextThreeLines() throws NumberFormatException, TrainingException, IOException {
Trainee traineeToWrite = new Trainee("Иван", "Иванов", 2);
File file = Files.createFile(tempDir.resolve("test.txt")).toFile();
FileService.writeTraineeToTextFileThreeLines(file, traineeToWrite);
assertTrue(file.exists());
assertEquals(3, Files.readAllLines(file.toPath()).size());
Trainee traineeRead = FileService.readTraineeFromTextFileThreeLines(file);
assertEquals(traineeToWrite, traineeRead);
}
@Test
public void testFileSerializeDeserializeTraineeBinary() throws TrainingException, ClassNotFoundException, IOException {
Trainee traineeToWrite = new Trainee("Иван", "Иванов", 2);
File file = Files.createFile(tempDir.resolve("test.txt")).toFile();
FileService.serializeTraineeToBinaryFile(file, traineeToWrite);
assertTrue(file.exists());
Trainee traineeRead = FileService.deserializeTraineeFromBinaryFile(file);
assertEquals(traineeToWrite, traineeRead);
}
@Test
public void testStringSerializeDeserializeTraineeJson() throws TrainingException {
Trainee traineeToWrite = new Trainee("Иван", "Иванов", 2);
String json = FileService.serializeTraineeToJsonString(traineeToWrite);
Trainee traineeRead = FileService.deserializeTraineeFromJsonString(json);
assertEquals(traineeToWrite, traineeRead);
}
@Test
public void testFileSerializeDeserializeTraineeJson() throws TrainingException, IOException {
Trainee traineeToWrite = new Trainee("Иван", "Иванов", 2);
File file = Files.createFile(tempDir.resolve("test.txt")).toFile();
FileService.serializeTraineeToJsonFile(file, traineeToWrite);
assertTrue(file.exists());
Trainee traineeRead = FileService.deserializeTraineeFromJsonFile(file);
assertEquals(traineeToWrite, traineeRead);
}
@Test
public void testThrowsIOException() {
Method[] declaredMethods = FileService.class.getDeclaredMethods();
for (Method method : declaredMethods) {
if (method.getName().equals("serializeTraineeToJsonString") || method.getName().equals("deserializeTraineeFromJsonString")) {
continue;
}
if (!Modifier.isPublic(method.getModifiers())) {
continue;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
boolean throwIOException = false;
for (Class<?> exception : exceptionTypes) {
if (exception == IOException.class) {
throwIOException = true;
break;
}
}
if (!throwIOException) {
fail("Every public method must throw IOException");
}
}
}
}
|
Go | UTF-8 | 518 | 3.734375 | 4 | [] | no_license | package raindrops
import "strconv"
//Convert function Converts a number to a string, the contents of which depend on the number's factors.
func Convert(input int) string {
RaindropNumbers := [3]int{3, 5, 7}
RaindropsStrings := [3]string{"Pling", "Plang", "Plong"}
var Outputstring string
for i := 0; i < len(RaindropNumbers); i++ {
if input%RaindropNumbers[i] == 0 {
Outputstring = Outputstring + RaindropsStrings[i]
}
}
if Outputstring == "" {
return strconv.Itoa(input)
}
return Outputstring
}
|
Java | UTF-8 | 5,597 | 2.140625 | 2 | [] | no_license | package application.controllers;
import application.domain.Account;
import application.domain.enums.AccountType;
import application.dto.AccountDto;
import application.dto.BankSharesDto;
import application.facade.BankSharesServicesFacade;
import application.repository.AccountRepository;
import application.services.AccountService;
import application.services.BankSharesServices;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {BankSharesController.class, BankSharesServices.class, BankSharesServicesFacade.class, AccountService.class})
@WebFluxTest
public class BankSharesControllerTest {
@Autowired
private
ApplicationContext applicationContext;
@Autowired
private
WebTestClient webTestClient;
@MockBean
private
AccountRepository accountRepository;
@InjectMocks
BankSharesDto bankSharesDto;
@Before
public void setUp(){
webTestClient =
WebTestClient.bindToApplicationContext(applicationContext)
.configureClient()
.baseUrl("/shares")
.build();
}
@Test
public void withdrawalNormalAccount() {
bankSharesDto.setCard("123");
bankSharesDto.setAmount(100D);
bankSharesDto.setPassword("123");
Account accountBase = Account.builder()
.accountType(AccountType.NORMAL)
.balance(1000D)
.password("123")
.card("123")
.build();
Mono<Account> accountMono = Mono.just(accountBase);
when(accountRepository.findById(bankSharesDto.getCard())).thenReturn(accountMono);
when(accountRepository.save(any())).thenReturn(accountMono);
webTestClient.post()
.uri("/withdrawal")
.body(Mono.just(bankSharesDto), BankSharesDto.class)
.exchange()
.expectStatus()
.isOk()
.expectBody(AccountDto.class)
.consumeWith(response ->
assertThat(Objects.requireNonNull(response.getResponseBody()).getBalance()).isEqualTo(900D));
}
@Test
public void deposit() {
bankSharesDto.setCard("123");
bankSharesDto.setAmount(100D);
bankSharesDto.setPassword("123");
Account accountBase = Account.builder()
.accountType(AccountType.NORMAL)
.balance(1000D)
.password("123")
.card("123")
.build();
Mono<Account> accountMono = Mono.just(accountBase);
when(accountRepository.findById(bankSharesDto.getCard())).thenReturn(accountMono);
when(accountRepository.save(any())).thenReturn(accountMono);
webTestClient.post()
.uri("/deposit")
.body(Mono.just(bankSharesDto), BankSharesDto.class)
.exchange()
.expectStatus()
.isOk()
.expectBody(AccountDto.class)
.consumeWith(response ->
assertThat(Objects.requireNonNull(response.getResponseBody()).getBalance()).isEqualTo(1100D));
}
@Test
public void transferSavingAccount() {
bankSharesDto.setCard("123");
bankSharesDto.setAmount(100D);
bankSharesDto.setPassword("123");
bankSharesDto.setAccountTransfer("456");
Account accountBaseSubmit = Account.builder()
.accountType(AccountType.SAVING)
.balance(1000D)
.password("123")
.card("123")
.build();
Account accountBaseTransfer = Account.builder()
.accountType(AccountType.SAVING)
.balance(1000D)
.password("123")
.card("456")
.build();
Mono<Account> accountSubmitMono = Mono.just(accountBaseSubmit);
Mono<Account> accountTransferMono = Mono.just(accountBaseTransfer);
when(accountRepository.findById(bankSharesDto.getCard())).thenReturn(accountSubmitMono);
when(accountRepository.save(accountBaseSubmit)).thenReturn(accountSubmitMono);
when(accountRepository.findById(bankSharesDto.getAccountTransfer())).thenReturn(accountTransferMono);
when(accountRepository.save(accountBaseTransfer)).thenReturn(accountTransferMono);
webTestClient.post()
.uri("/transfer")
.body(Mono.just(bankSharesDto), BankSharesDto.class)
.exchange()
.expectStatus()
.isOk()
.expectBody(AccountDto.class)
.consumeWith(response ->
assertThat(Objects.requireNonNull(response.getResponseBody()).getBalance()).isEqualTo(894));
}
} |
Java | UTF-8 | 3,194 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package com.ewcms.system.notice.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
import com.alibaba.fastjson.annotation.JSONField;
import com.ewcms.common.entity.BaseSequenceEntity;
import com.ewcms.common.plugin.entity.Movable;
/**
* 公告栏
*
* <ul>
* <li>title:标题</li>
* <li>titleStyle:标题样式</li>
* <li>content:内容</li>
* <li>externalLinks:外部链接地址</li>
* <li>createDate:创建时间</li>
* <li>updateDate:修改时间</li>
* <li>head:是否标题</li>
* <li>release:是否发布</li>
* <li>weight:顺序号</li>
* <li>
* </ul>
*
* @author wuzhijun
*
*/
@Entity
@Table(name = "sys_notice")
@SequenceGenerator(name="seq", sequenceName="seq_sys_notice_id", allocationSize = 1)
public class Notice extends BaseSequenceEntity<Long> implements Movable{
private static final long serialVersionUID = -845222640210042956L;
@Column(name = "title", nullable = false, unique = true)
private String title;
@Column(name = "title_style")
private String titleStyle;
@Column(name = "content", columnDefinition = "text")
private String content;
@Column(name = "external_links", columnDefinition = "text")
private String externalLinks;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "update_date")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
@Column(name = "is_head")
private Boolean head = Boolean.TRUE;
@Column(name = "is_release")
private Boolean release = Boolean.TRUE;
@Column(name = "weight")
private Integer weight;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitleStyle() {
return titleStyle;
}
public void setTitleStyle(String titleStyle) {
this.titleStyle = titleStyle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getExternalLinks() {
return externalLinks;
}
public void setExternalLinks(String externalLinks) {
this.externalLinks = externalLinks;
}
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Boolean getHead() {
return head;
}
public void setHead(Boolean head) {
this.head = head;
}
public Boolean getRelease() {
return release;
}
public void setRelease(Boolean release) {
this.release = release;
}
@Override
public Integer getWeight() {
return weight;
}
@Override
public void setWeight(Integer weight) {
this.weight = weight;
}
} |
Markdown | UTF-8 | 15,908 | 3.796875 | 4 | [] | no_license | #Binary/bitwise
### Basics:
- A bit is set if it is 1 and unset if it is 0. Example: 10 = 1010 in binary. The lowest bit is unset, the next is set, the next unset, etc.
- 65535 occurs frequently in the field of computing because it is (one less than 2 to the 16th power), which is the highest number that can be represented by an unsigned 16-bit binary number. It can be represented in hexadecimal as 0xFFFF.
### Bit Masking
Bit masking allows you to use operations that work on a bit-level, i.e edit particular bits in a byte or check if particular bit values are present or not.
You apply a mask. The mask itself is a binary number which specifies which bits we're interested in. You apply the mask with the usual binary operators AND, OR, XOR, etc.
AND will get a subset of the bits in x
OR will set a subset of the bits in x
XOR will toggle a subset of the bits in x
### & binary AND. a & b = 1 only if a AND b are 1
so 1100 & 1101 = 1100
def count_bits(x):
num_bits = 0
while x:
num_bits += x & 1
x >>= 1
return num_bits
`count_bits` works by inspecting each binary digit and seeing if it's 1. `x & 1` will only be 1 if x is 1.
if it's 1, we increment our counter, otherwise we add 0 (effectively not incrementing)
so our function here works by just constantly shifting the bits to the right and reading
the right-most one to see if it's 1 and then adding it to the count
10 >> 1 = 1010 >> 1 = 101. Just drop the last bit.
bin(13)
'0b1101'
bin(13 >> 1)
'0b110'
### | binary OR. a & b = 1 if either a OR b are 1
a = 60 = 0011 1100
b = 13 = 0000 1101
a | b = 0011 1101
bin(60 | 13)
'0b111101' = 0011 1101
### ^ Binary XOR. a ^ b = It copies the bit if it is set in one operand but not both.
bin(60 ^ 13)
'0b110001'
### ~ Binary Ones Complement
This is a _unary_ operator, only works on one number.
Inverts all the bits. Each 1 becomes 0 and each 0 becomes 1. So 1111 -> 0000, 0000 -> 1111, 1010 -> 0101
>>> bin(7)
'0b111'
>>> bin(~7)
'-0b1000'
Remember that negative numbers are stored as the two's complement of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits)
`1111 1110`
Why is this `-2`? Because you take its complement (invert all bits) and add 1. So 2 in binary is 0000 0010. The complement 1111 1101. Then we add one getting us 1111 1110. The first bit is is the sign bit, implying a negative.
**The complement operator (~) JUST FLIPS BITS. It is up to the machine to interpret these bits.**
### parity
The parity of a binary word is 1 if the number of 1s in the word is odd; otherwise, it is 0. For example, the parity of 1011 is 1, and the parity of 10001000 is 0.
This is the brute-force approach:
def parity(x):
result = 0
while x:
result ^= x & 1
x >>= 1
return result
How does this work? `parity` returns 1 if number of 1s is odd, otherwise 0.
`x & 1` checks if x is 1
then the XOR sets the result to 1 only it's already 0. If it's 1 then it gets set to 0.
Effectively, every time `result` is already 1, we wipe it back to zero using `^` if we encounter another 1.
The time complexity is _O(n)_, where n is the word size.
Can improve by using trick...
### unsetting/erasing the lowest set bit
`x &(x - 1)
>>> bin(10)
'0b1010'
>>> bin(10 & 10 -1)
'0b1000'
How does this work? Well, first we subtract 1. So 10 = 0b1010. 10 - 1 = 0b1001. Now we use &
1010
&
1001
=
1000
>>> bin(10 & 10 -1)
'0b1000'
>>> bin(10 & 9)
'0b1000'
We can use this to reduce time complexity. If _k_ is number of bits set to 1, then time complexity of this algo is _O(k)_:
def parity(x):
result = 0
while x:
result ^= 1
x &= x - 1 # drop the lowest set bit of x
return result
All we're doing here is just counting 1s because we just flip the result to = 1 if it's currently 0 and to 0 if currently 1. So that's just the odd/even tracker. And we keep dropping the lowest set digit, eventually getting to the number 0.
Observe:
>>> x = 13
>>> format(x, 'b')
'1101'
>>> x &= x -1
>>> x
12
>>> format(x, 'b')
'1100'
>>> x &= x -1
>>> x
8
>>> format(x, 'b')
'1000'
>>> x &= x -1
>>> x
0
>>> format(x, 'b')
'0'
### dealing with a very large number of words
Two keys to performance
1. process multiple bits at a time
2. cache results in array-based lookup table
Obviously can't just cache the parity of every 64-bit integer (an array with just the answer for every number). Way too much storage required!
But doesn't matter how we group bits when computing parity. The computation is associative.
So we can
1. take 64-bit integer and group into 4 16-bit subwords,
2. compute the parity of each subword
3. compute the parity of the four subresults
In other words if we have 1000 0101 0000 0001, we have
parity of 1000 = 1
parity of 0101 = 0
parity of 0000 = 0
parity of 0001 = 1
then take parity of results
parity of 1001 = 0
So we'll take all the 16-bit subwords and we _can_ feasibly cache those in an array. Plus 16 evenly divides 64 so code is simpler.
Let's illustrate the concept using 2-bit words (not like the 16-bit words we'll actually use).
We'll have arrays with the parities. For example [0, 1, 1, 0] are the parities of 0, 1, 2, 3 since 0 = 0, 1 = 01, 2 = 10, 3 = 11.
To get parity of 11001010 all we need is the parity of 11, 00, 10, 10. The cache shows us that the parity of these is 0, 0, 1, 1 which is 0!
But how do we first grab the 11 from 11101010 (diff # than before) to lookup the parity of it? We right shift by 6. 11101010 >> 6 = 00000011. This is the number 3. Use 3 as the index into the array to grab [0, 1, 1, (0)]. Hence the parity is 0.
Next we need the 10 from 11(10)1010. We right shift by 4 to get 0000111. But this is 7 which would give us an out-of-bounds access on the array bc the indices are only 0 through 3.
To solve this we bitwise AND our original number with the number we got after the right shift, namely the 00000011. So we have `11101010 & 00000011`. The `00000011` is the "mask" to get the last two bits. the result is `00000010` which is 2 which is [0, 1, (1), 0] in our array so the parity is 1.
**A mask defines which bits you want to keep, and which bits you want to clear. You apply the mask by:**
- Bitwise ANDing in order to extract a subset of the bits in the value
- Bitwise ORing in order to set a subset of the bits in the value
- Bitwise XORing in order to toggle a subset of the bits in the value
Here's the full solution from the book:
def parity(x):
MASK_SIZE = 16
BIT_MASK = 0xFFFF
return (PRECOMPUTED_PARITY[x >> (3 * MASK_SIZE)] ^
PRECOMPUTED_PARITY[(x >> (2 * MASK_SIZE)) & BIT_MASK] ^
PRECOMPUTED_PARITY[(x >> MASK_SIZE) & BIT_MASK] ^
PRECOMPUTED_PARITY[x & BIT_MASK])
`MASK_SIZE` is the number of bits we're working with or want to shift (in the simpler example the book gave earlier, mask size would be 2)
Then we have this `BIT_MASK` where each bit is set to 1. `0xFFFF` is 65535, the largest number that can be stored in a 16-bit binary number.
First we shift `x >> 3 * MAX_SIZE` to get the last MAX_SIZE bits.
For example, let's say we had the following 64-bit number:
`10001111 01110001 11001100 00010111 01010010 10100010 00110010 10010010`
Incidentally, this is `10336267020334674578` in base 10.
Ok so we want to get the _last_ 16 bits from this.
>>> x =
'1000111101110001110011000001011101010010101000100011001010010010'
>>> b = int(x, 2)
>>> b
10336267020334674578
>>> last_bits = b >> (3 * MASK_SIZE)
>>> bin(last_bits)
'0b1000111101110001'
In other words we went from
`10001111 01110001 11001100 00010111 01010010 10100010 00110010 10010010`
and got
`10001111 01110001`
i.e. the last (left most) 16 bits. This result itself is used as an index into our array and get the parity for that number, either a 0 or a 1. Then we just xor this with the next subword.
How do we get the next subword. Well, instead of right shifting with `3 * MASK_SIZE`, we do it with `2 * MASK_SIZE`, except now we have to use a bitmask to get at the those digits.
>>> BIT_MASK = 0xFFFF
>>> next_bits = b >> (2 * MASK_SIZE) & BIT_MASK
>>> bin(next_bits)
'0b1100110000010111'
In other words we got the digits
`11001100 00010111`
`10001111 01110001 [11001100 00010111] 01010010 10100010 00110010 10010010`
And then the same to get the next
>>> next_bits = (b >> 2) & BIT_MASK
>>> bin(next_bits)
'0b1000110010100100'
which is `10001100 10100100`
which is
`10001111 01110001 11001100 00010111 [01010010 10100010] 00110010 10010010`
By xoring all of these we set the result to 1 only if we have 1 and 0, other we set to 0, effectively flipping between odd and even by using xor.
In the end, the **time complexity is O(n/L) where n is the word size and L is the width of the words for which the results are cached.**
We can do one better using the fact that xor of two bits is defined to be 0 if both bits are 0 or if both are 1; otherwise it's 1. Observe:
>>> 0 ^ 0
0
>>> 1 ^ 1
0
>>> 1 ^ 0
1
>>> 0 ^ 1
1
xor is associative and commutative - doesn't matter how we group the bits and the order doesn't matter.
>>> 0 ^ 0 ^ 1 == 1 ^ 0 ^ 0 == (1 ^ 0) ^ 0 == 1 ^ (0 ^ 0)
True
And the xor of a group of bits is its parity, e.g. in the above example we have an odd number of 1s so the parity is 1 (True = 1). Can exploit this and use CPU's word-level xor to process multiple bits at the same time...
Example: the parity of <b63, b62...b3, b2, b1, b0> is equal to the parity of the xor of <b63, b62, ...b32> and <b31, b30...b0> and these 32-bit values can can be computed with a single shift and single 32-bit xor instruction. Repeat same op on on 32-bit, 16-bit, 8-bit, 4-bit, 2-bit and 1-bit operands to get the final result. (Leading bits are not meaningful and we have to explicitly extract result from the least significant bit)
Example: the parity of `11010111` is the same as the parity of `1101` xored with `0111`, i.e. of `1010`
>>> a = 13
>>> b = 7
>>> bin(a)
'0b1101'
>>> bin(b)
'0b111'
>>> bin(a ^ b)
'0b1010'
This in turn has the parity of 10 xored with 10, i.e. 0
>>> a = 2
>>> b = 2
>>> bin(a)
'0b10'
>>> bin(b)
'0b10'
>>> bin(a ^ b)
'0b0'
Example:
a = 1000111101110001 1100110000010111 010100101010001 00011001010010010
We can get the first 32 bits by right shifting `a >> 32` which gives us
1000111101110001 1100110000010111
So you can just keep xoring half the word size with itself to get the parity. As a final step we need to grab the last bit by using a mask of 1.
The time complexity will be _O(logn)_
def parity(x):
x ^= x >> 32
x ^= x >> 16
x ^= x >> 8
x ^= x >> 4
x ^= x >> 2
x ^= x >> 1
return x & 0x01
Easier to think of this on an 8-bit number
#take x = 11110101
def parity(x):
x ^= x >> 4 # 11110101 >> 4 = 1111 and 11110101 ^ 00001111 = 11111010
x ^= x >> 2 # 11111010 >> 2 = 111110 and 11111010 ^ 00111110 = 11000100
x ^= x >> 1 # 11000100 >> 1 = 1100010 and 11000100 ^ 1100010 = 0100110
return x & 0x01 # take the last bit which is 0 which is the parity of 11110101
###Right propagate the rightmost 1-bit.
`y = x | (x-1)`
`x - 1` only ever modifies bits to the right of the right-most set bit. The right-most bit turns into a 0 and the all the lower bits become 1.
Observe:
101010(1)(0) – 1
=
10101001
00101000 – 1
=
00100111
101111 – 1
=
101110
So all that's left to do is OR with that and this propagates the right-most bit.
### swap bits
We have some tricks e.g x & (x - 1) clears lowest set bit. x & ~(x - 1) extracts lowest set bit.
We can also extract a bit at position `i` with (x >> i) & 1
>>> x = 9
>>> bin(x)
'0b1001'
>>> bin((x >> 1) & 1)
'0b0'
>>> bin((x >> 2) & 1)
'0b0'
>>> bin((x >> 3) & 1)
'0b1'
So, to swap two bits in a number we first check if they're the same. If they are, we don't need to do anything. If they're different, flipping each bit is the same thing as swapping them.
Note: the left shift operator `x << n` has the effect of filling in `n` zeros to the right of `x`, e.g.:
`1001 << 2 = 100100`
So all we need to do is select the bits and XOR them since x ^ 1 = 1 if x is 0 otherwise x ^ 1 = 0 - so it flips/swaps them.
x = 10111
let's say we want to flip the 3 and 1 index
so i = 3 and j = 1
`1(0)1(1)1` so we want to get `1(1)1(0)1` or go from `10111` to `11101`.
first we check that they're different. They are so we set up a bit mask
bit_mask = (1 << i) | (1 << j)
1 << 3 = 1000
1 << 1 = 0010
We're simply creating two binary numbers, one with a bit set in the `i` position and one with a bit set in the `j` position. By ORing these, we have a number with bits set in the `i` *and* `j` positions. We can apply this mask to our input `x` because `x ^ 1` = 0` when `x = 1` and 1 when `x = 0` to swap the bits.
and now we OR them (outputs 1 if either is 1)
1000
|
0010
=
1010 # <---- this is our bit_mask
now we xor our original x with this bitmask
10111
^
01010
=
11101
Full solution is
def swap_bits(x, i, j):
if (x >> i) & 1 != (x >> j) & 1:
bit_mask = (1 << i) | (x << j)
x ^= bit_mask
return x
The time complexity is `O(1)`, independent of the word size.
### closest integer with the same weight
The weight of an integer is the number of bits set to 1 in it, e.g. 101 weight = 2, 11110 weight = 4, etc.
Write a program that takes x and outputs y which has the same weight as x (but not the same number duh) and where the difference |x-y| is as small as possible. If input is 6, for example, output should be 5. Since 6 = 110 and 5 = 101.
The hint we're given is to start with the LSB. Ok... so we know that `x & 1` gives the LSB of `x.
>>> 0b011 & 1
1
>>> 0b010 & 1
0
Here, if we flip the bit at index k1 and the bit at k2, k1 > k2
>>> a = 0b111
>>> b = 0b100 #flipped k1 and k2
Now let's check the difference. `a - b = 011` - the absolute value of the difference is 2^k1 - 2^k2. In our example here, that means a - b = 2^0 - 2^1 which is 3 or 011b. Given this, we want to make k1 as small as possible and k2 as close to k1 to have the difference be as small as possible.
Ok so we want to take the smallest index k1 possible and have the other index k2 be as close to that as possible. But we have the constraint that the bit at index k1 has to be different from the bit in k2. If we don't do that, the flip results in an integer with a different weight. In other words, if the bits were 0, 0 and we flipped em, we'd get 1, 1 and we'd now have a different weight cuz we just added two 1s. Alternatively, if those bits were 1, 1 and we flipped the to 0, 0...once again we got rid of two 1s. Whereas if the bits were 1, 0 or 0, 1 then we flip to 0,1 or 1,0 and we have the same weight. Ok....so...
So the smallest k1 we can use is the rightmost bit that's different from the LSB and k2 must be the very next bit. You can see this here:
>>> 0b110
6
>>> 0b101
5
We flipped the two rightmost bits that differ! **In summary, we want to swap the two rightmost consecutive bits that are different.**
Solution is:
def closest_int_same_bit_count(x):
NUM_UNSIGNED_BITS = 64
for i in range(NUM_UNSIGNED_BITS - 1): # loop will start at LSB
if (x >> i) & 1 != (x >> (i + 1)) & 1: # if the bits at k1 and k2 are different
x ^= (1 << i) | (1 << (i + 1)) # then swap em. We already know how to do this using XOR
return x
raise ValueError('All bits are 0 or 1') # special case - whatever
time complexity is _O(n)_ where _n_ is the integer width.
### reverse digits
42 -> 24, 89 -> 98, -314 -> -413
Hint: how would you solve if the input was given as a string?
|
Java | UTF-8 | 3,366 | 2.078125 | 2 | [] | no_license | package smc;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import helper.DataUrls;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.HttpRequester;
import utils.HttpRespons;
public class TimeTest {
private static String jz_url = DataUrls.ft_qlive;
private static String url = DataUrls.ft_collect;
static Map<String, String> params = new HashMap<String, String>();
public static String getJZMatchs(String issue) throws IOException {
HttpRequester request = new HttpRequester();
request.setDefaultContentEncoding("utf-8");
HttpRespons hr = request.sendGet(jz_url + issue);
String matchs = "";
String json = hr.getContent();
if (json == null || json.equals("")) {
System.out.println("empty content!!!");
return matchs;
} else {
// System.out.println(json);
}
JSONObject obj = JSONObject.fromObject(json);
JSONArray MIarray = obj.getJSONArray("MI");
for (int i = 0; i < MIarray.size(); i++) {
JSONObject MI = MIarray.getJSONObject(i);
JSONArray MSarray = MI.getJSONArray("MS");
for (int j = 0; j < MSarray.size(); j++) {
JSONObject M = MSarray.getJSONObject(j);
int match = M.getInt("MId");
String NUM = M.getString("NUM");
int IC = M.getInt("IC");
int SO = M.getInt("SO");
String SS = M.getString("SS");
if (!(NUM.equals("032") || NUM.equals("033"))) {
continue;
} else {
// if (IC == 1) {
// continue;
// }
request = new HttpRequester();
request.setDefaultContentEncoding("UTF-8");
hr = request.sendGet(url + match);
json = hr.getContent();
if (json == null || json.equals("")) {
System.out.println("json is empty");
} else {
// System.out.println(json);
}
obj = JSONObject.fromObject(json);
MIarray = obj.getJSONArray("MI");
MI = MIarray.getJSONObject(i);
MSarray = MI.getJSONArray("MS");
M = MSarray.getJSONObject(0);
int SO1 = M.getInt("SO");
String SS1 = M.getString("SS");
Date d = new Date();
String ssss = d.toString() + "\t" + NUM + "\t列表源:" + SO + "\t比分列表时间:" + SS + "\t方案详情时间:" + SS1
+ "\t方案源:" + SO1;
System.out.println(ssss);
saveToFile(ssss, "log.txt", false);
matchs = matchs + match;
if (j < MSarray.size() - 1) {
matchs = matchs + ",";
}
break;
}
}
}
System.out.println();
return matchs;
}
public static void saveToFile(String text, String path, boolean isClose) {
File file = new File(path);
BufferedWriter bf = null;
try {
FileOutputStream outputStream = new FileOutputStream(file, true);
OutputStreamWriter outWriter = new OutputStreamWriter(outputStream);
bf = new BufferedWriter(outWriter);
bf.append(text);
bf.newLine();
bf.flush();
if (isClose)
bf.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
for (int i = 0; i < 9 * 60 * 5; i++) {
getJZMatchs("2017-09-05");
Thread.sleep(1 * 1000);
}
}
}
|
Markdown | UTF-8 | 1,063 | 2.875 | 3 | [] | no_license | # Data Intensive Computing - Assignment 2
In this lab assignment done togheter with [Haris Poljo](https://github.com/harispoljo), we practiced stream processing and graph processing using Apache Spark, Apache Kafka, and Apache Cassandra. Moreover, we practiced Apache Spark GraphX within two jupyter notebook.
# Assignment 2 - Part 1
We implemented a Spark Streaming application which calculate the average value of (key, value) pairs and continously update it, while new pairs arrive. We read data from Apache Kafka and store the results in Cassandra continuosuly. The results are in the form of (key, average value) pairs.
* **Requirements**: Kafka 2.6.0, Cassandra 3.11.2, Python 2.7, Spark 2.4.3.
* **Run the code & implementation explanation**: Information can be found in LAB 2, PART 1.pdf
# Assignment 2 - Part 2
* **graphx_songs.ipynb**: Use GraphX to cluster music songs according to the tags attached to each songs.
* **graphx_social_network.ipynb**: Use a GraphX to analyse a property graph.
# Collaborators
- [Haris Poljo](https://github.com/harispoljo).
|
Markdown | UTF-8 | 2,168 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | ---
layout: default
title: More Quickstart Options
description: Quickstart options. This section outlines additional quickstart options to deploying lakeFS.
parent: Quick Start
nav_order: 50
has_children: false
---
# More Quickstart Options
{: .no_toc}
{% include learn_only.html %}
## Table of Contents
{: .no_toc .text-delta }
1. TOC
{:toc}
## Docker on Windows
To run a local lakeFS instance using [Docker Compose](https://docs.docker.com/compose/){:target="_blank"}:
1. Ensure you have Docker installed on your computer, and that compose version is 1.25.04 or higher. For more information, please see this [issue](https://github.com/treeverse/lakeFS/issues/894).
1. Run the following command in your terminal:
```bash
Invoke-WebRequest https://compose.lakefs.io | Select-Object -ExpandProperty Content | docker-compose -f - up
```
1. Check your installation by opening [http://127.0.0.1:8000/setup](http://127.0.0.1:8000/setup){:target="_blank"} in your web browser.
## On Kubernetes with Helm
You can install lakeFS on a Kubernetes cluster with the following commands:
```bash
# Add the lakeFS Helm repository
helm repo add lakefs https://charts.lakefs.io
# Deploy lakeFS with helm release "my-lakefs"
helm install my-lakefs lakefs/lakefs
```
## Using the Binary
Alternatively, you may opt to run the lakefs binary directly on your computer.
1. Download the lakeFS binary for your operating system:
[Download lakefs](../downloads.md){: .btn .btn-green target="_blank"}
1. Install and configure [PostgreSQL](https://www.postgresql.org/download/){:target="_blank"}
1. Create a configuration file:
```yaml
---
database:
connection_string: "postgres://localhost:5432/postgres?sslmode=disable"
blockstore:
type: "local"
local:
path: "~/lakefs_data"
auth:
encrypt:
secret_key: "a random string that should be kept secret"
gateways:
s3:
domain_name: s3.local.lakefs.io:8000
```
1. Create a local directory to store objects:
```sh
mkdir ~/lakefs_data
```
1. Run the server:
```bash
./lakefs --config /path/to/config.yaml run
```
|
JavaScript | UTF-8 | 1,771 | 2.546875 | 3 | [
"MIT"
] | permissive | import { getRoomName } from './helperFunctions'
import { ROOM_ID_PREFIX, CONFIG_CHANGE_EVENT } from '../constants/constants'
import { initializePubsub } from './pubsub'
import logger from '../utils/logger'
class StateManager {
constructor(io, costumeLogger = logger) {
this.logger = costumeLogger
this.io = io
this.startUp()
}
startUp() {
this.logger.log({ message: "StateManager: Initialize ", level: "info" })
const logger = this.logger
this.io.on('connection', function (socket) {
const { serviceName, environment } = socket.request._query;
logger.log({ message: `StateManager: connect serviceName:${serviceName}, environment:${environment}`, level: "info" })
const roomName = getRoomName(serviceName, environment)
socket.join(roomName)
});
}
emitChange(serviceName, environment) {
this.logger.log({ message: `StateManager: emit change on serviceName:${serviceName},environment:${environment} `, level: "info" })
const roomName = getRoomName(serviceName, environment)
this.io.to(roomName).emit(CONFIG_CHANGE_EVENT);
}
getAllActiveRoom() {
const roomKeys = Object.keys(this.io.sockets.adapter.rooms)
.filter(i => i.startsWith(ROOM_ID_PREFIX))
return roomKeys.map(key => ({
room: key,
length: this.io.sockets.adapter.rooms[key].length
}))
}
}
let stateManager;
export function initializeSocket(io) {
initializePubsub(io)
if (stateManager === undefined) {
stateManager = new StateManager(io)
return stateManager
}
throw new Error("already initialize")
}
export function getStateManager() {
return stateManager
} |
Go | UTF-8 | 2,180 | 3.40625 | 3 | [] | no_license | package crudbookstore
import (
"testing"
)
func TestBookStoreAdd(t *testing.T) {
var bookID = 1
newBook := &Book{
ID: 1,
Name: "It",
Language: "Spanish",
Status: "New",
Genre: "Terror",
Editorial: "Plaza&James",
Author: "Stephen King",
Price: 1300,
}
bookStore := NewBookStore()
bookFinded := bookStore.FindByID(bookID)
if bookFinded != nil {
t.Errorf("El libro con el ID %d ya existe!!!\n", bookID)
}
bookStore.Add(*newBook)
bookFinded = bookStore.FindByID(bookID)
if bookFinded == nil {
t.Errorf("El libro con el ID %d no fue agregado!!!\n", bookID)
}
if bookFinded.Name != newBook.Name {
t.Errorf("El libro con el ID %d no tiene el nombre de la consulta", bookID)
}
}
func TestBookStoreRead(t *testing.T) {
var bookID = 1
newBook := &Book{
ID: 1,
Name: "It",
Language: "Spanish",
Status: "New",
Genre: "Terror",
Editorial: "Plaza&James",
Author: "Stephen King",
Price: 1300,
}
bookStore := NewBookStore()
bookStore.Add(*newBook)
bookFinded := bookStore.FindByID(bookID)
if bookFinded == nil {
t.Errorf("El libro con el ID %d no fue encontrado en la bookstore!!!\n", bookID)
}
}
func TestBookStoreUpdate(t *testing.T) {
var bookID = 1
newBook := &Book{
ID: 1,
Name: "It",
Language: "Spanish",
Status: "New",
Genre: "Terror",
Editorial: "Plaza&James",
Author: "Stephen King",
Price: 1300,
}
bookStore := NewBookStore()
bookStore.Add(*newBook)
newBook.Price = 1500
bookStore.Update(*newBook)
bookFinded := bookStore.FindByID(bookID)
if bookFinded.Price != 1500 {
t.Errorf("El libro con el ID %d no se pudo eliminar!!!\n", bookID)
}
}
func TestBookStoreDelete(t *testing.T) {
var bookID = 1
newBook := &Book{
ID: 1,
Name: "It",
Language: "Spanish",
Status: "New",
Genre: "Terror",
Editorial: "Plaza&James",
Author: "Stephen King",
Price: 1300,
}
bookStore := NewBookStore()
bookStore.Add(*newBook)
bookStore.Delete(bookID)
bookFinded := bookStore.FindByID(bookID)
if bookFinded != nil {
t.Errorf("El libro con el ID %d no se pudo eliminar!!!\n", bookID)
}
}
|
Java | UTF-8 | 1,186 | 2.046875 | 2 | [] | no_license | package com.example.onsenseach;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class OnsenMapActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("OnsenMapActivity", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onsen_map);
//フラグメントトランザクションの開始
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
OnsenMapFragment fragment = new OnsenMapFragment();
if(getIntent() != null && getIntent().getExtras() != null) {
fragment.setArguments(getIntent().getExtras());
}
transaction.add(R.id.container, fragment);
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.onsen_map, menu);
return true;
}
@Override
public void onResume() {
super.onResume();
}
}
|
Java | UTF-8 | 10,328 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package com.hyphenate.chatuidemo;
import android.content.Context;
import com.hyphenate.chatuidemo.db.UserDao;
import com.hyphenate.chatuidemo.domain.RobotUser;
import com.hyphenate.chatuidemo.utils.PreferenceManager;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DemoModel {
UserDao dao = null;
protected Context context = null;
protected Map<Key,Object> valueCache = new HashMap<Key,Object>();
public DemoModel(Context ctx){
context = ctx;
PreferenceManager.init(context);
}
public boolean saveContactList(List<EaseUser> contactList) {
UserDao dao = new UserDao(context);
dao.saveContactList(contactList);
return true;
}
public Map<String, EaseUser> getContactList() {
UserDao dao = new UserDao(context);
return dao.getContactList();
}
public void saveContact(EaseUser user){
UserDao dao = new UserDao(context);
dao.saveContact(user);
}
/**
* save current username
* @param username
*/
public void setCurrentUserName(String username){
PreferenceManager.getInstance().setCurrentUserName(username);
}
public String getCurrentUsernName(){
return PreferenceManager.getInstance().getCurrentUsername();
}
public Map<String, RobotUser> getRobotList(){
UserDao dao = new UserDao(context);
return dao.getRobotUser();
}
public boolean saveRobotList(List<RobotUser> robotList){
UserDao dao = new UserDao(context);
dao.saveRobotUser(robotList);
return true;
}
public void setSettingMsgNotification(boolean paramBoolean) {
PreferenceManager.getInstance().setSettingMsgNotification(paramBoolean);
valueCache.put(Key.VibrateAndPlayToneOn, paramBoolean);
}
public boolean getSettingMsgNotification() {
Object val = valueCache.get(Key.VibrateAndPlayToneOn);
if(val == null){
val = PreferenceManager.getInstance().getSettingMsgNotification();
valueCache.put(Key.VibrateAndPlayToneOn, val);
}
return (Boolean) (val != null?val:true);
}
public void setSettingMsgSound(boolean paramBoolean) {
PreferenceManager.getInstance().setSettingMsgSound(paramBoolean);
valueCache.put(Key.PlayToneOn, paramBoolean);
}
public boolean getSettingMsgSound() {
Object val = valueCache.get(Key.PlayToneOn);
if(val == null){
val = PreferenceManager.getInstance().getSettingMsgSound();
valueCache.put(Key.PlayToneOn, val);
}
return (Boolean) (val != null?val:true);
}
public void setSettingMsgVibrate(boolean paramBoolean) {
PreferenceManager.getInstance().setSettingMsgVibrate(paramBoolean);
valueCache.put(Key.VibrateOn, paramBoolean);
}
public boolean getSettingMsgVibrate() {
Object val = valueCache.get(Key.VibrateOn);
if(val == null){
val = PreferenceManager.getInstance().getSettingMsgVibrate();
valueCache.put(Key.VibrateOn, val);
}
return (Boolean) (val != null?val:true);
}
public void setSettingMsgSpeaker(boolean paramBoolean) {
PreferenceManager.getInstance().setSettingMsgSpeaker(paramBoolean);
valueCache.put(Key.SpakerOn, paramBoolean);
}
public boolean getSettingMsgSpeaker() {
Object val = valueCache.get(Key.SpakerOn);
if(val == null){
val = PreferenceManager.getInstance().getSettingMsgSpeaker();
valueCache.put(Key.SpakerOn, val);
}
return (Boolean) (val != null?val:true);
}
public void setDisabledGroups(List<String> groups){
if(dao == null){
dao = new UserDao(context);
}
List<String> list = new ArrayList<String>();
list.addAll(groups);
for(int i = 0; i < list.size(); i++){
if(EaseAtMessageHelper.get().getAtMeGroups().contains(list.get(i))){
list.remove(i);
i--;
}
}
dao.setDisabledGroups(list);
valueCache.put(Key.DisabledGroups, list);
}
public List<String> getDisabledGroups(){
Object val = valueCache.get(Key.DisabledGroups);
if(dao == null){
dao = new UserDao(context);
}
if(val == null){
val = dao.getDisabledGroups();
valueCache.put(Key.DisabledGroups, val);
}
//noinspection unchecked
return (List<String>) val;
}
public void setDisabledIds(List<String> ids){
if(dao == null){
dao = new UserDao(context);
}
dao.setDisabledIds(ids);
valueCache.put(Key.DisabledIds, ids);
}
public List<String> getDisabledIds(){
Object val = valueCache.get(Key.DisabledIds);
if(dao == null){
dao = new UserDao(context);
}
if(val == null){
val = dao.getDisabledIds();
valueCache.put(Key.DisabledIds, val);
}
//noinspection unchecked
return (List<String>) val;
}
public void setGroupsSynced(boolean synced){
PreferenceManager.getInstance().setGroupsSynced(synced);
}
public boolean isGroupsSynced(){
return PreferenceManager.getInstance().isGroupsSynced();
}
public void setContactSynced(boolean synced){
PreferenceManager.getInstance().setContactSynced(synced);
}
public boolean isContactSynced(){
return PreferenceManager.getInstance().isContactSynced();
}
public void setBlacklistSynced(boolean synced){
PreferenceManager.getInstance().setBlacklistSynced(synced);
}
public boolean isBacklistSynced(){
return PreferenceManager.getInstance().isBacklistSynced();
}
public void allowChatroomOwnerLeave(boolean value){
PreferenceManager.getInstance().setSettingAllowChatroomOwnerLeave(value);
}
public boolean isChatroomOwnerLeaveAllowed(){
return PreferenceManager.getInstance().getSettingAllowChatroomOwnerLeave();
}
public void setDeleteMessagesAsExitGroup(boolean value) {
PreferenceManager.getInstance().setDeleteMessagesAsExitGroup(value);
}
public boolean isDeleteMessagesAsExitGroup() {
return PreferenceManager.getInstance().isDeleteMessagesAsExitGroup();
}
public void setDeleteMessagesAsExitChatRoom(boolean value) {
PreferenceManager.getInstance().setDeleteMessagesAsExitChatRoom(value);
}
public boolean isDeleteMessagesAsExitChatRoom() {
return PreferenceManager.getInstance().isDeleteMessagesAsExitChatRoom();
}
public void setTransfeFileByUser(boolean value) {
PreferenceManager.getInstance().setTransferFileByUser(value);
}
public boolean isSetTransferFileByUser() {
return PreferenceManager.getInstance().isSetTransferFileByUser();
}
public void setAutodownloadThumbnail(boolean autodownload) {
PreferenceManager.getInstance().setAudodownloadThumbnail(autodownload);
}
public boolean isSetAutodownloadThumbnail() {
return PreferenceManager.getInstance().isSetAutodownloadThumbnail();
}
public void setAutoAcceptGroupInvitation(boolean value) {
PreferenceManager.getInstance().setAutoAcceptGroupInvitation(value);
}
public boolean isAutoAcceptGroupInvitation() {
return PreferenceManager.getInstance().isAutoAcceptGroupInvitation();
}
public void setAdaptiveVideoEncode(boolean value) {
PreferenceManager.getInstance().setAdaptiveVideoEncode(value);
}
public boolean isAdaptiveVideoEncode() {
return PreferenceManager.getInstance().isAdaptiveVideoEncode();
}
public void setPushCall(boolean value) {
PreferenceManager.getInstance().setPushCall(value);
}
public boolean isPushCall() {
return PreferenceManager.getInstance().isPushCall();
}
public void setRestServer(String restServer){
PreferenceManager.getInstance().setRestServer(restServer);
}
public String getRestServer(){
return PreferenceManager.getInstance().getRestServer();
}
public void setIMServer(String imServer){
PreferenceManager.getInstance().setIMServer(imServer);
}
public String getIMServer(){
return PreferenceManager.getInstance().getIMServer();
}
public void enableCustomServer(boolean enable){
PreferenceManager.getInstance().enableCustomServer(enable);
}
public boolean isCustomServerEnable(){
return PreferenceManager.getInstance().isCustomServerEnable();
}
public void enableCustomAppkey(boolean enable) {
PreferenceManager.getInstance().enableCustomAppkey(enable);
}
public boolean isCustomAppkeyEnabled() {
return PreferenceManager.getInstance().isCustomAppkeyEnabled();
}
public void setCustomAppkey(String appkey) {
PreferenceManager.getInstance().setCustomAppkey(appkey);
}
public boolean isMsgRoaming() {
return PreferenceManager.getInstance().isMsgRoaming();
}
public void setMsgRoaming(boolean roaming) {
PreferenceManager.getInstance().setMsgRoaming(roaming);
}
public boolean isShowMsgTyping() {
return PreferenceManager.getInstance().isShowMsgTyping();
}
public void showMsgTyping(boolean show) {
PreferenceManager.getInstance().showMsgTyping(show);
}
public String getCutomAppkey() {
return PreferenceManager.getInstance().getCustomAppkey();
}
public void setUseFCM(boolean useFCM) {
PreferenceManager.getInstance().setUseFCM(useFCM);
}
public boolean isUseFCM() {
return PreferenceManager.getInstance().isUseFCM();
}
enum Key{
VibrateAndPlayToneOn,
VibrateOn,
PlayToneOn,
SpakerOn,
DisabledGroups,
DisabledIds
}
}
|
Shell | UTF-8 | 636 | 3.484375 | 3 | [] | no_license | #!/bin/bash
echo -e "\033[0;32mDeploying updates to GitHub...\033[0m"
echo -e "\033[0;32mBuild Module\033[0m"
hugo -t hugo-theme-minos # if using a theme, replace with `hugo -t <YOURTHEME>`
# Go To Public folder
cd public
# Add changes to git.
echo -e "\033[0;32mAdding changes before commit...\033[0m"
git add .
# Commit changes.
msg="rebuilding site `date`"
if [ $# -eq 1 ]
then msg="$1"
fi
echo -e "\033[0;32mCommit Changes\033[0m"
git commit -m "$msg"
# Push source and build repos.
echo -e "\033[0;32mPush Changes\033[0m"
git push origin master
echo -e "\033[0;32mFinish!\033[0m"
# Come Back up to the Project Root
cd ..
|
JavaScript | UTF-8 | 474 | 3.421875 | 3 | [
"MIT"
] | permissive | var fizzBuzz = function() {
var getResult = function(number) {
if (isMultipleOfThree(number) && isMultipleOfFive(number))
return "fizzBuzz";
if (isMultipleOfThree(number))
return "Fizz";
if (isMultipleOfFive(number))
return "Buzz";
return number.toString();
};
var isMultipleOfThree = function(number) {
return number % 3 === 0;
};
var isMultipleOfFive = function(number) {
return number % 5 === 0;
};
return {
getResult: getResult
};
}; |
C++ | UTF-8 | 1,478 | 3.015625 | 3 | [] | no_license | #include "Grid.h"
CGrid::CGrid()
{
objects.clear();
}
void CGrid::Init()
{
cells = new CCell*[numCol];
for (int i = 0; i < numCol; i++)
cells[i] = new CCell[numRow];
}
void CGrid::Add(LPGAMEOBJECT object, float x, float y)
{
int startX = x / CELL_WIDTH;
int startY = y / CELL_HEIGHT;
int endX = (x + object->GetWidth()) / CELL_WIDTH;
int endY = (y + object->GetHeight()) / CELL_HEIGHT;
for (int i = startX; i <= endX; i++)
{
/*for (int j = startY; j <= endY; j++)
{
cells[i][j].Add(object);
}*/
cells[i][startY].Add(object);
}
//cells[startX][startY].Add(object);
}
void CGrid::Add(LPGAMEOBJECT object, int xCell, int yCell)
{
cells[xCell][yCell].Add(object);
}
vector<LPGAMEOBJECT> CGrid::GetList()
{
CGame * game = CGame::GetInstance();
float x, y;
x = game->GetCamPosX();
y = game->GetCamPosY();
int startX = x / CELL_WIDTH;
int endX = (x + game->GetScreenWidth()) / CELL_WIDTH;
int startY = y / CELL_HEIGHT;
int endY = (y + game->GetScreenHeight()) / CELL_HEIGHT;
objects.clear();
for (int i = startX; i <= endX; i++)
{
for (int j = startY; j <= endY; j++)
{
if (cells[i][j].GetObjects().size() > 0)
{
for (int k = 0; k < cells[i][j].GetObjects().size(); k++)
{
objects.push_back(cells[i][j].GetObjects().at(k));
}
}
}
}
return objects;
}
void CGrid::Unload()
{
for (int i = 0; i < numCol; i++)
{
for (int j = 0; j < numRow; j++)
{
cells[i][j].Unload();
}
}
objects.clear();
}
|
C | UTF-8 | 510 | 3.84375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
char isprime(int n){
if(n<=1){
return 'N';
}
else{
for (int i=2;i<n;i++){
if((n%i)==0){
return 'N';
}
}
return 'Y';
}
}
int main (void){
char prime;
prime=isprime(100);
printf("100 is prime? - %c\n",prime);
prime= isprime(307);
printf("307 is prime? - %c\n",prime);
prime= isprime(1050);
printf("1050 is prime? - %c\n",prime);
prime= isprime(197);
printf("197 is prime? - %c\n",prime);
return EXIT_SUCCESS;
}
|
Java | UTF-8 | 1,005 | 2.0625 | 2 | [] | no_license | package hipevents.common;
import hipevents.event.exception.EventNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
@ControllerAdvice
@RestController
public class BaseExceptionHandler {
private Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@ExceptionHandler
public ResponseEntity handleEventNotFoundException(EventNotFoundException e) {
logger.warn("Event not found. id={}", e.id);
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
@ExceptionHandler
public ResponseEntity handleUndefinedException(Exception e) {
logger.error("Error={1}", e);
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
Ruby | UTF-8 | 551 | 2.6875 | 3 | [] | no_license | require 'json'
require 'rest-client'
class Licenses
GET_URL = 'https://data.fcc.gov/api/license-view/basicSearch/getLicenses'.freeze
def get_callsigns(search_value)
params = { searchValue: search_value, format: 'json' }
response = RestClient.get GET_URL, params: params
raise "Invalid response code: #{response.code}" unless response.code == 200
payload = JSON.parse(response.body)
case payload['status']
when 'OK'
payload['Licenses']['License'].map{|l| l['callsign']}
when 'Info'
[]
end
end
end
|
Java | UTF-8 | 769 | 1.789063 | 2 | [] | no_license | package pe.com.pacasmayo.sgcp.presentacion.gwt.util.cliente;
import java.util.Date;
import com.google.gwt.core.client.JavaScriptObject;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.widgets.form.fields.DateItem;
public class DateItemv2 extends DateItem{
static JavaScriptObject startDateJS = JSOHelper.toDateJS((new Date()));
static JavaScriptObject endDateJS = JSOHelper.toDateJS((new Date()));
static {
setDefaultDateRange(startDateJS, endDateJS);
}
private native static void setDefaultDateRange (JavaScriptObject startDateJS, JavaScriptObject endDateJS) /*-{
$wnd.isc.DateItem.addProperties({
startDate:startDateJS,
endDate:endDateJS
});
}-*/;
}
|
C++ | UTF-8 | 140 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float a = 2;
float b = 3;
float c = a/b;
cout << c;
return 0;
}
|
C++ | UTF-8 | 364 | 2.90625 | 3 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxNum=INT_MIN;
int temp=0;
for(const auto& num:nums){
if(temp+num>maxNum) {maxNum=temp+num;}
temp=temp+num;
if(temp<0) {temp=0;}
}
return maxNum;
}
}; |
Python | UTF-8 | 405 | 2.640625 | 3 | [] | no_license | import cv2
import numpy as np
import matplotlib.pyplot as plt
img =cv2.imread('Photos/park.jpg')
#BGR to gray
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#bgr to hsv
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#BGR to LAB
lab=cv2.cvtColor(img,cv2.COLOR_BGR2Lab)
#BGR to RGB
rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
cv2.imshow('RGB',rgb)
cv2.imshow('Park',img)
plt.imshow(rgb)
plt.show()
cv2.waitKey(0) |
C# | UTF-8 | 1,569 | 2.5625 | 3 | [] | no_license | using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace RemoteAudio
{
public class AudioServer
{
private static AudioServer instance;
private List<Stream> networkClients;
public AudioServer() {
instance = this;
networkClients = new List<Stream>();
}
public static AudioServer getInstance() {
return instance;
}
public List<Stream> getNetworkClients()
{
return networkClients;
}
public void start() {
// 开始监听http请求
string baseUrl = "http://*:" + ConfigurationManager.AppSettings["port"] + "/";
WebApp.Start<StartUp>(baseUrl);
Console.WriteLine("Server listening on " + ConfigurationManager.AppSettings["port"]);
}
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
lock(networkClients) {
networkClients.Add(outputStream);
}
Program.addClient(outputStream);
await Task.Run(() => {
while(networkClients.IndexOf(outputStream) != -1)
{
Thread.Sleep(1000);
}
});
Console.WriteLine("removed");
}
}
}
|
C# | UTF-8 | 1,389 | 3.234375 | 3 | [] | no_license | using AliasGameBL.Utillity;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AliasGameBL.Models
{
public class CardFactory
{
int MaxWordsCountInOneCard;
IShuffler<string> Shuffler;
ICutter<string> Cutter;
public CardFactory(int wordsCountInOneCard, IShuffler<string> shuffler, ICutter<string> cutter)
{
if (wordsCountInOneCard <= 0) throw new ArgumentException("Параметр wordsCountInOneCard должен быть больше нуля!");
this.MaxWordsCountInOneCard = wordsCountInOneCard;
this.Shuffler = shuffler;
this.Cutter = cutter;
}
public IEnumerable<Card> GetCards(IEnumerable<string> words)
{
var activeWords = Cutter.CutMultipleOfBasis(words, MaxWordsCountInOneCard);
var shuffledWords = Shuffler.Shuffle(activeWords);
var wordGroups = shuffledWords
.Select((word, index) => new
{
Word = word,
CardIndex = (int)(index / MaxWordsCountInOneCard)
})
.GroupBy(x => x.CardIndex)
.ToArray();
return wordGroups
.Select(x => new Card(x.Key, x.Select(w => w.Word).ToArray()))
.ToArray();
}
}
}
|
C++ | UTF-8 | 8,284 | 2.515625 | 3 | [
"WTFPL"
] | permissive | #if 0
#include <algorithm>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <limits>
#include "Common/alloc.h"
#include "Common/cpuinfo.h"
#include "Common/except.h"
#include "Common/linebuffer.h"
#include "Common/pixel.h"
#include "Common/plane.h"
#include "resize.h"
#include "resize_impl.h"
namespace zimg {;
namespace resize {;
namespace {;
bool resize_h_first(double xscale, double yscale)
{
double h_first_cost = std::max(xscale, 1.0) * 2.0 + xscale * std::max(yscale, 1.0);
double v_first_cost = std::max(yscale, 1.0) + yscale * std::max(xscale, 1.0) * 2.0;
return h_first_cost < v_first_cost;
}
unsigned ceillog2(unsigned x)
{
unsigned n = std::numeric_limits<unsigned>::digits;
for (; n != 0; --n) {
if (x & (1U << (n - 1)))
break;
}
return (1U << (n - 1)) < x ? n : n - 1;
}
template <class Alloc>
LineBuffer<void> alloc_line_buffer(Alloc &alloc, unsigned count, unsigned width, PixelType type)
{
unsigned log2count = ceillog2(count);
unsigned stride = align(width * pixel_size(type), ALIGNMENT);
unsigned pow2count = log2count >= std::numeric_limits<unsigned>::digits ? UINT_MAX : 1U << log2count;
unsigned mask = pow2count == UINT_MAX ? UINT_MAX : pow2count - 1;
void *ptr = alloc.allocate((size_t)pow2count * stride);
return{ ptr, width, stride, mask };
}
void invoke_impl(const ResizeImpl *impl, PixelType type, const LineBuffer<void> &src, LineBuffer<void> &dst, unsigned n, void *tmp)
{
switch (type) {
case PixelType::BYTE:
throw ZimgUnsupportedError{ "BYTE not supported for resize" };
case PixelType::WORD:
impl->process_u16(buffer_cast<uint16_t>(src), buffer_cast<uint16_t>(dst), n, tmp);
break;
case PixelType::HALF:
impl->process_f16(buffer_cast<uint16_t>(src), buffer_cast<uint16_t>(dst), n, tmp);
break;
case PixelType::FLOAT:
impl->process_f32(buffer_cast<float>(src), buffer_cast<float>(dst), n, tmp);
break;
default:
break;
}
}
} // namespace
struct ResizeContext {
LineBuffer<void> src_border_buf;
LineBuffer<void> dst_border_buf;
LineBuffer<void> tmp_buf;
void *tmp_data;
ResizeImpl *impl1;
ResizeImpl *impl2;
unsigned tmp_width;
unsigned tmp_height;
unsigned in_buffering1;
unsigned in_buffering2;
unsigned out_buffering1;
unsigned out_buffering2;
};
Resize::Resize(const Filter &f, int src_width, int src_height, int dst_width, int dst_height,
double shift_w, double shift_h, double subwidth, double subheight, CPUClass cpu)
try :
m_src_width{ (unsigned)src_width },
m_src_height{ (unsigned)src_height },
m_dst_width{ (unsigned)dst_width },
m_dst_height{ (unsigned)dst_height },
m_skip_h{ src_width == dst_width && shift_w == 0.0 && subwidth == src_width },
m_skip_v{ src_height == dst_height && shift_h == 0.0 && subheight == src_height },
m_impl_h{ create_resize_impl(f, true, src_width, dst_width, shift_w, subwidth, cpu) },
m_impl_v{ create_resize_impl(f, false, src_height, dst_height, shift_h, subheight, cpu) }
{
} catch (const std::bad_alloc &) {
throw ZimgOutOfMemory{};
}
template <class Alloc>
ResizeContext Resize::get_context(Alloc &alloc, PixelType type) const
{
ResizeContext ctx{};
if (!m_skip_h && !m_skip_v) {
double xscale = (double)m_dst_width / (double)m_src_width;
double yscale = (double)m_dst_height / (double)m_src_height;
bool h_first = resize_h_first(xscale, yscale);
ctx.impl1 = h_first ? m_impl_h.get() : m_impl_v.get();
ctx.impl2 = h_first ? m_impl_v.get() : m_impl_h.get();
ctx.tmp_width = h_first ? m_dst_width : m_src_width;
ctx.tmp_height = h_first ? m_src_height : m_dst_height;
ctx.in_buffering1 = std::min(ctx.impl1->input_buffering(type), m_src_height);
ctx.in_buffering2 = std::min(ctx.impl2->input_buffering(type), ctx.tmp_height);
ctx.out_buffering1 = ctx.impl1->output_buffering(type);
ctx.out_buffering2 = ctx.impl2->output_buffering(type);
ctx.src_border_buf = alloc_line_buffer(alloc, ctx.in_buffering1, m_src_width, type);
ctx.dst_border_buf = alloc_line_buffer(alloc, ctx.out_buffering2, m_dst_width, type);
ctx.tmp_buf = alloc_line_buffer(alloc, ctx.out_buffering1 + ctx.in_buffering2 - 1, ctx.tmp_width, type);
ctx.tmp_data = alloc.allocate(std::max(ctx.impl1->tmp_size(type, ctx.tmp_width), ctx.impl2->tmp_size(type, m_dst_width)));
} else if (!(m_skip_h && m_skip_v)) {
ctx.impl1 = m_impl_h ? m_impl_h.get() : m_impl_v.get();
ctx.in_buffering1 = std::min(ctx.impl1->input_buffering(type), m_src_height);
ctx.out_buffering1 = ctx.impl1->output_buffering(type);
ctx.src_border_buf = alloc_line_buffer(alloc, ctx.in_buffering1, m_src_width, type);
ctx.dst_border_buf = alloc_line_buffer(alloc, ctx.out_buffering1, m_dst_width, type);
ctx.tmp_data = alloc.allocate(ctx.impl1->tmp_size(type, m_dst_width));
}
return ctx;
}
size_t Resize::tmp_size(PixelType type) const
{
FakeAllocator alloc;
get_context(alloc, type);
return alloc.count();
}
void Resize::process1d(const ImagePlane<const void> &src, const ImagePlane<void> &dst, void *tmp) const
{
PixelType type = src.format().type;
LinearAllocator alloc{ tmp };
ResizeContext ctx = get_context(alloc, type);
LineBuffer<void> src_buf{ (void *)src.data(), (unsigned)src.width(), (unsigned)src.stride() * pixel_size(type), UINT_MAX };
LineBuffer<void> dst_buf{ dst.data(), (unsigned)dst.width(), (unsigned)dst.stride() * pixel_size(type), UINT_MAX };
bool overflow_flag = false;
unsigned src_linesize = m_src_width * pixel_size(type);
unsigned dst_linesize = m_dst_width * pixel_size(type);
for (unsigned i = 0; i < m_dst_height; i += ctx.out_buffering1) {
const LineBuffer<void> *in_buf = &src_buf;
LineBuffer<void> *out_buf = &dst_buf;
unsigned dep_first = ctx.impl1->dependent_line(i);
unsigned dep_last = dep_first + ctx.in_buffering1;
if (dep_last > m_src_height) {
if (!overflow_flag) {
copy_buffer_lines(src_buf, ctx.src_border_buf, src_linesize, dep_first, m_src_height);
overflow_flag = true;
}
in_buf = &ctx.src_border_buf;
}
if (i + ctx.out_buffering1 > m_dst_height)
out_buf = &ctx.dst_border_buf;
invoke_impl(ctx.impl1, type, *in_buf, *out_buf, i, ctx.tmp_data);
if (i + ctx.out_buffering1 > m_dst_height)
copy_buffer_lines(ctx.dst_border_buf, dst_buf, dst_linesize, i, m_dst_height);
}
}
void Resize::process2d(const ImagePlane<const void> &src, const ImagePlane<void> &dst, void *tmp) const
{
PixelType type = src.format().type;
LinearAllocator alloc{ tmp };
ResizeContext ctx = get_context(alloc, type);
LineBuffer<void> src_buf{ (void *)src.data(), (unsigned)src.width(), (unsigned)src.stride() * pixel_size(type), UINT_MAX };
LineBuffer<void> dst_buf{ dst.data(), (unsigned)dst.width(), (unsigned)dst.stride() * pixel_size(type), UINT_MAX };
bool overflow_flag = false;
unsigned buffer_pos = 0;
unsigned src_linesize = m_src_width * pixel_size(type);
unsigned dst_linesize = m_dst_width * pixel_size(type);
for (unsigned i = 0; i < m_dst_height; i += ctx.out_buffering2) {
const LineBuffer<void> *in_buf = &src_buf;
LineBuffer<void> *out_buf = &dst_buf;
unsigned dep2_first = ctx.impl2->dependent_line(i);
unsigned dep2_last = std::min(dep2_first + ctx.in_buffering2, ctx.tmp_height);
for (; buffer_pos < dep2_last; buffer_pos += ctx.out_buffering1) {
unsigned dep1_first = ctx.impl1->dependent_line(buffer_pos);
unsigned dep1_last = dep1_first + ctx.in_buffering1;
if (dep1_last > m_src_height) {
if (!overflow_flag) {
copy_buffer_lines(src_buf, ctx.src_border_buf, src_linesize, dep1_first, m_src_height);
overflow_flag = true;
}
in_buf = &ctx.src_border_buf;
}
invoke_impl(ctx.impl1, type, *in_buf, ctx.tmp_buf, buffer_pos, ctx.tmp_data);
}
if (i + ctx.out_buffering2 > m_dst_height)
out_buf = &ctx.dst_border_buf;
invoke_impl(ctx.impl2, type, ctx.tmp_buf, *out_buf, i, ctx.tmp_data);
if (i + ctx.out_buffering2 > m_dst_height)
copy_buffer_lines(ctx.dst_border_buf, dst_buf, dst_linesize, i, m_dst_height);
}
}
void Resize::process(const ImagePlane<const void> &src, const ImagePlane<void> &dst, void *tmp) const
{
if (m_skip_h && m_skip_v)
copy_image_plane(src, dst);
else if (m_skip_h || m_skip_v)
process1d(src, dst, tmp);
else
process2d(src, dst, tmp);
}
} // namespace resize
} // namespace zimg
#endif
|
PHP | UTF-8 | 1,571 | 2.78125 | 3 | [] | no_license | <?php
namespace MarsRover;
use PHPUnit\Framework\TestCase;
use MarsRover\Rover\Orientation;
class OrientationTest extends TestCase {
public function testGetOrientation() {
$pos = new Orientation(-1, 0);
self::assertEquals(2, $pos->determine_orientation());
$pos = new Orientation(0, 1);
self::assertEquals(3, $pos->determine_orientation());
}
public function testGetOrientationBadVector() {
$pos = new Orientation(0, 0);
static::expectException(\OutOfBoundsException::class);
$pos->determine_orientation();
}
public function testWrongOrientationXConstructor() {
static::expectException(\InvalidArgumentException::class);
$pos = new Orientation(-2, 0);
}
public function testWrongOrientationYConstructor() {
static::expectException(\InvalidArgumentException::class);
$pos = new Orientation(0, 2);
}
public function testSetOrientation() {
$pos = new Orientation(-1, 0);
self::assertEquals([1, 0], $pos->orient(0));
self::assertEquals([0, -1], $pos->orient(1));
}
public function testSetOrientationOutOfBounds() {
$pos = new Orientation(-1, 0);
self::assertEquals([0, -1], $pos->orient(5));
}
public function testTurn() {
$pos = new Orientation(1, 0);
$pos = $pos->turn(Orientation::TURN_LEFT);
self::assertEquals([0, 1], $pos->vector);
$pos = $pos->turn(Orientation::TURN_RIGHT);
self::assertEquals([1, 0], $pos->vector);
}
public function testTurnInsupportedOperation() {
$pos = new Orientation(1, 0);
static::expectException(\InvalidArgumentException::class);
$pos = $pos->turn(9999);
}
} |
Java | UTF-8 | 2,659 | 2.640625 | 3 | [] | no_license | package edu.hm.dako.chat.server;
import java.util.concurrent.atomic.AtomicInteger;
import edu.hm.dako.chat.common.ChatPDU;
import edu.hm.dako.chat.connection.Connection;
/**
* Abstrakte Klasse mit Basisfunktionalitaet fuer serverseitige Worker-Threads
*
* @author Peter Mandl
*
*/
public abstract class AbstractWorkerThread extends Thread {
// Verbindungs-Handle
protected Connection connection;
// Kennzeichen zum Beenden des Worker-Threads
protected boolean finished = false;
// Username des durch den Worker-Thread bedienten Clients
protected String userName = null;
// Client-Threadname
protected String clientThreadName = null;
// Startzeit fuer die Serverbearbeitungszeit
protected long startTime;
// Gemeinsam fuer alle Workerthreads verwaltete Liste aller eingeloggten
// Clients
protected SharedChatClientList clients;
// Referenzen auf globale Zaehler fuer Testausgaben
protected AtomicInteger logoutCounter;
protected AtomicInteger eventCounter;
protected AtomicInteger confirmCounter;
protected ChatServerGuiInterface serverGuiInterface;
public AbstractWorkerThread(Connection con, SharedChatClientList clients,
SharedServerCounter counter, ChatServerGuiInterface serverGuiInterface) {
this.connection = con;
this.clients = clients;
this.logoutCounter = counter.logoutCounter;
this.eventCounter = counter.eventCounter;
this.confirmCounter = counter.confirmCounter;
this.serverGuiInterface = serverGuiInterface;
}
/**
* Aktion fuer die Behandlung ankommender Login-Requests: Neuen Client anlegen
* und alle Clients informieren
*
* @param receivedPdu
* Empfangene PDU
*/
protected abstract void loginRequestAction(ChatPDU receivedPdu);
/**
* Aktion fuer die Behandlung ankommender Logout-Requests: Alle Clients
* informieren, Response senden und Client loeschen
*
* @param receivedPdu
* Empfangene PDU
*/
protected abstract void logoutRequestAction(ChatPDU receivedPdu);
/**
* Aktion fuer die Behandlung ankommender ChatMessage-Requests: Chat-Nachricht
* an alle Clients weitermelden
*
* @param receivedPdu
* Empfangene PDU
*/
protected abstract void chatMessageRequestAction(ChatPDU receivedPdu);
/**
* Aktion fuer die Behandlung ankommender ChatMessageConfirm-PDUs
*
* @param receivedPdu
*/
/**
* Verarbeitung einer ankommenden Nachricht eines Clients (Implementierung des
* serverseitigen Chat-Zustandsautomaten)
*
* @throws Exception
*/
protected abstract void handleIncomingMessage() throws Exception;
}
|
JavaScript | UTF-8 | 3,077 | 2.71875 | 3 | [
"MIT"
] | permissive | // Needs ability to choose device.
// All MIDI events should have the same structure, otherwise it'll
// be a nightmare.
//
// Should I juse use the default web-midi TypedArray data?
// - Pros:
// - Adheres to spec.
// - Allows usage of lib without relying on proprietary
// event structure.
// - Easier to adopt if you already know WebMIDI event data.
// - Will allow for things like Chordify/NoteRoundRobin to
// just emit spec-adhering events.
//
// - Cons:
// - Must have helpers to translate into command/channel/type/param1/param2,
// i.e. it's not done automatically.
//
//
// All MIDI effects should have a map of accepted events that it will respond to.
//
// Flow:
// - WebMIDI access
// - Event triggered
// - Event passed to whatever is listening
// - If !WebMIDI...?? Fail gracefully.
//
//
// MIDIMessageFilter
// -----------------
// - Listens to all incoming events
// - Only passes on those events that it's told to.
//
// Chordify
// ---------
// - Receive single MIDI note-on message
// - Create n MIDI note-on messages, according to the chord specified.
// - Allow for other MIDI events to change the chord.
// - Map MIDI note to particular chord
// - Map MIDI CC to chord change (sweep thru array of chords)
// - Receive single MIDI note-off message, send n MIDI note-off messages
// according to the chord connected to that note.
//
//
// Transposer
// ----------
// - Receive MIDI message
// - Transpose according to settings (single value or map)
//
//
// Randomizer
// --------
// - Receive MIDI messages
// - Emulate Live's `Random` MIDI effect
// - Emits altered MIDI message.
//
//
// VelocityControl
// --------
// - Emulate Live's Velocity MIDI effect.
//
//
// RoundRobin
// ----------
// - Takes a bunch of MIDIEffects and cycles through them one by one,
// incrementing the active effect index each time a message is passed.
//
// Scalify
// -------
// - Receive single MIDI note-on message
// - Translate to scale (nearest neighbour / force-up / force-down)
// - Create new MIDI note-on message and emit
// - Or, alter incoming note-on message and pass-on?
// - Pass custom translation maps (think Live's `Scale` module).
//
//
// Event Translator
// ----------------
// - Listen for one or more specific events
// - When events are triggered, translate to another message
// - Eg. will allow for C1 note-on event to be translated into a
// another message type.
// - Eg. C1-C2 could be mapped to mod-wheel event values (0-127 in multiples of 12).
//
//
// Chord Builder
// -------------
// - Merge chords together (each chord being merged can be given an offset, or root note)
// - Create chords by playing notes (ability to map MIDI message to rec start/stop)
// - Create chords by adding intervals one by one.
//
// General MIDI note message settings
// ----------------------------------
// - Ability to change temperament
// - Ability to change global tuning
// - Ability to change the value of a semitone (microtonal),
// or the value of a particular note's interval, or noteInOctave's interval. |
JavaScript | UTF-8 | 824 | 2.671875 | 3 | [
"MIT"
] | permissive | 'use strict'
const cheerio = require('cheerio')
const request = require('request-promise-native')
module.exports = ({ lat, lng, city, region, country } = {}) => {
const apiUrl = 'https://www.starbucks.com/store-locator'
return new Promise((resolve, reject) => {
if ((!lat || !lng, !city, !region, !country)) {
return reject(new TypeError('Options are required'))
}
const api = `${apiUrl}?map=${lat},${lng}&place=${city},${region},${country}`
request(api).then(res => {
if (res) {
const $ = cheerio.load(res)
const json = JSON.parse($('#bootstrapData').text())
const stores = json.storeLocator.locationState.locations
resolve(stores)
}
reject(
new TypeError(`Couldn't find any Starbucks store on this location`)
)
})
})
}
|
Markdown | UTF-8 | 2,187 | 3.171875 | 3 | [] | no_license | Programming Assignment 6
Due: Mon Dec 7, 11:59 pm
Note This assignment will include a separate presentation component. See the section below for presentation requirements.
Problem
The problem will be different for each team. Once your team has chosen a dataset, you can download problem-specific instructions/data files from Moodle.
Instructions
Create a new Python file and place intro comments using the template below.
Use comments to write the algorithm your program will follow, including functions.
Write the Python code corresponding to each of your algorithm's steps.
Commit and push changes and check your repository on github.com to confirm your updates before the deadline.
Intro comments template
# Team Members: [your names]
# Course: CS151, Dr. Rajeev
# Programming Assignment: 6
# Program Inputs: [What information do you request from the user?]
# Program Outputs: [What information do you display for the user?]
Requirements for Presentation:
Must use PowerPoint slides containing the following (in order):
Title slide with name of project and presenters
Description of chosen problem, dataset, and questions answered
Discussion of each question asked about the data:
Show results obtained including graphs and interpret them. You may include other relevant graphics (e.g. map of Baltimore neighborhoods for Baltimore datasets).
If a question requires user input, choose an input value that gives interesting results to present.
Brief statement of what you found easy, what you found difficult, and what you would do differently next time.
Each person should do similar amount of presenting, including presenting results from their own calculation functions.
Each group will be allotted 5 minutes total.
Grading: You will be graded on how well you meet the above guidelines, including how well you communicate your results and stay within the allotted time.
Practice your presentation: work through multiple iterations to get the right length. Be clear and concise without leaving out important information.
Submission
GitHub: Completed .py file (including comments).
Moodle: Your PowerPoint slides.
This assignment does not require a flowchart or test cases.
|
JavaScript | UTF-8 | 7,037 | 2.515625 | 3 | [
"MIT"
] | permissive | import { Scene } from '../scenes/Scene.js'
import { Camera } from '../cameras/Camera.js'
import { Mesh } from '../objects/Mesh.js'
import { PlaneBufferGeometry } from '../geometries/PlaneGeometry.js'
import { ShaderMaterial } from '../materials/ShaderMaterial.js'
import { WebGLRenderTarget } from './WebGLRenderTarget.js'
import { DataTexture } from '../textures/DataTexture.js'
import {
ClampToEdgeWrapping,
NearestFilter,
FloatType,
HalfFloatType,
RGBAFormat
} from '../constants.js'
function GPUComputationRenderer( sizeX, sizeY, renderer ) {
this.variables = [];
this.currentTextureIndex = 0;
var scene = new Scene();
var camera = new Camera();
camera.position.z = 1;
var passThruUniforms = {
texture: { value: null }
};
var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader );
scene.add( mesh );
this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {
var material = this.createShaderMaterial( computeFragmentShader );
var variable = {
name: variableName,
initialValueTexture: initialValueTexture,
material: material,
dependencies: null,
renderTargets: [],
wrapS: null,
wrapT: null,
minFilter: NearestFilter,
magFilter: NearestFilter
};
this.variables.push( variable );
return variable;
};
this.setVariableDependencies = function( variable, dependencies ) {
variable.dependencies = dependencies;
};
this.init = function() {
if ( ! renderer.extensions.get( "OES_texture_float" ) ) {
return "No OES_texture_float support for float textures.";
}
if ( renderer.capabilities.maxVertexTextures === 0 ) {
return "No support for vertex shader textures.";
}
for ( var i = 0; i < this.variables.length; i++ ) {
var variable = this.variables[ i ];
// Creates rendertargets and initialize them with input texture
variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
// Adds dependencies uniforms to the ShaderMaterial
var material = variable.material;
var uniforms = material.uniforms;
if ( variable.dependencies !== null ) {
for ( var d = 0; d < variable.dependencies.length; d++ ) {
var depVar = variable.dependencies[ d ];
if ( depVar.name !== variable.name ) {
// Checks if variable exists
var found = false;
for ( var j = 0; j < this.variables.length; j++ ) {
if ( depVar.name === this.variables[ j ].name ) {
found = true;
break;
}
}
if ( ! found ) {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
}
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function() {
var currentTextureIndex = this.currentTextureIndex;
var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
for ( var i = 0, il = this.variables.length; i < il; i++ ) {
var variable = this.variables[ i ];
// Sets texture dependencies uniforms
if ( variable.dependencies !== null ) {
var uniforms = variable.material.uniforms;
for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {
var depVar = variable.dependencies[ d ];
uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
}
}
// Performs the computation for this variable
this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
}
this.currentTextureIndex = nextTextureIndex;
};
this.getCurrentRenderTarget = function( variable ) {
return variable.renderTargets[ this.currentTextureIndex ];
};
this.getAlternateRenderTarget = function( variable ) {
return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
};
function addResolutionDefine( materialShader ) {
materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";
}
this.addResolutionDefine = addResolutionDefine;
// The following functions can be used to compute things manually
function createShaderMaterial( computeFragmentShader, uniforms ) {
uniforms = uniforms || {};
var material = new ShaderMaterial( {
uniforms: uniforms,
vertexShader: getPassThroughVertexShader(),
fragmentShader: computeFragmentShader
} );
addResolutionDefine( material );
return material;
}
this.createShaderMaterial = createShaderMaterial;
this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
wrapS = wrapS || ClampToEdgeWrapping;
wrapT = wrapT || ClampToEdgeWrapping;
minFilter = minFilter || NearestFilter;
magFilter = magFilter || NearestFilter;
var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, {
wrapS: wrapS,
wrapT: wrapT,
minFilter: minFilter,
magFilter: magFilter,
format: RGBAFormat,
type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? HalfFloatType : FloatType,
stencilBuffer: false
} );
return renderTarget;
};
this.createTexture = function( sizeXTexture, sizeYTexture ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
var a = new Float32Array( sizeXTexture * sizeYTexture * 4 );
var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType );
texture.needsUpdate = true;
return texture;
};
this.renderTexture = function( input, output ) {
// Takes a texture, and render out in rendertarget
// input = Texture
// output = RenderTarget
passThruUniforms.texture.value = input;
this.doRenderTarget( passThruShader, output);
passThruUniforms.texture.value = null;
};
this.doRenderTarget = function( material, output ) {
mesh.material = material;
renderer.render( scene, camera, output );
mesh.material = passThruShader;
};
// Shaders
function getPassThroughVertexShader() {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
}
function getPassThroughFragmentShader() {
return "uniform sampler2D texture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( texture, uv );\n" +
"\n" +
"}\n";
}
}
export { GPUComputationRenderer }
|
C++ | UTF-8 | 158 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int ival = 42;
int *pival = &ival;
cout<<pival<<"\t"<<*pival<<"\t"<<&pival;
return 0;
} |
JavaScript | UTF-8 | 690 | 2.515625 | 3 | [] | no_license | (function(window){
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.Sprite();
// constructors:
Hero.prototype.Sprite_initialize = Hero.prototype.initialize; //unique to avoid overiding base class
// public methods:
Hero.prototype.initialize = function(imgHero) {
var data = {
images: ["img/lapinou.png"],
frames: {width: 150, height: 90, regX: 75, regY: 45},
animations: {
// start, end, next, speed
walk: [1, 7, "walk"],
idle: [0, 0,"idle"],
jump: [3, 3,"jump"]
}
};
var animPersonnage = new createjs.SpriteSheet(data);
this.constructor(animPersonnage);
}
window.Hero=Hero;
}
(window));
|
Java | UTF-8 | 533 | 1.828125 | 2 | [] | no_license | package com.nexters.tagit.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.nexters.tagit.model.TagModel;
import com.nexters.tagit.model.UserTagModel;
public interface UserTagMapper {
void insert(UserTagModel userTag);
List<UserTagModel> selectByInit();
List<UserTagModel> selectById(UserTagModel userTagModel);
List<TagModel> selectByUserId(String user_id);
List<UserTagModel> selectByUserWithPaging(@Param("user_id") String user_id, @Param("index") int index, @Param("rfp") int rfp);
}
|
Markdown | UTF-8 | 2,560 | 2.890625 | 3 | [] | no_license | # Introduction
[Capacitor](https://capacitor.ionicframework.com) is a modern "Native Progressive Web Apps" platform. Through it, Bionic apps can currently be deployed in iOS and Android (Capacitor Web and Capacitor Electron coming soon).
## Requirements
### NodeJS
Capacitor depends on NodeJS. Please [install](https://nodejs.org/en/download/) or ensure that you are using a current NodeJS version:
```text
> node --version
v9.5.0
```
Capacitor requires ```npx```, a CLI tool installed along with nodejs:
```text
> npx --version
9.7.1
```
If npx is not available then upgrade node to a recent version.
!!! tip
If you need to maintain multiple versions of node then [Node Version Manager](https://github.com/creationix/nvm) (```nvm```) may be of help.
Windows users will have to make node commands available through PATH env variable.
### Python
Capacitor also requires Python in order to run some scripts. Bionic was only tested against [Python 2.7](https://www.python.org/downloads/).
If you are on Windows, please make python executables available in the PATH.
```text
> python --version
Python 2.7.15
```
### Android Studio
If you intend to target Android in this project, you will need to [download and install Android Studio](https://developer.android.com/studio).
### iOS
If you intend to target iOS (iPhone/iPad and whatever starts with i), you will need to have an Apple Mac and [download and install XCode](https://itunes.apple.com/us/app/xcode/id497799835?mt=12).
## Getting Started with Capacitor
First, we need to download and install Bionic's Capacitor Plugin. This step is only required once per project. From your project (or Blazor Client) directory do:
```text
> bionic platform add capacitor
🔍 Looking for capacitor platform plugin
☕ Found it! Adding capacitor plugin...
🚀 capacitor platform successfully added
```
This will create the necessary assets under ```platforms/capacitor```.
Next you need to initialize Capacitor. The process will ask for an App name and an App package ID. Please make sure the package ID follows the [Java package naming convention](https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html):
```text
> bionic platform capacitor init
...
? App name BionicApp
? App Package ID (must be a valid Java package) com.bionic.app
✔ Initializing Capacitor project in
...
```
## Capacitor Targets
Capacitor can deploy in 4 different targets:
- [Android](../android)
- Electron (not available through Bionic yet)
- [iOS](../ios)
- Web (not available through Bionic yet)
|
Java | UTF-8 | 377 | 2.859375 | 3 | [] | no_license | package exception;
public class InvalidNumberReslut extends Exception {
private static final long serialVersionUID = 1L;
private int resultNumber;
public InvalidNumberReslut(int resultNumber) {
this.resultNumber = resultNumber;
}
@Override
public String getMessage() {
return "One result was excepted, " + resultNumber + " has been receved.";
}
} |
Java | UTF-8 | 7,608 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | package com.github.anastr.speedviewlib;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import com.github.anastr.speedviewlib.components.Indicators.Indicator;
import com.github.anastr.speedviewlib.components.Indicators.NormalSmallIndicator;
/**
* this Library build By Anas Altair
* see it on <a href="https://github.com/anastr/SpeedView">GitHub</a>
*/
public class DeluxeSpeedView extends Speedometer {
private Path markPath = new Path(),
smallMarkPath = new Path();
private Paint centerCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG),
speedometerPaint = new Paint(Paint.ANTI_ALIAS_FLAG),
markPaint = new Paint(Paint.ANTI_ALIAS_FLAG),
smallMarkPaint = new Paint(Paint.ANTI_ALIAS_FLAG),
speedBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private RectF speedometerRect = new RectF();
private int speedBackgroundColor = Color.WHITE;
private boolean withEffects = true;
public DeluxeSpeedView(Context context) {
this(context, null);
}
public DeluxeSpeedView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DeluxeSpeedView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
initAttributeSet(context, attrs);
}
@Override
protected void defaultValues() {
super.setIndicator(new NormalSmallIndicator(getContext()));
super.setIndicatorColor(Color.parseColor("#00ffec"));
super.setCenterCircleColor(Color.parseColor("#e0e0e0"));
super.setLowSpeedColor(Color.parseColor("#37872f"));
super.setMediumSpeedColor(Color.parseColor("#a38234"));
super.setHighSpeedColor(Color.parseColor("#9b2020"));
super.setTextColor(Color.WHITE);
super.setBackgroundCircleColor(Color.parseColor("#212121"));
}
private void init() {
speedometerPaint.setStyle(Paint.Style.STROKE);
markPaint.setStyle(Paint.Style.STROKE);
smallMarkPaint.setStyle(Paint.Style.STROKE);
if (Build.VERSION.SDK_INT >= 11)
setLayerType(LAYER_TYPE_SOFTWARE, null);
setWithEffects(withEffects);
}
private void initAttributeSet(Context context, AttributeSet attrs) {
if (attrs == null) {
initAttributeValue();
return;
}
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DeluxeSpeedView, 0, 0);
speedBackgroundColor = a.getColor(R.styleable.DeluxeSpeedView_speedBackgroundColor, speedBackgroundColor);
withEffects = a.getBoolean(R.styleable.DeluxeSpeedView_withEffects, withEffects);
a.recycle();
setWithEffects(withEffects);
initAttributeValue();
}
private void initAttributeValue() {
speedBackgroundPaint.setColor(speedBackgroundColor);
}
@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
updateBackgroundBitmap();
}
private void initDraw() {
speedometerPaint.setStrokeWidth(getSpeedometerWidth());
markPaint.setColor(getMarkColor());
smallMarkPaint.setColor(getMarkColor());
centerCirclePaint.setColor(getCenterCircleColor());
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
initDraw();
RectF speedBackgroundRect = getSpeedUnitTextBounds();
speedBackgroundRect.left -= 2;
speedBackgroundRect.right += 2;
speedBackgroundRect.bottom += 2;
canvas.drawRect(speedBackgroundRect, speedBackgroundPaint);
drawSpeedUnitText(canvas);
drawIndicator(canvas);
canvas.drawCircle(getSize() / 2f, getSize() / 2f, getWidthPa() / 12f, centerCirclePaint);
drawNotes(canvas);
}
@Override
protected void updateBackgroundBitmap() {
Canvas c = createBackgroundBitmapCanvas();
initDraw();
float smallMarkH = getHeightPa() / 20f;
smallMarkPath.reset();
smallMarkPath.moveTo(getSize() / 2f, getSpeedometerWidth() + getPadding());
smallMarkPath.lineTo(getSize() / 2f, getSpeedometerWidth() + getPadding() + smallMarkH);
smallMarkPaint.setStrokeWidth(3);
float markH = getHeightPa() / 28f;
markPath.reset();
markPath.moveTo(getSize() / 2f, getPadding());
markPath.lineTo(getSize() / 2f, markH + getPadding());
markPaint.setStrokeWidth(markH / 3f);
float risk = getSpeedometerWidth() / 2f + getPadding();
speedometerRect.set(risk, risk, getSize() - risk, getSize() - risk);
speedometerPaint.setColor(getHighSpeedColor());
c.drawArc(speedometerRect, getStartDegree(), getEndDegree() - getStartDegree(), false, speedometerPaint);
speedometerPaint.setColor(getMediumSpeedColor());
c.drawArc(speedometerRect, getStartDegree()
, (getEndDegree() - getStartDegree()) * getMediumSpeedOffset(), false, speedometerPaint);
speedometerPaint.setColor(getLowSpeedColor());
c.drawArc(speedometerRect, getStartDegree()
, (getEndDegree() - getStartDegree()) * getLowSpeedOffset(), false, speedometerPaint);
c.save();
c.rotate(90f + getStartDegree(), getSize() / 2f, getSize() / 2f);
float everyDegree = (getEndDegree() - getStartDegree()) * .111f;
for (float i = getStartDegree(); i < getEndDegree() - (2f * everyDegree); i += everyDegree) {
c.rotate(everyDegree, getSize() / 2f, getSize() / 2f);
c.drawPath(markPath, markPaint);
}
c.restore();
c.save();
c.rotate(90f + getStartDegree(), getSize() / 2f, getSize() / 2f);
for (float i = getStartDegree(); i < getEndDegree() - 10f; i += 10f) {
c.rotate(10f, getSize() / 2f, getSize() / 2f);
c.drawPath(smallMarkPath, smallMarkPaint);
}
c.restore();
drawDefMinMaxSpeedPosition(c);
}
public boolean isWithEffects() {
return withEffects;
}
public void setWithEffects(boolean withEffects) {
this.withEffects = withEffects;
indicatorEffects(withEffects);
if (withEffects && !isInEditMode()) {
markPaint.setMaskFilter(new BlurMaskFilter(5, BlurMaskFilter.Blur.SOLID));
speedBackgroundPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.SOLID));
centerCirclePaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.SOLID));
} else {
markPaint.setMaskFilter(null);
speedBackgroundPaint.setMaskFilter(null);
centerCirclePaint.setMaskFilter(null);
}
updateBackgroundBitmap();
invalidate();
}
@Override
public void setIndicator(Indicator.Indicators indicator) {
super.setIndicator(indicator);
indicatorEffects(withEffects);
}
public int getSpeedBackgroundColor() {
return speedBackgroundColor;
}
public void setSpeedBackgroundColor(int speedBackgroundColor) {
this.speedBackgroundColor = speedBackgroundColor;
speedBackgroundPaint.setColor(speedBackgroundColor);
updateBackgroundBitmap();
invalidate();
}
}
|
PHP | UTF-8 | 2,516 | 2.578125 | 3 | [] | no_license | <?php
/**
* RoosterItem short summary.
*
* RoosterItem description.
*
* @version 1.0
* @author Erwin
*/
class RoosterItem extends RoosterItemBase
{
public function getString(){
global $types;
return $this->start->format('l H:i').'-'.$this->end->format('H:i').': '.$this->course.($this->type!==false?' - '.$types[$this->type]:'').($this->group!==false?' ('.$this->group.')':'').' door '.$this->teacher.' in '.$this->building.'/'.$this->room.' '.($this->start!=NULL?'op '.$this->start->format('d-m-Y').' ':'').'('.$this->studyguidenumber.', '.$this->usisactnumber.', '.$this->zrsid.')';
}
public function getDescription(){
global $types;
return $this->start->format('l H:i').'-'.$this->end->format('H:i').'\n'.
$this->course.($this->type!==false?' - '.$types[$this->type]:'').($this->group!==false?' ('.$this->group.')':'').'\n'.
'Teacher: '.$this->teacher.'\n'.
'Building/Room: '.$this->building.'/'.$this->room.'\n'.
($this->start!=NULL?'Date: '.$this->start->format('d-m-Y').'\n':'').
'Studyguidenumber: '.$this->studyguidenumber.' ('.$this->academicyear.')\n'.
'uSIS Act.nr: '.$this->usisactnumber.'\n'.
'ZRS-id: '.$this->zrsid;
}
public function getDescriptionHTML(){
global $types;
return '<!doctype html><html><head><meta name="Generator" content="'.PRODUCT_NAME.' '.PRODUCT_VERSION.'"><title></title></head><body><p><strong>'.
$this->course.($this->type!==false?' - '.$types[$this->type]:'').($this->group!==false?' ('.$this->group.')':'').'</strong><br>'.
'<em>Teacher: </em>'.$this->start->format('l H:i').'-'.$this->end->format('H:i').'<br>'.
'<em>Docent:</em> '.$this->teacher.'<br>'.
'<em>Building/Room:</em> <a href="http://www.leidenuniv.nl/loc/index.html?lang=eng">'.$this->building.'/'.$this->room.'</a><br>'.
($this->start!=NULL?'<em>Date:</em> '.$this->start->format('d-m-Y').'<br>':'').
'<em>Studyguidenumber:</em> <a href="https://studiegids.leidenuniv.nl/search/courses/?code='.$this->studyguidenumber.'&edition='.$this->academicyear.'">'.$this->studyguidenumber.'</a><br>'.
'<em>uSIS Act.nr:</em> <a href="https://usis.leidenuniv.nl/psp/S040PRD/?cmd=login">'.$this->usisactnumber.'</a><br>'.
'<em>ZRS-id:</em> '.$this->zrsid.'</p></body></html>';
}
public function getUID(){
$data = $this->academicyear.$this->start->format('d').$this->course.$this->teacher.$this->studyguidenumber.$this->group;
if($this->start==NULL){
return md5($data);
} else {
return md5($data.$this->start->getTimestamp());
}
}
}
|
Shell | UTF-8 | 2,910 | 3.921875 | 4 | [
"Apache-2.0"
] | permissive | #!/bin/bash
set -e
##------------------------------------
## Script Functions
##------------------------------------
# This function install all packages needed for the RTS2 installation.
function ubuntu_dependencies(){
sudo apt-get update
sudo apt-get install libtool -y
sudo apt-get install git postgresql postgresql-server-dev-9.5 libecpg-dev automake libtool libcfitsio3-dev libnova-dev libecpg-dev gcc g++ libncurses5-dev libgraphicsmagick++1-dev libx11-dev docbook-xsl xsltproc libxml2-dev libarchive-dev libjson-glib-dev libsoup2.4-dev pkg-config -y
sudo apt-get install libusb-1.0-0-dev libusb-dev check libwebsockets-dev -y;
}
# This function creates a new download directory used during the
# installation process.
function check_downloads_dir(){
pwd_dir=$(pwd)
echo $pwd_dir
if [ -d downloads ] ; then
echo "[ INFO ] Deleting previous downloads folder..."
sudo rm -r downloads
echo "[ OK ]"
fi
mkdir downloads
cd downloads
}
# Steps used for WCSTools installation.
function install_wcstools(){
wget http://tdc-www.harvard.edu/software/wcstools/wcstools-3.9.4.tar.gz
tar xzf wcstools-3.9.4.tar.gz
rm -rf wcstools-3.9.4.tar.gz
cd wcstools-3.9.4/
# Check if the current machine runs in 64bits architecture.
MACHINE_TYPE=`uname -m`
if [ ${MACHINE_TYPE} == 'x86_64' ]; then
# 64-bit
echo "[ INFO ] This machine runs over 64bits architecture. Setting flags..."
sed -i '/CFLAGS= -g -D_FILE_OFFSET_BITS=64/c\CFLAGS= -g -fPIC -D_FILE_OFFSET_BITS=64 ' libwcs/Makefile
echo "[ OK ]"
else
# 32-bit
echo "[ INFO ] This machine runs over 32bits architecture. No changes needed."
fi
make
cd libwcs
if [ -d /usr/local/include/wcstools ] ; then
echo "[ INFO ] Deleting previous WCSTools folder..."
sudo rm -r /usr/local/include/wcstools
echo "[ OK ]"
fi
sudo mkdir /usr/local/include/wcstools
sudo cp *.h /usr/local/include/wcstools/
sudo cp libwcs.a /usr/local/lib/libwcstools.a
cd ../../
echo "[ OK ] WCSTools installation completed."
}
# Commands used for RTS2 installation.
function install_rts2(){
git clone https://github.com/RTS2/rts2.git
cd rts2
./autogen.sh
./configure
aclocal
automake --add-missing
autoconf
autoheader
./configure
make
sudo make install
echo "[ OK ] RTS2 installation completed."
}
##------------------------------------
## RTS2 Installation Script
##------------------------------------
if [ "`lsb_release -is`" == "Ubuntu" ]
then
echo "[ INFO ] Installing Ubuntu dependencies."
ubuntu_dependencies
echo "[ INFO ] Creating a new directory for downloads."
check_downloads_dir
echo "[ INFO ] Installing WCSTools."
install_wcstools
echo "[ INFO ] Installing RTS2."
install_rts2
sudo ldconfig
echo "[ INFO ] Please continue with configuration process..."
else
echo "[ ERROR ] Unsupported Operating System. This script only runs over Ubuntu 16.04."
fi
exit 0
|
C | UTF-8 | 4,323 | 2.984375 | 3 | [
"ISC"
] | permissive | #ifdef _MSC_VER
#include <platform.h>
#endif
#include <CuTest.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "strings.h"
static void test_str_escape(CuTest * tc)
{
char scratch[64];
CuAssertStrEquals(tc, "12345678901234567890", str_escape("12345678901234567890", scratch, 16));
CuAssertStrEquals(tc, "123456789\\\"12345", str_escape("123456789\"1234567890", scratch, 16));
CuAssertStrEquals(tc, "1234567890123456", str_escape("1234567890123456\"890", scratch, 16));
CuAssertStrEquals(tc, "hello world", str_escape("hello world", scratch, sizeof(scratch)));
CuAssertStrEquals(tc, "hello \\\"world\\\"", str_escape("hello \"world\"", scratch, sizeof(scratch)));
CuAssertStrEquals(tc, "\\\"\\\\", str_escape("\"\\", scratch, sizeof(scratch)));
CuAssertStrEquals(tc, "\\\\", str_escape("\\", scratch, sizeof(scratch)));
}
static void test_str_replace(CuTest * tc)
{
char result[64];
str_replace(result, sizeof(result), "Hello $who!", "$who", "World");
CuAssertStrEquals(tc, "Hello World!", result);
}
static void test_str_hash(CuTest * tc)
{
CuAssertIntEquals(tc, 0, str_hash(""));
CuAssertIntEquals(tc, 140703196, str_hash("Hodor"));
}
static void test_str_slprintf(CuTest * tc)
{
char buffer[32];
memset(buffer, 0x7f, sizeof(buffer));
CuAssertTrue(tc, slprintf(buffer, 4, "%s", "herpderp") > 3);
CuAssertStrEquals(tc, "her", buffer);
CuAssertIntEquals(tc, 4, (int)str_slprintf(buffer, 8, "%s", "herp"));
CuAssertStrEquals(tc, "herp", buffer);
CuAssertIntEquals(tc, 0x7f, buffer[5]);
CuAssertIntEquals(tc, 8, (int)str_slprintf(buffer, 8, "%s", "herpderp"));
CuAssertStrEquals(tc, "herpder", buffer);
CuAssertIntEquals(tc, 0x7f, buffer[8]);
}
static void test_str_strlcat(CuTest * tc)
{
char buffer[32];
memset(buffer, 0x7f, sizeof(buffer));
buffer[0] = '\0';
CuAssertIntEquals(tc, 4, (int)str_strlcat(buffer, "herp", 4));
CuAssertStrEquals(tc, "her", buffer);
buffer[0] = '\0';
CuAssertIntEquals(tc, 4, (int)str_strlcat(buffer, "herp", 8));
CuAssertStrEquals(tc, "herp", buffer);
CuAssertIntEquals(tc, 0x7f, buffer[5]);
CuAssertIntEquals(tc, 8, (int)str_strlcat(buffer, "derp", 8));
CuAssertStrEquals(tc, "herpder", buffer);
CuAssertIntEquals(tc, 0x7f, buffer[8]);
}
static void test_str_strlcpy(CuTest * tc)
{
char buffer[32];
memset(buffer, 0x7f, sizeof(buffer));
CuAssertIntEquals(tc, 4, (int)str_strlcpy(buffer, "herp", 4));
CuAssertStrEquals(tc, "her", buffer);
CuAssertIntEquals(tc, 4, (int)str_strlcpy(buffer, "herp", 8)); /*-V666 */
CuAssertStrEquals(tc, "herp", buffer);
CuAssertIntEquals(tc, 0x7f, buffer[5]);
CuAssertIntEquals(tc, 8, (int)str_strlcpy(buffer, "herpderp", 8));
CuAssertStrEquals(tc, "herpder", buffer);
CuAssertIntEquals(tc, 0x7f, buffer[8]);
errno = 0;
}
static void test_sbstring(CuTest * tc)
{
char buffer[16];
sbstring sbs;
sbs_init(&sbs, buffer, sizeof(buffer));
CuAssertStrEquals(tc, "", sbs.begin);
sbs_strcpy(&sbs, "Hodor");
CuAssertStrEquals(tc, "Hodor", sbs.begin);
sbs_strcat(&sbs, "Hodor");
CuAssertStrEquals(tc, "HodorHodor", sbs.begin);
sbs_strcpy(&sbs, "Hodor");
CuAssertStrEquals(tc, "Hodor", sbs.begin);
sbs_strcpy(&sbs, "12345678901234567890");
CuAssertStrEquals(tc, "123456789012345", sbs.begin);
CuAssertPtrEquals(tc, sbs.begin + sbs.size - 1, sbs.end);
sbs_strcat(&sbs, "12345678901234567890");
CuAssertStrEquals(tc, "123456789012345", sbs.begin);
CuAssertPtrEquals(tc, buffer, sbs.begin);
sbs_strcpy(&sbs, "1234567890");
CuAssertStrEquals(tc, "1234567890", sbs.begin);
sbs_strncat(&sbs, "1234567890", 4);
CuAssertStrEquals(tc, "12345678901234", sbs.begin);
sbs_strncat(&sbs, "567890", 6);
CuAssertStrEquals(tc, "123456789012345", sbs.begin);
}
CuSuite *get_strings_suite(void)
{
CuSuite *suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_str_hash);
SUITE_ADD_TEST(suite, test_str_escape);
SUITE_ADD_TEST(suite, test_str_replace);
SUITE_ADD_TEST(suite, test_str_slprintf);
SUITE_ADD_TEST(suite, test_str_strlcat);
SUITE_ADD_TEST(suite, test_str_strlcpy);
SUITE_ADD_TEST(suite, test_sbstring);
return suite;
}
|
JavaScript | UTF-8 | 1,707 | 3.453125 | 3 | [] | no_license | //Select Height input
var gridHeight = document.getElementById("inputHeight");
gridHeight.addEventListener("change paste keyup", function (e) {});
//Select Height input
var gridWidth = document.getElementById("inputWeight");
gridWidth.addEventListener("change paste keyup", function (e) {});
//User clicks on Submit, it sets the values to user inputed value
var submit = document.querySelector("input#submit");
submit.addEventListener("click", function () {
gridHeightValue = gridHeight.value;
gridWidthValue = gridWidth.value;
//conditional statement to limit the number of rows and columns user can input
if (gridHeightValue > 100 || gridWidthValue > 70 || gridHeightValue <= 0 || gridWidthValue <= 0) {
alert("Please enter a valid number between 1 and 100 for grid height and 1 - 70 for grid width ");
} else
//function to make the grid
makeGrid();
});
//make grid
function makeGrid() {
//selects table
var table = document.querySelector("table");
//dynamically create row
for (var i = 0; i < gridHeight.value; i++) {
var tr = document.createElement("tr");
tr = table.insertRow(-1);
//dynamically create cell
for (var j = 0; j < gridWidth.value; j++) {
var td = document.createElement("td");
td = tr.insertCell(-1);
}
}
}
// button to clear grid
$('#reset').on('click', function () {
event.preventDefault()
$('tr').remove();
});
//make table clickable and add color
$("table").delegate("td", "click change", function () {
$("td").each(element => {
var color = document.getElementById("colorPicker");
color.addEventListener("change", function () {});
$(this).css("background-color", color.value);
});
}); |
Markdown | UTF-8 | 675 | 3.625 | 4 | [] | no_license | # Bash-Scripts
Collection of bash script projects
Project: Calculator
This project looked at simulating a simple calculator in bash script. The calculator prompts the user for an operand, then an operator and then a second operand. The answer is displayed after each calulation. The subsequent operation uses the previous result, the answer, as the first operand.
The operand can accept: any digit, MR, MC, C, X
The operator can accept: +, -, *, /, MS, M+, MC, C, X
The functions perform the following actions:
C: Clear result, keep memory
MS: Stores result to memory
M+: Adds result to memory
MR: Recalls the value in memory
MC: clears the memory
X: Off, exits Unix
|
Python | UTF-8 | 877 | 3.484375 | 3 | [
"MIT"
] | permissive | # three solutions, some are consulted from
# https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/543154/3-solutions-or-Easy-to-Understand-or-Faster-or-Python
class Solution:
# No. 1: use set
def repeatedNTimes(self, A: List[int]) -> int:
res = set()
for n in A:
if n in res:
return n
else:
res.add(n)
# No. 2: calculate
def repeatedNTimes(self, A: List[int]) -> int:
res = set(A)
repeated_val = sum(A) - sum(res)
repeated_time = len(A) - len(res)
return repeated_val // repeated_time
# No.3: use constant space
def repeatedNTimes(self, A: List[int]) -> int:
A.sort()
for i in range(1, len(A)):
if A[i-1] == A[i]:
return A[i] |
PHP | UTF-8 | 1,383 | 2.59375 | 3 | [] | no_license | <?php defined('IN_APP') or die('Get out of here');
/**
* Scaffold v0.1
* by the Codin' Co.
*
* Here lies the basic bootstrapper, which instantiates all the classes and loads
* all of the files up properly. Here goes!
*/
if(get_magic_quotes_gpc()) {
$_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
$_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
$_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
$_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}
// Load the rest of the config
$config = array();
$files = array('environment', 'language', 'routes', 'database');
// Try loading the config files
// If they don't work, log to an array for now
// Get our badFiles array ready
$badFiles = array();
// Loop all the config files to check they're good
foreach($files as $file) {
$filename = BASE . 'config/' . $file . '.php';
if(file_exists($filename)) {
include $filename;
} else {
$badFiles[] = $filename;
}
}
// Include the functions
include_once CORE_BASE . 'functions.php';
// Load our core classes
$classes = array('config', 'error', 'response', 'ajax', 'file', 'input', 'url', 'routes', 'helper');
load_classes(array('scaffold'), load_classes($classes, $config, false));
|
Java | UTF-8 | 1,105 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package com.nick.netty.server;
import com.nick.NettyProperties;
import io.netty.channel.ChannelHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* Netty server template class
* @author NickFayne 2018-07-03 5:43
* @since 1.0.0
*/
public class NettyServerTemplate implements InitializingBean, DisposableBean {
private NettyServer nettyServer;
private NettyProperties nettyProperties;
public NettyServerTemplate(NettyProperties nettyProperties) {
this.nettyProperties = nettyProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
Integer serverPort = nettyProperties.getServerPort();
Boolean ssl = nettyProperties.getSsl();
nettyServer = new NettyServer(serverPort, ssl);
}
public void addServerCustomHandler(ChannelHandler channelHandler){
nettyServer.addServerHandler(channelHandler);
}
public void start(){
nettyServer.start();
}
@Override
public void destroy() throws Exception {
}
}
|
Java | UTF-8 | 12,547 | 2.328125 | 2 | [] | no_license | /**
*
*/
package by.bsuir.facultative.dao.mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import by.bsuir.facultative.dao.StudentDAO;
import by.bsuir.facultative.dao.pool.ConnectionPool;
import by.bsuir.facultative.entity.Course;
import by.bsuir.facultative.entity.Student;
import by.bsuir.facultative.entity.User;
import by.bsuir.facultative.exception.ConnectionPoolException;
import by.bsuir.facultative.exception.DAOException;
/**
* @author SBozhko
*
*/
public class MysqlStudentDAO implements StudentDAO {
private static final Logger logger = Logger
.getLogger(MysqlStudentDAO.class);
private Connection connection = null;
private static final String LOGIN_STUDENT_QUERY = "SELECT user.email, user.password, student.fullName, student.id, user.id FROM user JOIN student ON user.id = student.idUser WHERE user.email = ? AND user.password = ?";
private static final String GET_COURSES_QUERY = "SELECT course.title, course.description, course.hours, course.id FROM course JOIN archive ON course.id = archive.idCourse WHERE archive.idStudent = ?";
private static final String SELECT_USER_BY_EMAIL = "SELECT user.id FROM user WHERE user.email = ?";
private static final String INSERT_NEW_USER = "INSERT INTO user (email, password) VALUES (?, ?)";
private static final String INSERT_NEW_STUDENT = "INSERT INTO student (fullName, idUser) VALUES (?, ?)";
private static final String GET_MARK_BY_ID_COURSE_AND_ID_STUDENT = "SELECT archive.mark FROM archive WHERE archive.idCourse = ? and archive.idStudent = ?";
private static final String SELECT_ALL_COURSES = "SELECT course.id, course.title, course.description, course.hours FROM course";
private static final String SELECT_COURSE_BY_ID = "SELECT course.id, course.title, course.description, course.hours FROM course WHERE course.id = ?";
private static final String ADD_COURSE_TO_STUDENT = "INSERT INTO archive (idStudent, idCourse) VALUES (?, ?)";
private static final String SELECT_STUDENT_BY_EMAIL = "SELECT * FROM student JOIN user ON user.id = student.idUser WHERE user.email = ?";
private static final String DELETE_STUDENT_COURSE = "DELETE FROM archive WHERE idCourse = ? and idStudent = ?";
public MysqlStudentDAO(Connection con) {
this.connection = con;
}
@Override
public boolean isExists(User newUser) throws DAOException {
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(SELECT_USER_BY_EMAIL);
prStatement.setString(1, newUser.getEmail());
ResultSet resultSet = prStatement.executeQuery();
if (resultSet.next()) {
prStatement.close();
ConnectionPool.releaseConnection(connection);
return true;
} else {
prStatement.close();
ConnectionPool.releaseConnection(connection);
return false;
}
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error(e);
throw new DAOException(e);
}
}
@Override
public long insertUser(User newUser) throws DAOException {
PreparedStatement preparedStatement;
try {
preparedStatement = connection.prepareStatement(INSERT_NEW_USER,
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, newUser.getEmail());
preparedStatement.setString(2, newUser.getPassword());
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
long idUser = 0;
if (rs.next()) {
idUser = rs.getLong(1);
logger.debug("id User = " + idUser);
}
preparedStatement = connection.prepareStatement(INSERT_NEW_STUDENT);
preparedStatement.setString(1, newUser.getFullName());
preparedStatement.setLong(2, idUser);
preparedStatement.executeUpdate();
preparedStatement.close();
ConnectionPool.releaseConnection(connection);
return idUser;
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error(e);
throw new DAOException(e);
}
}
@Override
public Set<Course> getAllCourses() throws DAOException {
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(SELECT_ALL_COURSES);
ResultSet resultSet = prStatement.executeQuery();
Set<Course> courses = new HashSet<Course>();
Course course = null;
while (resultSet.next()) {
course = new Course();
course.setId(resultSet.getLong(1));
course.setTitle(resultSet.getString(2));
course.setDescription(resultSet.getString(3));
course.setHours(resultSet.getInt(4));
logger.info(course);
courses.add(course);
}
prStatement.close();
ConnectionPool.releaseConnection(connection);
return courses;
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error(e);
throw new DAOException(e);
}
}
@Override
public Course getCourse(long idCourse) throws DAOException {
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(SELECT_COURSE_BY_ID);
prStatement.setLong(1, idCourse);
ResultSet resultSet = prStatement.executeQuery();
Course course = null;
if (resultSet.next()) {
course = new Course();
course.setId(resultSet.getLong(1));
course.setTitle(resultSet.getString(2));
course.setDescription(resultSet.getString(3));
course.setHours(resultSet.getInt(4));
logger.info(course);
}
prStatement.close();
ConnectionPool.releaseConnection(connection);
return course;
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error(e);
throw new DAOException(e);
}
}
@Override
public void enterForCourse(Student student, Course course)
throws DAOException {
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(ADD_COURSE_TO_STUDENT);
prStatement.setLong(1, student.getIdStudent());
prStatement.setLong(2, course.getId());
prStatement.executeUpdate();
prStatement.close();
ConnectionPool.releaseConnection(connection);
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error(e);
throw new DAOException(e);
}
}
@Override
public boolean checkUserByEmail(User newUser) throws DAOException {
logger.debug("checkUserByEmail");
logger.debug(newUser);
logger.debug(newUser.getEmail());
logger.debug(newUser.getPassword());
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(SELECT_STUDENT_BY_EMAIL);
logger.debug("prStatement");
prStatement.setString(1, newUser.getEmail());
logger.debug("setString");
ResultSet resultSet = prStatement.executeQuery();
logger.debug("resultSet");
if (resultSet.next()) {
prStatement.close();
ConnectionPool.releaseConnection(connection);
logger.debug("true from checkUserByEmail");
return true;
} else {
prStatement.close();
ConnectionPool.releaseConnection(connection);
return false;
}
} catch (SQLException e) {
logger.error("sql problems", e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error("pool problems", e);
throw new DAOException(e);
}
}
@Override
public User selectUserByEmailAndPassword(User user) throws DAOException {
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(LOGIN_STUDENT_QUERY);
User loginUser = new Student();
prStatement.setString(1, user.getEmail());
prStatement.setString(2, user.getPassword());
logger.info("login " + user.getEmail());
logger.info("password " + user.getPassword());
ResultSet rs = null;
rs = prStatement.executeQuery();
if (rs.next()) {
loginUser.setEmail(rs.getString(1));
loginUser.setPassword(rs.getString(2));
loginUser.setFullName(rs.getString(3));
((Student) loginUser).setIdStudent(rs.getLong(4));
loginUser.setIdUser(rs.getLong(5));
logger.info(loginUser);
prStatement = connection.prepareStatement(GET_COURSES_QUERY);
prStatement.setLong(1, ((Student) loginUser).getIdStudent());
ResultSet coursesRS = null;
coursesRS = prStatement.executeQuery();
Set<Course> courses = new HashSet<Course>();
Map<Course, Integer> marks = new HashMap<Course, Integer>();
Course course = null;
while (coursesRS.next()) {
course = new Course();
course.setTitle(coursesRS.getString(1));
course.setDescription(coursesRS.getString(2));
course.setHours(coursesRS.getInt(3));
course.setId(coursesRS.getLong(4));
logger.debug(course);
prStatement = connection
.prepareStatement(GET_MARK_BY_ID_COURSE_AND_ID_STUDENT);
prStatement.setLong(1, course.getId());
prStatement
.setLong(2, ((Student) loginUser).getIdStudent());
ResultSet marksRS = prStatement.executeQuery();
if (marksRS.next()) {
marks.put(course, marksRS.getInt(1));
}
courses.add(course);
}
((Student) loginUser).setMarks(marks);
}
prStatement.close();
ConnectionPool.releaseConnection(connection);
return loginUser;
} catch (SQLException e) {
logger.error("sql problems", e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error("pool problems", e);
throw new DAOException(e);
}
}
@Override
public void refuseFromCourse(User user, Course course) throws DAOException {
logger.info("refuseFromCourse()");
PreparedStatement preparedStatement;
try {
preparedStatement = connection
.prepareStatement(DELETE_STUDENT_COURSE);
preparedStatement.setLong(1, course.getId());
preparedStatement.setLong(2, ((Student) user).getIdStudent());
logger.debug(preparedStatement);
preparedStatement.executeUpdate();
logger.debug("course deleted from archive");
preparedStatement.close();
ConnectionPool.releaseConnection(connection);
} catch (SQLException e) {
logger.error("sql problems", e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error("pool problems", e);
throw new DAOException(e);
}
}
@Override
public Map<Course, Integer> getCoursesAndMarks(User user) throws DAOException {
logger.info("getCoursesAndMarks()");
PreparedStatement prStatement;
try {
prStatement = connection.prepareStatement(GET_COURSES_QUERY);
prStatement.setLong(1, ((Student) user).getIdStudent());
ResultSet coursesRS = null;
coursesRS = prStatement.executeQuery();
Set<Course> courses = new HashSet<Course>();
Map<Course, Integer> marks = new HashMap<Course, Integer>();
Course course = null;
while (coursesRS.next()) {
course = new Course();
course.setTitle(coursesRS.getString(1));
course.setDescription(coursesRS.getString(2));
course.setHours(coursesRS.getInt(3));
course.setId(coursesRS.getLong(4));
logger.debug(course);
prStatement = connection
.prepareStatement(GET_MARK_BY_ID_COURSE_AND_ID_STUDENT);
prStatement.setLong(1, course.getId());
prStatement.setLong(2, ((Student) user).getIdStudent());
ResultSet marksRS = prStatement.executeQuery();
if (marksRS.next()) {
marks.put(course, marksRS.getInt(1));
}
courses.add(course);
}
// ((Student) user).setMarks(marks);
prStatement.close();
ConnectionPool.releaseConnection(connection);
return marks;
} catch (SQLException e) {
logger.error("sql problems", e);
throw new DAOException(e);
} catch (ConnectionPoolException e) {
logger.error("pool problems", e);
throw new DAOException(e);
}
}
@Override
public Course addCourse(Course newCourse, User user) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Student> getStudentsOfCourse(Course course) {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateStudentMark(Student student) {
// TODO Auto-generated method stub
}
@Override
public void updateCourse(Course course) {
// TODO Auto-generated method stub
}
@Override
public List<Course> getCourses(User user) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteCourse(Course course) {
// TODO Auto-generated method stub
}
}
|
C++ | UHC | 4,101 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "DungeonScene.h"
#include<memory>
#include "Scene.h"
#include "MonsterManager.h"
#include "EquipItem.h"
#include"EventScene.h"
DungeonScene::DungeonScene(std::weak_ptr<Game> game) : Scene(game)
{
Floor = 0;
Event = 0;
srand(UINT(time(NULL)));
}
DungeonScene::~DungeonScene()
{
}
void DungeonScene::printStatus()
{
using namespace SteamB23;
std::shared_ptr<std::string>headitemName;//string Ÿ Ʈ
std::shared_ptr<std::string>bodyitemName;
std::shared_ptr<std::string>weaponitemName;
auto game = std::dynamic_pointer_cast<AbyssGame, Game>(GetGame());
auto status = game->GetPlayerData()->GetStatus();
int maxHp = game->GetPlayerData()->GetHP();//ִä
char maxHpStr[30];
auto abyssGame = std::dynamic_pointer_cast<AbyssGame, Game>(GetGame());
auto playerdata = abyssGame->GetPlayerData();//÷̾
std::shared_ptr< EquipItem> head = playerdata->GetEquipItem(EquipType::Head);
std::shared_ptr< EquipItem> body = playerdata->GetEquipItem(EquipType::Body);
std::shared_ptr< EquipItem> weapon = playerdata->GetEquipItem(EquipType::Weapon);
//Ӹ ̸
if (head != nullptr)
headitemName = head->GetName();
else headitemName = std::make_shared<std::string>(".");
char headequip[30];
// ̸
if (weapon != nullptr)
weaponitemName = weapon->GetName();
else weaponitemName = std::make_shared<std::string>(".");
char weaponequip[30];
// ̸
if (body != nullptr)
bodyitemName = body->GetName();
else bodyitemName = std::make_shared<std::string>(".");
char bodyequip[30];
int currHp = playerdata->GetCurrentHP();// hp
int attack = playerdata->GetStrikingPower();//ݷ
char attackStr[30];
// ųī
char killCounterStr[30];
wsprintfA(attackStr, "ݷ :: %d", attack);
wsprintfA(maxHpStr, "ü :: %d / %d", currHp, maxHp);
wsprintfA(bodyequip, " :: %s", bodyitemName->c_str());
wsprintfA(weaponequip, " :: %s", weaponitemName->c_str());
wsprintfA(headequip, "Ӹ :: %s", headitemName->c_str());
wsprintfA(killCounterStr, " :: %d", abyssGame->GetKillCounter());
ConsoleTextBox inventory = ConsoleTextBox({
maxHpStr,attackStr,"-----------------",bodyequip,weaponequip,headequip,"-----------------",killCounterStr
},
80 - 30, 0, 30,
SteamB23::ConsoleColor::DarkMagenta);
inventory.Present();
}
void DungeonScene::Run()
{
using namespace SteamB23;
Console::Clear();
auto game = std::dynamic_pointer_cast<AbyssGame, Game>(GetGame());
std::cout << " " << Floor << " ̴." << std::endl;
Event = rand() % 3 + 1;
if (Event == 2)//ƹϵ Ͼ ʾҴ.
{
std::cout << "ƹ ϵ Ͼ ʾҽϴ." << std::endl << " Ͻðڽϱ?";
int A;
printStatus();
ConsoleOption battleMenu = ConsoleOption(
{
"",
"",
},
34, 10, 11);
switch (battleMenu.GetSelect())
{
case 0:
Floor++;
GetGame()->GetSceneManager()->SetNextScene(shared_from_this());
break;
case 1:
GetGame()->GetSceneManager()->SetNextScene(std::make_shared<MainScene>(GetGame()));
}
}
if (Event == 3)//Ư ̺Ʈ
{
std::cout << "!!! ߰ߴ ƾƾ!";
Floor++;
std::SkipableSleep(1000);
GetGame()->GetSceneManager()->SetNextScene(std::make_shared<EventScene>(GetGame()));
}
if (Event == 1)//
{
std::cout << " !!!";
Floor++;
auto abyssGame = std::dynamic_pointer_cast<AbyssGame>(GetGame());
auto battleScene = std::make_shared<BattleScene>(abyssGame, abyssGame->GetPlayerData(), MonsterManager::GetMonster(Floor));
GetGame()->GetSceneManager()->SetNextScene(battleScene);
}
printStatus();
}
std::shared_ptr<DungeonScene> DungeonScene::GetInstance(std::shared_ptr<Game> game)
{
if (instance == nullptr)
instance = std::make_shared<DungeonScene>(game);
return instance;
}
std::shared_ptr<DungeonScene> DungeonScene::instance; |
C# | UTF-8 | 903 | 3.5 | 4 | [] | no_license | // https://open.kattis.com/problems/tri
// Steve Jia
using System;
public class Solution{
public static void Main(){
string[] symbols = new string[]{"+", "-", "*", "/"};
Func<int, int, int>[] operations = {
(x, y) => x + y,
(x, y) => x - y,
(x, y) => x * y,
(x, y) => x / y
};
int[] inputs = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
for(int i = 0; i < operations.Length; i++){
if(operations[i](inputs[0], inputs[1]) == inputs[2]){
Console.WriteLine($"{inputs[0]}{symbols[i]}{inputs[1]}={inputs[2]}");
break;
}
else if(operations[i](inputs[1], inputs[2]) == inputs[0]){
Console.WriteLine($"{inputs[0]}={inputs[1]}{symbols[i]}{inputs[2]}");
break;
}
}
}
} |
Python | UTF-8 | 586 | 2.765625 | 3 | [] | no_license | import json
import datetime
import time
import random
import requests
import test_config
def test_random_quote_api_get():
req = requests.get(test_config.RANDOM_QUOTE_API_URL)
assert req.status_code == 200
assert len(req.json()) == 1
def test_random_quote_api_with_supplied_number_in_body():
num_quotes = random.randint(1, 5)
body = {'number': num_quotes}
print(test_config.RANDOM_QUOTE_API_URL)
print(body)
req = requests.post(test_config.RANDOM_QUOTE_API_URL, json=body)
assert req.status_code == 200
assert len(req.json()) == num_quotes
|
Python | UTF-8 | 1,168 | 3.515625 | 4 | [] | no_license | import os
from art import logo
def clear_console():
'''Clears console independent of OS'''
command = 'clear'
if os.name in ['nt', 'dos']:
command = 'cls'
os.system(command)
def get_bidders(dict):
'''Adds new bidders to auction'''
while True:
bidder = input("What's your name? ")
bid = int(input("What's your bid? $"))
dict[bidder] = bid
add_bidder = ''
while add_bidder not in ["yes", "no"]:
add_bidder = input("Add another bidder? Yes or No: ").lower()
clear_console()
if add_bidder == "no":
break
def print_winners(dict):
'''Print winners names and bid'''
winner_bid = 0
winner_name = ''
for bidder, bid in dict.items():
if bid > winner_bid:
winner_bid = bid
winner_name = bidder
elif bid == winner_bid:
winner_name += f" and {bidder}"
print(f"{winner_name} won with a bid of ${winner_bid}.")
if __name__ == '__main__':
print(logo)
print("Welcome to Secret Auction Program.")
bidders = {}
get_bidders(bidders)
print_winners(bidders)
|
Markdown | UTF-8 | 1,090 | 2.59375 | 3 | [
"MIT"
] | permissive | The `vesperabr/validation` package provides an easy whay to validate input data.
It could be used in pure PHP or in Laravel projects.
## Installation
You can install the package via composer:
```bash
$ composer require vesperabr/validation
```
The package will automatically register itself in Laravel.
## How to use in Laravel
All you need to do is append the rule to your rules list.
```php
public function store(Request $request)
{
$validated = $request->validate([
'cpf' => 'required|cpf',
]);
}
```
### Available rules
- cnpj
- cpf
- cpf_ou_cnpj
- uf
## How to use in PHP
```php
use Vespera\Validation\Cpf;
$validation = Cpf::make('111.111.111-11')->validate();
```
### Avaiable classes
- `Vespera\Validation\Cnpj`
- `Vespera\Validation\Cpf`
- `Vespera\Validation\CpfOuCnpj`
- `Vespera\Validation\Uf`
## Testing
```bash
$ composer test
```
## Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
## Credits
- [Ricardo Monteiro](https://github.com/ricazao)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
|
Python | UTF-8 | 759 | 3.359375 | 3 | [] | no_license | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return
start = ListNode(0)
current = head
pre = start
next = None
while(current is not None):
next = current.next
while(pre.next is not None and pre.next.val < current.val):
pre = pre.next
current.next = pre.next
pre.next = current
pre = start
current = next
return start.next
|
C++ | UTF-8 | 3,591 | 2.78125 | 3 | [] | no_license | #include <math.h>
#ifdef __APPLE_CC__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
bool mouseisdown=false ;
bool loopr=false ;
int mx,my;
int ry=30;
int rx=30;
void timer(int p)
{
ry-=5;
glutPostRedisplay();
if (loopr)
glutTimerFunc(200,timer,0);
}
void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON)
{
if (state == GLUT_DOWN)
{ mouseisdown=true ; loopr=false ;}
else
mouseisdown=false ;
}
if (button== GLUT_RIGHT_BUTTON)
if (state == GLUT_DOWN)
{loopr=true ; glutTimerFunc(200,timer,0);}
}
void motion(int x, int y)
{
if (mouseisdown==true )
{
ry+=x-mx;
rx+=y-my;
mx=x;
my=y;
glutPostRedisplay();
}
}
void special(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
ry-=5;
glutPostRedisplay();
break ;
case GLUT_KEY_RIGHT:
ry+=5;
glutPostRedisplay();
break ;
case GLUT_KEY_UP:
rx+=5;
glutPostRedisplay();
break ;
case GLUT_KEY_DOWN:
rx-=5;
glutPostRedisplay();
break ;
}
}
void init()
//设置OpenGL的一些状态变量的初始值
{
glEnable(GL_DEPTH_TEST); //深度测试
glDepthFunc(GL_LESS); //设置深度测试函数
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); //设置多边形显示模式为正反面都是填充显示
glClearColor(1,1,1,1); //设置刷新背景色
glClearDepth(1); //设置清除深度缓冲区所用的值
}
void display()
{
float red[3]={1,0,0};
float blue[3]={0,1,0};
float green[3]={0,0,1};
float yellow[3]={1,1,0};
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(ry,0,1,0);
glRotatef(rx,1,0,0);
glBegin(GL_QUADS);
glColor3fv(green);
glVertex3f(0.5,0.5,0);
glVertex3f(-0.5,0.5,0);
glVertex3f(-0.5,-0.5,0);
glVertex3f(0.5,-0.5,0);
glEnd();
glBegin(GL_QUADS);
glColor3fv(red);
glVertex3f(0.5,0.5,0.3);
glVertex3f(-0.5,0.5,-0.3);
glVertex3f(-0.5,-0.5,-0.3);
glVertex3f(0.5,-0.5,0.3);
glEnd();
glBegin(GL_QUADS);
glColor3fv(yellow);
glVertex3f(0.5,0.5,-0.3);
glVertex3f(-0.5,0.5,0.3);
glVertex3f(-0.5,-0.5,0.3);
glVertex3f(0.5,-0.5,-0.3);
glEnd();
glFlush();
glutSwapBuffers();
}
int main(int argc, char ** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE| GLUT_RGBA|GLUT_DEPTH); //设置显示模式:单缓冲区, RGBA颜色模式
glutInitWindowSize (400, 400); //设置窗口宽度、高度
glutInitWindowPosition(100,100); //设置窗口位置
glutCreateWindow ("double"); //弹出窗口
init();
glutDisplayFunc (display); //设置窗口刷新的回调函数
glutMouseFunc(mouse); //设置鼠标器按键回调函数
glutMotionFunc(motion);
glutSpecialFunc(special);
glutMainLoop(); //开始主循环
return 0;
}
|
Ruby | UTF-8 | 1,006 | 3.734375 | 4 | [] | no_license | =begin Informacoes
*****************************************
* Curso de Ruby *
*****************************************
* Aluno.....: Paulo Guilherme *
* Linguagem.: Ruby *
* Arquivo...: Ola_Mundo.rb *
* Aula......: 01 *
* Data......: 11 de Agosto de 2021 *
*****************************************
=end
#Comando P
puts "\n\nUsando o comando \"p\""
puts "Comandos: \np \"Ola \" \np \"Mundo\" \np \"!\"\n\nResultado:\n"
p "Ola "
p "Mundo"
p "!"
#Comando Puts
puts "\n\nUsando o comando \"puts\""
puts "Comandos: \nputs \"Ola \" \nputs \"Mundo\" \nputs \"!\"\n\nResultado:\n"
puts "Ola "
puts "Mundo"
puts '!'
#Comando Print
puts "\n\nUsando o comando \"print\""
puts "Comandos: \nprint \"Ola \" \nprint \"Mundo\" \nprint \"!\"\n\nResultado:\n"
print "Ola "
print "Mundo"
print '!'
puts "\n\n\n" #Imprime tres linhas em branco
#Fim do codigo |
JavaScript | UTF-8 | 3,465 | 3.03125 | 3 | [] | no_license | var assert = require('assert');
/**
@fileOverview The **Shorten** class is used to shorten a specified URL
@example
var shortSrv = Shorten();
shortSrv.OriginalUrl = "http://www.example.com";
shortSrv.Shorten(function(err, r) {
//TODO
});
*/
// create an instance of Shorten.
var Shorten = function() {
if(!(this instanceof Shorten)) return new Shorten();
this.OriginalUrl = "";
this.DbControl = null;
};
Shorten.prototype = {
constructor: Shorten,
base62Volcabulary: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
collection: null,
//return true if this.OriginalUrl is a valid URL.
//valid URL has the format "http://www.example.com"
isValidUrl: function() {
var urlRegexp = /^http[s]?:\/\/www\.\w+\.\w+(\/\w+)*/;
var matchResult = urlRegexp.exec(this.OriginalUrl);
return matchResult != null;
},
//encode a number to a string
encodeUrl: function(seqNum) {
var codes = [];
var result = "";
//calc base62 code
while(true) {
codes.push(seqNum % 62);
seqNum = parseInt(seqNum / 62);
if(seqNum === 0) break;
}
codes.forEach(function(c) {
result += this.base62Volcabulary.charAt(c);
}, this);
return result;
},
//decode the string to the number
decodeUrl: function(eu) {
var seqNum = 0;
//map from string to base62 codes
for(var i = 0; i < eu.length; ++i) {
for(var j = 0; j < this.base62Volcabulary.length; ++j) {
if(this.base62Volcabulary.charAt(j) === eu.charAt(i)) {
seqNum += Math.pow(62, i) * j;
break;
}
}
}
return seqNum;
},
// return the shorten form of this.OrignalUrl
ShortenUrl: function(callback) {
var self = this;
if(!self.isValidUrl()) {
callback(new Error("invalid URL"));
return;
}
assert(self.DbControl, "must setup the db controller");
//search db to see if it has already been shoretened.
self.DbControl.Find({originalurl: self.OriginalUrl}, function(err, d) {
if(err) {
callback(err);
return;
}
//already shortened.
if(d) {
console.log("already shortened");
callback(null, d.shortenurl);
} else {
self.DbControl.NextSequence(function(err, seq) {
if(err) {
callback(err);
return;
}
console.log("next seq number: " + seq);
var encUrl = self.encodeUrl(seq);
self.DbControl.Insert(self.OriginalUrl,
encUrl,
seq,
function(err, r) {
if(err) {
callback(err);
return;
}
callback(null, encUrl);
})
});
}
});
}
};
module.exports = Shorten; |
Swift | UTF-8 | 5,736 | 3.21875 | 3 | [] | no_license | //
// PasswordController.swift
// iPasswordKeeper
//
// Created by Tobi Kuyoro on 23/11/2019.
// Copyright © 2019 Lambda School. All rights reserved.
//
import Foundation
import CoreData
enum HTTPMethod: String {
case get = "GET"
case put = "PUT"
case post = "POST"
case delete = "DELETE"
}
class PasswordController {
let fireBaseURL = URL(string: "https://password-keeper-87eb9.firebaseio.com/")!
func put(password: Password, completion: @escaping()-> Void = {} ) {
let identifier = password.identifier ?? UUID()
password.identifier = identifier
let requestURL = fireBaseURL.appendingPathComponent(identifier.uuidString).appendingPathExtension("json")
var request = URLRequest(url: requestURL)
request.httpMethod = HTTPMethod.put.rawValue
guard let representation = password.passwordRepresntation else {
NSLog("Error")
completion()
return
}
do {
request.httpBody = try JSONEncoder().encode(representation)
} catch {
NSLog("Error encoding task: \(error)")
completion()
return
}
URLSession.shared.dataTask(with: request) { (_, _, error) in
if let error = error{
NSLog("Error putting task: \(error)")
completion()
return
}
completion()
}.resume()
}
func fetchEntryFromServer(completion: @escaping()-> Void = {}){
let requestURL = fireBaseURL.appendingPathExtension("json")
URLSession.shared.dataTask(with: requestURL) { (data, _, error) in
if let error = error{
NSLog("error fetching tasks: \(error)")
completion()
}
guard let data = data else{
NSLog("Error getting data task:")
completion()
return
}
do{
let decoder = JSONDecoder()
let passwordRepresentation = Array(try decoder.decode([String: PasswordRepresentation].self, from: data).values)
self.update(with: passwordRepresentation)
} catch {
NSLog("Error decoding: \(error)")
}
}.resume()
}
func update(with representations: [PasswordRepresentation]){
let identifiersToFetch = representations.compactMap({ UUID(uuidString: $0.identifier)})
let representationsByID = Dictionary(uniqueKeysWithValues: zip(identifiersToFetch, representations))
//Make a mutable copy of Dictionary above
var passwordToCreate = representationsByID
let context = CoreDataStack.share.container.newBackgroundContext()
context.performAndWait {
do {
let fetchRequest: NSFetchRequest<Password> = Password.fetchRequest()
//Name of Attibute
fetchRequest.predicate = NSPredicate(format: "identifier IN %@", identifiersToFetch)
//Which of these tasks already exist in core data?
let exisitingPassword = try context.fetch(fetchRequest)
//Which need to be updated? Which need to be put into core data?
for password in exisitingPassword {
guard let identifier = password.identifier,
// This gets the task representation that corresponds to the task from Core Data
let representation = representationsByID[identifier] else{return}
password.passwordString = representation.passwordString
password.website = representation.website
passwordToCreate.removeValue(forKey: identifier)
}
//Take these tasks that arent in core data and create
for representation in passwordToCreate.values{
Password(passwordRepresentation: representation, context: context)
}
CoreDataStack.share.save(context: context)
} catch {
NSLog("Error fetching tasks from persistent store: \(error)")
}
}
}
//CRUD
@discardableResult func cratePassword(with passwordString: String, website: String) -> Password {
let password = Password(passwordString: passwordString, website: website, context: CoreDataStack.share.mainContext)
put(password: password)
CoreDataStack.share.save()
return password
}
func updatePassword(password: Password, with passwordString: String, website: String){
password.passwordString = passwordString
password.website = website
put(password: password)
CoreDataStack.share.save()
}
func delete(password: Password){
CoreDataStack.share.mainContext.delete(password)
CoreDataStack.share.save()
}
}
|
Markdown | UTF-8 | 596 | 2.65625 | 3 | [] | no_license | # Gradient Project #
was inspired by [uigradients](http://uigradients.com/), [Adobe Kuler](https://color.adobe.com/create/color-wheel/), and others. It is intended for designers and programmer who want more control over their color palettes.
[](http://jzwood.github.io/Waterfall-Color-Gradient/)
### **use case** ###
Specifically, the Gradient Project is unique because it gives **discrete** color gradients (instead of continuous ones). This is helpful for finding the exact hue between two arbitrary colors or tinting colors in a precise direction.
|
Markdown | UTF-8 | 977 | 3.4375 | 3 | [] | no_license | # factors_caching
To run:
`ruby ./factors.rb`
Since the output representation is up to me, I choose to have the output in sorted order, which allows me to use the cache for
different permutations of the same input array and use the same result.
To account for the "reverse factors" implementation, I chose to cache both the result of the factors calculation as well as the
reverse factors. This allows the computation for both in a single pass (traverse the array once and calculate both results), but
slows down the initial computation for the benefit of only having to calculate a given array (or its permuations) only once and
having both results in the future.
If there was a possibility for other questions, I would have made the cache more general and cached each individual result for each
number in the array so that it would be easier in the future to use the cache for other results. For example, "For a given array,
output how many entries have 2 factors."
|
C# | UTF-8 | 5,148 | 2.5625 | 3 | [] | no_license | using NUnit.Framework;
using SistemaApoioEstudo.BLL.DAO;
using SistemaApoioEstudo.BLL.Entidades;
using SistemaApoioEstudo.BLL.Negocio;
using SistemaApoioEstudo.BLL.Utilitarios;
using System;
namespace SistemaApoioEstudo.Teste.TestesLogin
{
[TestFixture]
public class UC20_Logar
{
private Usuario usuarioInicial;
private NegocioUsuario negocioUsuario;
private IUsuarioDAO usuarioDAO;
public UC20_Logar()
{
usuarioInicial = new Usuario()
{
Nome = "Alexandre",
Senha = "athens"
};
negocioUsuario = new NegocioUsuario();
usuarioDAO = new UsuarioDAO();
}
[SetUp]
public void TestFixtureSetup()
{
//_Exclui e Cadastra o usuário "Alexandre" com senha "athens".
Usuario usuarioInicialRetorno = usuarioDAO.ConsultarNome(usuarioInicial.Nome);
if (usuarioInicialRetorno != null)
{
usuarioDAO.Excluir(usuarioInicialRetorno.Id);
}
usuarioDAO.Cadastrar(usuarioInicial);
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
//_Exclui o usuário "Alexandre".
usuarioInicial = usuarioDAO.ConsultarNome(usuarioInicial.Nome);
if (usuarioInicial != null)
{
usuarioDAO.Excluir(usuarioInicial.Id);
}
}
[Test]
public void CT01UC20FB_Logar_comDadosValidos_comSucesso()
{
negocioUsuario.ValidarNome(usuarioInicial.Nome);
negocioUsuario.ValidarSenha(usuarioInicial.Senha);
Usuario usuarioRetorno = usuarioDAO.Consultar(usuarioInicial);
if (usuarioInicial.Equals(usuarioRetorno))
{
Login.RegistrarUsuario(usuarioRetorno);
}
Assert.IsTrue(usuarioInicial.Equals(usuarioRetorno));
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CT02UC20FA_Logar_comNomeEmBranco_semSucesso()
{
Usuario usuarioNomeBranco = new Usuario()
{
Nome = " ",
Senha = ""
};
negocioUsuario.ValidarNome(usuarioNomeBranco.Nome);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CT03UC20FA_Logar_comSenhaEmBranco_semSucesso()
{
Usuario usuarioSenhaBranco = new Usuario()
{
Nome = "Danilo",
Senha = " "
};
negocioUsuario.ValidarSenha(usuarioSenhaBranco.Senha);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CT04UC20FA_Logar_comNomeAcimaDe15Caracteres_semSucesso()
{
Usuario usuarioNomeCaracteres = new Usuario()
{
Nome = "Alexandreshigueru",
Senha = ""
};
negocioUsuario.ValidarNome(usuarioNomeCaracteres.Nome);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CT05UC20FA_Logar_comSenhaAcimaDe10Caracteres_semSucesso()
{
Usuario usuarioSenhaCaracteres = new Usuario()
{
Nome = "Danilo",
Senha = "danilodelphi"
};
negocioUsuario.ValidarSenha(usuarioSenhaCaracteres.Senha);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void CT06UC20FA_Logar_comNomeNulo_semSucesso()
{
Usuario usuarioNomeNulo = new Usuario()
{
Nome = "Alexandre",
Senha = ""
};
negocioUsuario.ValidarNome(null);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void CT07UC20FA_Logar_comSenhaNula_semSucesso()
{
Usuario usuarioSenhaNula = new Usuario()
{
Nome = "Danilo",
Senha = "delphi"
};
negocioUsuario.ValidarSenha(null);
}
[Test]
[ExpectedException(typeof(Exception))]
public void CT08UC20FA_Logar_comNomeIncorreto_semSucesso()
{
Usuario usuarioNomeIncorreto = new Usuario()
{
Nome = "Danilo",
Senha = "delphi"
};
usuarioDAO.Consultar(usuarioNomeIncorreto);
}
[Test]
[ExpectedException(typeof(Exception))]
public void CT09UC20FA_Logar_comSenhaIncorreta_semSucesso()
{
Usuario usuarioSenhaIncorreta = new Usuario()
{
Nome = "Alexandre",
Senha = "creta"
};
Usuario usuarioRetorno = usuarioDAO.Consultar(usuarioSenhaIncorreta);
}
[Test]
public void CT10UC20FB_Logar_deslogar()
{
Login.RemoverUsuario();
Assert.AreEqual(null, Login.Usuario);
}
}
} |
Markdown | UTF-8 | 815 | 3.3125 | 3 | [] | no_license | # Lem in
Algorithm to find the quickest way to get n ants across a farm.
## Rules
At the beginning, all the ants are in the room ##start. The goal is to bring them to the room ##end with as few turns as possible. Each room can only contain one ant at a time (except at ##start and ##end which can contain as many ants as necessary).
At each turn each ant can be moved once through a tube (the room at the receiving end must be empty).
## How to compile
From the root of the repository run `make`
## How to run
From the root of the repository run `./lem-in < [lem in file]`
## Lem in file
The lem in file contains the number of ants, the rooms and the links.
## Example
```
$ ./lem-in < test_lemin/3.lmin
3
##start
0 1 0
##end
1 5 0
2 9 0
3 13 0
0-2
2-3
3-1
L1-2
L1-3 L2-2
L1-1 L2-3 L3-2
L2-1 L3-3
L3-1
```
|
Markdown | UTF-8 | 4,497 | 2.625 | 3 | [] | no_license | ---
description: "How to Make Super Quick Homemade Pineapple Thunder"
title: "How to Make Super Quick Homemade Pineapple Thunder"
slug: 3410-how-to-make-super-quick-homemade-pineapple-thunder
date: 2020-06-02T04:54:48.463Z
image: https://img-global.cpcdn.com/recipes/f4831ed28dd33d10/751x532cq70/pineapple-thunder-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/f4831ed28dd33d10/751x532cq70/pineapple-thunder-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/f4831ed28dd33d10/751x532cq70/pineapple-thunder-recipe-main-photo.jpg
author: Cordelia Stephens
ratingvalue: 4.5
reviewcount: 15593
recipeingredient:
- "2 cups Fresh pineapple juice"
- "2 cups Any cola drink 1 cup vanilla icecream"
- " Crushed ice"
- "2 tbsp Sugar syrup"
- " Icing sugar"
- "1/2 tsp Black pepper"
- " Pineapple slices to decorate"
recipeinstructions:
- "Blend and strain the juice of pineapple."
- "Add sugar syrup into the juice.Add vanilla ice cream. Churn it."
- "At the serving time dip the rim of glasses in the icing sugar to coat it."
- "Half fill the glasses with crushed ice."
- "Pour juice mixed with ice cream and sugar syrup into glasses."
- "Now fill them with cola drink."
- "Sprinkle black pepper. Decorate with a slice of pineapple"
- "Serve chilled."
categories:
- Recipe
tags:
- pineapple
- thunder
katakunci: pineapple thunder
nutrition: 295 calories
recipecuisine: American
preptime: "PT14M"
cooktime: "PT44M"
recipeyield: "4"
recipecategory: Dessert
---

Hello everybody, it's John, welcome to our recipe site. Today, I will show you a way to prepare a distinctive dish, pineapple thunder. One of my favorites food recipes. This time, I am going to make it a little bit unique. This is gonna smell and look delicious.
Pineapple Thunder is one of the most popular of current trending meals on earth. It is simple, it's quick, it tastes yummy. It's appreciated by millions daily. They are nice and they look fantastic. Pineapple Thunder is something which I have loved my whole life.
The Thunder V Pineapple mimics a flash bang and is designed based off of the real deal used by our military in World War II, Vietnam, and other conflicts. Apocalyptic Thunder Pineapple NEIPA. Добавить в мои рецепты. Airsoft Grenade Grenades Thunder Pineapple Packing Bag Packaging Pomegranates Pinecone Pine Apple. Buy BuudaBomb Pineapple Thunder Gummies and more THC infused edibles from Canada's best Calm any storm with BuudaBomb's Pineapple Thunder Gummies!
To get started with this recipe, we must prepare a few components. You can cook pineapple thunder using 7 ingredients and 8 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Pineapple Thunder:
1. Make ready 2 cups Fresh pineapple juice
1. Get 2 cups Any cola drink 1 cup vanilla icecream
1. Prepare Crushed ice
1. Prepare 2 tbsp Sugar syrup
1. Take Icing sugar
1. Get 1/2 tsp Black pepper
1. Make ready Pineapple slices to decorate
Pineapple tart or nanas tart is a small, bite-size pastries filled or topped with pineapple jam, commonly found throughout different parts of Southeast Asia such as Indonesia (kue nastar), Malaysia. Our thunder B can be attached to tactical vest or jacket. Its color and shape are very similar to a real grenade used by military force. Sold by Evogen Nutrition and ships from Amazon Fulfillment.
<!--inarticleads2-->
##### Steps to make Pineapple Thunder:
1. Blend and strain the juice of pineapple.
1. Add sugar syrup into the juice.Add vanilla ice cream. Churn it.
1. At the serving time dip the rim of glasses in the icing sugar to coat it.
1. Half fill the glasses with crushed ice.
1. Pour juice mixed with ice cream and sugar syrup into glasses.
1. Now fill them with cola drink.
1. Sprinkle black pepper. Decorate with a slice of pineapple
1. Serve chilled.
Its color and shape are very similar to a real grenade used by military force. Sold by Evogen Nutrition and ships from Amazon Fulfillment.
So that is going to wrap this up for this special food pineapple thunder recipe. Thanks so much for reading. I am confident that you will make this at home. There is gonna be interesting food at home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your family, colleague and friends. Thank you for reading. Go on get cooking!
|
C | UTF-8 | 1,528 | 2.75 | 3 | [
"MIT"
] | permissive | #include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "Name.h"
#include "Name_r.h"
#include "mathlib.h"
#include "parse.h"
#include "value.h"
#include "value_r.h"
struct Math
{
struct Name _;
double (*funct)(double);
};
#define funct(tree) (((struct Math *)left(tree))->funct)
static double doMath(const void *tree)
{
double result = exec(right(tree));
errno = 0;
result = funct(tree)(result);
if (errno)
error("error in %s : %s",
((struct Math *)left(tree))->_.name,
strerror(errno));
return result;
}
static void freeMath(void *tree)
{
delete (right(tree));
free(tree);
}
static const struct Type _Math = {mkBin, doMath, freeMath};
const void *Math = &_Math;
void initMath(void)
{
static const struct Math functions[] = {
{{&_Math, "sin", MATH}, sin},
{{&_Math, "cos", MATH}, cos},
{{&_Math, "tan", MATH}, tan},
{{&_Math, "asin", MATH}, asin},
{{&_Math, "acos", MATH}, acos},
{{&_Math, "atan", MATH}, atan},
{{&_Math, "sinh", MATH}, sinh},
{{&_Math, "cosh", MATH}, cosh},
{{&_Math, "tanh", MATH}, tanh},
{{&_Math, "exp", MATH}, exp},
{{&_Math, "log", MATH}, log},
{{&_Math, "log10", MATH}, log10},
{{&_Math, "sqrt", MATH}, sqrt},
{{&_Math, "ceil", MATH}, ceil},
{{&_Math, "floor", MATH}, floor},
{{&_Math, "abs", MATH}, fabs},
{{0}}};
const struct Math *mp;
for (mp = functions; mp->_.name; ++mp)
install(mp);
} |
C# | UTF-8 | 643 | 3.296875 | 3 | [] | no_license | using System.Collections.Generic;
namespace Blackjack
{
class CardPlayer
{
public readonly List<Hand> Hands = new List<Hand>();
public void ReceiveCard(Card card, Hand hand)
{
hand.AddCard(card);
}
public void AddHand(Hand hand)
{
Hands.Add(hand);
}
public void RemoveHand(Hand hand)
{
}
public List<Card> RemoveHandAndReturnCards(Hand hand)
{
var cards = hand.ClearAndReturnHand();
Hands.RemoveAll(handInHands => handInHands == hand);
return cards;
}
}
}
|
Markdown | UTF-8 | 515 | 2.515625 | 3 | [] | no_license | ## Fast style transfer
Implemented using tensorflow functional API.
examples:
<img src="images/original.jpg" height="200">
Style | Trained
:-------------------------:|:-------------------------:
<img src="images/style1.jpg" height="100"> | <img src="images/style1-trained.jpg" height="100">
<img src="images/style2.jpg" height="100"> | <img src="images/style2-trained.jpg" height="100">
After training to test the style on a new image
`python main.py --image <path-to-image>`
|
Python | UTF-8 | 545 | 3.546875 | 4 | [] | no_license | #Lint code: Merge two sworted arrays
def main():
a = input().split()
for i in range(0,len(a)):
a[i] = int(a[i])
b = input().split()
for i in range(0,len(b)):
b[i] = int(b[i])
c = []
ia = 0
ib = 0
len_a = len(a)
len_b = len(b)
while ia < len(a) and ib < len(b):
if a[ia] < b[ib]:
c.append(a[ia])
ia+=1
else:
c.append(b[ib])
ib+=1
if ia != len(a):
while ia < len(a):
c.append(a[ia])
ia+=1
if ib != len(b):
while ib < len(b):
c.append(b[ib])
ib+=1
print(c)
if __name__ == "__main__":
main() |
C# | UTF-8 | 492 | 2.765625 | 3 | [] | no_license | using System;
using System.Collections.ObjectModel;
using System.Linq;
namespace UserLogic.Domain
{
[Serializable]
public class Projects : ObservableCollection<Project>
{
public bool IsExist(Project project)
{
var con = from p in this
where (p.Id == project.Id)
select p;
if (con.Count() == 0)
{
return false;
}
return true;
}
}
} |
JavaScript | UTF-8 | 1,210 | 3.125 | 3 | [] | no_license | // The http.createServer() method includes request and response parameters which is supplied by NodeJs
//The request object can be used to get information about the current HTTP request
//e.g -> url,request,header, and data.
//The response object can be used to send a response for a current HTTP request.
//If the response from the HTTP server is supposed to be displayed as HTML,
// you should include an HTTP header with the correct content type:
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
const data = fs.readFileSync(`${__dirname}/userAPI/userApi.json`,'utf-8')
const objData = JSON.parse(data)
if (req.url == '/') {
res.end('Hello world!');
} else if (req.url == '/contact') {
res.end('Contact us Page');
} else if (req.url == '/about') {
res.end('About us Page');
}else if(req.url == '/userapi'){
res.writeHead(200, {'content-type': 'application/json'});
res.end(objData[2].name)
}
else {
res.writeHead(404, { 'content-type': 'text/html' });
res.end('404 Page Not Found');
}
});
// server.listen(8000, '127.0.0.1', () => {
// console.log('Port running successfully.');
// });
|
C# | UTF-8 | 1,529 | 2.703125 | 3 | [] | no_license | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Attributes;
using System.Linq;
using System.Collections.Generic;
namespace AttributesUnitTests
{
[TestClass]
public class AttributesTypesTest
{
[TestMethod]
public void CanGetTypesToCount()
{
var expected = 18;
var actual = AttributesTypes.AssemblyTypes.Count();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void CanGetAttributesTypesInTheAssembly()
{
var expected = new List<Type>
{
typeof(XamlCanvasLeft),typeof(XamlCanvasTop),typeof(XamlClick),
typeof(XamlContent),typeof(XamlHeight),typeof(XamlName),
typeof(XamlTabIndex),typeof(XamlWidth),typeof(XamlGridColumn),
typeof(XamlGridRow),typeof(XamlForeground),typeof(XamlBackground),
typeof(XamlHeader),typeof(XamlFontSize),typeof(XamlFontFamily),
typeof(XamlFontStyle),typeof(XamlFontWeight),typeof(XamlTextDecorations)
};
var actual = AttributesTypes.AssemblyTypes;
foreach(var type in actual)
{
try
{
Assert.IsTrue(expected.Contains(type));
}
catch(Exception)
{
Assert.Fail("Xaml Attribute " + type.Name + " not found in expected list!");
}
}
}
}
}
|
C# | UTF-8 | 1,871 | 2.5625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RestaurantApp.Core;
using RestaurantApp.Data;
namespace RestaurantApp.Pages.Restaurants
{
public class DeleteModel : PageModel
{
private readonly RestaurantContext _context;
public DeleteModel(RestaurantContext restaurantContext)
{
this._context = restaurantContext;
}
[BindProperty]
public Restaurant Restaurant { get; set; }
public string ErrMessage { get; set; }
public async Task<IActionResult> OnGetAsync(int? id, bool? saveChangesErr = false)
{
if (id == null) return NotFound();
Restaurant = await _context.Restaurants
.AsNoTracking()
.FirstOrDefaultAsync(r => r.Id == id);
if (Restaurant == null) return NotFound();
if (saveChangesErr.GetValueOrDefault())
{
ErrMessage = String.Format("Delete {ID} failed. Try again.", id);
}
return Page();
}
public async Task<IActionResult> OnPostAsync(int? id)
{
if (id == null) return NotFound();
var restaurant = await _context.Restaurants.FindAsync(id);
if (restaurant == null) return NotFound();
try
{
_context.Restaurants.Remove(restaurant);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
catch (DbUpdateException ex)
{
return RedirectToAction("./Delete",
new { id, saveChangesErr = true });
}
}
}
} |
Java | UTF-8 | 1,196 | 2.28125 | 2 | [] | no_license | package com.community.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.community.dao.AdminDAO;
import com.community.entity.Admin;
import com.community.service.AdminService;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
private AdminDAO adminDAO;
@Override
public Admin login(String adminName, String adminPassword) {
return adminDAO.queryByNameAndPsw(adminName, adminPassword);
}
@Override
public boolean register(Admin admin) {
if (adminDAO.insert(admin)>0) {
return true;
} else {
return false;
}
}
@Override
public boolean updatePassword(int adminId, String adminPassword) {
if (adminDAO.updatePassword(adminId, adminPassword)>0) {
return true;
} else {
return false;
}
}
@Override
public boolean delete(int adminId) {
if(adminDAO.delete(adminId)>0){
return true;
}else {
return false;
}
}
@Override
public List<Admin> getAdmin(String adminName) {
return adminDAO.queryByName(adminName);
}
@Override
public List<Admin> getAllAdmins() {
return adminDAO.queryAll();
}
}
|
Java | UTF-8 | 4,243 | 3.734375 | 4 | [] | no_license | package com.wenx.demo.multithread;
import java.util.concurrent.*;
/**
* @author Wenx
* @date 2019/11/18
*/
public class ForkJoinDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 本质是一个线程池,默认的线程数量:CPU的核数
// 默认情况下,并行线程数量等于可用处理器的数量
// ForkJoinPool与其他类型的ExecutorService的区别主要在于它使用了工作窃取:
// 池中的所有线程都试图查找和执行提交给池的任务和/或其他活动任务创建的任务
// (如果不存在工作,则最终阻塞等待工作)。
ForkJoinPool forkJoinPool = new ForkJoinPool();
// 适合数据处理、结果汇总、统计等场景
// 举个栗子计算1+2+3+…100W的结果,拆分多个线程进行计算,合并汇总返回
// 查询多个接口的数据,合并返回
// 其他例子,查数据库的多个表数据,分多次查询
// fork/join
// forkJoinPool.submit()
// 计算1+2+3+…100W的结果,这里只是举个例子
long time1 = System.currentTimeMillis();
// 提交可分解的RecursiveTask任务
ForkJoinTask<Long> forkJoinTask = forkJoinPool.submit(new SumTask(1, 1000000));
System.out.println("结果为:" + forkJoinTask.get() + " 执行时间" + (System.currentTimeMillis() - time1));
//forkJoinPool.shutdown();
// 实际执行Fork、Join、从队列存取等操作都需要消耗时间,请在合适的场景使用
long time2 = System.currentTimeMillis();
long sum = 0L;
for (int i = 1; i <= 1000000; i++) {
sum += i;
}
System.out.println("结果为:" + sum + " 执行时间" + (System.currentTimeMillis() - time2));
// 提交可分解的RecursiveAction任务
forkJoinPool.submit(new PrintAction(1, 1000));
//阻塞当前线程直到 ForkJoinPool 中所有的任务都执行结束
forkJoinPool.awaitTermination(2, TimeUnit.SECONDS);
forkJoinPool.shutdown();
}
}
class SumTask extends RecursiveTask<Long> {
private static final int THRESHOLD = 1000;
private int start; // 开始下标
private int end; // 结束下标
public SumTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
// 如果当前任务的计算量在阈值范围内,则直接进行计算
if (end - start < THRESHOLD) {
return computeByUnit();
} else { // 如果当前任务的计算量超出阈值范围,则进行计算任务拆分
// 计算中间索引
int middle = (start + end) / 2;
//定义子任务-迭代思想
SumTask left = new SumTask(start, middle);
SumTask right = new SumTask(middle + 1, end);
//划分子任务-fork
left.fork();
right.fork();
//合并计算结果
return left.join() + right.join();
}
}
private long computeByUnit() {
long sum = 0L;
for (int i = start; i <= end; i++) {
sum += i;
}
return sum;
}
}
class PrintAction extends RecursiveAction {
private static final int THRESHOLD = 20;
private int start; // 开始下标
private int end; // 结束下标
public PrintAction(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected void compute() {
//当end-start的值小于MAX时,开始打印
if ((end - start) < THRESHOLD) {
computeByUnit();
} else {
// 将大任务分解成两个小任务
int middle = (start + end) / 2;
PrintAction left = new PrintAction(start, middle);
PrintAction right = new PrintAction(middle + 1, end);
left.fork();
right.fork();
}
}
private void computeByUnit() {
for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + "的值:" + i);
}
}
}
|
Shell | UTF-8 | 143 | 2.6875 | 3 | [] | no_license | #!/bin/bash
# Checks the WAN IP.
#vers="wan_chck-0.4"
wan_ip="$(curl -s www.icanhazip.com | awk '{print $1}')"
echo "wan_ip=$wan_ip"
exit 0 |
JavaScript | UTF-8 | 1,149 | 2.78125 | 3 | [] | no_license | canvas = createCanvas(windowWidth / 2, windowHeight / 1.5);
engine = Engine.create();
world = engine.world;
function setup(){
let canvasmouse = mouse.create(canvas.elt);
canvasmouse.pixelRatio = pixelDensity();
let options = {
mouse: canvasmouse
};
pendulum1 = new Pendulum(100, 250, 100, 100);
pendulum2 = new Pendulum(200, 250, 100, 100);
pendulum3 = new Pendulum(300, 250, 100, 100);
pendulum4 = new Pendulum(400, 250, 100, 100);
pendulum5 = new Pendulum(500, 250, 100, 100);
sling1 = new Sling(100, 50, 5, 200);
sling2 = new Sling(200, 50, 5, 200);
sling3 = new Sling(300, 50, 5, 200);
sling4 = new Sling(400, 50, 5, 200);
sling5 = new Sling(500, 50, 5, 200);
mConstraint = MouseConstraint.create(engine, options);
World.add(world, mConstraint);
}
function draw(){
background(255);
Engine.update(engine);
pendulum1.display();
pendulum2.display();
pendulum3.display();
pendulum4.display();
pendulum5.display();
sling1.display();
sling2.display();
sling3.display();
sling4.display();
sling5.display();
}
function mouseDragged(){
Matter.body.setPositon(pendulum1.body({ x: mouseX, y: mouseY });
} |
Java | UTF-8 | 10,605 | 2.140625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cit260.neversync.control;
import byui.cit260.neversync.exceptions.GameControlException;
import byui.cit260.neversync.exceptions.MapControlException;
import byui.cit260.neversync.view.ErrorView;
import cit260.neversync.model.Actor;
import cit260.neversync.model.Game;
import cit260.neversync.model.InventoryItem;
import cit260.neversync.model.ItemType;
import cit260.neversync.model.Map;
import cit260.neversync.model.Player;
import cit260.neversync.model.Question;
import cit260.neversync.model.Scores;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import neversync.NeverSync;
/**
*
* @author Ben Langston and Jeff Ledbetter
*/
public class GameControl implements Serializable {
public static Player savePlayer(String playersName) {
if (playersName == null || playersName.length() < 3) {
return null;
} else {
Player player = new Player();
player.setName(playersName);
NeverSync.setPlayer(player);
return player;
}
}
public GameControl() {
}
public static int createNewGame(Player player) throws GameControlException {
// Check for invalid inputs
if (player == null) {
return -1;
}
Game game = new Game();
Scores score = new Scores();
game.setPlayer(player);
NeverSync.setCurrentGame(game);
game.setPlayer(player);
game.setInventory(GameControl.createItems());
ArrayList<Actor> Actors = createActors();
game.setActors(Actors);
// set initial values
game.setYear(1);
game.setStarved(1);
game.setNewPopulation(5);
game.setBushelsHarvested(3000);
game.setBushelsInTithes(300);
game.setWheatEatenByRats(0);
game.setHideReport(false);
game.setHasItem(false);
game.getScore();
score.getNewScore();
score.getHighScore();
// game.setBushelsPerAcreHarvested();
game.setAcresOwned(1000);
game.setCurrentPopulation(100);
game.setWheatInStorage(2700);
// game.setInventoryType.items;
Map map = new Map();
try {
game.setMap(MapControl.createMap(game, 5, 5));
} catch (MapControlException ex) {
ErrorView.display("Error:", ex.getMessage());
}
if (map == null) {
throw new GameControlException("Map creation has failed");
} else {
return 1;
}
}
public static InventoryItem[] createItems() {
InventoryItem[] items = new InventoryItem[16];
InventoryItem item = new InventoryItem();
item.setItemType("oil");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(1.50);
items[ItemType.oil.ordinal()] = item;
item = new InventoryItem();
item.setItemType("lumber");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(5.00);
items[ItemType.lumber.ordinal()] = item;
item = new InventoryItem();
item.setItemType("ore");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(10.00);
items[ItemType.ore.ordinal()] = item;
item = new InventoryItem();
item.setItemType("grain");
item.setQuantityInStock(100);
item.setRequiredAmount(5);
item.setPricePerUnit(2.00);
items[ItemType.grain.ordinal()] = item;
item = new InventoryItem();
item.setItemType("legume");
item.setQuantityInStock(20);
item.setRequiredAmount(1);
item.setPricePerUnit(2.50);
items[ItemType.legume.ordinal()] = item;
item = new InventoryItem();
item.setItemType("water");
item.setQuantityInStock(100);
item.setRequiredAmount(1);
item.setPricePerUnit(1.00);
items[ItemType.water.ordinal()] = item;
item = new InventoryItem();
item.setItemType("honey");
item.setQuantityInStock(200);
item.setRequiredAmount(2);
item.setPricePerUnit(2.00);
items[ItemType.honey.ordinal()] = item;
item = new InventoryItem();
item.setItemType("salt");
item.setQuantityInStock(200);
item.setRequiredAmount(4);
item.setPricePerUnit(1.25);
items[ItemType.salt.ordinal()] = item;
item = new InventoryItem();
item.setItemType("axe");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(3.00);
items[ItemType.axe.ordinal()] = item;
item = new InventoryItem();
item.setItemType("hammer");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(3.00);
items[ItemType.hammer.ordinal()] = item;
item = new InventoryItem();
item.setItemType("drill");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(4.50);
items[ItemType.drill.ordinal()] = item;
item = new InventoryItem();
item.setItemType("shovel");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(2.50);
items[ItemType.shovel.ordinal()] = item;
item = new InventoryItem();
item.setItemType("sickle");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(5.00);
items[ItemType.sickle.ordinal()] = item;
item = new InventoryItem();
item.setItemType("saw");
item.setQuantityInStock(10);
item.setRequiredAmount(1);
item.setPricePerUnit(2.50);
items[ItemType.saw.ordinal()] = item;
item = new InventoryItem();
item.setItemType("nails");
item.setQuantityInStock(50);
item.setRequiredAmount(5);
item.setPricePerUnit(1.50);
items[ItemType.nails.ordinal()] = item;
item = new InventoryItem();
item.setItemType("antiplague");
item.setQuantityInStock(1);
item.setRequiredAmount(1);
item.setPricePerUnit(100);
items[ItemType.antiplague.ordinal()] = item;
return items;
}
public static Question createQuestion() {
return null;
}
public static ArrayList<Actor> createActors() {
ArrayList<Actor> actors = new ArrayList<>();
actors.add(Actor.Lehi);
actors.add(Actor.Jacob);
actors.add(Actor.Laman);
actors.add(Actor.Lemuel);
actors.add(Actor.Zoram);
actors.add(Actor.Sam);
actors.add(Actor.Sariah);
actors.add(Actor.Nephi);
return actors;
}
public static void saveGame(Game game, String filePath)
throws GameControlException {
if (filePath == null || game == null) {
throw new GameControlException(
"Error saving game");
}
if (!filePath.contains(".")) {
filePath += ".dat";
}
try (ObjectOutputStream out
= new ObjectOutputStream(new FileOutputStream(filePath))) {
out.writeObject(game);
} catch (Exception ex) {
throw new GameControlException("Game Could Not Be Saved. "
+ "Error: " + ex.getMessage());
}
}
public static Game getGame(String filePath) throws GameControlException {
if (filePath == null) {
throw new GameControlException(
"Error Loading Game");
}
if (!filePath.contains(".")) {
filePath += ".dat";
}
Game game = null;
try (FileInputStream in = new FileInputStream(filePath)) {
ObjectInputStream saved = new ObjectInputStream(in);
game = (Game) saved.readObject();
} catch (Exception e) {
throw new GameControlException(
e.getMessage());
}
{
NeverSync.setCurrentGame(game);
}
return game;
}
public static void saveHighScore(int score)
throws GameControlException {
if (score == 0) {
throw new GameControlException(
"Error saving score");
}
try (DataOutputStream out
= new DataOutputStream(new FileOutputStream("gameScore.dat"))) {
// = new IntegerOutputStream(new FileOutputStream("gameScore.dat"))) {
// out.writeObject(player);
// out.writeObject(score);
out.writeInt(score);
} catch (Exception ex) {
throw new GameControlException("Game Could Not Be Saved. "
+ "Error: " + ex.getMessage());
}
}
public static int getScore() throws GameControlException {
Scores score = new Scores();
int newScore = 0;
// String player = null;
// Player player = new Player();
try (FileInputStream in = new FileInputStream("gameScore.dat")) {
DataInputStream saved = new DataInputStream(in);
newScore = (int) saved.readInt();
// System.out.println(newScore);
// player = (String) saved.readObject();
} catch (Exception e) {
throw new GameControlException(
e.getMessage());
}
{
score.setHighScore(newScore);
}
return newScore;
}
public static void resetHighScore(int score)
throws GameControlException {
if (score < 0) {
throw new GameControlException(
"Error saving score");
}
try (DataOutputStream out
= new DataOutputStream(new FileOutputStream("gameScore.dat"))) {
out.writeInt(score);
} catch (Exception ex) {
throw new GameControlException("Game Could Not Be Saved. "
+ "Error: " + ex.getMessage());
}
}
}
|
Java | UTF-8 | 679 | 2.78125 | 3 | [] | no_license | package de.te.layouting.layouting;
import de.te.layouting.geometry.IBounds;
public interface IGeometricalLayoutConstraint {
/**
* Converts the <code>currentBounds</code> into reasonable legal bounds. If
* <code>currentBounds</code> is legal, than it should be returned without
* change.
*
* @param currentBounds
* - the bounds that a given Object should have.
* @return
*/
IBounds getLegalBounds(IBounds currentBounds);
/**
* Checks, wheter the Bounds are legal with respect to this constraint.
*
* @param currentBounds
* @return true, if everything is alright.
*/
boolean isLegal(IBounds currentBounds);
}
|
Markdown | UTF-8 | 1,043 | 2.90625 | 3 | [] | no_license | # Digit_Recognition_Keras
## About:
MNIST dataset from keras is used for Digit Recogintion {0-9}. Convolution Neural Network used for modelling.
* Data-set is loaded from mnist of keras
* Archiecture:-
1) Two convolution layers
2) Two max. pooling layers
3) Flatten layer
4) Dense layer
5) Dense Output layer {Will have 10 nodes, because its classifier for 10 nodes}
In convolution 2D layer 'relu' activation function is used. Same in first dense layer.
But in output dense layer 'softmax' activation function is used because its a classification problem of more than one classes.
Model is ran over 60000 random train images and 10000 random test images from the dataset.
>> loss: 0.0834 - accuracy: 0.9819
{Result may vary a little because of randomness of data set used for training of the model}
Note:- Please check the "MNIST_using_CNN.ipynb" jupyter notebook for better understanding of the model.
Architecture and trainable parameters are then saved to 'model.h5'. Which is loaded in "app.py" for deployment using Flask.
|
C++ | UTF-8 | 444 | 3.375 | 3 | [] | no_license | /*
CPSC 121-0X
Paul De Palma
depalma
Example 1
*/
//i/o, variables, arithmetic operator, assignment
#include <iostream>
using namespace std;
int main()
{
double hours, rate, pay;
//Get hours
cout << "How many hours did your work? ";
cin >> hours;
//Get rate
cout << "How much did you get paid per hour? ";
cin >> rate;
//calculate pay
pay = hours * rate;
//display the pay
cout << "You have earned $" << pay << endl;
return 0;
}
|
Markdown | UTF-8 | 6,115 | 3.265625 | 3 | [] | no_license | # Web page scraper
**Author**: Claude Gibert 2016.
## Foreword
I apologise for greatly over-engineering this test. I could have hard-coded the program using Beautiful Soup into a program which would have been hardly longer than the main program here. However I have written page scrapers in the past and I know that if all the web page orgnisation is in the code logic, it is costly to maintain those programs everytime they break, as this requires understanding the code logic again.
I wanted to take up the challenge of describing the web page organisation in a 'scenario' file and write generic code to find all the pieces of information needed from the page(s). This took longer than 2 hours but there was a long week-end.
## Description
Scraping HTML pages is a fragile process which can break everytime the contents or the style of a web page is changed. In order to increase the robustness of the process, it is often tempting to be as little specific as possible regarding the tags which are searched. However, this may cause worse problems that breakage: this may cause *capturing the wrong information without even knowing it*.
As an example of this, in the page describing one particular ripe fruit, we find:
```html
<h3 class="productDataItemHeader">Description</h3>
<div class="productText">
<p>Apricots</p>
<p>
</div>
<h3 class="productDataItemHeader">Nutrition</h3>
<div class="productText">
<div>
<p>
<strong>Table of Nutritional Information</strong>
</p>
...
</div>
<h3 class="productDataItemHeader">Size</h3>
<div class="productText">
<p>5Count</p>
</div>
...
```
If we look for div, class="productText" we will find more than one tag. We could decide that the description if the first one found, but a change in the order, or the insertion of another tag before would break the system. In that case it probably pays off to be specific about what we are looking for. So the strategy is to look for h3, class="productDataItemHeader", check that it contains the string *Description*, take the next sibling tag and search for the *paragraph* tag.
## Design
We decide that the application should raise an exception if the expected conditions for a web page are not met. It is important to be notified if the application fails to find tags as this may mean that the page was changed.
#### 1. Define the different types of search needed and the data needed
Implement those searches using Beautiful Soup and make sure they raise an exception if the tag is not found. This is found in the TagFinder and TagUtils classes.
#### 2. Create tools
Create re-usable tools to support the application: the classes Config, Factory, PageFetcher, TagConsumer
#### 3. Define a format for describing the "geography" of web pages
This is done using a yaml text file, please see the scenarios section and implement support classes: Child, Parent, Sibling
#### 4. Make a map of all tags needed by the application
Access to each tag is given using a hierarchical path (please see also the scenarios section)
#### 5. Write the application to produce what is needed.
This part is completely application dependent and quite 'hard-coded'.
## The scenarios file
The file describes which tag we are looking for in a particular HTML file and how to find them. It also enables the user to name paths to the tags. Here is the file included in the project:
```yaml
ripe fruits: <---- name of the scenario corresponding to a web page
type: parent <---- type parent: can find more than one tage and returns a list
name: product <---- this will be used to create the path
tag_name: div <---- we are looking for <div class="product ">
attr:
class_: "product "
inner: <---- embedded tags
- type: parent
name: productInfo
tag_name: div <---- we look for <div class="productInfo">
attr:
class_: productInfo
inner: <---- embedded tags
- type: child <---- this is the final tag, no more embeded ones
name: link <---- this tag will be mapped as product.productInfo.link
tag_name: a <---- we look for <a ....>
attr: {}
- type: child
name: price <---- this tag will be mapped ad product.price
tag_name: p <---- we look for <p class="pricePerUnit">
attr:
class_: pricePerUnit
description: <---- scenario for the subpage
type: sibling <---- type sibling: return the first tag sibling after the tag found
name: itemHeader
tag_name: h3 <---- we look for the tag after <h3 class="productDataItemHeader">
attr:
class_: productDataItemHeader
contents: Description <---- find the tag which contains the word "Description"
inner:
- type: child
name: description <---- this tag will be mapped itemHeader.description
tag_name: p
attr: {}
```
## Installation and dependencies
The file requirements.txt contains the dependencies create with pip. Run pip install -r requirements.txt.
The dependencies are also named in the setup.py file, these should install with the module. This is a Python 2.7.x program.
To run the application: **python ripefruits.py** the ouput is printed out in the standard output.
## Tests
The tests focus on the tag search logic, making sure that exceptions are raised if something is not found and also making sure that tags are found when they are present.
Please see the test files for more information.
In the main directory run **./run_tests.bash**
## Not done
I don't think the library will work if we describe a page with a parent containing parents (list of lists of tags). I decided not to address this at this point, it would be easy to fix.
In this program, the sub-pages are fetched from the main program, it could be good to implement a mechanism in the 'child' class to read the next scenario name to run from a link. It could then concatenate the paths together to access the tags.
|
Java | UTF-8 | 1,452 | 3.375 | 3 | [] | no_license | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner sc =new Scanner(System.in);
int row=sc.nextInt();
int col=sc.nextInt();
int a[][]=new int[row][col];
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
a[i][j]=sc.nextInt();
}
}
//East=j++ ; South=i++ ; West=j-- ; North=i--
int dir=0; // 0=East, 1=South, 2=West, 3=North
int i=0,j=0;
while(true)
{
dir = (dir + a[i][j]) %4;
if(dir==0)
{
j++;
}
else if(dir==1)
{
i++;
}
else if(dir==2)
{
j--;
}
else if(dir==3)
{
i--;
}
if(i<0)
{
i++;
break;
}
else if(j<0)
{
j++;
break;
}
else if(i==a.length)
{
i--;
break;
}
else if(j==a[0].length)
{
j--;
break;
}
}
System.out.println(i);
System.out.println(j);
}
}
|
Markdown | UTF-8 | 8,922 | 2.734375 | 3 | [] | no_license | # SEAView
SEAView (*"**S**CU-**E**DU-**A**lignment"*) is a tool for annotating content in two-part essays, which contain a summary and an argument. This tool is used to annotate elementary discourse units (EDUs) from the argument section, and align them with semantically similar summary content units (SCUs) from the summary section.
Please cite this paper if you use the tool:
Gao, Yanjun, et al. "[Rubric Reliability and Annotation of Content and Argument in Source-Based Argument Essays](https://www.aclweb.org/anthology/W19-4452/)." Proceedings of the Fourteenth Workshop on Innovative Use of NLP for Building Educational Applications. 2019.
[BibTeX Citation](https://www.aclweb.org/anthology/papers/W/W19/W19-4452.bib)
### Table of Contents
**[Requirements](#requirements)**<br>
**[Features](#features)**<br>
**[Workflow](#workflow)**<br>
**[Interface](#interface)**<br>
**[Annotation Guidelines](#annotation-guidelines)**<br>
**[Class Documentation](#class-documentation)**<br
## Requirements
Java 8 or higher.
## Features
Create and view SCU-EDU alignments, depicting semantically similar EDUs and SCUs in essays. <br />
Export SCU-EDU alignments in XML.
## Workflow
The annotation process has four main steps for annotating a set of wise crowd and peer essays, designed to be performed using this tool and DUCView. See the [DUCView README](https://github.com/psunlpgroup/DucView-1.5) for information on steps 1 and 2, and for more information about SCUs. The four annotation steps are summarized below:
<br /><br />
### Workflow Table
| Step # | Tool | Annotate | Align With | Input | Output |
| ------- | ------- | --------------- | --------------- | --------------- | ---------------------------- |
| 1 | DUCView | Wise crowd SCUs | | \*.txt | \*.pyr (pyramid) |
| 2 | DUCView | Peer SCUs | | \*.pyr + \*.txt | \*.pan (peer annotation) |
| 3 | SEAView | Wise crowd EDUs | Wise crowd SCUs | \*.pyr | \*.sea (SEA annotation) |
| 4 | SEAView | Peer EDUs | Peer SCUs | \*.pan | \*.sep (SEA peer annotation) |
### Workflow Explanation
1. See the [DUCView README](https://github.com/psunlpgroup/DucView-1.5).
2. See [DUCView README](https://github.com/psunlpgroup/DucView-1.5).
3. Wise crowd EDUs are annotated from a set of wise crowd essays and aligned with wise crowd SCUs from the pyramid created in step 1. The final output is a \*.sea file, or SEA (SCU-EDU alignment) annotation. This file includes a list of EDUs, a list of SCUs matched with the EDUs, and an alignment table. <br />
4. Analogous to step 3 but for peer annotation. Peer EDUs are annotated from a single peer essay and aligned with peer SCUs from the peer annotation created in step 2. The final output is a \*.sep file, or SEA peer annotation. This file includes the same components as the \*.sea file but for the peer essays. <br>
## Interface
The figure below shows the workspace in SEAView for a completed \*.sep file (the output of step 4). A completed \*.sea file would have an equivalent appearance in the tool but would have more content in the left panel since there would be several wise crowd essays instead of one peer essay. The components in red are described in more detail in the section "SEAView Components."

### SEAView Components
#### To drag and drop an EDU:
- *Left click* to highlight text on the left pane.
- *Left click/Right click* to drag into the table.
#### To drag and drop an SCU:
- *Left click* an SCU to highlight it on the right pane
- *Left click* to drag into the table.
#### To view the SCU-EDU Alignment:
- Select File > SEA Annotation (or SEA Peer Annotation) > Show SCU-EDU Alignment
#### Table functions:
- **Sort**: sort the table by the order in which the EDUs occurred in the text
- **Change label**: change the label of an EDU/SCU
- **Remove**: remove an EDU or SCU from the table, or remove a contributor from an EDU
#### Pyramid functions:
- **Show model essays**: when creating an SEP annotation the model essays can be viewed
- **Expand/collapse** the pyramid
- **Order** by number of contributors or alphabetical order
#### Options:
- **Text size**
- **Set label mode**: choose whether to change EDU labels when the EDU is created or manually later
- **Set DND mode**: choose whether left click or right click is used to drag highlighted text from the left pane into the table as an EDU
- **Set RegEx**: there are two regular expressions to set. **Document Header RegEx**: Divides essays from each other. **Summary Divider RegEx**: Divides the summary from the argument in a single essay. **These must be set prior to annotation.**
## Annotation Guidelines
To perform either step 3 or 4 in the workflow described above, there are two main steps:
1. Identification of all the EDUs in the argument text
2. Alignment of EDUs with any SCUs that share the same meaning
### Identify EDUs in the argument text
To perform step 1, EDUs must be segmented from full sentences. Definitions of EDUs vary, but simply put, an EDU is similar to a clause. Generally, we define EDUs to be propositions derived from tensed clauses that are not verb arguments (such as '*that*'-complements of verbs of belief). Annotators first identify the start and end of tensed clauses, omitting discourse connectives from the EDU spans, which can be discontinuous. Annotators then provide a paraphrase of the EDU span as an independent simple sentence. EDU annotation is illustrated in the following example:
<br /><br />
**Sample sentence**: SEAView is a useful tool which was made at Penn State.<br />
**Segmentation**: \[SEAView is a useful tool\] \[which was made at Penn State\].<br />
**Segmented text**:
1. SEAView is a useful tool
2. which was made at Penn State<br />
**Paraphrased EDUs**:
1. SEAView is a useful tool
2. SEAView was made at Penn State
Beginning with the sample sentence, first the annotator must identify the start and end of the tensed clauses, omitting discourse connectives (such as the word "because"), yielding the segmentation shown directly below it. That segmentation is split into the two texts shown in the segmented text section. However, the second text is not an independent simple sentence. It needs the subject relative pronoun to be converted to an independent pronoun to rephrase the EDU as a stand-alone sentence. The paraphrased EDU is shown in the final section above. The sentence has been made into two independent simple sentences, each of which has been paraphrased as a stand-alone sentence. EDUs can be highlighted and dragged from the argument text according to the instructions in "SEAView Components" into the center panel.
### Align EDUs with any SCUs that share the same meaning
Once all of the EDUs in the argument have been annotated, the EDUs in the table must be aligned with SCUs (found in the pyramid on the right panel). SCUs and EDUs are aligned based on similar meaning. Many EDUs will not have a similar SCU in the pyramid and therefore will not be aligned. In the diagram above, note that most EDUs were not matched with an SCU. SCUs are dragged into the center panel according to the instructions in "SEAView Components."
## Class Documentation
This section contains an overview of the most important classes in the project's Java source code and their functions. <br />
#### SEAView
- Contains the main function
- Is primarily responsible for creating the GUI using Swing
- Handles parsing and writing of XML files
- Creates and views the SCU-EDU alignment table
#### SEATable
- The main table in SEAView
- Shows aligned EDUs and SCUs
- Provides functions for interacting with the table, such as drag and drop support and sorting
#### SCU
- Defines an SCU/EDU with an ID, label, and a comment
#### SCUContributor
- Defines an SCU/EDU contributor - a portion of the text from a summary that makes up an SCU
- Includes a list of the contributor's SCUContributorParts, which may be non-adjacent in the text
#### SCUContributorPart
- Defines a part of an SCU/EDU contributor
- Includes the starting and ending indices of the SCU/EDU contributor in the essay, as well as the text
#### SEAViewTextPane
- Defines the left pane of SEAView, containing the essay text
- Includes functions for displaying, highlighting, and selecting text
#### SCUTree
- Defines a tree for SCUs/EDUs
- Used to display the pyramid and the EDUs in the table
- Includes various functions for interacting with SCUs/EDUs such as highlighting and drag and drop
#### EssayAndSummaryNum
- Simple class that contains a pair of values indicating where text came from
- Primarily used by the SEATable class to determine whether an EDU is valid, based on whether it came from a summary or an argument, and whether it comes from the right essay number
|
Python | UTF-8 | 2,305 | 3.203125 | 3 | [
"MIT"
] | permissive | """
A simple grid world environment
"""
import numpy as np
import random
from ..common import MDP
from ..exceptions import EpisodeDoneError, InvalidActionError
from ..actions import LEFT, RIGHT, UP, DOWN
from .helper_utilities import flatten_state, unflatten_state
class GridWorldMDP(MDP):
def __init__(self, P, R, gamma, p0, terminal_states, size, seed=1337, skip_check=False,
convert_terminal_states_to_ints=False):
"""
(!) if terminal_states is not empty then there will be an absorbing state. So
the actual number of states will be size x size + 1
if there is a terminal state, it should be the last one.
:param P: Transition matrix |S| x |A| x |S|
:param R: Transition matrix |S| x |A|
:param gamma: discount factor
:param p0: initial starting distribution
:param terminal_states: Must be a list of (x,y) tuples. use skip_terminal_state_conversion if giving ints
:param size: the size of the grid world (i.e there are size x size (+ 1)= |S| states)
:param seed:
:param skip_check:
"""
if not convert_terminal_states_to_ints:
terminal_states = list(map(lambda tupl: int(size * tupl[0] + tupl[1]), terminal_states))
self.size = size
self.human_state = (None, None)
self.has_absorbing_state = len(terminal_states) > 0
super().__init__(P, R, gamma, p0, terminal_states, seed=seed, skip_check=skip_check)
def reset(self):
super().reset()
self.human_state = self.unflatten_state(self.current_state)
return self.current_state
def flatten_state(self, state):
"""Flatten state (x,y) into a one hot vector"""
return flatten_state(state, self.size, self.state_space)
def unflatten_state(self, onehot):
"""Unflatten a one hot vector into a (x,y) pair"""
return unflatten_state(onehot, self.size, self.has_absorbing_state)
def step(self, action):
state, reward, done, info = super().step(action)
self.human_state = self.unflatten_state(self.current_state)
return state, reward, done, info
def set_current_state_to(self, tuple_state):
return super().set_current_state_to(self.flatten_state(tuple_state).argmax())
|
Markdown | UTF-8 | 1,583 | 3.140625 | 3 | [] | no_license | ---
layout: commandcall
category: CommandCall
title: "MESSAGE_DELETE"
tags: 1.3 1.5
---
The command MESSAGE_DELETE deletes the message with the given ID from the DB.
# Syntax:
```adoscript
{% raw %}
CC "Application" MESSAGE_DELETE messageid:intValue [ userid:intValue | username:strValue]
#--> RESULT ecode:intValue
{% endraw %}
```
{: .line-numbers}
# Parameters:
|`messageid`|intValue, the ID of the message|
|`userid`|intValue, the ID of the user|
|`username`|strValue, the name of the user|
# Returns:
ecode - intValue, 0 if the message was deleted successfully, 1 if wrong parameters have been passed - message was not deleted, 2 if no valid users have been passed - message was not deleted, 3 if an error occured while deleting the message (although the parameters seemed OK)
# Remarks:
If a message was sent to n recipients, there will be n rows in the DB. If MESSAGE_DELETE is called without any userid/username, all n rows will be deleted. If a userid/username is given, just this one row is deleted.
# See Also:
Example 1:
Delete all messages containing the string "Write letter" at the start of the DATA part of the message.
```adoscript
{% raw %}
CC "Application" MESSAGE_SEARCH "Write letter"
IF (ecode = 0)
{
SET n: (tokcnt (messageids, " "))
IF (n = 0)
{
CC "AdoScript" INFOBOX "No messages found!"
}
ELSE
{
FOR id in:(messageids)
{
CC "Application" MESSAGE_DELETE messageid:(VAL id)
}
}
}
ELSE
{
CC "AdoScript" ERRORBOX "An error occured while searching messages!"
}
{% endraw %}
```
{: .line-numbers}
|
PHP | UTF-8 | 2,108 | 3.171875 | 3 | [] | no_license | <!DOCTYPE HTML>
<html>
<head>
<title>Homework 5</title>
<meta charset="utf-8" />
<style>
.error {
color: #FF0000;
}
.correct {
color: #008000;
}
</style>
</head>
<body>
<h1>Homework 5 </h1>
<form method="post" action="hw5_1.php"> First Name:
<input type="text" name="fname"><span class="error"></span>
<br> Last Name:
<input type="text" name="lname"><span class="error"></span>
<br> Email Address:
<input type="text" name="email" placeholder="xyz1234@truman.edu"><span class="error"></span>
<br>
<input type="submit" name="submit" value="Submit">
<br> <span class="error"></span> <span class="correct"></span> </form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["fname"]) || empty($_POST["lname"]) || empty($_POST["email"])) //make sure all enteries are filled in
{
$error = "All entries are required!";
echo $error;
}
else
{
$error = " ";
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
if( !preg_match("/^[a-zA-Z]+$/", $fname) || !preg_match("/^[a-zA-Z]+$/", $lname) || !preg_match("/^[a-zA-Z]{2,3}\d{4}@truman.edu/", $email) )
{
if(!preg_match("/^[a-zA-Z]+$/", $fname)) //check to see if fname is in right format
{$fnameError = "First Name is not in the right format \n ";
echo $fnameError;}
if(!preg_match("/^[a-zA-Z]+$/", $lname)) //check to see if lname is in right format
{$lnameError = "Last Name is not in the right format \n";
echo $lnameError;}
if(!preg_match("/^[a-zA-Z]{2,3}\d{4}@[a-z]\.[a-z]/", $email)) //check to see if email is in right format
{$emailError = "Email is not in the right format, please enter an valid truman email\n";
echo $emailError;}
}
else
{
$db = new PDO("mysql:dbname=adn6627CS315;host=mysql.truman.edu", "adn6627", "aiquieje");
$db->exec("INSERT INTO adn6627CS315.hw5 (FirstName, LastName, EmailAddress) VALUES ('$fname','$lname','$email')");
$success = "Record Added Successfully!";
echo $success;
}
}
}
?>
</body>
</html>
|
JavaScript | UTF-8 | 4,442 | 2.9375 | 3 | [] | no_license | var mysql = require("mysql");
var inquirer = require("inquirer");
require('console.table');
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "Zubenelakrab",
database: "bamazon"
});
connection.connect(function (err) {
if (err) throw err;
console.log("\n");
menu();
})
function menu() {
inquirer.prompt({
name: "options",
type: "list",
message: "What would you like to do?",
choices: ["View Products for Sale",
"View Low Inventory",
"Add to Inventory",
"Add New Product"]
}).then(function (response) {
switch (response.options) {
case "View Products for Sale": viewInventory("all");
break;
case "View Low Inventory": viewInventory(5);
break;
case "Add to Inventory": updateQuantity();
break;
case "Add New Product": addProduct();
break;
};
});
}
function viewInventory(limit) {
var query = "";
if (limit === "all") {
query = "SELECT * FROM products";
connection.query(query, function (error, response) {
console.table("\n", response);
next();
})
} else {
query = "SELECT * FROM products WHERE stock_quantity <= " + limit;
connection.query(query, function (error, response) {
console.table("\n", response);
next();
})
}
}
function updateQuantity() {
inquirer.prompt([
{
name: "item",
type: "input",
message: "Enter the ID of the product that you would like to update.",
validate: function (value) {
if (isNaN(parseInt(value)) === false) {
return true;
}
return false;
}
},
{
name: "quantity",
type: "input",
message: "Enter the new stock number for this product",
validate: function (value) {
if (isNaN(parseInt(value)) === false) {
return true;
}
return false;
}
}
]).then(function (answer) {
var query = "UPDATE products SET ? WHERE ?";
connection.query(query, [{ stock_quantity: answer.quantity }, { id: answer.item }], function (error) {
if (error) throw error;
console.log("\nUpdate Successful!");
next();
});
});
}
function addProduct() {
inquirer.prompt([
{
name: "newItem",
type: "input",
message: "Please enter the name of the new product.",
},
{
name: "newDept",
type: "input",
message: "Please enter the product's department.",
},
{
name: "newPrice",
type: "input",
message: "Please enter the price of the product.",
validate: function (value) {
if (isNaN(parseFloat(value)) === false) {
return true;
}
return false;
}
},
{
name: "newQuantity",
type: "input",
message: "Please enter how many of the product we have in stock.",
validate: function (value) {
if (isNaN(parseInt(value)) === false) {
return true;
}
return false;
}
}
]).then(function (answer) {
var query = "INSERT INTO products SET ?";
connection.query(query, {
product_name: answer.newItem,
department_name: answer.newDept,
price: answer.newPrice,
stock_quantity: answer.newQuantity
}, function (error) {
if (error) throw error;
console.log("\nUpdate Successful!")
next();
});
});
}
function next() {
inquirer.prompt({
name: "confirm",
type: "confirm",
message: "Would you like to do anything else?",
default: true
}).then(function (answer) {
if (answer.confirm) {
console.log("\n");
menu();
} else {
console.log("Sayonara!");
connection.end();
};
});
} |
Markdown | UTF-8 | 3,563 | 2.984375 | 3 | [] | no_license | import { Meta, Source } from '@storybook/addon-docs/blocks';
import ThemeDisplay from './theme-display';
<Meta title='Standardization|General/Styles' />
# Styles (CSS)
Custom style usage should be kept as minimal as possible for consistency's sake. Generally, components from Material-Ui and the other Highpoint component packages will provide props for different style variants, so custom styles will generally only be needed for fixing spacing and other small modifications. The Highpoint CX apps use several methods for styling elements and components.
## Bootstrap Classes [Docs](https://getbootstrap.com/docs/4.3/layout/utilities-for-layout/)
Bootstrap utility classes can be used for a number of different styles. The most commonly used classes in CX are [padding/margins](https://getbootstrap.com/docs/4.3/utilities/spacing/), [display](https://getbootstrap.com/docs/4.3/utilities/display/), and [flexbox styles](https://getbootstrap.com/docs/4.3/utilities/flex/). See the Bootstrap documentation for details on how these classes can be used.
<Source code={`
<div className="pr-2 pr-lg-3 d-flex" />
// The 'pr-2' class will give the div a style of 'padding-right: 8px'. The 'pr-lg-3' style will override the 'pr-2' style if the screen size is larger than the 'lg' breakpoint, giving the div a style of 'padding-right: 12px'. The 'd-flex' class will apply a 'display: flex' style to the div.
`} />
## Material UI Styles [@material-ui/styles](https://material-ui.com/styles/basics/)
Our main styling method is Material-UI's inbuild styling system which uses the makeStyles hook to generate dynamic class names for use in a component.
The makeStyles hook also allows access to the Material-UI theme which contains colors, breakpoints, and other reusable styles.
<Source code={`
import { makeStyles } from '@material-ui/styles';
const useStyles = makeStyles(theme => {
divStyle: {
width: '100%',
height: '10px',
color: theme.palette.text.primary
},
});
const MyComponent = () => {
const classes = useStyles();
return(<div className={classes.divStyle}>)
};
`} />
### Theme Content
<ThemeDisplay />
## Emotion CSS [react-emotion](https://www.npmjs.com/package/react-emotion/v/9.2.12)
Highpoint apps use the react-emotion library to generate custom css class names from normal css markup. See the emotion documentation for advanced usage.* The most common usage:
<Source code={`
import { css } from 'react-emotion';
const myClass = css\`border-radius: 4px;\`;
<div className={myClass} />
`} />
*Note: The react-emotion library currently use Emotion 9.0, so make sure to reference the [legacy 9.0 version of the documentation](https://5bb1495273f2cf57a2cf39cc--emotion.netlify.com/docs/introduction)
## bs-css [Docs](https://github.com/SentiaAnalytics/bs-css)
In Reason, we use the bs-css library to generate css class names. bs-css is just a statically typed interface to the Emotion library. See the bs-css documentation for details. The most common usage:
<Source code={`
let myClass = Css.style([Css.borderRadius(\`px(4))]);
<div className={myClass} />
`} />
## SASS
Most projects are also equiped with a SASS loader for including some static classes and other custom styles. It is **NOT** recommended to use SASS classes to style components or elements. If a custom style needs to be applied to an element or component, the required CSS should be generated and applied through JS (most likely through Emotion). This way, custom styles will always be located in the same file in which the component/element is used. |
Java | UTF-8 | 6,859 | 1.875 | 2 | [] | no_license | package me.yaran.app;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;
import com.crashlytics.android.Crashlytics;
import atiar.DetectConnection;
import io.fabric.sdk.android.Fabric;
public class Web extends AppCompatActivity{
WebView mWebview;
String linkToOpen = "https://yaran.me/";
String MyUA = "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36";
private ViewTreeObserver.OnScrollChangedListener mOnScrollChangedListener;
LinearLayout linearLayoutForSplash, linearLayoutForVideo;
Context mContext;
ProgressBar mProgressBar;
SwipeRefreshLayout swipeRefreshLayout;
VideoView videoView;
int counter = 0;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
getSupportActionBar().hide();
setContentView(R.layout.activity_web);
mContext = this;
linearLayoutForSplash = findViewById(R.id.splash);
mWebview = findViewById(R.id.webView);
mProgressBar = findViewById(R.id.pb);
swipeRefreshLayout = findViewById(R.id.swipRefreshLayout);
linearLayoutForVideo = findViewById(R.id.videoLinearLayout);
videoView = findViewById(R.id.videoView);
//read the valu of sharedpreferenes for first time run the app
counter = BP.getPreferenceInt(this,BP.Key_Counter);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.GONE);
swipeRefreshLayout.setEnabled(false);
}else {
renderWebPage(linkToOpen);
}
CookieSyncManager.createInstance(mContext);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (!DetectConnection.checkInternetConnection(mContext)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.GONE);
swipeRefreshLayout.setEnabled(false);
}else {
mWebview.reload();
}
}
});
}
// Custom method to render a web page
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
protected void renderWebPage(String urlToRender){
//WEBVIEW
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.getSettings().setUserAgentString(MyUA);
mWebview.getSettings().setDomStorageEnabled(true);
mWebview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
mWebview.getSettings().setLoadsImagesAutomatically(true);
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setAppCachePath(getApplication().getCacheDir().toString());
mWebview.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
playVideo();
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url){
// Do something when page loading finished
swipeRefreshLayout.setRefreshing(false);
linearLayoutForSplash.setVisibility(View.GONE);
mWebview.setVisibility(View.VISIBLE);
}
});
mWebview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebview.loadUrl(urlToRender);
//mWebview.reload();
}
@Override
public void onBackPressed() {
if(mWebview.canGoBack()) {
mWebview.goBack();
} else {
super.onBackPressed();
}
}
@Override
protected void onResume() {
super.onResume();
CookieSyncManager.getInstance().startSync();
}
@Override
protected void onPause() {
super.onPause();
CookieSyncManager.getInstance().stopSync();
}
@Override
public void onStart() {
super.onStart();
swipeRefreshLayout.getViewTreeObserver().addOnScrollChangedListener(mOnScrollChangedListener =
new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (mWebview.getScrollY() == 0)
swipeRefreshLayout.setEnabled(true);
else
swipeRefreshLayout.setEnabled(false);
}
});
}
@Override
public void onStop() {
swipeRefreshLayout.getViewTreeObserver().removeOnScrollChangedListener(mOnScrollChangedListener);
super.onStop();
}
private void playVideo(){
if (counter == 0){
BP.setPreferenceInt(mContext,BP.Key_Counter,1);
linearLayoutForVideo.setVisibility(View.VISIBLE);
videoView.setVisibility(View.VISIBLE);
//String path = "android.resource://" + getPackageName() + "/" + R.raw.intro;
String path = "https://yaran.me/wp-content/uploads/2019/01/video-1548653232.mp4";
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoPath(path);
videoView.requestFocus();
videoView.start();
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
linearLayoutForVideo.setVisibility(View.GONE);
videoView.setVisibility(View.GONE);
}
});
}
}
}
|
JavaScript | UTF-8 | 2,002 | 2.640625 | 3 | [
"MIT"
] | permissive | 'use strict';
(function() {
var profileId = document.querySelector('#profile-id') || null;
var profileUsername = document.querySelector('#profile-username') || null;
var displayName = document.querySelector('#display-name') || null;
var apiUrl = appUrl + '/api/:id';
var userinfo = document.querySelector('.user-info');
var myWall = document.querySelector('.my-wall') || null;
function updateHtmlElement(data, element, userProperty) {
element.innerHTML = data[userProperty];
}
ajaxFunctions.ready(function() {
ajaxFunctions.ajaxRequest('GET', appUrl + '/authenticated', function(isAuthenticated) {
if (JSON.parse(isAuthenticated)) {
if (userinfo)
userinfo.removeAttribute('style');
ajaxFunctions.ajaxRequest('GET', apiUrl, function(data) {
var userObject = JSON.parse(data).twitter;
if (myWall) {
myWall.removeAttribute('style');
myWall.addEventListener('click', function() {
window.location.href = window.location.origin + '/my';
});
}
if (userObject.displayName !== null) {
updateHtmlElement(userObject, displayName, 'displayName');
}
else {
updateHtmlElement(userObject, displayName, 'username');
}
if (profileId !== null) {
updateHtmlElement(userObject, profileId, 'id');
}
if (profileUsername !== null) {
updateHtmlElement(userObject, profileUsername, 'username');
}
});
}
else {
userinfo.innerHTML = '<a href="/auth/twitter"><div class="btn" id="login-btn"><p><i class="fa fa-twitter" aria-hidden="true" style="font-size:25px;"></i>LOGIN WITH TWITTER</p></div></a>';
userinfo.removeAttribute('style');
}
});
});
})();
|
Python | UTF-8 | 571 | 4.03125 | 4 | [] | no_license |
# Description
#
# The method isatty() returns True if the file is connected (is associated with a terminal device) to a tty(-like)
# device, else False. Syntax
#
# Following is the syntax for isatty() method −
#
# fileObject.isatty();
#
# Parameters
#
# NA
#
# Return Value
#
# This method returns true if the file is connected (is associated with a terminal device) to a tty(-like) device,
# else false. Example Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
ret = fo.isatty()
print("Return value : ", ret)
# Close opend file
fo.close() |
Markdown | UTF-8 | 1,812 | 2.84375 | 3 | [] | no_license | # PHP recommended staff
Packages, tools, articles, websites, tutorials, etc.,
recommended to PHP developers by [Saritasa](https://github.com/Saritasa) team.
Includes lots of frontend stuff, especially related with [VueJS](https://vuejs.org/) framework,
as we use it intensively.
## Update knowledge database
### Edit list.yaml file
Just edit **list.yaml** file and commit it to master branch. It will be published on GH Phages site automatically.
1. Edit **list.yaml** with your favorite editor to add/update knowledge base
2. Run application in development mode locally, that you didn't break anything (ex. unexpected changes to application):
```npm install && npm run serve```.
3. Open in browser at http://localhost:8080 and check, if your changes are visible as you expected.
4. Commit and push your changes:
```bash
git add docs/list.yaml
git commit -m "explan, what you added/changed"
git push
```
## Build and run
### Run project for development
1. ```npm install``` - install all required dependencies
2. ```npm run serve``` - build application in development mode and run development HTTP server locally
Before you make pull request, make sure, that linters pass without errors or warnings:
```
npm run lint
```
Also see [other commands](https://cli.vuejs.org/guide/cli-service.html#using-the-binary),
available with [Vue CLI](https://cli.vuejs.org/).
### Build for production
#### (when applications sources were changed)
To update SPA application, hosted on GitHub Pages:
1. ```npm install``` - install all required dependencies
2. ```npm run build``` - update files in 'docs' folder and commit them
3. ```git add docs``` - add changed result files to commit
4. ```git commit -m "explain why you changed app"``` - commit your chages
5. ```git push``` - submit changes to GitHub
|
Java | UTF-8 | 8,451 | 2.171875 | 2 | [
"MIT"
] | permissive | package io.hoplin;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import io.hoplin.executor.WorkerExecutorService;
import io.hoplin.executor.WorkerThreadPool;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of {@link RabbitMQClient}
* <p>
* https://www.rabbitmq.com/consumer-prefetch.html
*/
public class DefaultRabbitMQClient implements RabbitMQClient {
private static final Logger log = LoggerFactory.getLogger(DefaultRabbitMQClient.class);
private final RabbitMQOptions options;
private final Channel channel;
private final ConnectionProvider provider;
private DefaultQueueConsumer consumer;
private final Publisher publisher;
private ExecutorService executor;
public DefaultRabbitMQClient(final RabbitMQOptions options) {
this.options = Objects.requireNonNull(options, "Options are required and can't be null");
this.provider = ConnectionProvider.createAndConnect(options);
this.channel = provider.acquire();
final WorkerThreadPool publisherExecutor = WorkerExecutorService.getInstance()
.getPublisherExecutor();
final WorkerThreadPool subscriberExecutor = WorkerExecutorService.getInstance()
.getSubscriberExecutor();
this.executor = subscriberExecutor.getExecutor();
this.publisher = new Publisher(publisherExecutor.getExecutor());
channel.addReturnListener(new UnroutableMessageReturnListener(options));
}
@Override
public <T> void basicConsume(final String queue, final Class<T> clazz,
final java.util.function.Consumer<T> handler) {
basicConsume(queue, QueueOptions.of(false), clazz, handler);
}
@Override
public <T> void basicConsume(final String queue, final Class<T> clazz,
final BiFunction<T, MessageContext, Reply<?>> handler) {
basicConsume(queue, QueueOptions.of(false), clazz, handler);
}
@Override
public synchronized <T> void basicConsume(final String queue,
final QueueOptions options,
final Class<T> clazz,
final BiFunction<T, MessageContext, Reply<?>> handler) {
Objects.requireNonNull(queue);
Objects.requireNonNull(clazz);
Objects.requireNonNull(handler);
Objects.requireNonNull(options);
try {
if (consumer == null) {
//basic.qos method to allow you to limit the number of unacknowledged messages
final boolean autoAck = options.isAutoAck();
final int prefetchCount = options.getPrefetchCount();
final boolean publisherConfirms = options.isPublisherConfirms();
log.info("basicConsume autoAck : {} ", autoAck);
log.info("basicConsume prefetchCount : {} ", prefetchCount);
log.info("basicConsume publisherConfirms : {} ", publisherConfirms);
// Enables create acknowledgements on this channel
if (publisherConfirms) {
channel.confirmSelect();
channel.addConfirmListener(this::confirmedAck, this::confirmedNack);
}
consumer = new DefaultQueueConsumer(queue, channel, options, executor);
channel.basicQos(prefetchCount);
final String consumerTag = channel.basicConsume(queue, autoAck, consumer);
if (log.isDebugEnabled()) {
log.debug("Assigned consumer tag : {}", consumerTag);
}
}
// add the handler
consumer.addHandler(clazz, handler);
} catch (final IOException e) {
log.error("Unable to subscribe messages", e);
throw new HoplinRuntimeException("Unable to subscribe messages", e);
}
}
@Override
public synchronized <T> void basicConsume(final String queue,
final QueueOptions options,
final Class<T> clazz,
final Consumer<T> handler) {
// wrap handler into our BiFunction
final BiFunction<T, MessageContext, Reply<?>> consumer = (msg, context) -> {
handler.accept(msg);
return Reply.withEmpty();
};
basicConsume(queue, options, clazz, consumer);
}
private void confirmedAck(long deliveryTag, boolean multiple) {
log.info("PublisherConfirmed ACK(deliveryTag, multiple) :: {}, {}", deliveryTag, multiple);
}
private void confirmedNack(long deliveryTag, boolean multiple) {
log.info("PublisherConfirmed NACK(deliveryTag, multiple) :: {}, {}", deliveryTag, multiple);
}
@Override
public void exchangeDeclare(final String exchange,
final String type,
final boolean durable,
final boolean autoDelete) {
exchangeDeclare(exchange, type, durable, autoDelete, Collections.emptyMap());
}
@Override
public void exchangeDeclare(final String exchange,
final String type,
final boolean durable,
final boolean autoDelete,
final Map<String, Object> arguments) {
with((channel) -> {
channel.exchangeDeclare(exchange, type, durable, autoDelete, arguments);
return null;
});
}
@Override
public void queueDeclare(final String queue,
final boolean durable,
final boolean exclusive,
final boolean autoDelete) {
queueDeclare(queue, durable, exclusive, autoDelete, Collections.emptyMap());
}
@Override
public AMQP.Queue.DeclareOk queueDeclare(final String queue,
final boolean durable,
final boolean exclusive,
final boolean autoDelete,
final Map<String, Object> arguments) {
return with(
channel -> channel.queueDeclare(queue, durable, exclusive, autoDelete, arguments));
}
@Override
public void queueBind(final String queue, final String exchange, final String routingKey) {
with(channel -> {
channel.queueBind(queue, exchange, routingKey);
return null;
});
}
@Override
public String queueDeclareTemporary() {
return with(channel -> channel.queueDeclare().getQueue());
}
@Override
public void disconnect() throws IOException {
if (provider != null) {
provider.disconnect();
}
}
private <T> T with(final ThrowableChannel<T> handler) {
try {
return handler.handle(channel);
} catch (final Exception e) {
log.error("Unable to execute operation on channel", e);
}
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isOpenChannel() {
return false;
}
@Override
public QueueStats messageCount(final String queue) {
try {
return messageCountAsync(queue).get();
} catch (final ExecutionException | InterruptedException e) {
log.error("Unable to get message count", e);
}
return new QueueStats(0, 0);
}
@Override
public CompletableFuture<QueueStats> messageCountAsync(final String queue) {
return CompletableFuture.supplyAsync(() -> with(
channel -> new QueueStats(channel.consumerCount(queue), channel.messageCount(queue))),
executor);
}
@Override
public <T> void basicPublish(final String exchange, final String routingKey, final T message) {
basicPublish(exchange, routingKey, message, Collections.emptyMap());
}
@Override
public <T> void basicPublish(final String exchange, final String routingKey, final T message,
final Map<String, Object> headers) {
try {
basicPublishAsync(exchange, routingKey, message, headers).get();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
} catch (final ExecutionException e) {
log.error("Unable to publish message", e);
throw new HoplinRuntimeException("Unable to publish message", e);
}
}
@Override
public <T> CompletableFuture<Void> basicPublishAsync(final String exchange,
final String routingKey, final T message,
final Map<String, Object> headers) {
return publisher.basicPublishAsync(provider, exchange, routingKey, message, headers);
}
@Override
public void basicAck(final long deliveryTag, final boolean multiple) {
throw new RuntimeException("Not yet implemented");
}
@Override
public Channel channel() {
return provider.acquire();
}
private interface ThrowableChannel<T> {
T handle(final Channel channel) throws Exception;
}
}
|
Markdown | UTF-8 | 1,619 | 3.3125 | 3 | [] | no_license | [返回首页](https://EbolaEmperor.github.io)
[返回专题](https://EbolaEmperor.github.io/special/Matrix)
# 【HNOI2002】公交车路线 题解
阅读了一下题面,忽然就笑了出来,这不是就邻接矩阵的幂的模板题吗!
至于邻接矩阵的幂是什么,以后有空再说。过段时间在我们学校的交流活动中我会讲这个玩意儿。
我的代码毫无压力,甚至还想让出题人把n的规模扩大到2^60
嗯,都说了是邻接矩阵的幂了。所以,把题目上那幅图用邻接矩阵建出来,注意点E不要连出边,因为题目上说了主人公没那么蠢,不会到了E还继续走。
然后,计算这个邻接矩阵的n次幂就好了,最终答案在g[A][E]中
时间复杂度:非常非常轻松的O(log n)
```cpp
#include<bits/stdc++.h>
#define Mod 1000
using namespace std;
struct Matrix
{
int m,n;
int a[15][15];
void init(int x,int y){m=x;n=y;memset(a,0,sizeof(a));}
};
Matrix operator * (const Matrix &a,const Matrix &b)
{
Matrix ans;
ans.m=a.m;
ans.n=b.n;
for(int i=0;i<a.m;i++)
for(int j=0;j<b.n;j++)
{
ans.a[i][j]=0;
for(int k=0;k<b.m;k++) ans.a[i][j]=(ans.a[i][j]+a.a[i][k]*b.a[k][j]%Mod)%Mod;
}
return ans;
}
Matrix QuickPow(Matrix &a,int b)
{
Matrix ans;
ans.init(a.m,a.n);
for(int i=0;i<ans.m;i++) ans.a[i][i]=1;
while(b)
{
if(b&1) ans=ans*a;
a=a*a;
b>>=1;
}
return ans;
}
int main()
{
Matrix G;
G.init(8,8);
for(int i=0;i<7;i++)
G.a[i][i+1]=G.a[i+1][i]=1;
G.a[0][7]=G.a[7][0]=1;
G.a[4][3]=G.a[4][5]=0;
int n;
cin>>n;
G=QuickPow(G,n);
cout<<G.a[0][4]<<endl;
return 0;
}
```
|
Java | UTF-8 | 8,134 | 1.96875 | 2 | [] | no_license | package app.roundtable.nepal.activity.managers;
import android.content.Context;
import com.squareup.picasso.Picasso;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import app.roundtable.nepal.R;
import app.roundtable.nepal.activity.database.Manager;
import app.roundtable.nepal.activity.network.ApiClient;
import app.roundtable.nepal.activity.network.ApiUrls;
import app.roundtable.nepal.activity.network.MultipartUtility;
import app.roundtable.nepal.activity.util.ApplicationPreferences;
/**
* Created by afif on 20/6/15.
*/
public class LoginManager extends Manager {
private Context mContext;
private ApiClient mApiClient;
private ApplicationPreferences mSharedPreferences;
public LoginManager(Context context) {
this.mContext = context;
mApiClient = new ApiClient();
mSharedPreferences= new ApplicationPreferences(mContext);
}
public String doEmailLogin(String email, String password) throws IOException {
ApplicationPreferences mPreferences = new ApplicationPreferences(mContext);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("otp", password));
pairs.add(new BasicNameValuePair("os","gcm"));
pairs.add(new BasicNameValuePair("token", mPreferences.getGcmRegistrationId()));
String response = mApiClient.executePostRequestWithHeader(pairs, ApiUrls.LOGIN_API_PATH);
return response;
}
public String getOTPRequest(String email) throws IOException {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email",email));
String response = mApiClient.executePostRequestWithHeader(pairs,ApiUrls.REQUEST_API_PATH);
return response;
}
public String requestNewAccess(String userName, String email, String table_name) throws IOException {
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("email",email));
pairs.add(new BasicNameValuePair("name",userName));
pairs.add(new BasicNameValuePair("table_name",table_name));
String response = mApiClient.executePostRequestWithHeader(pairs, ApiUrls.REQUEST_ACCESS_API_PATH);
return response;
}
public void saveUserInfo(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONObject memberInfo = dataObject.getJSONObject("member_info");
JSONObject details = memberInfo.getJSONObject("details");
mSharedPreferences.setIsLoggedIn(true);
mSharedPreferences.setUserId(details.getString("member_id"));
mSharedPreferences.setUserName(details.getString("fname"));
mSharedPreferences.setUserLastName(details.getString("lname"));
mSharedPreferences.setUserGender(details.getString("gender"));
mSharedPreferences.setUserMobile(details.getString("mobile"));
mSharedPreferences.setUserEmail(details.getString("email"));
mSharedPreferences.setUserBloodGroup(details.getString("blood_group"));
mSharedPreferences.setSpouseName(details.getString("spouse_name"));
mSharedPreferences.setUserDOB(details.getString("dob"));
mSharedPreferences.setSpouseDOB(details.getString("spouse_dob"));
mSharedPreferences.setUserProfileImage(details.getString("image_big_url"));
mSharedPreferences.setUserResidencePhone(details.getString("res_phone"));
mSharedPreferences.setOfficePhone(details.getString("office_phone"));
mSharedPreferences.setUserDesignation(details.getString("designation"));
mSharedPreferences.setResidenceCity(details.getString("res_city"));
mSharedPreferences.setOfficeCity(details.getString("office_city"));
mSharedPreferences.setUserState(details.getString("state"));
mSharedPreferences.setAnniversaryDate(details.getString("anniversary_date"));
mSharedPreferences.setTableId(details.getString("table_id"));
mSharedPreferences.setTableCode(details.getString("table_code"));
mSharedPreferences.setTableName(details.getString("table_name"));
mSharedPreferences.setAddress(details.getString("address"));
mSharedPreferences.setCompany(details.getString("company"));
}
public String updateProfile(String[] params) throws IOException {
String response = null;
MultipartUtility builder = new MultipartUtility(ApiUrls.EDIT_PROFILE_API_PATH,"UTF-8");
String imagePath = params[0];
if(imagePath != null && !imagePath.equals("")){
File file = new File(imagePath);
builder.addFilePart("profile_image", file);
}
builder.addFormField("fname", params[1]);
builder.addFormField("lname", params[2]);
builder.addFormField("email", params[3]);
builder.addFormField("blood_group", params[4]);
builder.addFormField("mobile", params[5]);
builder.addFormField("spouse_name", params[6]);
builder.addFormField("dob", params[7]);
builder.addFormField("spouse_dob", params[8]);
builder.addFormField("anniversary_date", params[9]);
//builder.addFormField("res_phone", params[11]);
builder.addFormField("office_phone", params[10]);
//builder.addFormField("designation", params[13]);
builder.addFormField("res_city", params[11]);
//builder.addFormField("office_city", params[15]);
//builder.addFormField("state", params[16]);
builder.addFormField("company", params[12]);
builder.addFormField("address", params[13]);
builder.addFormField("gender", params[14]);
builder.addFormField("member_id", mSharedPreferences.getUserId());
builder.addFormField("table_id", mSharedPreferences.getTableId());
response = builder.finish();
return response;
}
public void saveupdatedData(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONObject details = dataObject.getJSONObject("updated_info");
mSharedPreferences.setUserId(details.getString("member_id"));
mSharedPreferences.setUserName(details.getString("fname"));
mSharedPreferences.setUserLastName(details.getString("lname"));
mSharedPreferences.setUserGender(details.getString("gender"));
mSharedPreferences.setUserMobile(details.getString("mobile"));
mSharedPreferences.setUserEmail(details.getString("email"));
mSharedPreferences.setUserBloodGroup(details.getString("blood_group"));
mSharedPreferences.setSpouseName(details.getString("spouse_name"));
mSharedPreferences.setUserDOB(details.getString("dob"));
mSharedPreferences.setSpouseDOB(details.getString("spouse_dob"));
mSharedPreferences.setUserProfileImage(details.getString("image_big_url"));
mSharedPreferences.setUserResidencePhone(details.getString("res_phone"));
mSharedPreferences.setOfficePhone(details.getString("office_phone"));
mSharedPreferences.setUserDesignation(details.getString("designation"));
mSharedPreferences.setResidenceCity(details.getString("res_city"));
mSharedPreferences.setOfficeCity(details.getString("office_city"));
mSharedPreferences.setUserState(details.getString("state"));
mSharedPreferences.setAnniversaryDate(details.getString("anniversary_date"));
mSharedPreferences.setTableId(details.getString("table_id"));
mSharedPreferences.setCompany(details.getString("company"));
mSharedPreferences.setAddress(details.getString("address"));
mSharedPreferences.setProfileUpdated(true);
}
}
|
Shell | UTF-8 | 1,104 | 3.21875 | 3 | [] | no_license | # #!/bin/bash
# #vpncmd /client localhost /cmd accountlist >> awk -F "|" '/Status/ print{$
# # choice=""
# # read choice
# # # fchoice=$(cat logs/account.txt | awk NR==$choice)
# # ./test2.sh "$fchoice"
# # dhclient vpn_ss -v | grep '10.20.*' &> /dev/null
# # if [ $? == 0 ]; then
# # echo "matched"
# # fi
# # if dhclient vpn_ss -v | grep -q '10.20.30'; then
# # echo "matched"
# # fi
# dhclient vpn_ss -v > logs/gateway.txt 2>&1
# # if [[ grep logs/gateway.txt -e '10.20.*' = true ]]
# # then
# # echo 'Found it'
# # fi
# # And here we have Bash Patterns:
# # if [[ "$VARIABLE" == ! ]]
# # then
# # echo "matched"
# # else
# # echo "nope"
# # fi
# chown jrm logs/gateway.txt
# if grep -q '192.168.*' logs/gateway.txt; then
# echo found
# echo "" > logs/gateway.txt
# else
# echo not found
# echo "" > logs/gateway.txt
# fi
server=$(awk -F '|' '/^Server Name/{print $2}' logs/status.txt | xargs)
echo $server
route add -host $server gw 192.168.1.1
# route del -host $server gw 192.168.1.1
# ip route del $server via 192.168.1.1 dev wlp2s0 proto static |
Java | UTF-8 | 1,572 | 3.5625 | 4 | [] | no_license | package com.example.Animal_Farm;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
public class Farm {
ArrayList<com.example.Animal_Farm.Animal> animals;
public Farm() {
animals = new ArrayList<com.example.Animal_Farm.Animal>();
}
public void addAnimal(com.example.Animal_Farm.Animal a) {
animals.add(a);
}
public com.example.Animal_Farm.Animal getAnimal(int index) {
return animals.get(index);
}
public ArrayList<com.example.Animal_Farm.Animal> getHeaviestAnimals() {
ArrayList<com.example.Animal_Farm.Animal> sortedAnimals = new ArrayList<com.example.Animal_Farm.Animal>();
for (com.example.Animal_Farm.Animal a: this.animals) {
sortedAnimals.add(a);
}
Collections.sort(sortedAnimals, new Comparator<com.example.Animal_Farm.Animal>() {
@Override public int compare(com.example.Animal_Farm.Animal a1, com.example.Animal_Farm.Animal a2) {
return (int)(a2.getWeight() - a1.getWeight());
}
});
return sortedAnimals;
}
public void printCatNames() {
for (com.example.Animal_Farm.Animal a: this.animals) {
if (a instanceof Cat) {
System.out.println(a.getName());
}
}
}
public int averageLegs() {
int totalLegs = 0;
for (com.example.Animal_Farm.Animal a: this.animals) {
totalLegs = totalLegs + a.getLegs();
}
return (int)(totalLegs/animals.size());
}
}
|
C# | UTF-8 | 1,584 | 2.9375 | 3 | [] | no_license | using projektlabor.covid19login.adminpanel.datahandling;
using projektlabor.covid19login.adminpanel.datahandling.entities;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace projektlabor.covid19login.adminpanel.datahandling.entities
{
public class SimpleUserEntity : Entity
{
public const string
ID = "id",
FIRSTNAME = "firstname",
LASTNAME = "lastname";
// Copy-Paste generated. Just change the class name
// Automatically grabs and stores all attributes from the class to easily serialize and deserialize those
private static readonly Dictionary<string, FieldInfo> ATTRIBUTES = GetAttributes(typeof(SimpleUserEntity));
public static readonly string[] ATTRIBUTE_LIST = GetAttributeNames(typeof(SimpleUserEntity));
/// The users unique id
[EntityInfo(ID)]
public int? Id;
/// The users firstname
[EntityInfo(FIRSTNAME)]
public string Firstname;
/// The users lastname
[EntityInfo(LASTNAME)]
public string Lastname;
/// <summary>
/// Checks if the user matches the search
/// </summary>
/// <param name="search"></param>
/// <returns>True if the user matches; else false</returns>
public bool IsMatching(string search) => this.ToString().ToLower().Contains(search.ToLower());
public override string ToString() => $"{this.Firstname} {this.Lastname}";
protected override Dictionary<string, FieldInfo> Attributes() => ATTRIBUTES;
}
}
|
Markdown | UTF-8 | 375 | 2.859375 | 3 | [] | no_license | To use, simply run ./reconcile.py in a directory containing listings.txt and products.txt,
or direct it to the files:
./reconcile.py --listings path/to/listings.txt --products path/to/products.txt
By default, output is sent to stdout. To redirect output, use the --output argument.
For additional arguments and help on using the program, run
./reconcile.py --help |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.