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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 6,965 | 3.171875 | 3 |
[] |
no_license
|
<h1 align="center">JavaScript Games</h1>
<h2 align="center">
<img src="assets/gamepad.png" height="300px" width="310;ppx">
</h2>
- ### 🚥 Connect [](https://github.com/amirtha4501/JavaScriptGames/tree/master/Connect)
- ### 🧠 Memory Game [](https://github.com/amirtha4501/JavaScriptGames/tree/master/MemoryGame)
- ### 🐍 Snake Game [](https://github.com/amirtha4501/JavaScriptGames/tree/master/SnakeGame)
- ### ✈️ Space Invaders [](https://github.com/amirtha4501/JavaScriptGames/tree/master/SpaceInvaders)
- ### 📦 Tetris [](https://github.com/amirtha4501/JavaScriptGames/tree/master/Tetris)
- ### 🐭 Whac A Mole [](https://github.com/amirtha4501/JavaScriptGames/tree/master/WhacAMole)
## 🧾 Description
- ### Connect
It's a two-player connection board game, in which the players take turns dropping colored discs into a seven-column, six-row vertically suspended grid.
The objective of the game is to be the first to form a horizontal, vertical, or diagonal line of four of one's own discs.
- ### Memory Game
A game that improve the memory and brain power. The thing is to match between each couple of images.
- ### Snake Game
A game in which a snake needs to explore an environment and catch the fruit without hitting any obstacle or itself.
Every time the snake catches a fruit, its size increases.
- ### Space Invaders
It is a fixed shooter in which the player controls a laser cannon by moving it horizontally across the bottom of the screen and firing at descending aliens.
- ### Tetris
It is a tile-matching game where we've to arrange the falling blocks of different shapes to fill the line.
- ### Whac A Mole
A game which involves quickly and repeatedly hitting the heads of moles with a pointer as they pop up from the holes.
## 🧱 Tech
- HTML
- CSS
- JavaScript
## 💻 Setup
- Clone the repository
` git clone https://github.com/amirtha4501/JavaScriptGames.git `
- Boot up a terminal on the directory.
- Run the website on localhost
`http-server -1`
## 🤔 How to play
### - Connect
- The board is empty🗌 at the start of the game.
- The aim for both players is to make a straight line⬇️ of four own pieces.
- The line can be vertical⬆️, horizontal➡️ or diagonal↘️.
- Before starting, players decide randomly which of them will be the beginner🎲.
- Moves are made alternatively, one by turn.
- The game is over if four of the same colour is connected and the player who owns that colour is the winner🏆.
### - Memory Game
- Initially, there will be 12 cards.
- Turn over🔄 any of the cards.
- Remember💡 what was on each card and where it was.
- If you couple the card's image with it's pair, the score will be incremented⏫.
- The game is over when all the cards have been matched💯.
### - Snake Game
- Press the arrow key↘️.
- Control the 🐍snake using the arrow keys.
- Use the up arrow⬆️ to move up, down arrow⬇️ to move down, left arrow⬅️ to turn left and the right arrow➡️ to turn right.
- Chase down the apples🍎.
- Play until your snake hits ⚕️itself.
### - Space Invaders
- Initially, the aliens👽 will be at the top of the game space.
- The shooter✈️ is fixed at the base and it is horizontally movable.
- Move🕹️ the shooter to shoot the descending aliens with the laser.
- Press spacebar to shoot🔥.
- Press left⬅️ and right➡️ arrows to move the shooter accordingly.
- The game is over🥴 if the aliens reached the land.
### - Tetris
- Use up arrow⬆️ to rotate the block📦.
- Use left⬅️ and right➡️ arrow to move the block to sidewards.
- Use down arrow⬇️ to move downwards fastly.
- We can maintain the score💯 by filling all the blank space in a line of the screen.
- The game is over🤐 if the blocks reach the top of the screen.
### - Whac A Mole
- A mole🐭 will pop up from the boxes.
- You've 60 seconds of time⏰ to show your nimbleness.
- You have to quickly and repeatedly click the heads of moles.
- The game is over, after a minute⏳.
## 🧐 What's the outcome
- ### Connect
- querySelector()
- addEventListener()
- onclick
- classList.contains()
- classList.add()
- For loops
- Arrow functions
- ### Frogger
- querySelector()
- addEventListener()
- setInterval()
- clearInterval()
- forEach()
- classList.contains()
- classList.add()
- classList.remove()
- ### Memory Game
- push()
- querySelector()
- setAttribute()
- getAttribute()
- createElement()
- appendChild()
- Math.random()
- sort()
- For loops
- ### Snake Game
- querySelector()
- addEventListener()
- setInterval()
- keyCodes()
- pop()
- unshift()
- push()
- classList.contains()
- classList.add()
- classList.remove()
- ### Space Invaders
- querySelector()
- addEventListener()
- Switch cases
- keyCodes
- indexOf()
- includes()
- classList
- setInterval()
- clearInterval()
- push()
- ### Tetris Game
- querySelector()
- addEventListener()
- Array.from()
- Math.floor()
- forEach()
- classList()
- setInterval()
- clearInterval() <!-- - style.backgroundImage -->
- getElementsByClassName()
- splice()
- some()
- concat()
- appendChild()
- Arrow functions
- ### Whac A Mole
- querySelector()
- addEventListener()
- setInterval()
- classList()
- forEach()
- Arrow functions
## 📁 Project Structure
├───assets
└───Connect
└───images
└───connect.css
└───connect.html
└───connect.js
└───Frogger
└───frogger.css
└───frogger.html
└───frogger.js
└───MemoryGame
└───images
└───memory-game.css
└───memory-game.html
└───memory-game.js
└───SnakeGame
└───snake.css
└───snake.html
└───snake.js
└───SpaceInvaders
└───space-invaders.css
└───space-invaders.html
└───space-invaders.js
└───Tetris
└───tetris.css
└───tetris.html
└───tetris.js
└───WhacAMole
└───images
└───whac.css
└───whac.html
└───whac.js
|
Java
|
ISO-8859-1
| 2,027 | 2.75 | 3 |
[] |
no_license
|
package carvajal.autenticador.android.util;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import android.os.AsyncTask;
/**
* Implementacin de lo Mtodos utilitarios para la verificacin de
* conectividad.
*
* @author grasotos
*/
public class AsyncTaskUtilities {
/**
* Log de la aplicacin Android Log4j
*/
private final static Logger log4jDroid = Logger.getLogger(AsyncTaskUtilities.class);
/**
* Implementacin del Mtodo que verifica la conexin a una IP local
* haciendo ping.
*
* @author grasotos
*/
public class VerificarConexionIpLocal extends AsyncTask<String, Void, Boolean> {
/**
* Verifica la conexin a una IP local haciendo ping. String[] datos = {
* ip, timeOut };
*
* @param direccionIP
* Direccin IP .
* @param timeOut
* Tiempo de espera de respuesta.
* @return Estado de la conexin a Internet.
* @author grasotos
*/
@Override
protected Boolean doInBackground(final String... params) {
boolean conexion = Boolean.FALSE;
try {
final InetAddress inetAddress = InetAddress.getByName(params[0]);
if (inetAddress != null && inetAddress.isReachable(Integer.parseInt(params[1]))) {
conexion = Boolean.TRUE;
}
} catch (UnknownHostException e) {
log4jDroid.error("AutenticadorAndroidProject:AsyncTaskUtilities:VerificarConexionUrlLocal:doInBackground", e);
} catch (NumberFormatException e) {
log4jDroid.error("AutenticadorAndroidProject:AsyncTaskUtilities:VerificarConexionUrlLocal:doInBackground", e);
} catch (IOException e) {
log4jDroid.error("AutenticadorAndroidProject:AsyncTaskUtilities:VerificarConexionUrlLocal:doInBackground", e);
} catch (Exception e) {
log4jDroid.error("AutenticadorAndroidProject:AsyncTaskUtilities:VerificarConexionUrlLocal:doInBackground", e);
}
return conexion;
}
}
}
|
Markdown
|
UTF-8
| 2,226 | 2.703125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<img align="left" height="96" width="229" src="https://github.com/kumina/k8s-redirectory/blob/master/documentation/_static/redirectory_logo.png">
Redirectory is a tool that manages redirects on a kubernetes cluster.
Requests that would usually end in a **404 PAGE NOT FOUND** can now be
redirected to new pages specified with custom rules. It binds itself as
the default backend (essential a wild card) of your ingress controller
and catches all the request that the cluster can't find an ingress rule
for. After that with the help of the
[Hyperscan](https://www.hyperscan.io) regex engine the request is
permanently redirected to the new destination based on the rules. If there is
no rule that matches the request you can specify a default redirecting
destination.
# Installation
The best installation experience is with [Helm](https://github.com/helm/helm).
Just run:
```shell
$ helm install --name=redirectory redirectory/conf/helm
```
More information about this can be found
[here](https://redirectory.readthedocs.io/en/latest/misc/install.html).
# Docker images
First we have to build the Hyperscan image because it is a base of the
other two images.
## Hyperscan image
Before we can use Redirectory you must have the Hyperscan library
installed. Here is a link to the
[getting started](https://github.com/intel/hyperscan/blob/master/doc/dev-reference/getting_started.rst)
documentation. But we also have prepaired a Docker image. You can find
the `Dockerfile` in: `redirectory/conf/hyperscan-docker` and run the
`./build.sh` file. The interaction between Python and Hyperscan is made
with this awesome library
[python-hyperscan](https://github.com/darvid/python-hyperscan).
## Redirectory images
There are two images. One for the management pod and one for the worker
pods. The two files are correspondingly `Dockerfile_Management` and
`Dockerfile_Worker`. You can run the `./build_redirectory_images.sh`
file to build them both.
# Documentation
The documentation is hosted on Read the Docs and can be found at
[redirectory.readthedocs.io](https://redirectory.readthedocs.io).
# License
Redirectory is licensed under the BSD 3-Clause License License. See the
[LICENSE](LICENSE) file in the project repository.
|
JavaScript
|
UTF-8
| 1,022 | 2.53125 | 3 |
[] |
no_license
|
var Discord = require("discord.js");
var exports = module.exports = {};
var request = require('request');
exports.test = function(msg) {
var data = {};
data.title = "hello";
data.color = [0,0,256];
var a = new Discord.RichEmbed();
msg.channel.sendEmbed({
color: 3447003,
title: 'This is an embed',
url: 'http://google.com',
description: 'This is a test embed to showcase what they look like and what they can do.',
fields: [{
name: 'Fields',
value: 'They can have different fields with small headlines.'
},
{
name: 'Masked links',
value: 'You can put [masked links](http://google.com) inside of rich embeds.'
},
{
name: 'Markdown',
value: 'You can put all the *usual* **__Markdown__** inside of them.'
}
],
timestamp: new Date(),
footer: {
text: '© Example'
}});
msg.channel.sendEmbed(a);
}
|
PHP
|
UTF-8
| 3,166 | 2.53125 | 3 |
[] |
no_license
|
<?php
use Phinx\Migration\AbstractMigration;
class N4903 extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('cta_budget', ['id' => false,
'primary_key' => 'cta_budget_id']);
$table->addColumn('cta_budget_id', 'integer',
['signed' => false, 'limit' => 10, 'identity' => true]);
$table->addColumn('agreement_id', 'integer', ['signed' => false, 'limit' => 10, 'null' => false]);
$table->addForeignKey('agreement_id', 'agreement', 'agreement_id', [
'constraint' => 'FK_cta_budget_agreement',
'update' => 'CASCADE',
'delete' => 'RESTRICT'
]);
$table->addColumn('is_closed', 'boolean', ['default' => false, 'signed' => false, 'null' => false]);
$table->addColumn('is_active', 'boolean', ['default' => true, 'signed' => false, 'null' => false]);
$table->create();
// =================
$table = $this->table('cta_budget_row', ['id' => false,
'primary_key' => 'cta_budget_row_id']);
$table->addColumn('cta_budget_row_id', 'integer',
['signed' => false, 'limit' => 10, 'identity' => true]);
$table->addColumn('cta_budget_id', 'integer', ['signed' => false, 'limit' => 10, 'null' => false]);
$table->addForeignKey('cta_budget_id', 'cta_budget', 'cta_budget_id', [
'constraint' => 'FK_cta_budget_row_cta_budget',
'update' => 'CASCADE',
'delete' => 'CASCADE'
]);
$table->addColumn('agreement_product_id', 'integer', ['signed' => false, 'limit' => 10, 'null' => false]);
$table->addForeignKey('agreement_product_id', 'agreement_product', 'agreement_product_id', [
'constraint' => 'FK_cta_budget_row_agreement_product',
'update' => 'CASCADE',
'delete' => 'RESTRICT'
]);
$table->addColumn('price', 'integer', ['signed' => false, 'limit' => 10, 'null' => false]);
$table->addColumn('quantity', 'integer', ['signed' => true, 'limit' => 10, 'null' => false]);
$table->addColumn('date_start', 'date', ['null' => false]);
$table->addColumn('date_end', 'date', ['null' => false]);
$table->addColumn('is_active', 'boolean', ['default' => true, 'signed' => false, 'null' => false]);
$table->create();
$table = $this->table('agreement_product');
$table->addColumn('account_number', 'string', ['default' => 0, 'null' => false, 'limit' => 50]);
$table->update();
}
}
|
C++
|
UTF-8
| 2,141 | 2.8125 | 3 |
[] |
no_license
|
#include "PWM.h"
PWM_PCA985::PWM_PCA985()
{
std::cout << "[Actuator|PWM] Initializing" << std::endl;
pwmDriver = new I2CDevice(PCA985_DEVICE_ID);
if(!pwmDriver->isValid()) {
std::cout << "[Actuator|PWM] Failed to create i2c device!" << std::endl;
}
init();
}
PWM_PCA985::~PWM_PCA985()
{
delete pwmDriver;
}
void PWM_PCA985::init()
{
// Wir setzen die maximale PWM Frequenz, die ist für uns geeignet
pwmDriver->write8(PRE_SCALE, 0x03); // 0x03 ist minimaler Faktor
pwmDriver->write8(MODE1, 0x01); // Exit sleep mode
}
void PWM_PCA985::enableLEDs(bool debug) {
// LEDS on
std::cout << "[Actuator|PWM] Enabling LEDs" << std::endl;
pwmDriver->write8(0x2B, 0x10);
pwmDriver->write8(0x2D, 0x00);
}
void PWM_PCA985::disableLEDs(bool debug) {
// LEDS off
std::cout << "[Actuator|PWM] Disabling LEDs" << std::endl;
pwmDriver->write8(0x2B, 0x00);
pwmDriver->write8(0x2D, 0x10);
}
void PWM_PCA985::drive(bool debug)
{
if(!isDebugMode || debug) {
std::cout << "[Actuator|PWM] Enabling motor" << std::endl;
//pwmDriver->write8(0x07, 0x10);
//pwmDriver->write8(0x09, 0x00);
int onSteps = (unsigned int)((1.0f - pwmMotorOnPercentage) * (float)0xFFF); // Maximalwert 4095;
pwmDriver->write8(MOTOR_ON_L, onSteps & 0xFF);
pwmDriver->write8(MOTOR_ON_H, (onSteps & 0xF00) >> 8);
pwmDriver->write8(MOTOR_OFF_L, 0x00);
pwmDriver->write8(MOTOR_OFF_H, 0x00);
}
}
void PWM_PCA985::stop(bool debug)
{
// Always allow disable
std::cout << "[Actuator|PWM] Disabling motor" << std::endl;
pwmDriver->write8(0x07, 0x00);
pwmDriver->write8(0x09, 0x10);
/*write8(MOT1_ON_H, 0b00000000); //Bitte checken
write8(MOT2_ON_H, 0b00000000);
write8(MOT1_OFF_H, 0b00010000);
write8(MOT2_OFF_H, 0b00010000); //bitte checken
std::cout << "Setting PWM0 and PWM1 to: STOP!";
*/
}
void PWM_PCA985::resetlaser()
{
/*HIER K�NNTE IHRE WERBUNG STEHEN*/
}
void PWM_PCA985::enable(bool debug)
{
drive(debug);
}
void PWM_PCA985::disable(bool debug)
{
stop(debug);
}
int PWM_PCA985::getActuatorType()
{
return ACTUATOR_LIST::ENGINE_PWM;
}
|
Python
|
UTF-8
| 2,822 | 2.953125 | 3 |
[] |
no_license
|
import turtle
import numpy as np
import pygame
from config import *
from game_object import GameObject, DynamicObject
class Rocket(DynamicObject):
def __init__(self, position=(SCREEN_WIDTH / 2, 0), rotation=np.pi / 2, scale=10):
super().__init__(position, rotation, scale)
self.time_since_thrust = 0
self.corner = [(0, 0), (0, 0)]
# Engine
self.orange_shape = np.array(((-1, 0), (-0.75, -1), (-0.5, 0), (-0.25, -1), (0, 0),
(0.25, -1), (0.5, 0), (0.75, -1), (1, 0)))
self.yellow_shape = np.array(((-1, 0), (-0.75, -0.75), (-0.5, 0), (-0.25, -0.75), (0, 0),
(0.25, -0.75), (0.5, 0), (0.75, -0.75), (1, 0)))
# Rocket
self.left_wing_shape = np.array(((-1, 0.25), (-2, 0), (-1.75, 1), (-1, 2)))
self.right_wing_shape = np.array(((1, 0.25), (2, 0), (1.75, 1), (1, 2)))
self.main_shape = np.array(((-1, 0.25), (-1, 6), (0, 7.5), (1, 6), (1, 0.25), (0, 0.25)))
def draw(self, screen):
if self.time_since_thrust > 0:
pygame.draw.polygon(screen, (255, 69, 0), self.get_world_position(self.orange_shape), 0)
pygame.draw.polygon(screen, (255, 215, 0), self.get_world_position(self.yellow_shape), 0)
pygame.draw.polygon(screen, (0, 0, 0), self.get_world_position(self.left_wing_shape), 0)
pygame.draw.polygon(screen, (0, 0, 0), self.get_world_position(self.right_wing_shape), 0)
pygame.draw.polygon(screen, (255, 0, 0), self.get_world_position(self.main_shape), 0)
pygame.draw.circle(screen, (0, 255, 0), self.corner[0], 5)
pygame.draw.circle(screen, (0, 255, 0), self.corner[1], 5)
def update(self, deltatime, events, keys):
if self.time_since_thrust > 0:
self.time_since_thrust -= deltatime
if keys[pygame.K_SPACE]:
self.acceleration[0] += np.sin(self.rotation) * ROCKET_ACCELERATION_SPEED
self.acceleration[1] += np.cos(self.rotation) * ROCKET_ACCELERATION_SPEED
self.time_since_thrust = ROCKET_ENGINE_ANIM_DURATION
if keys[pygame.K_LEFT]:
self.angular_acceleration += ROCKET_ANGULAR_ACCELERATION
if keys[pygame.K_RIGHT]:
self.angular_acceleration -= ROCKET_ANGULAR_ACCELERATION
self.acceleration[1] += 100
super().update(deltatime, events, keys)
def get_bounding_box_corners(self):
x1, y1 = self.get_world_position(self.main_shape)[:, 0].min(), self.get_world_position(self.main_shape)[:, 1].min()
x2, y2 = self.get_world_position(self.main_shape)[:, 0].max(), self.get_world_position(self.main_shape)[:, 1].max()
self.corner = (int(x1), int(y1)), (int(x2), int(y2))
return (x1, y1), (x2, y1), (x2, y2), (x1, y2)
|
Java
|
UTF-8
| 1,051 | 3.265625 | 3 |
[] |
no_license
|
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BallTest {
/**
* Test that updatePosition changes the x and y position of the ball instance when called
*/
@Test
void updatePosition() {
Ball ball = new Ball();
assertEquals(ball.getPosition().x, 250);
assertEquals(ball.getPosition().y, 250);
ball.updatePosition(0.167);
assertNotEquals(ball.getPosition().x, 250);
assertNotEquals(ball.getPosition().y, 250);
}
/**
* Test that ball returns to initial position after reset is called
*/
@Test
void reset() {
Ball ball = new Ball();
assertEquals(ball.getPosition().x, 250);
assertEquals(ball.getPosition().y, 250);
ball.updatePosition(0.167);
assertNotEquals(ball.getPosition().x, 250);
assertNotEquals(ball.getPosition().y, 250);
ball.reset();
assertEquals(ball.getPosition().x, 250);
assertEquals(ball.getPosition().y, 250);
}
}
|
C#
|
UTF-8
| 1,460 | 2.515625 | 3 |
[] |
no_license
|
using CIV.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CIV.Controllers
{
[Route("api/[controller]")]
public class GameController: Controller
{
private readonly IHubContext<GameHub> _gameHubContext;
private readonly IGameService _gameService;
public GameController(
IHubContext<GameHub> gameHubContext,
IGameService gameService)
{
_gameHubContext = gameHubContext;
_gameService = gameService;
}
public async Task Post([FromBody] CreateGameModel model)
{
await _gameService.AddGame(model.Name, model.Creator);
}
[HttpGet("{name}/creator")]
public async Task<object> GetCreator(string name)
{
return new { username = await _gameService.GetGameCreator(name) };
}
[HttpGet("{name}/state")]
public object GetState(string name)
{
return new
{
turn = 1,
phase = "Phase 1",
currentPlayer = User.Identity.Name,
timeElapsedInMilliseconds = 12
};
}
[HttpGet("{name}/players")]
public async Task<IEnumerable<string>> GetPlayers(string name)
{
return await _gameService.GetPlayerNames(name);
}
}
}
|
PHP
|
UTF-8
| 3,112 | 2.6875 | 3 |
[] |
no_license
|
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/classes/photoCollection.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/classes/photo.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/classes/photo_comment.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/classes/photo_annotation.php';
include_once 'verifySession.php';
include_once 'verifyCollectionPermission.php';
function displayPhotoCollections($pdo, $id){
echo '<div class="photo_collection_wrapper">';
if(isset($_GET['userid'])){
#If user ID is set, we will display other peoples photocollections
try{
$stmt = $pdo->prepare("SELECT first_name
FROM user
WHERE id = :id");
$stmt->execute(['id'=>$_GET['userid']]);
$name = $stmt->fetch();
$stmt = $pdo->prepare("SELECT id, name, description, (SELECT count(*) FROM photo WHERE album_id = p.id) AS noOfPhotos
FROM photo_album AS p
WHERE user_owner = :id
ORDER BY id DESC");
$stmt->execute(['id'=>$_GET['userid']]);
if($stmt->rowCount() == 0){
echo "No photo collections found.";
return;
}
}
catch(PDOException $e){
echo $e->getCode();
}
echo '<h1>'.$name['first_name'].'\'s Photo Collections</h1>';
foreach($stmt as $row){
if(verifyCollectionPermission($pdo, $_GET['userid'], $row['id'])){
echo '<a href="displayPhotos.php?collectionid='.$row['id'].'">';
echo '<div class="photo_collection">';
echo $row['name'];
echo '<br>';
echo 'Contains '.$row['noOfPhotos'].' photos.';
echo '</div>';
echo '</a>';
}
}
}
else{
#Display our photocollections
echo '<form action="photo_functions/addPhotoCollection.php" method="POST">';
echo '<label>Name: </label><input type="text" name="name"></input>';
echo '<label>Description: </label><input type="text" name="desc"></input>';
echo '<label>Privacy: </label><select name="privacy">';
echo '<option value="0">Public</option>';
echo '<option value="1">Friends of Friends</option>';
echo '<option value="2">Friends</option>';
echo '</select>';
echo '<input type="submit" value="Add Collection">';
echo '</form>';
try{
$stmt = $pdo->prepare("SELECT id, name, description, (SELECT count(*) FROM photo WHERE album_id = p.id) AS noOfPhotos
FROM photo_album AS p
WHERE user_owner = :id");
$stmt->execute(['id'=>$id]);
if($stmt->rowCount() == 0){
echo "No photo collections found.";
return;
}
}
catch(PDOException $e){
echo $e->getCode();
}
foreach($stmt as $row){
echo '<a href="displayPhotos.php?collectionid='.$row['id'].'">';
echo '<div class="photo_collection">';
echo $row['name'];
echo '<br>';
echo 'Contains '.$row['noOfPhotos'].' photos.';
echo '</div>';
echo '</a>';
echo '<form action="photo_functions/deletePhotoCollection.php" method="POST">';
echo '<input type="hidden" name="collectionid" value="'.$row['id'].'"></input>';
echo '<input type="submit" value="Delete">';
echo '</form>';
}
}
echo '</div>';
}
?>
|
C++
|
UTF-8
| 3,268 | 2.703125 | 3 |
[] |
no_license
|
#pragma once
#include <vector>
#include <Eigen/Core>
struct Coordinate {
public:
int idx_[ 8 ];
float val_[ 8 ];
float nval_[ 8 ];
};
class ControlGrid
{
public:
ControlGrid(void);
~ControlGrid(void);
public:
std::vector< Eigen::Vector3f > ctr_;
int resolution_;
float length_;
float unit_length_;
int min_bound_[ 3 ];
int max_bound_[ 3 ];
public:
void Load( FILE * f, int res, float len );
public:
void ResetBBox() { min_bound_[ 0 ] = min_bound_[ 1 ] = min_bound_[ 2 ] = 100000000; max_bound_[ 0 ] = max_bound_[ 1 ] = max_bound_[ 2 ] = -100000000; }
void RegulateBBox( float vi, int i ) {
int v0 = ( int )floor( vi / unit_length_ ) - 1;
int v1 = ( int )ceil( vi / unit_length_ ) + 1;
if ( v0 < min_bound_[ i ] ) {
min_bound_[ i ] = v0;
}
if ( v1 > max_bound_[ i ] ) {
max_bound_[ i ] = v1;
}
}
inline int GetIndex( int i, int j, int k ) {
return i + j * ( resolution_ + 1 ) + k * ( resolution_ + 1 ) * ( resolution_ + 1 );
}
inline bool GetCoordinate( const Eigen::Vector3f & pt, Coordinate & coo ) {
int corner[ 3 ] = {
( int )floor( pt( 0 ) / unit_length_ ),
( int )floor( pt( 1 ) / unit_length_ ),
( int )floor( pt( 2 ) / unit_length_ )
};
if ( corner[ 0 ] < 0 || corner[ 0 ] >= resolution_
|| corner[ 1 ] < 0 || corner[ 1 ] >= resolution_
|| corner[ 2 ] < 0 || corner[ 2 ] >= resolution_ )
return false;
float residual[ 3 ] = {
pt( 0 ) / unit_length_ - corner[ 0 ],
pt( 1 ) / unit_length_ - corner[ 1 ],
pt( 2 ) / unit_length_ - corner[ 2 ]
};
// for speed, skip sanity check
coo.idx_[ 0 ] = GetIndex( corner[ 0 ], corner[ 1 ], corner[ 2 ] );
coo.idx_[ 1 ] = GetIndex( corner[ 0 ], corner[ 1 ], corner[ 2 ] + 1 );
coo.idx_[ 2 ] = GetIndex( corner[ 0 ], corner[ 1 ] + 1, corner[ 2 ] );
coo.idx_[ 3 ] = GetIndex( corner[ 0 ], corner[ 1 ] + 1, corner[ 2 ] + 1 );
coo.idx_[ 4 ] = GetIndex( corner[ 0 ] + 1, corner[ 1 ], corner[ 2 ] );
coo.idx_[ 5 ] = GetIndex( corner[ 0 ] + 1, corner[ 1 ], corner[ 2 ] + 1 );
coo.idx_[ 6 ] = GetIndex( corner[ 0 ] + 1, corner[ 1 ] + 1, corner[ 2 ] );
coo.idx_[ 7 ] = GetIndex( corner[ 0 ] + 1, corner[ 1 ] + 1, corner[ 2 ] + 1 );
coo.val_[ 0 ] = ( 1 - residual[ 0 ] ) * ( 1 - residual[ 1 ] ) * ( 1 - residual[ 2 ] );
coo.val_[ 1 ] = ( 1 - residual[ 0 ] ) * ( 1 - residual[ 1 ] ) * ( residual[ 2 ] );
coo.val_[ 2 ] = ( 1 - residual[ 0 ] ) * ( residual[ 1 ] ) * ( 1 - residual[ 2 ] );
coo.val_[ 3 ] = ( 1 - residual[ 0 ] ) * ( residual[ 1 ] ) * ( residual[ 2 ] );
coo.val_[ 4 ] = ( residual[ 0 ] ) * ( 1 - residual[ 1 ] ) * ( 1 - residual[ 2 ] );
coo.val_[ 5 ] = ( residual[ 0 ] ) * ( 1 - residual[ 1 ] ) * ( residual[ 2 ] );
coo.val_[ 6 ] = ( residual[ 0 ] ) * ( residual[ 1 ] ) * ( 1 - residual[ 2 ] );
coo.val_[ 7 ] = ( residual[ 0 ] ) * ( residual[ 1 ] ) * ( residual[ 2 ] );
return true;
}
inline void GetPosition( const Coordinate & coo, Eigen::Vector3f & pos ) {
pos = coo.val_[ 0 ] * ctr_[ coo.idx_[ 0 ] ] + coo.val_[ 1 ] * ctr_[ coo.idx_[ 1 ] ]
+ coo.val_[ 2 ] * ctr_[ coo.idx_[ 2 ] ] + coo.val_[ 3 ] * ctr_[ coo.idx_[ 3 ] ]
+ coo.val_[ 4 ] * ctr_[ coo.idx_[ 4 ] ] + coo.val_[ 5 ] * ctr_[ coo.idx_[ 5 ] ]
+ coo.val_[ 6 ] * ctr_[ coo.idx_[ 6 ] ] + coo.val_[ 7 ] * ctr_[ coo.idx_[ 7 ] ];
}
};
|
Markdown
|
UTF-8
| 833 | 2.984375 | 3 |
[] |
no_license
|
# node-errno
[](https://travis-ci.org/evanlucas/node-errno)
An easier way to track errno's
This is mainly for use with [node-launchctl](http://github.com/evanlucas/node-launchctl)
## Install
```bash
$ npm install syserrno
```
## API
### #strerror(errno)
Params:
- {Number} errno The error number
Example:
```js
var errno = require('errno')
console.log(errno.strerror(148))
// outputs "Invalid domain"
```
### #errorForCode(code)
Params:
- {String} code The error code
Example:
```js
var errno = require('errno')
var err = errno.errorForCode('EIVALDO')
console.log(err)
```
Returns: An Error object containing
```js
{
code: 'EIVALDO',
msg: 'Invalid domain',
errno: 148
}
```
### #errorForErrno(errno)
Params:
- {Number} errno The error number
|
C++
|
UTF-8
| 4,629 | 3.28125 | 3 |
[] |
no_license
|
/*
Li Chen Koh's solution to Google Code Jam Round 2 2017 Problem B
This is adapted from my original submission during the live contest.
Full Problem Statement:
https://code.google.com/codejam/contest/5314486/dashboard#s=p1&a=0
Problem Summary:
You have a roller coaster that has N seats numbered 1 through N from front to
back.
There are C customers and M tickets in total.
Each ticket is assigned to a customer and seat.
A customer may buy any number of tickets.
For each ticket, you may choose to replace its assigned seat number with a
smaller seat number. This is called a promotion.
To honor all the tickets, you may need to have multiple roller coaster rides.
You want to minimize the number of roller coaster rides required to honor all
tickets.
As a secondary objective, you want to minimize the number of promotions.
Constraints: 2 <= N, C <= 1000, 1 <= M <= 1000
Solution:
We have 2 lower bounds on the number of rides R:
(1) The number of tickets bought by a single customer must not exceed R
(2) The number of tickets with seat number less than or equal to k must not
exceed R * k
The number of promotions P has a simple lower bound too:
(3) The number of tickets assigned to a single seat must not exceed R by more
than P.
It turns out both of these lower bounds are tight, but the proof is relatively
complicated.
Runtime: O(N + C + M)
Memory usage: O(N + C)
*/
#include <bits/stdc++.h>
#include <assert.h>
using namespace std;
// We are given the following parameters:
// The first parameter is vector<int> seatIdToNumberOfTickets:
// seatIdToNumberOfTickets[seatId] is the number of tickets assigned to the
// seat with seatId as its ID.
// The second paramter is vector<int> customerIdToNumberOfTickets:
// seatIdToNumberOfTickets[customerId] is the number of tickets assigned to
// customer with customerId as their ID.
//
// This function computes the minimum number of rides needed to honor all
// seats as a primary objective, and minimizes the number of promotions as
// a secondary objective.
// The return value is a pair of integers: The first integer is the number
// of rides, and the second integer is the number of promotions.
pair<int,int> getMinimumRidesAndPromotions(
const vector<int> &seatIdToNumberOfTickets,
const vector<int> &customerIdToNumberOfTickets
) {
int numberOfSeats = (int)seatIdToNumberOfTickets.size() - 1;
int numberOfCustomers = (int)customerIdToNumberOfTickets.size() - 1;
int ridesNeeded=0;
for (int customerId = 1; customerId <= numberOfCustomers; customerId++) {
ridesNeeded = max(ridesNeeded, customerIdToNumberOfTickets[customerId]);
}
int sumOfTicketsUpToSeatId = 0;
for (int seatId = 1; seatId <= numberOfSeats; seatId++) {
sumOfTicketsUpToSeatId += seatIdToNumberOfTickets[seatId];
ridesNeeded = max(
ridesNeeded,
(sumOfTicketsUpToSeatId + seatId - 1) / seatId
);
}
int promotionsNeeded=0;
for (int seatId = 1; seatId <= numberOfSeats; seatId++) {
promotionsNeeded += max(0, seatIdToNumberOfTickets[seatId] - ridesNeeded);
}
return make_pair(ridesNeeded, promotionsNeeded);
}
// We read the test case from standard input, and return a pair of vector<int>
// The first vector<int> is seatIdToNumberOfTickets:
// seatIdToNumberOfTickets[seatId] is the number of tickets assigned to the
// seat with seatId as its ID.
// The second vector<int> is customerIdToNumberOfTickets
// seatIdToNumberOfTickets[customerId] is the number of tickets assigned to
// customer with customerId as their ID.
pair<vector<int>, vector<int> > readInput() {
int numberOfSeats, numberOfCustomers, numberOfTickets;
scanf("%d%d%d", &numberOfSeats, &numberOfCustomers, &numberOfTickets);
vector<int> seatIdToNumberOfTickets(numberOfSeats + 1, 0);
vector<int> customerIdToNumberOfTickets(numberOfCustomers + 1, 0);
for (int ticketId = 0; ticketId < numberOfTickets; ticketId++) {
int seatId, customerId;
scanf("%d%d", &seatId, &customerId);
seatIdToNumberOfTickets[seatId]++;
customerIdToNumberOfTickets[customerId]++;
}
return make_pair(seatIdToNumberOfTickets, customerIdToNumberOfTickets);
}
int main()
{
int numberOfTests; scanf("%d",&numberOfTests);
for (int testNumber=1;testNumber<=numberOfTests;testNumber++) {
const pair<vector<int>, vector<int> > &input = readInput();
pair<int,int> minimumRidesAndPromotions = getMinimumRidesAndPromotions(
input.first, input.second);
int ridesNeeded = minimumRidesAndPromotions.first;
int promotionsNeeded = minimumRidesAndPromotions.second;
printf("Case #%d: %d %d\n", testNumber, ridesNeeded, promotionsNeeded);
}
}
|
Python
|
UTF-8
| 791 | 3.640625 | 4 |
[] |
no_license
|
import unittest
"""
Chocolate covered candy
Phil the confectioner is making a new batch of chocolate covered candy. Each candy centre is shaped like an ellipsoid of revolution defined by the equation:
$b^2 x^2 + b^2 y^2 + a^2 z^2 = a^2 b^2$.
Phil wants to know how much chocolate is needed to cover one candy centre with a uniform coat of chocolate one millimeter thick.
If $a = 1$ mm and $b = 1$ mm, the amount of chocolate required is $\dfrac{28}{3} \pi$ mm3
If $a = 2$ mm and $b = 1$ mm, the amount of chocolate required is approximately 60.35475635 mm3.
Find the amount of chocolate in mm3 required if $a = 3$ mm and $b =1$ mm. Give your answer as the number rounded to 8 decimal places behind the decimal point.
"""
class Test(unittest.TestCase):
def test(self):
pass
|
Java
|
UTF-8
| 1,835 | 2.234375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright [2016] [Muhammad Afzal]
*
* 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 org.uclab.scl.datamodel;
/**
* @version MM v2.5
* @author Afzal
*
*/
public class UserSchedule {
private String startTime;
private long userID;
private String scheduledTask;
private String endTime;
private long userScheduleID;
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getScheduledTask() {
return scheduledTask;
}
public void setScheduledTask(String scheduledTask) {
this.scheduledTask = scheduledTask;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public long getUserScheduleID() {
return userScheduleID;
}
public void setUserScheduleID(long userScheduleID) {
this.userScheduleID = userScheduleID;
}
@Override
public String toString() {
return "ClassPojo [startTime = " + startTime + ", userID = " + userID
+ ", scheduledTask = " + scheduledTask + ", endTime = " + endTime
+ ", userScheduleID = " + userScheduleID + "]";
}
}
|
Python
|
UTF-8
| 4,572 | 3.234375 | 3 |
[] |
no_license
|
import datetime
import time
from random import randint
class PeriodRandomizer:
def __init__(self):
# 0 - 23 format
self.from_hour = 7
self.to_hour = 23
self.from_time = None
self.to_time = None
self.work_for = 6 * 60 # means bot will be working for a total of # minutes
# periods
self.min_periods = 2
self.max_periods = 4
# in minutes
self.min_period_length = 30
self.max_period_length = 0
self.actual_length = 0
self.periods = []
# timing
self.next_info_print = 0
def randomize(self):
self.periods = []
now = datetime.datetime.now()
self.from_time = datetime.datetime(now.year, now.month, now.day, self.from_hour)
self.to_time = datetime.datetime(now.year, now.month, now.day, self.to_hour)
minute_len = (self.to_time - self.from_time).seconds / 60
if (self.work_for > minute_len):
self.periods.append(Period(self.from_time, self.to_time)) # work whole time
return
no_of_periods = randint(self.min_periods, self.max_periods)
while(len(self.periods) < no_of_periods):
start_minute = randint(0, minute_len)
period_len = randint(self.min_period_length, self.work_for / (no_of_periods - 1))
if (len(self.periods) == no_of_periods - 1):
period_len = self.work_for - self.actual_length
if (period_len < self.min_period_length):
period_len = self.min_period_length
start_here = self.from_time + datetime.timedelta(minutes = start_minute)
stop_here = self.from_time + datetime.timedelta(minutes = start_minute + period_len)
# if (((self.to_time - stop_here).seconds / 60) < self.min_period_length):
# continue
# if (((start_here - self.from_time).seconds / 60) < self.min_period_length):
# continue
period_proposition = Period(start_here, stop_here)
if (len(self.periods) == 0):
self.periods.append(period_proposition)
self.actual_length += period_proposition.get_length()
continue
valid = True
for period in self.periods:
if (period_proposition.during(period)):
valid = False
break
if (valid):
self.periods.append(period_proposition)
self.actual_length += period_proposition.get_length()
self.remove_late_periods()
def remove_late_periods(self):
valid_periods = []
for period in self.periods:
if (period.restarts_in() >= 0 or period.is_active()):
valid_periods.append(period)
self.periods = valid_periods
def is_active(self):
if (len(self.periods) == 0):
if(self.from_time.day != datetime.datetime.now().day):
self.randomize()
else:
if (self.next_info_print < time.time()):
print('work for day done, wait till midnight for next periods.')
self.next_info_print = time.time() + 60
return
# print info about bot restart
for period in self.periods:
if (period.is_active()):
return True
if (self.next_info_print < time.time()):
print('bot restarts in {0:.0f} minutes'.format(self.restarts_in_s() / 60))
self.next_info_print = time.time() + 60
return False
def restarts_in_s(self):
now = datetime.datetime.now()
time_diff = (self.to_time - now).seconds
for period in self.periods:
start_t = period.get_start_time()
period_diff = (start_t - now).seconds
if (time_diff > period_diff):
time_diff = period_diff
return time_diff
def info(self):
print('time periods, total: {0:.0f} minutes'.format(self.actual_length))
for period in self.periods:
period.get_times()
class Period:
def __init__(self, from_time, to_time):
self.start_time = from_time
self.end_time = to_time
def is_active(self):
now = datetime.datetime.now()
if (now > self.start_time and now < self.end_time):
return True
return False
def during(self, period):
if (self.start_time >= period.start_time and self.start_time <= period.end_time):
return True
if (self.end_time >= period.start_time and self.end_time <= period.end_time):
return True
if (self.start_time <= period.start_time and self.end_time >= period.end_time):
return True
return False
def get_length(self):
return (self.end_time - self.start_time).seconds / 60
def get_start_time(self):
return self.start_time
def restarts_in(self):
return self.start_time.hour - datetime.datetime.now().hour
def get_times(self):
print('from {0} to {1}, minutes: {2}, active: {3}, wait for {4} hours'.format(self.start_time, self.end_time, self.get_length(), self.is_active(), self.restarts_in()))
|
Java
|
UTF-8
| 1,011 | 1.890625 | 2 |
[] |
no_license
|
package com.neorays.cnfgs;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan("com.neorays.controller")
@EnableWebMvc
public class WebAppConfiguration {
// for creating InternalResourceViewResolver class obj
@Bean
public InternalResourceViewResolver createInternalResourceViewresolver() {
InternalResourceViewResolver irvr = null;
// create object
irvr = new InternalResourceViewResolver();
//set suffix and prefix
irvr.setSuffix(".jsp");
irvr.setPrefix("/WEB-INF/pages/");
return irvr;
}// method
}// class
|
Swift
|
UTF-8
| 709 | 3.03125 | 3 |
[] |
no_license
|
//
// CircularViewing.swift
// TMS
//
// Created by Suke Hozumi on 8/7/16.
// Copyright © 2016 yhozumi. All rights reserved.
//
import UIKit
//CircularViewing protocol helps with reusability and abstraction of configuring a view to a circular view
protocol CircularViewing {
func configureCircular(view: [UIView])
}
//Protocol Extension allows a default implementation of the method.
extension CircularViewing {
///Arrays of views that will be evaluated and will be made a circlar view
func configureCircular(view: [UIView]) {
let _ = view.map {
if $0.frame.width == $0.frame.height {
$0.layer.cornerRadius = $0.frame.width / 2
$0.clipsToBounds = true
}
}
}
}
|
C#
|
UTF-8
| 749 | 3 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode
{
class _328//奇偶链表
{
public ListNode OddEvenList(ListNode head)
{
if (head==null||head.next==null)
return head;
ListNode odd = head;//奇数
ListNode evenHead = head.next;//偶数链头
ListNode even = evenHead;
while (even!=null&&even.next!=null)
{
odd.next = even.next;
even.next = even.next.next;
even = even.next;
odd = odd.next;
}
odd.next = evenHead;
return head;
}
}
}
|
Java
|
UTF-8
| 2,208 | 3.59375 | 4 |
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
/***
* Klasa opisująca użytkownika systemu typu trener
* @author Maria
*
*/
public class Trener extends Osoba {
private ArrayList<Uzytkownik> podopieczni = new ArrayList<Uzytkownik>();
/***
* Konstruktot
* @param nick Nazwa konta
* @param zdjecieProfilowe Zdjęcie profilowe
*/
public Trener(String nick, byte[] zdjecieProfilowe) {
super(nick, zdjecieProfilowe);
}
/***
* Metoda, która sprawdza czy można założyć konto trenera o podanym nick-u
* @param nick Nazwa trenera
* @return True - jeśli konto zostało założone, false - jeśli nie da się założyć konta
*/
public static boolean zalozKonto(String nick) {
try {
List<Trener> l = (List<Trener>) getEkstensje(Trener.class);
for (Trener o : l) {
if (o.getNick().equals(nick)) {
System.out.println("Jest juz trener z nickiem: " + nick);
return false;
}
}
} catch (Exception e) { // jeśli brak ekstensji to nie ma jeszcze takiego trenera
// e.printStackTrace();
System.out.println("Nie ma trenera z nickiem: " + nick);
return true;
}
return true;
}
/***
* Metoda, która loguje trenera do systemu
* @param nick Nazwa trenera
* @return True - jeśli trener został pomyślnie zalogowany, false - jeśli trenera nie da się zalogować do systemu
*/
public static Trener zalogujSie(String nick) {
try {
List<Trener> l = (List<Trener>) getEkstensje(Trener.class);
for (Trener t : l) {
if (t.getNick().equals(nick))
return t;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
/***
* Metoda ustawiającego podopiecznego
* @param u Podopieczny
*/
public void dodajPodopiecznego(Uzytkownik u) {
if (!podopieczni.contains(u)) {
this.podopieczni.add(u);
}
}
/**
* Metoda usuwająca podopiecznego
* @param u Podopieczny
*/
public void usunPodopiecznego(Uzytkownik u) {
if (podopieczni.contains(u)) {
this.podopieczni.remove(u);
}
}
/***
* Metoda wyświetlająca listę podopiecznych
*/
public void wyswietlListePodopiecznych() {
for (Uzytkownik uzytkownik : podopieczni) {
uzytkownik.toString();
}
}
}
|
Java
|
UTF-8
| 1,653 | 2.78125 | 3 |
[] |
no_license
|
package com.simplilearn.training.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String description;
private String brand;
private String category;
private String price;
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(Integer id, String name, String description, String brand, String category, String price) {
super();
this.id = id;
this.name = name;
this.description = description;
this.brand = brand;
this.category = category;
this.price = price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return String.format("Product [id=%s, name=%s, description=%s, brand=%s, category=%s]", id, name, description,
brand, category);
}
}
|
C#
|
UTF-8
| 1,909 | 2.875 | 3 |
[] |
no_license
|
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
public struct Int32Fog
{
//something like union
[FieldOffset(0)] public Int32 Value;
[FieldOffset(0)] public byte Byte1;
[FieldOffset(1)] public byte Byte2;
[FieldOffset(2)] public byte Byte3;
[FieldOffset(3)] public byte Byte4;
[FieldOffset(4)] public byte Byte5;
[FieldOffset(5)] public byte Byte6;
public Int32Fog(Int32 value)
{
Byte1 = Byte2 = 0;
Byte3 = Byte4 = 0;
Byte5 = Byte6 = 0;
Value = value;
//move Byte1 to Byte5 & move Byte2 to Byte6
Byte5 = Byte1;
Byte6 = Byte2;
//clear the memeory
Byte1 = 0;
Byte2 = 0;
}
public Int32 toInt32 () {
Int32 result = 0;
//restore value
Byte1 = Byte5;
Byte2 = Byte6;
result = Value;
//clear the memeory
Byte1 = 0;
Byte2 = 0;
return result;
}
public override string ToString() {
return toInt32().ToString();
}
public static implicit operator Int32(Int32Fog value)
{
return value.toInt32();
}
public static implicit operator Int32Fog(Int32 value)
{
return new Int32Fog(value);
}
}
[StructLayout(LayoutKind.Explicit)]
public struct Int16Fog {
//something like union
[FieldOffset(0)] public Int16 Value;
[FieldOffset(0)] public byte Byte1;
[FieldOffset(1)] public byte Byte2;
[FieldOffset(2)] public byte Byte3;
public Int16Fog(Int16 value)
{
Byte1 = Byte2 = Byte3 = 0;
Value = value;
//move Byte1 to Byte3
Byte3 = Byte1;
//clear the memeory
Byte1 = 0;
}
public Int16 toInt16 () {
Int16 result = 0;
//restore value
Byte1 = Byte3;
result = Value;
//clear the memeory
Byte1 = 0;
return result;
}
public override string ToString() {
return toInt16().ToString();
}
public static implicit operator Int16(Int16Fog value)
{
return value.toInt16();
}
public static implicit operator Int16Fog(Int16 value)
{
return new Int16Fog(value);
}
}
|
Python
|
UTF-8
| 2,505 | 3.625 | 4 |
[] |
no_license
|
#!/usr/bin/env python3
"""
Mailroom 1
"""
import sys
donors = [("Robyn Rihanna", [100, 200, 300]),
("Ariana Grande", [2250, 4000, 1000]),
("Beyonce Carter-Knowles", [150000, 3500, 25000]),
("Aubrey Drake Graham", [15000, 5500.25, 1200]),
("Justin Bieber", [2500, 250, 750.50])
]
def print_donors():
for donor in donors:
print(donor[0])
def find_donor(name_entered):
for donor in donors:
if name_entered.strip().lower() == donor[0].lower():
return donor
return None
def send_email(name_entered, donation):
print(
"""Dear {},
Your generous ${:,.2f} donation just made our day!
Thank you!
-The Charity""".format(name_entered.title(), donation)
)
def thank_you():
while True:
name_entered = input("Enter the name of a donor or 'list' to view "
"donors >>> ").lower().strip()
if name_entered == "list":
print_donors()
else:
break
donation = float(input("Enter donation amount >>> "))
donor = find_donor(name_entered)
if donor is None:
donor = (name_entered.title(), [])
donor[1].append(donation)
donors.append(donor)
print("Successfully added new donor to database")
else:
donor[1].append(donation)
print("Successfully updated existing donor.")
send_email(name_entered, donation)
def sort_key(donors):
return donors[1]
def create_report():
print("{:30s} | {:11s} | {:9s} | {:12s}".format(
"Donor Name", "Total Given", "Num Gifts", "Average Gift"))
print("-" * 72)
donors.sort(key=sort_key, reverse=True)
for donor in donors:
print("{:30s} $ {:11,.2f} {:9d} $ {:12,.2f}".format(
donor[0], sum(donor[1]), len(donor[1]),
sum(donor[1]) / len(donor[1])))
def exit_program():
print("Exiting Program. Goodbye!")
sys.exit()
def main():
print("Welcome to Mailroom!")
while True:
print("Select an option:")
print("'r' - Create Report \n"
"'t' - Send Thank You \n"
"'q' - Quit")
action = input(" >>> ")
action = action.strip()
action = action[0].lower()
if action == 'r':
create_report()
elif action == 't':
thank_you()
elif action == 'q':
exit_program()
else:
print("Not a valid option. Please select 't', 'q', or 'r'")
if __name__ == "__main__":
main()
|
C++
|
UTF-8
| 3,257 | 2.625 | 3 |
[] |
no_license
|
// -*- Mode: c++; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil -*-
// NOTE: the first line of this file sets up source code indentation rules
// for Emacs; it is also a hint to anyone modifying this file.
// File : the_document.hxx
// Author : Pavel Aleksandrovich Koshevoy
// Created : Tue Apr 04 15:38:30 MDT 2004
// Copyright : (C) 2004
// License : MIT
// Description : Document framework class.
#ifndef THE_DOCUMENT_HXX_
#define THE_DOCUMENT_HXX_
// local includes:
#include "doc/the_registry.hxx"
#include "doc/the_procedure.hxx"
#include "utils/the_text.hxx"
// forward declarations:
class the_view_t;
class the_bbox_t;
//----------------------------------------------------------------
// the_document_t
//
class the_document_t
{
public:
the_document_t(const the_text_t & name);
virtual ~the_document_t() {}
virtual the_document_t * clone() const
{ return new the_document_t(*this); }
// regenerate the unrolled procedures geometry:
virtual bool regenerate();
// draw the unrolled procedures geometry:
virtual void draw(const the_view_t & view) const;
// calculate the bounding box of unrolled procedures geometry:
virtual void calc_bbox(const the_view_t & view, the_bbox_t & bbox) const;
// this function splits procedures into active and rolled back:
void unroll(the_procedure_t * proc);
// append a new procedure to the unrolled procedure list:
inline void add_proc(the_procedure_t * proc)
{
registry().add(proc);
procs_.push_back(proc->id());
}
// remove a procedure from the unrolled procedure list:
inline void del_proc(the_procedure_t * proc)
{
procs_.remove(proc->id());
registry().del(proc);
}
// accessor to the currently active procedure:
inline the_procedure_t * active_procedure() const
{
if (procs_.empty()) return NULL;
return registry().elem<the_procedure_t>(procs_.back());
}
// check whether a procedure of a given type is currently active:
template <typename proc_t>
inline proc_t * active_procedure() const
{
if (procs_.empty()) return NULL;
return dynamic_cast<proc_t *>(registry().elem(procs_.back()));
}
// accessors:
inline const the_text_t & name() const { return name_; }
inline the_text_t & name() { return name_; }
inline const the_registry_t & registry() const { return registry_; }
inline the_registry_t & registry() { return registry_; }
// accessor to the currently unrolled procedures:
inline const std::list<unsigned int> & procs() const
{ return procs_; }
inline const std::list<unsigned int> & rolled_back_procs() const
{ return rolled_back_procs_; }
// file io:
bool save(std::ostream & stream) const;
bool load(std::istream & stream);
private:
// the name of this document:
the_text_t name_;
// the document registry:
the_registry_t registry_;
// unrolled and rolled-back procedures of the document:
std::list<unsigned int> procs_;
std::list<unsigned int> rolled_back_procs_;
};
extern bool save(const the_text_t & magic,
const the_text_t & filename,
const the_document_t * doc);
extern bool load(const the_text_t & magic,
const the_text_t & filename,
the_document_t *& doc);
#endif // THE_DOCUMENT_HXX_
|
Java
|
UTF-8
| 7,824 | 1.914063 | 2 |
[] |
no_license
|
package entidades;
import java.io.Serializable;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import enumerados.Raza;
import enumerados.TipoParto;
import enumerados.convert.RazaConvert;
import enumerados.convert.TipoPartoConvert;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/*
consultaTerneraIdTernera = DatabaseManager.getConnection().prepareStatement("SELECT * FROM TERNERAS WHERE ID_TERNERA=?");
consultaTerneraNroCaravana = DatabaseManager.getConnection().prepareStatement("SELECT * FROM TERNERAS WHERE NRO_CARAVANA=?");
*/
/**
* The persistent class for the TERNERAS database table.
*
*/
@Entity
@Table(name="TERNERAS")
@NamedQueries({
@NamedQuery(name="Ternera.obtenerTodasTerneras", query="SELECT t FROM Ternera t"),
@NamedQuery(name="Ternera.obtenerTerneraNroCaravana", query="SELECT t FROM Ternera t WHERE t.nroCaravana = :nroCaravana"),
@NamedQuery(name="Ternera.obtenerTerneraId", query="SELECT t FROM Ternera t WHERE t.idTernera LIKE :idTernera")
})
public class Ternera implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="TERNERAS_IDTERNERA_GENERATOR", sequenceName="SEQ_TERNERA")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TERNERAS_IDTERNERA_GENERATOR")
@Column(name="ID_TERNERA")
private long idTernera;
@Column(name="CAUSA_BAJA")
private String causaBaja;
@Column(name="CAUSA_MUERTE")
private String causaMuerte;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="America/Montevideo")
@Temporal(TemporalType.DATE)
@Column(name="FECHA_BAJA")
private Date fechaBaja;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="America/Montevideo")
@Temporal(TemporalType.DATE)
@Column(name="FECHA_MUERTE")
private Date fechaMuerte;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="America/Montevideo")
@Temporal(TemporalType.DATE)
@Column(name="FECHA_NACIMIENTO")
private Date fechaNacimiento;
@Column(name="NRO_CARAVANA")
private long nroCaravana;
@Convert(converter = TipoPartoConvert.class)
private TipoParto parto;
@Column(name="PESO_NACIMIENTO")
private BigDecimal pesoNacimiento;
@Convert(converter = RazaConvert.class)
private Raza raza;
//bi-directional many-to-one association to ConsumoAlimentoTernera
@JsonIgnore
@OneToMany(mappedBy="ternera")
private List<ConsumoAlimentoTernera> consumoAlimentoTerneras;
//bi-directional many-to-one association to ConsumoMedicamentoTernera
@JsonIgnore
@OneToMany(mappedBy="ternera")
private List<ConsumoMedicamentoTernera> consumoMedicamentoTerneras;
//bi-directional many-to-one association to EnfermedadTernera
@JsonIgnore
@OneToMany(mappedBy="ternera")
private List<EnfermedadTernera> enfermedadTerneras;
//bi-directional many-to-one association to Peso
@JsonIgnore
@OneToMany(mappedBy="ternera")
private List<Peso> pesos;
//bi-directional many-to-one association to Guachera
@ManyToOne
@JoinColumn(name="ID_GUACHERA")
private Guachera guachera;
//bi-directional many-to-one association to Madre
@ManyToOne
@JoinColumn(name="ID_MADRE")
private Madre madre;
//bi-directional many-to-one association to Padre
@ManyToOne
@JoinColumn(name="ID_PADRE")
private Padre padre;
public Ternera() {
}
public long getIdTernera() {
return this.idTernera;
}
public void setIdTernera(long idTernera) {
this.idTernera = idTernera;
}
public String getCausaBaja() {
return this.causaBaja;
}
public void setCausaBaja(String causaBaja) {
this.causaBaja = causaBaja;
}
public String getCausaMuerte() {
return this.causaMuerte;
}
public void setCausaMuerte(String causaMuerte) {
this.causaMuerte = causaMuerte;
}
public Date getFechaBaja() {
return this.fechaBaja;
}
public void setFechaBaja(Date fechaBaja) {
this.fechaBaja = fechaBaja;
}
public Date getFechaMuerte() {
return this.fechaMuerte;
}
public void setFechaMuerte(Date fechaMuerte) {
this.fechaMuerte = fechaMuerte;
}
public Date getFechaNacimiento() {
return this.fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public long getNroCaravana() {
return this.nroCaravana;
}
public void setNroCaravana(long nroCaravana) {
this.nroCaravana = nroCaravana;
}
public TipoParto getParto() {
return this.parto;
}
public void setParto(TipoParto parto) {
this.parto = parto;
}
public BigDecimal getPesoNacimiento() {
return this.pesoNacimiento;
}
public void setPesoNacimiento(BigDecimal pesoNacimiento) {
this.pesoNacimiento = pesoNacimiento;
}
public Raza getRaza() {
return this.raza;
}
public void setRaza(Raza raza) {
this.raza = raza;
}
public List<ConsumoAlimentoTernera> getConsumoAlimentoTerneras() {
return this.consumoAlimentoTerneras;
}
public void setConsumoAlimentoTerneras(List<ConsumoAlimentoTernera> consumoAlimentoTerneras) {
this.consumoAlimentoTerneras = consumoAlimentoTerneras;
}
public ConsumoAlimentoTernera addConsumoAlimentoTernera(ConsumoAlimentoTernera consumoAlimentoTernera) {
getConsumoAlimentoTerneras().add(consumoAlimentoTernera);
consumoAlimentoTernera.setTernera(this);
return consumoAlimentoTernera;
}
public ConsumoAlimentoTernera removeConsumoAlimentoTernera(ConsumoAlimentoTernera consumoAlimentoTernera) {
getConsumoAlimentoTerneras().remove(consumoAlimentoTernera);
consumoAlimentoTernera.setTernera(null);
return consumoAlimentoTernera;
}
public List<ConsumoMedicamentoTernera> getConsumoMedicamentoTerneras() {
return this.consumoMedicamentoTerneras;
}
public void setConsumoMedicamentoTerneras(List<ConsumoMedicamentoTernera> consumoMedicamentoTerneras) {
this.consumoMedicamentoTerneras = consumoMedicamentoTerneras;
}
public ConsumoMedicamentoTernera addConsumoMedicamentoTernera(ConsumoMedicamentoTernera consumoMedicamentoTernera) {
getConsumoMedicamentoTerneras().add(consumoMedicamentoTernera);
consumoMedicamentoTernera.setTernera(this);
return consumoMedicamentoTernera;
}
public ConsumoMedicamentoTernera removeConsumoMedicamentoTernera(ConsumoMedicamentoTernera consumoMedicamentoTernera) {
getConsumoMedicamentoTerneras().remove(consumoMedicamentoTernera);
consumoMedicamentoTernera.setTernera(null);
return consumoMedicamentoTernera;
}
public List<EnfermedadTernera> getEnfermedadTerneras() {
return this.enfermedadTerneras;
}
public void setEnfermedadTerneras(List<EnfermedadTernera> enfermedadTerneras) {
this.enfermedadTerneras = enfermedadTerneras;
}
public EnfermedadTernera addEnfermedadTernera(EnfermedadTernera enfermedadTernera) {
getEnfermedadTerneras().add(enfermedadTernera);
enfermedadTernera.setTernera(this);
return enfermedadTernera;
}
public EnfermedadTernera removeEnfermedadTernera(EnfermedadTernera enfermedadTernera) {
getEnfermedadTerneras().remove(enfermedadTernera);
enfermedadTernera.setTernera(null);
return enfermedadTernera;
}
public List<Peso> getPesos() {
return this.pesos;
}
public void setPesos(List<Peso> pesos) {
this.pesos = pesos;
}
public Peso addPeso(Peso peso) {
getPesos().add(peso);
peso.setTernera(this);
return peso;
}
public Peso removePeso(Peso peso) {
getPesos().remove(peso);
peso.setTernera(null);
return peso;
}
public Guachera getGuachera() {
return this.guachera;
}
public void setGuachera(Guachera guachera) {
this.guachera = guachera;
}
public Madre getMadre() {
return this.madre;
}
public void setMadre(Madre madre) {
this.madre = madre;
}
public Padre getPadre() {
return this.padre;
}
public void setPadre(Padre padre) {
this.padre = padre;
}
}
|
Python
|
UTF-8
| 2,129 | 3.8125 | 4 |
[] |
no_license
|
#CSV
# Q1 read the ford_escort.csv example file using python csv library and print each row
import csv
with open('ford_escort.csv', 'r') as file:
reader = csv.reader(file, delimiter = ',')
for row in reader:
print(row)
# Q2 Extend the above so that the data is read into a dictionary
import csv
with open('ford_escort.csv', 'r') as file:
csv_file = csv.DictReader(file)
for row in csv_file:
print(row)
# Q3. Write the following data as CSV to a file. Adde a header row with titles.
['Joe', 'Bloggs', 40]
['Jane', 'Smith', 50]
import csv
with open('trial.csv', mode = 'w') as file:
writer = csv.writer(file, delimiter = ',')
writer.writerow(['First', 'Surname', 'Age'])
writer.writerow(['Joe', 'Bloggs', '40'])
writer.writerow(['Jane', 'Smith', '50'])
# Q4. Write another block of code that will append the following data to the file created in Q3
['Mike', 'Wazowski', 40]
import csv
with open('trial.csv', 'a') as file:
writer = csv.writer(file, delimiter = ',')
writer.writerow(['Mike', 'Wazowski', '40'])
#EXTRA WORK - WRITING FROM A DICTIONARY
import csv
with open('dictionary.csv', 'w') as file:
fieldnames = ['first_name', 'surname', 'age']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({
'first_name': 'Jack',
'surname': 'Smith',
'age': 25
})
#JSON
# Q1: read the example.json handout file using the native python json library,
# print the object that is created
import json
with open('example.json', 'r') as json_file:
data = json.load(json_file)
print(json.dumps(data, indent =3))
# indent allows for spacing in between values
# Q2: print the "id" of all the items in the menu
import json
with open('example.json', 'r') as json_file:
data = json.load(json_file)
print(json.dumps(data['menu']['items'], indent =3))
# #Q3 Write the following data as JSON to a file
import json
data = {
'president': {
'name': 'Zaphod Beeblebrox',
'species': 'Betelgeusian'
}
}
with open('data_file.json', 'w') as write_file:
json.dump(data, write_file)
|
C#
|
UTF-8
| 3,467 | 2.53125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StudentEVL
{
public partial class manageUserForm : Form
{
public manageUserForm()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
LoginForm log = new LoginForm();
log.Show();
this.Hide();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
homeForm hom = new homeForm();
hom.Show();
this.Hide();
}
private void clear_Click(object sender, EventArgs e)
{
dataClear();
}
private void dataClear()
{
userID.Text = "";
username.Text = "";
passworduser.Text = "";
usertype.Text = "";
}
private void populate()
{
con.Open();
string query = "select * from userTable";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
SqlCommandBuilder builder = new SqlCommandBuilder();
var ds = new DataSet();
sda.Fill(ds);
dataGridViewUser.DataSource = ds.Tables[0];
con.Close();
}
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-9G2BI4L\MSSQLSERVER01;Initial Catalog=studentEVL;Integrated Security=True");
private void save_Click(object sender, EventArgs e)
{
if(userID.Text=="" || username.Text=="" || passworduser.Text=="" || usertype.Text == "")
{
MessageBox.Show("Missing any information");
}
else
{
try
{
con.Open();
string query = "insert into userTable values('"+ userID.Text + "','" + username.Text + "','" + passworduser.Text + "','" + usertype.Text + "')";
SqlCommand cmd = new SqlCommand(query , con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("new user created");
dataClear();
populate();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void manageUserForm_Load(object sender, EventArgs e)
{
populate();
}
private void delete_Click(object sender, EventArgs e)
{
if (userID.Text == "")
{
MessageBox.Show("Please select data for delete!");
}
else
{
con.Open();
string query = "delete userTable where Id = '"+ userID.Text +"'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("User deleted!");
populate();
dataClear();
}
}
private void dataGridViewUser_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
userID.Text = dataGridViewUser.CurrentRow.Cells[0].Value.ToString();
}
}
}
|
Markdown
|
UTF-8
| 555 | 2.640625 | 3 |
[] |
no_license
|
# File reporter.py
## Class Reporter
This class should be used to print instead of print()
It should be imported as follows:
from urnai.utils.reporter import Reporter as rp
or
from utils.reporter import Reporter as rp
And then the function report should be called to print:
rp.report("My message")
If the message is a debug one, a level different from 0
should be used:
rp.report("Debug message", 2)
## Method report()
* Arguments: message, verbosity_lvl, end
## Method save()
* Arguments: persist_path
## Method load()
* Arguments: persist_path
|
Ruby
|
UTF-8
| 3,099 | 2.578125 | 3 |
[] |
no_license
|
require 'csv'
require 'json'
require 'mongo'
require 'gnuplot'
require 'rest-client'
def mean(array)
array.inject(array.inject(0) { |sum, x| sum += x } / array.size.to_f)
end
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'analytics')
perfomance_data = nil
verified_compensations = client["verified_compensations"].find
success = []
unsuccessful = []
verified_compensations.each do |document|
# puts document
vulnerable_image = client["vulnerabilities"].find("image_name" => "#{document["image_name"]}").first
if vulnerable_image["vulnerabilities"].keys.count > document["vulnerabilities"].count
success << document
puts "For #{document["image_name"]} we compensated to #{document["vulnerabilities"].keys.count} from #{vulnerable_image["vulnerabilities"].keys.count}"
else
puts "Could not improve for #{document["image_name"]}"
unsuccessful << document
end
end
puts "Sucessful for #{success.count} from #{verified_compensations.count}"
csv_file = "./consolidated/compensations/compensation_results_50_2.csv"
compensations = client["compensations"].find
CSV.open(csv_file,"wb") do |csv|
csv << ["image_name","image_id","runtime","pull_time","vulnerabilities_count_before","vulnerabilities_count_after","improvement","timestamp"]
compensations.each do |document|
puts document
# processing_runtime << document["runtime_total"]/1000 unless document["runtimte_total"].infinite?
# pull_time << document["pull_time"] unless document["pull_time"].infinite?
# total_image_size << document["virtual_image_size"].to_f
#
timestamp = Time.parse(document["timestamp"])
verified_compensation = client["verified_compensations"].find(:image_id => "#{document["compensated_image_id"]}").first
# TODO Thinks
vulnerable_image = client["vulnerabilities"].find("image_name" => "#{document["image_name"]}").first
vulnerabilities_before = vulnerable_image["vulnerabilities"].keys.count
vulnerabilities_after = verified_compensation["vulnerabilities"].count
improvement = 0
if vulnerabilities_before > vulnerabilities_after
improvement = 1
else
improvement = 0
end
# if !document["complete_runtime"].infinite?
# starttime_stamp = timestamp - document["complete_runtime"]
# else
#
# end
# starttime_stamp = timestamp - document["complete_runtime"]
# if !document["runtime"].infinite?
# processingtime_stamp = starttime_stamp + document["runtime"]/1000
# else
# processingtime_stamp = "NA"
# end
# complete_runtime << document["complete_runtime"] unless document["complete_runtime"].infinite?
csv << [document["image_name"],document["image_id"],document["runtime_total"]/1000,document["pull_time"],vulnerabilities_before,vulnerabilities_after,timestamp]
# csv << [document["runtime"]/1000,document["complete_runtime"],document["virtual_image_size"],document["vulnerabilities"].keys.count,document["timestamp"]]
end
end
puts "Sucessful for #{success.count} from #{verified_compensations.count}"
|
C
|
UTF-8
| 4,339 | 2.59375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
typedef unsigned char u8;
#define SHORT_MESSAGE 0x10
#define LONG_MESSAGE 0x11
struct hidpp2_message {
u8 report_id;
u8 device_index;
u8 feature_index;
#define HIDPP_SET_FUNC(msg, func) ((msg)->func_swId |= ((func) << 4))
u8 func_swId;
u8 params[16]; // 3 or 16 params
} __attribute__((__packed__));
struct feature {
uint16_t featureId;
#define FEAT_TYPE_MASK 0xc0
#define FEAT_TYPE_OBSOLETE 0x80
#define FEAT_TYPE_SWHIDDEN 0x40
u8 featureType;
};
#define SOFTWARE_ID 0x04 /* getRandom() -- guaranteed to be random. */
#define FEATURE_INDEX_IROOT 0x00
#define FID_IFEATURESET 0x0001
static
const char *
get_feature_name(uint16_t featureId) {
switch (featureId) {
case 0x0000: return "IRoot";
case FID_IFEATURESET: return "IFeatureSet";
case 0x0003: return "IFirmwareInfo";
case 0x0005: return "GetDeviceNameType";
case 0x1000: return "batteryLevelStatus";
case 0x1B00: return "SpecialKeysMSEButtons";
case 0x1D4B: return "WirelessDeviceStatus";
default: return "unknown";
}
}
/**
* Initialize common values of a HID++ 2.0 message: report_id, device_index and
* software ID. Remaining fields: feature_index, func, params.
*/
#define INIT_HIDPP_SHORT(msg, dev_index) \
memset((msg), 0, sizeof *(msg)); \
(msg)->report_id = SHORT_MESSAGE; \
(msg)->device_index = dev_index; \
(msg)->func_swId = SOFTWARE_ID
static
bool
do_hidpp2_request(int fd, struct hidpp2_message *msg) {
struct hidpp_message *hid10_message = (struct hidpp_message *) msg;
if (!do_write(fd, hid10_message)) {
return false;
}
// use do_read_skippy in case there are interleaving notifications
// sub id is feature index in HID++ 2.0
if (!do_read_skippy(fd, hid10_message, 0x11, hid10_message->sub_id)) {
puts("WTF");
return false;
}
return true;
}
// Returns feature index for featureId
static
u8
get_feature(int fd, u8 device_index, uint16_t featureId) {
struct hidpp2_message msg;
INIT_HIDPP_SHORT(&msg, device_index);
msg.feature_index = FEATURE_INDEX_IROOT;
HIDPP_SET_FUNC(&msg, 0); // GetFeature(featureId)
msg.params[0] = featureId >> 8;
msg.params[1] = featureId & 0xFF;
if (!do_hidpp2_request(fd, &msg)) {
return 0;
}
return msg.params[0];
}
// Returns number of features or 0 on error.
static
u8
get_feature_count(int fd, u8 device_index, u8 ifeatIndex) {
struct hidpp2_message msg;
INIT_HIDPP_SHORT(&msg, device_index);
// XXX: is this variable? Can't it be hard-coded to 0x01?
msg.feature_index = ifeatIndex;
HIDPP_SET_FUNC(&msg, 0); // GetCount()
if (!do_hidpp2_request(fd, &msg)) {
fprintf(stderr, "Failed to request features count\n");
return 0;
}
return msg.params[0];
}
// Get featureId and type for a given featureIndex.
static
bool
get_featureId(int fd, u8 device_index, u8 ifeatIndex, u8 featureIndex, struct feature *feat) {
struct hidpp2_message msg;
INIT_HIDPP_SHORT(&msg, device_index);
// XXX: is this variable? Can't it be hard-coded to 0x01?
msg.feature_index = ifeatIndex;
HIDPP_SET_FUNC(&msg, 1); // GetFeatureId(featureIndex)
msg.params[0] = featureIndex;
if (!do_hidpp2_request(fd, &msg)) {
return false;
}
feat->featureId = (msg.params[0] << 8) | msg.params[1];
feat->featureType = msg.params[2];
return true;
}
void
hidpp20_print_features(int fd, u8 device_index) {
u8 i, count, ifeatIndex;
ifeatIndex = get_feature(fd, device_index, FID_IFEATURESET);
if (!ifeatIndex) {
fprintf(stderr, "Failed to get feature information\n");
return;
}
count = get_feature_count(fd, device_index, ifeatIndex);
printf("Total number of HID++ 2.0 features: %i\n", count);
for (i = 0; i <= count; i++) {
struct feature feat;
if (get_featureId(fd, device_index, ifeatIndex, i, &feat)) {
printf(" %2i: [%04X] %c%c %s\n", i, feat.featureId,
feat.featureType & FEAT_TYPE_OBSOLETE ? 'O' : ' ',
feat.featureType & FEAT_TYPE_SWHIDDEN ? 'H' : ' ',
get_feature_name(feat.featureId));
if (feat.featureType & ~FEAT_TYPE_MASK) {
printf("Warning: unrecognized feature flags: %#04x\n",
feat.featureType & ~FEAT_TYPE_MASK);
}
} else {
fprintf(stderr, "Failed to get feature, is device connected?\n");
}
}
puts("(O = obsolete feature; H = SW hidden feature)");
}
|
TypeScript
|
UTF-8
| 1,135 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
import { z } from 'zod'
export const WORD_IS_NOT_INCLUDED_ERROR = 'WordIsNotIncludedError'
export const WORD_IS_ALREADY_PRESENT_ERROR = 'WordIsAlreadyFoundError'
export const WORD_LENGTH_IS_LESS_THAN_REQUIRED_ERROR =
'WordLengthIsLessThanRequiredError'
export type ApplyWordError = [
typeof WORD_IS_NOT_INCLUDED_ERROR,
typeof WORD_IS_ALREADY_PRESENT_ERROR,
typeof WORD_LENGTH_IS_LESS_THAN_REQUIRED_ERROR,
][number]
export const ApplyWordErrorMessages: Record<ApplyWordError, string> = {
[WORD_IS_NOT_INCLUDED_ERROR]:
'Это слово или нельзя составить или оно не существительное в единственном числе',
[WORD_IS_ALREADY_PRESENT_ERROR]: 'Это слово уже найдено',
[WORD_LENGTH_IS_LESS_THAN_REQUIRED_ERROR]:
'Слово должно быть не менее {{charsAmount}} букв',
} as const
export const wordLengthIsLessThanRequiredErrorParamsSchema = z.object({
required_length: z.number(),
})
export const isErrorApplyWordError = (err: string): err is ApplyWordError =>
Object.keys(ApplyWordErrorMessages).includes(err)
|
C#
|
UTF-8
| 1,681 | 3.1875 | 3 |
[] |
no_license
|
using System;
using System.Security.Principal;
namespace DirectoryLibrary
{
public class DirectoryUtility
{
/// <summary>
/// 特別解析 objectguid 和 objectsid 的值,轉為人類可閱讀的字串,其它皆轉為字串。
/// </summary>
/// <param name="name">Attribut Name</param>
/// <param name="value">Attribut Value</param>
/// <returns></returns>
public static string ExtractAttributValue(string name, object value)
{
string valueString;
if (name.Contains("objectguid") && value is byte[] && ((byte[])value).Length == 16)
{
Guid guid = new Guid(value as byte[]);
valueString = guid.ToString();
}
else if (name == "objectsid" && value is byte[])
{
// A security identifier (SID) is used to uniquely identify a security principal or security group.
// Security principals can represent any entity that can be authenticated by the operating system, such as a user account, a computer account, or a thread or process that runs in the security context of a user or computer account.
// https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/security-identifiers
// https://www.lijyyh.com/2015/08/sid-deep-dive.html
SecurityIdentifier sid = new SecurityIdentifier((byte[])value, 0);
valueString = sid.Value;
}
else
{
valueString = value.ToString();
}
return valueString;
}
}
}
|
Java
|
UTF-8
| 3,568 | 2.78125 | 3 |
[] |
no_license
|
package com.mycompany.app;
import static spark.Spark.get;
import static spark.Spark.port;
import static spark.Spark.post;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import spark.ModelAndView;
import spark.template.mustache.MustacheTemplateEngine;
public class App {
public static String encode(ArrayList<Integer> array, ArrayList<Integer> array2, String name, String lastname) {
System.out.println("inside encode");
String s = "";
if((array == null) || (array2 == null))
return "";
else {
if (array.size() < name.length()) {
for(int i=0; i<name.length(); i++) {
array.add(array.get(0));
}
}
for(int i=0; i<name.length(); i++) {
char c = (char)(name.charAt(i) + array.get(i));
s += c;
}
s += " ";
if (array2.size() < lastname.length()) {
for(int i=0; i<lastname.length(); i++) {
array2.add(array2.get(0));
}
}
for(int i=0; i<lastname.length(); i++) {
char c = (char)(lastname.charAt(i) + array2.get(i));
s += c;
}
return s;
}
}
public static void main(String[] args) {
port(getHerokuAssignedPort());
get("/", (req, res) -> "Hello, World");
post("/compute", (req, res) -> {
//System.out.println(req.queryParams("input1"));
//System.out.println(req.queryParams("input2"));
String input1 = req.queryParams("input1");
java.util.Scanner sc1 = new java.util.Scanner(input1);
sc1.useDelimiter("[;\r\n]+");
java.util.ArrayList<Integer> inputList = new java.util.ArrayList<>();
while (sc1.hasNext()) {
int value = Integer.parseInt(sc1.next().replaceAll("\\s",""));
inputList.add(value);
}
System.out.println(inputList);
String input2 = req.queryParams("input2");
java.util.Scanner sc2 = new java.util.Scanner(input2);
sc2.useDelimiter("[;\r\n]+");
java.util.ArrayList<Integer> inputList2 = new java.util.ArrayList<>();
while (sc2.hasNext()) {
int value2 = Integer.parseInt(sc2.next().replaceAll("\\s",""));
inputList2.add(value2);
}
System.out.println(inputList2);
String input3 = req.queryParams("input3").replaceAll("\\s","");
String input4 = req.queryParams("input4").replaceAll("\\s","");
String result = App.encode(inputList, inputList2, input3, input4);
Map map = new HashMap();
map.put("result", result);
return new ModelAndView(map, "compute.mustache");
}, new MustacheTemplateEngine());
get("/compute",
(rq, rs) -> {
Map map = new HashMap();
map.put("result", "not computed yet!");
return new ModelAndView(map, "compute.mustache");
},
new MustacheTemplateEngine());
}
static int getHerokuAssignedPort() {
ProcessBuilder processBuilder = new ProcessBuilder();
if (processBuilder.environment().get("PORT") != null) {
return Integer.parseInt(processBuilder.environment().get("PORT"));
}
return 4567; //return default port if heroku-port isn't set (i.e. on localhost)
}
}
|
JavaScript
|
UTF-8
| 9,346 | 2.515625 | 3 |
[] |
no_license
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is gContactSync.
*
* The Initial Developer of the Original Code is
* Josh Geenen <gcontactsync@pirules.org>.
* Portions created by the Initial Developer are Copyright (C) 2008-2016
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/** Containing object for gContactSync */
var gContactSync = gContactSync || {};
/**
* Sets up an HTTP request.<br>
* The constructor is not all that useful so extend this class if you must
* make repetitive HTTP requests.<br><br>
* You may setup callbacks based on different HTTP status codes:
* <ul>
* <li>0 (offline): use <b>mOnError</b></li>
* <li>200 (OK): use <b>mOnSuccess</b></li>
* <li>201 (CREATED): use <b>mOnCreated</b></li>
* <li>400 (BAD REQUEST): use <b>mOn401</b></li>
* <li>401 (UNAUTHORIZED): use <b>mOn401</b></li>
* <li>403 (FORBIDDEN): use <b>mOn401</b></li>
* <li>503 (SERVICE_UNAVAILABLE): use <b>mOn503</b></li>
* <li><anything else>: use <b>mOnError</b></li>
* </ul>
* <br>Sample usage:
* <pre>
* // Create and setup a new HttpRequest
* var myHttpRequest = new gContactSync.HttpRequest();
* myHttpRequest.mUrl = "http://www.pirules.org";
* myHttpRequest.mType = "GET";
* myHttpRequest.addHeaderItem("Content-length", 0);
* // setup the callbacks
* myHttpRequest.mOnSuccess = function myRequestSuccess(aHttpReq) {
* gContactSync.alert("Request succeeded. Content:\n\n" + aHttpReq.statusText);
* };
* myHttpRequest.mOnOffline = function myRequestOffline(aHttpReq) {
* gContactSync.alert("You are offline");
* };
* myHttpRequest.mOnError = function myRequestError(aHttpReq) {
* gContactSync.alert("Request failed...Status: " + aHttpReq.status);
* };
* // send the request
* myHttpRequest.send();
* </pre>
* @constructor
* @class
*/
gContactSync.HttpRequest = function gCS_HttpRequest() {
if (window.XMLHttpRequest) {
this.mHttpRequest = new XMLHttpRequest();
}
if (!this.mHttpRequest) {
throw "Error - could not create an XMLHttpRequest" +
gContactSync.StringBundle.getStr("pleaseReport");
}
this.mParameters = [];
};
gContactSync.HttpRequest.prototype = {
/** Content types */
CONTENT_TYPES: {
/** URL encoded */
URL_ENC: "application/x-www-form-urlencoded",
/** ATOM/XML */
ATOM: "application/atom+xml",
/** XML */
XML: "application/xml"
},
/**
* Adds a content override to the header in case a firewall blocks DELETE or
* PUT requests.
* @param aType {string} The type of override. Must be DELETE or PUT.
*/
addContentOverride: function HttpRequest_addContentOverride(aType) {
switch (aType) {
case "delete":
case "DELETE":
this.addHeaderItem("X-HTTP-Method-Override", "DELETE");
break;
case "put":
case "PUT":
this.addHeaderItem("X-HTTP-Method-Override", "PUT");
break;
default:
throw "Error - type sent to addContentOverride must be DELETE or PUT";
}
},
/**
* Adds a header label/value pair to the arrays of header information
* @param aLabel {string} The label for the header.
* @param aValue {string} The value for the header.
*/
addHeaderItem: function HttpRequest_addHeaderItem(aLabel, aValue) {
if (!this.mHeaderLabels) {
this.mHeaderLabels = [];
this.mHeaderValues = [];
}
this.mHeaderLabels.push(aLabel);
this.mHeaderValues.push(aValue);
},
/**
* Adds a parameter/value pair to the request.
* @param aParameter {string} The parameter.
* @param aValue {string} The value.
*/
addParameter: function HttpRequest_addParameter(aLabel, aValue) {
if (aValue) {
this.mParameters.push(aLabel + "=" + encodeURIComponent(aValue));
} else {
this.mParameters.push(aLabel);
}
},
/**
* Sends the HTTP Request with the information stored in the object.<br>
* Note: Setup everything, including the callbacks for different statuses
* including mOnSuccess, mOnError, mOnFail, and mOnCreated first.<br>
* See the class documentation for a sample request.
*/
send: function HttpRequest_send() {
var params = this.mParameters.join("&");
// log the basic info for debugging purposes
gContactSync.LOGGER.VERBOSE_LOG("HTTP Request being formed");
gContactSync.LOGGER.VERBOSE_LOG(" * Caller is: " + this.send.caller.name);
gContactSync.LOGGER.VERBOSE_LOG(" * URL: " + this.mUrl);
gContactSync.LOGGER.VERBOSE_LOG(" * Type: " + this.mType);
gContactSync.LOGGER.VERBOSE_LOG(" * Content-Type: " + this.mContentType);
if (params.length) {
gContactSync.LOGGER.VERBOSE_LOG(" * Parameters: " + params);
if (this.mType === "POST") {
this.mBody = this.mBody ? params + this.mBody : params;
} else {
this.mUrl = this.mUrl + "?" + params;
}
}
this.mHttpRequest.open(this.mType, this.mUrl, true); // open the request
// set the header
this.addHeaderItem("Content-Type", this.mContentType);
gContactSync.LOGGER.VERBOSE_LOG(" * Setting up the header: ");
for (var i = 0; i < this.mHeaderLabels.length; i++) {
gContactSync.LOGGER.VERBOSE_LOG(" o " + this.mHeaderLabels[i] +
": " + this.mHeaderValues[i]);
this.mHttpRequest.setRequestHeader(this.mHeaderLabels[i],
this.mHeaderValues[i]);
}
var httpReq = this.mHttpRequest,
onSuccess = this.mOnSuccess,
onOffline = this.mOnOffline,
onFail = this.mOnError,
onCreated = this.mOnCreated,
on401 = this.mOn401,
on503 = this.mOn503;
// Use the requested timeout value. Timeouts result in readyState = 4, status = 0 and
// are handled by the offline callback.
httpReq.timeout = gContactSync.Preferences.mSyncPrefs.httpRequestTimeout.value;
httpReq.onreadystatechange = function httpReq_readyState() {
var callback = [];
// if the request is done then check the status
if (httpReq.readyState === 4) {
// this may be called after the address book window is closed
// if the window is closed there will be an exception thrown as
// explained here - https://www.mozdev.org/bugs/show_bug.cgi?id=20527
gContactSync.LOGGER.VERBOSE_LOG(" * The request has finished with status: " +
httpReq.status + "/" +
(httpReq.status ? httpReq.statusText : "offline"));
if (httpReq.status) {
gContactSync.LOGGER.VERBOSE_LOG(" * Headers:\n" +
httpReq.getAllResponseHeaders() + "\n");
}
switch (httpReq.status) {
case 0: // the user is offline
callback = onOffline || onFail;
break;
case 201: // 201 CREATED
callback = onCreated;
break;
case 200: // 200 OK
callback = onSuccess;
break;
case 400: // 400 Bad Request (typically invalid_grant)
case 401: // 401 Unauthorized (Token Expired in Gmail)
case 403: // 403 Forbidden (typically invalid_grant caused by username/token mismatch)
callback = on401 || onFail;
break;
case 503: // 503 Service unavailble (Server is busy, user exceeded quota, etc.)
callback = on503 || onFail;
break;
default: // other status
callback = onFail;
}
if (callback) {
gContactSync.LOGGER.VERBOSE_LOG(" * Running the function callback");
callback.call(this, httpReq);
}
} // end of readyState
};
try {
this.mHttpRequest.send(this.mBody); // send the request
} catch (e) {
gContactSync.LOGGER.LOG_ERROR(" * Error sending request", e);
this.mOnError(this.mHttpRequest);
}
gContactSync.LOGGER.VERBOSE_LOG(" * Request Sent");
}
};
|
C#
|
UTF-8
| 922 | 2.75 | 3 |
[] |
no_license
|
using System;
using System.Threading;
using Confluent.Kafka;
namespace ApacheKafkaExample.Producer1
{
class Program
{
static void Main(string[] args)
{
var config = new ProducerConfig { BootstrapServers = "localhost:9092" };
Action<DeliveryReport<Null, string>> handler = r =>
Console.WriteLine(!r.Error.IsError
? $"Delivered message to {r.TopicPartitionOffset}"
: $"Delivery Error: {r.Error.Reason}");
using (var p = new ProducerBuilder<Null, string>(config).Build())
{
for (int i = 0; i < 10; ++i)
{
p.Produce("my-topic1", new Message<Null, string> { Value = i.ToString() }, handler);
Thread.Sleep(TimeSpan.FromSeconds(1));
}
p.Flush(TimeSpan.FromSeconds(10));
}
}
}
}
|
Python
|
UTF-8
| 449 | 3.015625 | 3 |
[] |
no_license
|
from tqdm import tqdm
def save_img(name, data_array):
data = _print_img(data_array)
with open(name, 'w') as f:
f.write(data)
def _print_img(data_array):
w = len(data_array[1])
h = len(data_array)
rows = []
for row in tqdm(data_array):
row_data = [str(int(pix*255)) for pix in row]
rows.append(' '.join(row_data))
data = '\n'.join(rows)
return f"""P2
{w} {h}
255
{data}
"""
|
Python
|
UTF-8
| 831 | 3.671875 | 4 |
[] |
no_license
|
loops
for loop
savings = [100,200,150,450,600]
sum=0
for saved in savings:
sum+=saved
print("total savings are",sum)
#
a="whats up"
for i in a:
print(i) # for single line use end parameter in print
savings = [100,200,150,450,600]
sum=0
for saved in savings[0:3]:
sum+=saved
print("total savings are",sum)
#remeber to use for to iterate in a dictionary by for key,val in dictionary.items()
dict1 = {1:'a', 2:'b', 3:'c'}
for key,val in dict1.items():
print("key is {0} and value is {1}".format(key,val))
# ranges
for i in range(6):
print(i)
for i in range(1,10):
print(i)
for i in range(10,0,-1):
print(i)
for i in range(10,0,-1):
print(i)
#while loops
num = 0
#
# while num<10:
# print(num)
# num+=1
num = 0
while num<=50:
if num%2==0:
print(num)
num+=1
if num >40:
break
if num == 37:
num+=1
continue
|
Java
|
UTF-8
| 352 | 1.859375 | 2 |
[] |
no_license
|
package com.lukasz.myweather.webApi;
import com.lukasz.myweather.POJO.WeekWeather;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by Lukasz on 2018-03-07.
* Upload Picture
*/
public interface WebService {
@GET("daily?&APPID=032a76b432cfa81e175c33bc81dae187")
Call<WeekWeather> getWeather(@Query("id") int cityId );
}
|
JavaScript
|
UTF-8
| 390 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import mongoose, { Schema } from 'mongoose';
const locationSchema = new Schema({
name: String,
});
locationSchema.statics.create = function (locationName) {
const location = {name: locationName};
const newLocation = new this(location);
return newLocation.save().catch(e=>console.log(e));
};
const location = mongoose.model('location', locationSchema);
export default location;
|
Markdown
|
UTF-8
| 1,629 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
Sanjay Nair (sanjaysn@usc.edu)
-----------------------------
Compler requirements
---------------------
Implementation of this project is done using c++. The implemenation uses std library classes such as std::string and std::map. My nunki account (default setup by ISD) points to the g++ directory /usr/usc/gnu/gcc/3.3.2.
NOTE:
-----
Normally your shell should point to g++ and standard C++ libaries. You have to do the following step ONLY if your setup does not point to g++ and standard c+ libraries.
Make sure that your path environment variable points to openssl lib
setenv LD_LIBRARY_PATH /home/scf-22/csci551b/openssl/lib:/lib
-----------------------------------------------
If you don't have the g++ and std library path in your PATH variable, you have to do the following:
Include the following in your .cshrc file
if($?LD_LIBRARY_PATH) then
setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:/usr/usc/gnu/gcc/3.3.2/lib
else
setenv LD_LIBARY_PATH /usr/usc/gnu/gcc/3.3.2/lib
endif
setenv PATH /usr/usc/gnu/gcc/3.3.2//bin:${PATH}
Design details
--------------
The project is implemented using object oriented methods. Main method is implemented in a file called hw2.cc which is responsible for parsing the input. A Basedump class is created to abstract the dumps. Derived classes such as Base64EncDump, Base64DecDump etc. overrides the dump method to provide specific behavior. This way hw2 can create appropriate object based on the input option and call dump on the correct object. The dump method on the called object will perform appropriate dumps (base64 encoding, base64 decoding, sha-1, md-5, des encoding and des decoding).
|
Java
|
UTF-8
| 2,488 | 2.578125 | 3 |
[] |
no_license
|
package AlienWarsLogin;
import restShared.AccountDTO;
import Hashing.HashingClass;
import javax.sql.rowset.CachedRowSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AlienwarsLogin {
private DbClass dbClass = new DbClass();
public boolean addAccount(String userName, String password, String email) {
try {
String hashedPassword = HashingClass.hashPassword(password);
Map<Integer, Object> map = new HashMap<Integer, Object>();
map.put(1, userName);
map.put(2, hashedPassword);
map.put(3, email);
String procedure = "INSERT INTO [dbo].[User] (userName, password, email) VALUES(?,?,?)";
dbClass.executeNonQuery(procedure, map);
return true;
} catch (Exception e) {
return false;
}
}
public AccountDTO getUserByUserName(String userName) {
String procedure = "SELECT uId, userName, password, email FROM [dbo].[User] WHERE userName = ?";
if (userName.contains("@"))
procedure = "SELECT email, password FROM [dbo].[User] WHERE email = ?";
Map<Integer, Object> map = new HashMap<Integer, Object>();
map.put(1, userName);
try {
CachedRowSet cachedRowSet = dbClass.executeQuery(procedure, map);
if (cachedRowSet.next()) {
return new AccountDTO(cachedRowSet.getInt(1), cachedRowSet.getString(2), cachedRowSet.getString(3), cachedRowSet.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public List<AccountDTO> getAll() {
String procedure = "SELECT uId, userName, password, email FROM [dbo].[User]";
List<AccountDTO> accounts = new ArrayList<>();
Map<Integer, Object> map = new HashMap<Integer, Object>();
try {
CachedRowSet cachedRowSet = dbClass.executeQuery(procedure, map);
while (cachedRowSet.next()) {
accounts.add(new AccountDTO(
cachedRowSet.getInt("userId"),
cachedRowSet.getString("userName"),
cachedRowSet.getString("password"),
cachedRowSet.getString("email")));
}
} catch (SQLException e) {
e.printStackTrace();
}
return accounts;
}
}
|
Python
|
UTF-8
| 6,233 | 2.53125 | 3 |
[] |
no_license
|
from __future__ import print_function
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.colors import rgb2hex
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import csv
df = pd.read_csv('4GRP_spatial_difference_summary_rev.csv', usecols=[
'state', 'abb', 'rho', 'phi', 'theta', 'total', 'rho_per', 'phi_per', 'theta_per', 'latitude', 'longitude'])
df_location = pd.read_csv('location.csv', usecols=['state', 'abb', 'capital', 'latitude', 'longitude'])
# Lambert Conformal map of lower 48 states.
plt.figure()
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
shp_info = m.readshapefile('st99_d00','states',drawbounds=True)
# shp_info = m.readshapefile('gz_2010_us_040_00_500k', 'states',drawbounds=True)
# Dictionary {'yyy':xxx, ..., }
# dic.keys() -> Return the index
drho ={k: float(v) for k,v in df.groupby("state")["rho"]}
dphi ={k: float(v) for k,v in df.groupby("state")["phi"]}
dtheta ={k: float(v) for k,v in df.groupby("state")["theta"]}
A = df['phi'].values
exclusions = ['District of Columbia','Puerto Rico', 'Rhode Island', 'Delaware', 'Hawaii', 'New Hampshire', 'South Carolina','Louisiana', 'Kentucky', 'Missouri', 'West Virginia', 'Vermont', 'Oklahoma', 'Arizona', 'Maine', 'Kansas', 'Utah', 'Nebraska', 'Nevada', 'Idaho', 'New Mexico', 'South Dakota', 'North Dakota', 'Montana','Wyoming','Alaska']
lons = df['longitude'].values
lats = df['latitude'].values
abbs = df['abb'].values
percentages = df['phi_per'].values
include = df['state'].values
# lons =[]
# lats = []
# for i, statename in enumerate(df['state']):
# lons.append(df['longitude'][i])
# lats.append(df['latitude'][i])
# for i, statename in enumerate(df_location['state']):
# if statename not in exclusions:
# lons.append(df_location['longitude'][i])
# lats.append(df_location['latitude'][i])
print(shp_info)
# choose a color for each state based on population density.
colors={}
statenames=[]
patches = []
color_values =[]
cmap = plt.cm.jet # use 'hot' colormap plt.cm.bwr #
vmin = 1.0; vmax = 2.0 # set range.
phi_max = max(A)
phi_min = min(A)
print(m.states_info[0].keys())
for shapedict in m.states_info:
statename = shapedict['NAME']
# skip DC and Puerto Rico.
if statename in include: #not in exclusions: #['District of Columbia','Puerto Rico']:
phis = dphi[statename]
# calling colormap with value between 0 and 1 returns
# rgba value. Invert color range (hot colors are high
# population), take sqrt root to spread out colors more.
# color_value = 1.-np.sqrt((phis-vmin)/(vmax-vmin))
color_value = (phis-phi_min)/(phi_max-phi_min)
colors[statename] = cmap(color_value)[:3]
color_values.append(color_value)
statenames.append(statename)
# cycle through state names, color each one.
ax = plt.gca() # get current axes instance
polys = np.array([])
for nshape,seg in enumerate(m.states):
# skip DC and Puerto Rico.
if statenames[nshape] not in exclusions: #['District of Columbia','Puerto Rico']:
color = rgb2hex(colors[statenames[nshape]])
poly = Polygon(seg,facecolor=color,edgecolor=color)
# ax.add_patch(poly)
patches.append(poly)
# colors = np.random.rand(len(patches))
p = PatchCollection(patches, cmap=plt.cm.jet, alpha=0.6)
# p.set_array(np.array(A))
# p.set_array(np.array(color_values))
re_color = np.array(color_values) * (phi_max-phi_min) + phi_min
p.set_array(re_color)
# p.set_array(np.array(colors))
ax.add_collection(p)
# plt.colorbar(p, orientation="horizontal")
plt.colorbar(p, shrink=0.7,orientation="horizontal")
# c = plt.colorbar(cmap, orientation='horizontal')
# fig = plt.gci()
# m.colorbar()
# cb = m.colorbar("bottom", size="5%", pad="2%")
# draw meridians and parallels.
# m.drawparallels(np.arange(25,65,20),labels=[1,0,0,0])
# m.drawmeridians(np.arange(-120,-40,20),labels=[0,0,0,1])
# plt.title('Filling State Polygons by Population Density')
for lon, lat, abb, percentage in zip(lons, lats, abbs, percentages):
x,y = m(lon, lat)
# msize = mag * min_marker_size
# marker_string = get_marker_color(mag)
# m.plot(x, y, 'bo', markersize=6)
# state = df_location['state'] if df_location['latitude'] == lat
if abb=='WA':
position = (35, -10)
elif abb=='OR':
position = (20, -25)
elif abb=='CA':
position = (30, -60)
elif abb=='MN':
position = (0, 0)
elif abb=='IA':
position = (10, -10)
elif abb=='WI':
position = (10, 5)
elif abb=='MS':
position = (15, -20)
elif abb=='GA':
position = (26, -25)
elif abb=='FL':
position = (10, -40)
elif abb=='IL':
position = (16, -10)
elif abb=='IN':
position = (14, -10)
elif abb=='OH':
position = (10, -10)
elif abb=='MI':
position = (12, -15)
elif abb=='NY':
position = (-2, -5)
elif abb=='PA':
position = (-5, -10)
elif abb=='VA':
position = (0, -15)
elif abb=='MA':
position = (-10, 50)
elif abb=='CT':
position = (30, -70)
elif abb=='NJ':
position = (45, -90)
elif abb=='MD':
position = (30, -120)
else:
position = (10,-20)
if abb not in ['MA', 'CT', 'NJ', 'MD']:
plt.annotate('%s \n %d %%' % (abb, percentage) ,
xy = (x, y), xytext = position,
textcoords = 'offset points', ha = 'right', va = 'bottom')
else:
m.plot(x, y, 'ro', markersize=6)
plt.annotate('%s \n %d %%' % (abb, percentage) ,
xy = (x, y), xytext = position,
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'None', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
plt.show()
|
C#
|
UTF-8
| 3,296 | 2.78125 | 3 |
[] |
no_license
|
#region
//
// Bdev.Net.Dns by Rob Philpott, Big Developments Ltd. Please send all bugs/enhancements to
// rob@bigdevelopments.co.uk This file and the code contained within is freeware and may be
// distributed and edited without restriction.
//
#endregion
using System;
using Bdev.Net.Dns.Records;
namespace Bdev.Net.Dns
{
/// <summary>
/// Represents a Resource Record as detailed in RFC1035 4.1.3
/// </summary>
[Serializable]
public class ResourceRecord : IEquatable<ResourceRecord>
{
/// <summary>
/// Construct a resource record from a pointer to a byte array
/// </summary>
/// <param name="pointer">the position in the byte array of the record</param>
internal ResourceRecord(Pointer pointer)
{
// extract the domain, question type, question class and Ttl
Domain = pointer.ReadDomain();
Type = (DnsType) pointer.ReadShort();
Class = (DnsClass) pointer.ReadShort();
Ttl = pointer.ReadInt();
// the next short is the record length, we only use it for unrecognized record types
int recordLength = pointer.ReadShort();
// and create the appropriate RDATA record based on the dnsType
switch (Type)
{
case DnsType.NS:
Record = new NSRecord(pointer);
break;
case DnsType.MX:
Record = new MXRecord(pointer);
break;
case DnsType.ANAME:
Record = new ANameRecord(pointer);
break;
case DnsType.CNAME:
Record = new CNameRecord(pointer);
break;
case DnsType.SOA:
Record = new SoaRecord(pointer);
break;
case DnsType.TXT:
Record = new TXTRecord(pointer, recordLength);
break;
default:
{
// move the pointer over this unrecognized record
pointer.Seek(recordLength);
break;
}
}
}
// read only properties applicable for all records
public string Domain { get; }
public DnsType Type { get; }
public DnsClass Class { get; }
public int Ttl { get; }
public RecordBase Record { get; }
public bool Equals(ResourceRecord other)
{
return other != null && Type.Equals(other.Type) && Class.Equals(other.Class) &&
Domain.Equals(other.Domain) &&
Record.Equals(other.Record);
}
}
// Answers, Name Servers and Additional Records all share the same RR format
[Serializable]
public class Answer : ResourceRecord
{
internal Answer(Pointer pointer) : base(pointer)
{
}
}
[Serializable]
public class NameServer : ResourceRecord
{
internal NameServer(Pointer pointer) : base(pointer)
{
}
}
[Serializable]
public class AdditionalRecord : ResourceRecord
{
internal AdditionalRecord(Pointer pointer) : base(pointer)
{
}
}
}
|
Python
|
UTF-8
| 145 | 2.9375 | 3 |
[] |
no_license
|
s = int(input())
n = [1,0,0]
if s < 3:
print(n[s])
else:
for i in range(s-2):
n.append(n[-1]+n[-3])
print((n[-1])%1000000007)
|
Go
|
UTF-8
| 487 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
package slash
import (
"fmt"
"github.com/nlopes/slack"
)
type SlackMessageError struct {
*slack.Msg
}
func NewSlackMessageError(text string) *SlackMessageError {
return &SlackMessageError{
&slack.Msg{
ResponseType: "ephemeral",
Text: text,
},
}
}
func NewSlackMessageErrorf(format string, tokens ...interface{}) *SlackMessageError {
return NewSlackMessageError(fmt.Sprintf(format, tokens...))
}
func (s *SlackMessageError) Error() string {
return s.Text
}
|
Python
|
UTF-8
| 352 | 4.125 | 4 |
[] |
no_license
|
def bubble_sort(array: list):
length = len(array)
x = 0
while x < length:
for i in range(length - 1):
if array[i] > array[i+1]:
array[i+1], array[i] = array[i], array[i+1]
else:
pass
x += 1
return array
print(bubble_sort([6, 5, 3, 1, 8, 7, 2, 4]))
|
Java
|
UTF-8
| 162 | 1.953125 | 2 |
[] |
no_license
|
package com.github.kayvannj.permission_utils;
public abstract class Func {
/* access modifiers changed from: protected */
public abstract void call();
}
|
C++
|
UTF-8
| 391 | 3.015625 | 3 |
[] |
no_license
|
#ifndef _USERS_H_
#define _USERS_H_
#include <string.h>
class User
{
public:
User(){}
User(char*, char*);
//重载 "==" 运算符
bool operator ==(const User& u) const{
if(!strcmp(userName, u.userName)
&& !strcmp(password, u.password))
return true;
return false;
}
private:
char userName[20];
char password[20];
};
#endif
|
C
|
UTF-8
| 5,460 | 2.59375 | 3 |
[] |
no_license
|
/*
* sapi.c
*
* Created on: May 7, 2021
* Author: wels
*/
#include "main.h"
#include "sapi.h"
tick_t tickCounter = 0;
extern UART_HandleTypeDef huart2;
//Función Inicializa los periféricos
void boardInit(void){
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
}
void Delays_NB(void){
delay_ms(&MEF_Normal,TIEMPO_NORMAL);
delay_ms(&MEF_Lento,TIEMPO_LENTO);
delay_ms(&MEF_Rapido,TIEMPO_RAPIDO);
delay_ms(&MEF_Boton,TIEMPO_BOTON);
}
//Delay No Bloqueante
/*
* -> void delay_ms(delay_t * delay,tick_t duration) : Función para crear el delay y la duración
* -> bool_t delayRead(delay_t * delay) : Lee si el retardo se efectuó
* */
void delay_ms(delay_t * delay,tick_t duration){
delay->duration = duration/1;
delay->running = 0;
}
bool_t delayRead(delay_t * delay){
bool_t timeArrived = 0;
if( !delay->running ) {
delay->startTime = tickRead();
delay->running = 1;
}
else {
if ((tick_t)(tickRead()-delay->startTime) >= delay->duration ) {
timeArrived = 1;
delay->running = 0;
}
}
return timeArrived;
}
//Delay Bloqueante
/*
* -> void tickRead(void) : Retorna el valor tickCounter del Callback Timer 11
* -> void tickWrite(uint16_t ticks) : Escribe el valor tick en tickCounter
* -> void delay(uint16_t ticks) : Función retardo
* */
uint16_t tickRead(void){
return tickCounter;
}
void tickWrite(uint16_t ticks){
tickCounter = ticks;
}
void delay(uint16_t ticks){
uint16_t tiempo = 0;
tiempo = tickRead();
while((tickRead() - tiempo) <= ticks);
tickWrite(0);
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 4;
RCC_OscInitStruct.PLL.PLLN = 84;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B0_Pin */
GPIO_InitStruct.Pin = B0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B0_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : LED0_Pin */
GPIO_InitStruct.Pin = LED0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(LED0_GPIO_Port, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
|
Java
|
UTF-8
| 741 | 3.25 | 3 |
[] |
no_license
|
import java.awt.Color;
import java.awt.Point;
public class ShapeFactory {
public myShape create(String shape,Point start,Point end,Color strokeColor,Color fillColor,float stroke) {
if (shape.equals("line")) {
return new Line(shape,start,end,strokeColor,fillColor,stroke);
} else if (shape.equals("rectangle")) {
return new Rectangle(shape,start,end,strokeColor,fillColor,stroke);
} else if (shape.equals("circle")) {
return new Circle(shape,start,end,strokeColor,fillColor,stroke);
} else if (shape.equals("ellipse")) {
return new Ellipse(shape,start,end,strokeColor,fillColor,stroke);
} else if (shape.equals("square")) {
return new Square(shape,start,end,strokeColor,fillColor,stroke);
}
return null;
}
}
|
Shell
|
UTF-8
| 5,668 | 4.34375 | 4 |
[] |
no_license
|
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
BLUE=$(tput setaf 4)
RESET=$(tput sgr0)
SOURCE="${BASH_SOURCE[0]}"
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" >/dev/null && pwd)"
debug() {
echo "${BLUE}DEBUG:${RESET} $*"
}
info() {
echo "${GREEN}INFO:${RESET} $*"
}
error() {
echo "${RED}ERROR:${RESET} $*" >&2
}
usage() {
echo "Usage: $0 [--help] [--input INPUT] [--output-dir OUTPUT]"
echo
echo "Convert labeled WKT of the form"
echo
echo " some-label: POLYGON((...))"
echo " some-label: POINT(...)"
echo
echo "or unlabeled WKT with one geometry per line to CSV files of the form"
echo
echo " some-label.polygon.csv:"
echo " geometry,label"
echo " \"POLYGON((...))\",\"some-label\""
echo " some-label.point.csv:"
echo " geometry,label"
echo " \"POINT(...)\",\"some-label\""
echo
echo "This allows for easily generating QGIS project layers with commandline-tooling"
echo
echo " --help, -h Show this help and exit"
echo " --input, -i INPUT The input file to read the labeled WKT from. Defaults to stdin"
echo " --output-dir, -o OUTPUT The directory to output the generated CSV files in. Defaults to CWD"
echo
echo "NOTE: This tool will happily append to any existing CSV layer files in the OUTPUT directory"
}
get_geometry_type() {
local geometry="$1"
echo "$geometry" | grep --only-matching --extended-regexp '^[a-zA-Z]+' | tr '[:upper:]' '[:lower:]'
}
filter_wkt() {
local input="$1"
echo "$input" | "$SCRIPT_DIR/filter-wkt.sh" || true
}
parse_feature_from_line() {
local line="$1"
# An associative array passed as a nameref. Contains the keys: "geometry", "label", and
# "layer_type" if the given line was successfully parsed, empty otherwise.
local -n feature="$2"
local geometry
local layer_type
local label
local -a parts
IFS=':' read -ra parts <<<"$line"
if [[ "${#parts[@]}" -eq 1 ]]; then
label="unlabeled"
geometry="${parts[0]}"
elif [[ "${#parts[@]}" -eq 2 ]]; then
label="${parts[0]}"
geometry="${parts[1]}"
else
error "Unexpected number of :'s in '$line'"
return
fi
geometry="$(filter_wkt "$geometry")"
if [[ -z "$geometry" ]]; then
error "Failed to extract a WKT geometry from '$line'"
return
fi
set +o errexit
layer_type="$(get_geometry_type "$geometry")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
error "Failed to parse geometry type from '$geometry'"
# Don't exit, because we want to just ignore invalid inputs
return
fi
set -o errexit
# Too verbose for nominal use
# debug "Parsed layer type='$layer_type' from geometry='$geometry'"
feature[geometry]="$geometry"
feature[label]="$label"
feature[layer_type]="$layer_type"
}
slugify() {
local input="$1"
echo "$input" | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | tr '[:upper:]' '[:lower:]'
}
shellquote() {
local input="$1"
# using %q also escapes spaces and parentheses, but double quotes are the only thing we need to
# escape.
printf '%q' "$input" | sed -E 's|\\([^"])|\1|g'
echo
}
create_layer_file_if_not_exists() {
local layer_filename="$1"
if [[ ! -f "$layer_filename" ]]; then
info "Creating $layer_filename..."
echo "geometry,label" >"$layer_filename"
fi
}
append_feature_to_layer() {
local layer_filename="$1"
# shellcheck disable=SC2178
local -n feature="$2"
local geometry
geometry="$(shellquote "${feature[geometry]}")"
local label
label="$(shellquote "${feature[label]}")"
echo "\"$geometry\",\"$label\"" >>"$layer_filename"
}
add_line_to_layer() {
local line="$1"
local output_dir="$2"
local -A parsed_feature
parse_feature_from_line "$line" parsed_feature
# Don't log errors here; log them at the source of the error, so that they have more contextual
# meaning
if [[ ! "${parsed_feature[geometry]+_}" ]]; then
return
elif [[ ! "${parsed_feature[label]+_}" ]]; then
return
elif [[ ! "${parsed_feature[layer_type]+_}" ]]; then
return
fi
local layer_name="${parsed_feature[label]}"
local layer_type="${parsed_feature[layer_type]}"
layer_name="$(slugify "$layer_name")"
if [[ -z "$layer_name" ]]; then
layer_name="$layer_type"
else
layer_name="$layer_name.$layer_type"
fi
local layer_filename="$output_dir/$layer_name.csv"
create_layer_file_if_not_exists "$layer_filename"
append_feature_to_layer "$layer_filename" parsed_feature
}
wkt2csv() {
local input="$1"
local output_dir="$2"
if [[ ! -d "$output_dir" ]]; then
info "Creating directory '$output_dir'..."
mkdir -p "$output_dir"
fi
while read -r line; do
add_line_to_layer "$line" "$output_dir"
done <"$input"
}
main() {
local input="/dev/stdin"
local output_dir="."
while [[ $# -gt 0 ]]; do
case "$1" in
--help | -h)
usage
exit 0
;;
--input | -i)
input="$2"
shift
;;
--output | --output-dir | -o)
output_dir="$2"
shift
;;
*)
error "Unexpected option: $1"
usage >&2
exit 1
;;
esac
shift
done
wkt2csv "$input" "$output_dir"
}
main "$@"
|
C
|
UTF-8
| 6,844 | 3.3125 | 3 |
[] |
no_license
|
struct{
int id;
char name[51];
char lastname[51];
float salary;
int sector;
int isEmpty;
}typedef eEmployee;
struct{
int id;
char description[30];
}typedef eSector;
/** \brief funcion para mostrar el menu del ABM
*
* \return un int (opcion a ejecutar del menu)
*
*/
int menuABM (void);
/** \brief funcion para inicializar empleados
*
* \param list la estructura de empleados
* \param len el tamanio del array de estructuras
* \return int 0 para indicar que se iniciaron correctamente los empleados
*
*/
void initEmployees (eEmployee* list, int len);
/** \brief funcion para buscar espacio libre
*
* \param list la estructura de empleados
* \param len el tamanio del array de estructuras
* \return indice libre para ingresar empleado
*
*/
int findEmpty (eEmployee* list, int len);
/** \brief funcion de genera un numero random entro 1000 y 1999
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return int el numero random para utilizar como id
*
*/
int randomId(eEmployee* list, int len);
/** \brief funcion para encontrar un empleado por su id
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return int la posicion del empleado si lo encuentra o -1 si no lo encuentra
*
*/
int findEmployeeById (eEmployee* list, int len, int id);
/** \brief funcion para darle baja logica al empleado
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param el id del empleado para su buscarlo y darle baja logica
* \return int -1 si no pudo dar de baja y 0 si logro dar de baja
*
*/
int removeEmployee (eEmployee* list, int len, int id);
/** \brief funcion para agregar empleado
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return void
*
*/
void addEmployee (eEmployee* list, int len);
/** \brief funcion para imprimir empleado
*
* \param sectors la estructura de sectores
* \param len int el tamanio del array de estructuras
* \param la estructura de un empleado a mostrar
* \return void
*
*/
void printEmployee (eSector* sectors, int lenSec, eEmployee emp);
/** \brief funcion para recorrer el array de estructuras de empleado e imprimirlos
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param sectors la estructura de sectores
* \param len int el tamanio del array de estructuras
* \return void
*
*/
void printEmployees (eEmployee* list, int len, eSector* sectors, int lenSec);
/** \brief funcion para encontrar si el sector solicitados esta entre los disponibles
*
* \param sectors la estructura de sectores
* \param len int el tamanio del array de estructuras
* \param id del sector a buscar
* \param descripcion del sector
* \return 0 si no lo encrontro y 1 si lo logro encontrar
*
*/
int findSector (eSector* sectors, int lenSec, int idSector, char desc[]);
/** \brief funcion para ordenar empleados por orden ascendente o descendente
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param la opcion de orden que quiere hacer
* \return void
*
*/
void sortEmpleyees (eEmployee* list, int len, int order);
/** \brief funcion para burbujeo de estructuras
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param int del indice a cambiar
* \param int del indice a cambiar
* \return void
*
*/
void bubble (eEmployee* list, int len, int i, int j);
/** \brief funcion para saber si el array esta vacio o no
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return int -1 si no esta vacio y 0 si esta vacio
*
*/
int isEmpty (eEmployee* list, int len);
/** \brief funcion para obtener el salario total de los empleados
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return float el salario total de todos los empleados
*
*/
float totalSalary (eEmployee* list, int len);
/** \brief funcion para obtener el promedio de salario de todos los empleados
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return float el salario promedio de todos los empleados
*
*/
float averageSalary (eEmployee* list, int len);
/** \brief funcion para obtener cuantos empleados superar el salario promedio
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return int cantidad de empleados que superan el salario promedio
*
*/
int higherAverage (eEmployee* list, int len);
/** \brief funcion para obtener el total de empleados activos
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \return int cantidad de empleados activos
*
*/
int getEmployees (eEmployee* list, int len);
/** \brief funcion menu de informes de empleados
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param sectors la estructura de sectores
* \param len int el tamanio del array de estructuras
* \return void
*
*/
void reports (eEmployee* list, int len, eSector* sectors, int lenSec);
/** \brief funcion de menu de cambios
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param id del empleado a cambiar
* \return void
*
*/
void changesMenu (eEmployee* list, int len, int id);
/** \brief funcion para cambiar nombre
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param id del empleado a cambiar
* \return void
*
*/
void changeName (eEmployee* list, int len, int id);
/** \brief funcion para cambiar apellido
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param id del empleado a cambiar
* \return void
*
*/
void changeLastname (eEmployee* list, int len, int id);
/** \brief funcion para cambiar salario
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param id del empleado a cambiar
* \return void
*
*/
void changeSalary (eEmployee* list, int len, int id);
/** \brief funcion para cambiar sector
*
* \param list eEmployee* la estructura de empleados
* \param len int el tamanio del array de estructuras
* \param id del empleado a cambiar
* \return void
*
*/
void changeSector (eEmployee* list, int len, int id);
|
PHP
|
UTF-8
| 5,393 | 2.765625 | 3 |
[] |
no_license
|
<?php
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
require_once "src/Cuisine.php";
require_once "src/Restaurant.php";
$DB = new PDO('pgsql:host=localhost;dbname=restaurants_test');
class CuisineTest extends PHPUnit_Framework_TestCase
{
protected function tearDown()
{
Cuisine::deleteAll();
}
function test_getFoodType()
{
//Arrange
$food_type = "Pizza";
$id = null;
$test_Cuisine = new Cuisine($food_type, $id);
//Act
$result = $test_Cuisine->getFoodType();
//Assert
$this->assertEquals($food_type, $result);
}
function test_setFoodType()
{
//Arrange
$food_type = "Soup";
$id = null;
$test_Cuisine = new Cuisine($food_type, $id);
$test_Cuisine->save();
//Act
$test_Cuisine->setFoodType("Bread");
$result = $test_Cuisine->getFoodType();
//Assert
$this->assertEquals($result, "Bread");
}
function test_getId()
{
//Arrange
$food_type = "Pizza";
$id = 1;
$test_Cuisine = new Cuisine($food_type, $id);
//Act
$result = $test_Cuisine->getId();
//Assert
$this->assertEquals(1, $result);
}
function test_setId()
{
//Arrange
$food_type = "Mexican";
$id = null;
$test_Cuisine = new Cuisine($food_type, $id);
//Act
$test_Cuisine->setId(2);
$result = $test_Cuisine->getId();
//Assert
$this->assertEquals(2, $result);
}
function test_getAll()
{
//Arrange
$food_type1 = "Mexican";
$id1 = null;
$food_type2 = "Pizza";
$id2 = null;
$test_Cuisine1 = new Cuisine($food_type1, $id1);
$test_Cuisine1->save();
$test_Cuisine2 = new Cuisine($food_type2, $id2);
$test_Cuisine2->save();
//Act
$result = Cuisine::getAll();
//Assert
$this->assertEquals([$test_Cuisine1, $test_Cuisine2], $result);
}
function test_save()
{
//Arrange
$food_type = "Food truck";
$id = null;
$test_Cuisine = new Cuisine($food_type, $id);
$test_Cuisine->save();
//Act
$result = Cuisine::getAll();
//Assert
$this->assertEquals($test_Cuisine, $result[0]);
}
function test_deleteAll()
{
//Arrange
$food_type1 = "Mexican";
$id1 = null;
$food_type2 = "Pizza";
$id2 = null;
$test_Cuisine1 = new Cuisine($food_type1, $id1);
$test_Cuisine1->save();
$test_Cuisine2 = new Cuisine($food_type2, $id2);
$test_Cuisine2->save();
//Act
Cuisine::deleteAll();
$result = Cuisine::getAll();
//Assert
$this->assertEquals([], $result);
}
function test_find()
{
//Arrange
$food = "Noodle";
$id = 1;
$food2 = "Soup";
$id2=2;
$test_Cuisine = new Cuisine($food, $id);
$test_Cuisine->save();
$test_Cuisine2 = new Cuisine($food2, $id2);
$test_Cuisine2->save();
//Act
$result = Cuisine::find($test_Cuisine->getId());
//Assert
$this->assertEquals($test_Cuisine, $result);
}
function test_updateType()
{
//Arrange
$food_type = "Japanese";
$id = 1;
$test_cuisine = new Cuisine ($food_type, $id);
$test_cuisine->save();
$new_food_type = "Chinese";
//Act
$test_cuisine->updateType($new_food_type);
//Assert
$this->assertEquals("Chinese", $test_cuisine->getFoodType());
}
function testDeleteCusine()
{
//Arrange
$cuisine = "Prime Steak";
$id = 1;
$test_cuisine = new Cuisine($cuisine, $id);
$test_cuisine->save();
$cuisine2 = "Lobster";
$id2=2;
$test_cuisine2 = new Cuisine($cuisine2, $id2);
$test_cuisine2->save();
//Act
$test_cuisine->delete();
//Assert
$this->assertEquals([$test_cuisine2], Cuisine::getAll());
}
function testDeleteCuisineTypeFromRestaurant()
{
//Arrang
$cuisine = "Sea Crab";
$id = null;
$test_cuisine = new Cuisine($cuisine, $id);
$test_cuisine->save();
$restaurant = "Mom Kitchen";
$cuisine_id = $test_cuisine->getId();
$test_restaurant = new Restaurant($id, $restaurant, $cuisine_id);
$test_restaurant->save();
//Act
$test_cuisine->delete();
//Assert
$this->assertEquals([], Restaurant::getAll());
}
}
?>
|
Java
|
UTF-8
| 2,753 | 2.5625 | 3 |
[] |
no_license
|
package com.sreekanth.duelist;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class Agecalc extends Activity implements OnClickListener {
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
private TextView tv;
String birthdate;
DateTime FUP1cdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agecalc);
// mDateButton = (Button) findViewById(R.id.date_button);
tv = (TextView) findViewById(R.id.textView1);
ib = (ImageButton) findViewById(R.id.imageButton1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) findViewById(R.id.editText);
ib.setOnClickListener(this);
}
@Override
public void onClick(View v) {
showDialog(0);
}
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
birthdate = selectedDay + "/" + (selectedMonth + 1) + "/"
+ selectedYear+" 00:00:00";
try {
FUP1cdate = new DateTime(dateformat.parse(birthdate));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateTime now = new DateTime();
Period period = new Period(FUP1cdate, now, PeriodType.yearMonthDay());
//Now access the values as below
int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();
if (days > 15){
months=months+1;
}
if (months > 6){
years = years +1;
}
tv.setText("Result : " +period.getYears() + " Years "+ period.getMonths() + " Months "+period.getDays() + " Days " +"\n"
+ "Age Near Birthday " + years);
};
};
}
|
Java
|
UTF-8
| 596 | 3.328125 | 3 |
[] |
no_license
|
package lv.javaguru.workshops.streams.t0_ananonymousclasses;
import lv.javaguru.workshops.streams.code.User;
import java.time.LocalDateTime;
public class A1_AnonymousImmutableClassExample {
/**
* TODO :
* create object of anonymous class which
* extends class User and overrides method
* getNickname().
* Use nickname "john" in constructor but
* getNickname should return value "nick"
*/
public static void main(String[] args) {
User user = new User("john", LocalDateTime.now(), true);
System.out.println(user.getNickname());
}
}
|
C
|
UTF-8
| 347 | 3.4375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
int main(){
int sum = 0;
for (int i = 100; i <= 200; i++)
{
int j = 0;
for ( j = 2; j <= i; j++)
{
if (i%j == 0)
{
break;
}
}
if (j == i){
sum++;
printf("%d ", i);
}
}
printf("\n");
printf("100µ½200Ö®¼ä×ܹ²ÓÐ%d¸öËØÊý", sum);
getchar();
return 0;
}
|
Python
|
UTF-8
| 391 | 3.21875 | 3 |
[] |
no_license
|
#!/usr/bin/python
m = 100 #have user input
a = [0] * (m + 1)
#base cases
a[1] = 1 # one black
a[2] = 2 # two black, one red
a[3] = 4 # black/red, red/black, green, 3black
a[4] = 8 # red/red, red/black/black, black/black/red, black/red/black, green/black, black/green, blue, 4 black
for i in range(5,m + 1):
a[i] = a[i - 1] + a[i - 2] + a[i - 3] + a[i - 4]
total = a[-1]
print total
|
JavaScript
|
UTF-8
| 1,436 | 3.140625 | 3 |
[] |
no_license
|
jQuery(document).ready(function() {
//tabs change on click
$( function() {
$( "#highseastabs" ).tabs();
} );
//tabs change on mouseover
$( function() {
$( "#sunnyscapetabs" ).tabs({
event:"mouseover"
});
});
var btn = document.getElementById("subBtn");
btn.onclick = sendMsg;
function sendMsg() {
var userInput = window.prompt("What is the last number in your postal code? (0-9)");
if (isNaN(userInput)) {
window.alert("That is not a Number. Please enter a number between 0 and 9.");
document.getElementById("closestLoc").innerHTML = "Ask me your closest location again." ;
}
else if (userInput === null || userInput === "") {
window.alert("That's not a number. Enter a number.");
document.getElementById("closestLoc").innerHTML = "Ask me your closest location again." ;
}
else if (userInput <= 5) {
document.getElementById("closestLoc").innerHTML = "Your closest location is High Seas" ;
}
else if (userInput >5 && userInput <=9 ) {
document.getElementById("closestLoc").innerHTML = "Your closest location is Sunnyscape" ;
}
else {
document.getElementById("closestLoc").innerHTML = "Invalid number. Ask me your closest location again." ;
}
}
}); //END OF .ready FUNCTION
|
Markdown
|
UTF-8
| 547 | 2.953125 | 3 |
[] |
no_license
|
# Week 8 - Day 1
> **Agenda:** Simple ES6 Modules
## 50 Shades Demo
This project is designed to show the problem with global variables. It has a variable called bookInfo that contains information about the book.
To change the book price:
* Load the page
* Open chrome console
* Type: ```bookInfo.price = 0.01```
## Build out the 50 Shades Project with modules
* Create `javascripts/helpers/book.js` with the book info
* Import that into main.js and show how you can get stuff from other files
* Create store component
* Create cart component
|
C
|
UTF-8
| 5,621 | 3.515625 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include "../include/Errors.h"
#include "../include/Node.h"
#include "../include/Heap.h"
int heap_test()
{
// Heap tests.
Heap* test_heap = NULL;
int err = 0;
Node* tmp = NULL;
if (err = heap_init(&test_heap))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
if (err = node_init(&tmp,-1,-1))
printf("ERROR: %d\n", err);
tmp->priority = 9.5;
if (err = heap_insert_min(test_heap,tmp))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
else
printf("min: %f\n", tmp->priority);
if (err = node_init(&tmp,-1,-1))
printf("ERROR: %d\n", err);
tmp->priority = 7.9;
if (err = heap_insert_min(test_heap,tmp))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
else
printf("min: %f\n", tmp->priority);
if (err = node_init(&tmp,-1,-1))
printf("ERROR: %d\n", err);
tmp->priority = 8.7;
if (err = heap_insert_min(test_heap,tmp))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
else
printf("min: %f\n", tmp->priority);
if (err = heap_delete_min(test_heap))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
else
printf("min: %f\n", tmp->priority);
if (err = heap_delete_min(test_heap))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
else
printf("min: %f\n", tmp->priority);
if (err = heap_delete_min(test_heap))
printf("ERROR: %d\n", err);
if (err = heap_find_min(test_heap, &tmp))
printf("ERROR: %d\n", err);
else
printf("min: %f\n", tmp->priority);
if (err = heap_free(&test_heap))
printf("ERROR: %d\n", err);
return SUCCESS;
}
int heap_init(Heap** heap)
{
Heap* new_heap = malloc(sizeof(Heap));
// malloc failed, return error.
if (new_heap == NULL)
return MEMERR;
new_heap->data = NULL;
new_heap->size = 0;
*heap = new_heap;
return SUCCESS;
}
int heap_find_min(Heap* heap, Node** tmp)
{
if (heap == NULL)
return NULLPTR;
// if there is atleast one element in the heap
if (heap->size > 0)
{
*tmp = heap->data[0];
return SUCCESS;
}
// if no elements, return error
return HEAP_EMPTY;
}
int heap_insert_min(Heap* heap, Node* new_node)
{
// increase heap size.
++(heap->size);
// return pointer for realloc
Node** ret_ptr = NULL;
// attempt to increase size of heap->data
ret_ptr = realloc(heap->data, heap->size * sizeof(Node*));
// if realloc failed, decrement size of heap
// heap->data remains unchanged.
// return error
if (ret_ptr == NULL)
{
--(heap->size);
return MEMERR;
}
// realloc successful
else
heap->data = ret_ptr;
if (heap->data == NULL)
return NULLPTR;
int i = 0, p = 0;
// from the last position in the heap.
for (i=(heap->size)-1;i>=0;i=p)
{
// if root node, insert there.
if (i==0)
{
heap->data[0] = new_node;
break;
}
// index of parent node.
p = (i - 1) / 2;
// insert based on priority.
if (heap->data[p]->priority > new_node->priority)
heap->data[i] = heap->data[p];
// correct position found, break and return success
else
{
heap->data[i] = new_node;
break;
}
}
return SUCCESS;
}
int heap_delete_min(Heap* heap)
{
int lc = 0, rc = 0, mn = 0, i =0;
if (heap->data == NULL)
return NULLPTR;
// decrement heap size
--(heap->size);
// start from root
for (i=0;i<(heap->size);)
{
// indices of left and right child in Heap binary tree
lc = 2*i+1;
rc = lc+1;
// if left child exists
if (lc<(heap->size))
{
mn = heap->data[lc]->priority < heap->data[(heap->size)]->priority ? lc : (heap->size);
if (rc<(heap->size))
mn = heap->data[mn]->priority < heap->data[rc]->priority ? mn : rc;
// replace current node with smallest of last, left and right
heap->data[i] = heap->data[mn];
// do the same for the smallest of last, left and right
if (i==mn)
break;
i=mn;
}
// if no children, then insert here.
else
{
heap->data[i] = heap->data[(heap->size)];
break;
}
}
Node** ret_ptr = NULL;
ret_ptr = realloc(heap->data, heap->size * sizeof(Node*));
if (ret_ptr == NULL)
{
// realloc failed, return error.
if (heap->size > 0)
{
++(heap->size);
return MEMERR;
}
// realloc succeded and heap is empty.
heap->data = NULL;
return SUCCESS;
}
// realloc succeded and heap is not empty.
else
heap->data = ret_ptr;
return SUCCESS;
}
int heap_free(Heap** heap)
{
int i = 0, err = 0;
// free each node
for (i=0;i<(*heap)->size;++i)
if (err = node_free((*heap)->data[i]))
return err;
free(*heap);
*heap = NULL;
return SUCCESS;
}
|
Python
|
UTF-8
| 554 | 2.515625 | 3 |
[] |
no_license
|
from balanced_partition import balanced_partition
from nose_xml_reader import read_nose_xml
with open('/tmp/nosetests.xml') as f:
test_result = read_nose_xml(f.read())
p1, p2 = balanced_partition([
(testcase['classname'] + '.' + testcase['name'], testcase['time'])
for testcase in test_result if testcase['status'] == 'ok'
])
p3, p4 = balanced_partition(p1[0])
p5, p6 = balanced_partition(p2[0])
print len(p1[0]), p1[1]
print len(p2[0]), p2[1]
print len(p3[0]), p3[1]
print len(p4[0]), p4[1]
print len(p5[0]), p5[1]
print len(p6[0]), p6[1]
|
JavaScript
|
UTF-8
| 1,803 | 2.828125 | 3 |
[] |
no_license
|
const BADGE_TYPES = {
NUM_CASES_NEWBIE: {
name: 'Newbie',
description: '< 10 Cases'
},
NUM_CASES_NOVICE: {
name: 'Novice',
description: '10 to 25 Cases'
},
NUM_CASES_ROOKIE: {
name: 'Rookie',
description: '25 to 50 Cases'
},
NUM_CASES_INTERMEDIATE: {
name: 'Intermediate',
description: '50 to 100 Cases'
},
NUM_CASES_PROFICIENT: {
name: 'Proficient',
description: '100 to 200 Cases'
},
NUM_CASES_EXPERIENCED: {
name: 'Experienced',
description: '200 to 300 Cases'
},
NUM_CASES_ADVANCED: {
name: 'Advanced',
description: '300 to 400 Cases'
},
NUM_CASES_SENIOR: {
name: 'Senior',
description: '400 to 500 Cases'
},
NUM_CASES_EXPERT: {
name: 'Expert',
description: '500 to 1000 Cases'
},
NUM_CASES_GURU: {
name: 'Guru',
description: '1000+ Cases'
}
};
function getBadgeByNumberOfCases(numberOfCases) {
switch (numberOfCases) {
case numberOfCases < 10:
return BADGE_TYPES.NUM_CASES_NEWBIE;
case numberOfCases < 25:
return BADGE_TYPES.NUM_CASES_NOVICE;
case numberOfCases < 50:
return BADGE_TYPES.NUM_CASES_ROOKIE;
case numberOfCases < 100:
return BADGE_TYPES.NUM_CASES_INTERMEDIATE;
case numberOfCases < 200:
return BADGE_TYPES.NUM_CASES_PROFICIENT;
case numberOfCases < 300:
return BADGE_TYPES.NUM_CASES_EXPERIENCED;
case numberOfCases < 400:
return BADGE_TYPES.NUM_CASES_ADVANCED;
case numberOfCases < 500:
return BADGE_TYPES.NUM_CASES_SENIOR;
case numberOfCases < 1000:
return BADGE_TYPES.NUM_CASES_EXPERT;
case numberOfCases > 1000:
return BADGE_TYPES.NUM_CASES_GURU;
default:
return BADGE_TYPES.NUM_CASES_NEWBIE;
}
}
export { BADGE_TYPES, getBadgeByNumberOfCases };
|
Java
|
UTF-8
| 343 | 2.046875 | 2 |
[] |
no_license
|
package test.testngVsJunit.junit;
import org.junit.Test;
/**
* @author <a href="mailto:joyrap@qq.com">joyrap@qq.com</a>
* @date 7/16/15
*/
public class TestWithException {
@Test(expected = NullPointerException.class)
public void throwNullPointException() {
// throw new NullPointerException();
throw new IllegalArgumentException();
}
}
|
Java
|
UTF-8
| 3,705 | 2.203125 | 2 |
[] |
no_license
|
package co.edu.ufps.petsworld.Administrator;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import co.edu.ufps.petsworld.Administrator.Model.Citas;
import co.edu.ufps.petsworld.Administrator.Model.Veterinarios;
import co.edu.ufps.petsworld.R;
import co.edu.ufps.petsworld.RegistrarCitasActivity;
import co.edu.ufps.petsworld.RegistrarVeterinariosActivity;
import co.edu.ufps.petsworld.SignUpActivity;
public class VeterinariosActivity extends AppCompatActivity {
RecyclerView contenedorVeterinarios;
FloatingActionButton registrarVeterinarios;
VeterinariosAdapter veterinariosAdapter;
private static final String TAG = "VeterinariosActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_veterinarios);
contenedorVeterinarios = findViewById(R.id.contenedorVeterinarios);
veterinariosAdapter = new VeterinariosAdapter(cargarDatosFirebase());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(VeterinariosActivity.this);
contenedorVeterinarios.setLayoutManager(layoutManager);
contenedorVeterinarios.setAdapter(veterinariosAdapter);
registrarVeterinarios = findViewById(R.id.registrarVeterinarios);
registrarVeterinarios.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
registrarVeterinarios();
}
});
}
private void registrarVeterinarios() {
Intent intent = new Intent(this, RegistrarVeterinariosActivity.class);
startActivity(intent);
}
public ArrayList<Veterinarios> cargarDatosFirebase(){
final ArrayList<Veterinarios> veterinarios = new ArrayList<>();
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
// Read from the database
myRef.child("veterinarios").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
if (dataSnapshot.exists()) {
veterinarios.clear();
for (DataSnapshot data : dataSnapshot.getChildren()) {
Veterinarios veterinario = data.getValue(Veterinarios.class);
veterinarios.add(veterinario);
veterinariosAdapter.notifyDataSetChanged();
}
//Log.d(TAG, "Value is: ");
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
return veterinarios;
}
}
|
Shell
|
UTF-8
| 938 | 3.328125 | 3 |
[] |
no_license
|
function sigint() {
echo -n "SIGINT: "
if pkill -P $$ ; then
echo "$0: killed all child processes"
else
echo "$0: Failed to kill child processes"
fi
exit 1
}
trap sigint SIGINT
#workdir=$TMPDIR/harmonic-oscillator
workdir=/data/work/harmonic-oscillator
#workdir=harmonic-oscillator
mkdir -p $workdir/frames{1,2,3}
QR=$workdir/qr
CR=$workdir/cr
QN=$workdir/qn
CN=$workdir/cn
FPS=20
MOVIE_FILE=harmonic-oscillator-solanim.mp4
nproc=$(($(nproc)/3)) # divided by 3 because we create one process for each of the three stages of processing
for ((i=1; i <= $nproc; i++));
do
for ((stage=1; stage <= 3; stage++));
do
./solanim.py -P $nproc -p $i -d $workdir/frames$stage -s ${QR}$stage -s ${CR}$stage -s ${QN}$stage -s ${CN}$stage &
done
done
wait
ffmpeg -loglevel quiet -y -r $FPS -f image2 -pattern_type glob -i $workdir'/frames*/*.png' -f mp4 -q:v 0 -vcodec libx264 -r $FPS $MOVIE_FILE
|
JavaScript
|
UTF-8
| 2,385 | 4.0625 | 4 |
[] |
no_license
|
//
//
//
//
//
//
//
//
/*
let nombre = "Julian"
let apellido = "Fuoco"
let edad = 28
let disp = false
let vestimenta = {
remera: "Nike",
pantalon: "Adiddas"
}
let segundoArray = ["Pepe", 30, true]
//.length
let miPrimerArray = [nombre, apellido, edad, disp, vestimenta, segundoArray, "Hola", 56, 56];
for (i = 0; i < miPrimerArray.length; i++) {
console.log(miPrimerArray[i]);
}
*/
//.push
/*
let numeros = ["ZZZ", "TTT"]
let test = ["Juan", "Pedro", 5, true, "Nicolas"]
console.log(test);
let nuevoTexto = "AAA"
test.push(nuevoTexto)
console.log(test);
test.unshift("BBB")
console.log(test);
let listaNueva = test.concat(numeros)
console.log(listaNueva);
//join()
let pasarDatos = listaNueva.join(",")
console.log(pasarDatos)
*/
/*
let listaOrdenada = listaNueva.sort()
//.slice(1,3)
let recorte = listaOrdenada.slice(0, 3)
console.log(recorte);
*/
class Producto {
constructor(nombre, precio) {
this.nombre = nombre;
this.precio = precio
}
}
const Producto1 = new Producto("Remera", 5000);
const Producto2 = new Producto("Mate", 1000);
const Producto3 = new Producto("Pelota", 1700);
const Producto4 = new Producto("Auto", 15000000);
const Producto5 = new Producto("Mate", 2000);
const Productos = []
Productos.push(Producto1)
Productos.push(Producto2)
Productos.push(Producto3)
Productos.push(Producto4)
Productos.push(Producto5)
//console.log(Productos.find(Producto => Producto.nombre == "Mate"));
/*
let dato = prompt()
let orden1 = Productos.filter(Producto => Producto.nombre == dato)
let ProductosOrdenados = orden1.sort(function(a, b) {
if (a.precio > b.precio) {
return -1;
}
if (a.precio < b.precio) {
return 1;
}
return 0;
});
console.log(ProductosOrdenados);
*/
let objetoPrueba = { nombre: "Juan", apellido: "Martin", edad: 20, fun: function() { return a + b } };
//for in
/*for (const propiedad in objetoPrueba) {
console.log(` ${propiedad} = ${objetoPrueba[propiedad]} esto es for in`);
}
*/
//for of
/*
for (const objeto of Productos) {
for (const propiedad in objeto) {
console.log(` ${propiedad} = ${objeto[propiedad]} esto es for in`);
}
}
*/
//foreach
Productos.forEach(e => { console.log(e.nombre) })
|
Java
|
UTF-8
| 1,251 | 2.21875 | 2 |
[] |
no_license
|
package com.example.prototype2.Room;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
@Dao
public interface PlanDao {
@Query("SELECT * FROM plan_table")
List<Plan> getAll();
@Query("SELECT * FROM plan_table WHERE id IN (:userIds)")
List<Plan> loadAllByIds(int[] userIds);
@Query("SELECT*FROM plan_table WHERE id=:id")
LiveData<Plan> findById(int id);
@Query("SELECT * from plan_table ORDER BY plan_name ASC")
LiveData<List<Plan>> getAlphabetizedWords();
@Insert(onConflict = OnConflictStrategy.IGNORE)
//to insert one plan
void insert(Plan plan);
@Insert
void insertAll(Plan plan);
@Query("DELETE FROM plan_table")
void deleteAll();
@Delete
void deletePlan(Plan plan);
@Update
void updatePlan(Plan plan);
@Query("SELECT*FROM plan_table WHERE year=:year AND month=:month AND day=:day")
LiveData<List<Plan>> getByDate(int year,int month,int day);
@Query("SELECT*FROM plan_table WHERE category =:category")
LiveData<List<Plan>>getByCategory(String category);
}
|
PHP
|
UTF-8
| 3,899 | 3.0625 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete member</title>
</head>
<body>
<?php
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
echo "<pre>"; var_dump($_POST); var_dump($_GET);echo "</pre>";
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
//retrieve the memberid from the URL
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET['id'];
if (empty($id) or !is_numeric($id)) {
echo "<h2>Invalid memberID</h2>"; //simple error feedback
exit;
}
}
/* the data was sent using a form therefore we use the $_POST instead of $_GET
check if we are saving data first by checking if the submit button exists in
the array */
if (isset($_POST['submit']) and !empty($_POST['submit'])
and ($_POST['submit'] == 'Delete')) {
/* validate incoming data - only the first field is done for
you in this example - rest is up to you do*/
$error = 0; //clear our error flag
$msg = 'Error: ';
/* memberID (sent via a form it is a string not a number so we try
a type conversion!) */
if (isset($_POST['id']) and !empty($_POST['id'])
and is_integer(intval($_POST['id']))) {
$id = cleanInput($_POST['id']);
} else {
$error++; //bump the error flag
$msg .= 'Invalid member ID '; //append error message
$id = 0;
}
//save the member data if the error flag is still clear and member id is > 0
if ($error == 0 and $id > 0) {
$query = "DELETE FROM member WHERE memberID=?";
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'i',$id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Member details deleted.</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
}
//locate the member to edit by using the memberID
//we also include the member ID in our form for sending it back for saving the data
$query = 'SELECT * FROM member WHERE memberid='.$id;
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
?>
<h1>Member Detail View</h1>
<h2><a href='listmembers.php'>[Return to the member listing]</a></h2>
<?php
//makes sure we have the member
if ($rowcount > 0) {
echo "<fieldset><legend>Member detail #$id</legend><dl>";
$row = mysqli_fetch_assoc($result);
echo "<dt>Name:</dt><dd>".$row['firstname']."</dd>".PHP_EOL;
echo "<dt>Lastname:</dt><dd>".$row['lastname']."</dd>".PHP_EOL;
echo "<dt>Email:</dt><dd>".$row['email']."</dd>".PHP_EOL;
echo "<dt>Username:</dt><dd>".$row['username']."</dd>".PHP_EOL;
echo "<dt>Password:</dt><dd>".$row['password']."</dd>".PHP_EOL;
echo "<dt>Role:</dt><dd>".$row['role']."</dd>".PHP_EOL;
echo '</dl></fieldset>'.PHP_EOL;
?>
<form method="POST" action="deletemember.php">
<h2>Are you sure you want to delete this member?</h2>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" name="submit" value="Delete">
<a href="listmembers.php">[Cancel]</a>
</form>
<?php
} else echo "<h2>No member found, possibly deleted!</h2>"; //suitable feedback
mysqli_free_result($result); //free any memory used by the query
mysqli_close($DBC); //close the connection once done
?>
</body>
</html>
|
PHP
|
UTF-8
| 2,196 | 2.953125 | 3 |
[
"ISC"
] |
permissive
|
<?php
declare(strict_types=1);
namespace Jarenal\App\Model;
use Exception;
use Jarenal\Core\ModelAbstract;
/**
* Class ProductQueries
* @package Jarenal\App\Model
*/
class ProductQueries extends ModelAbstract
{
/**
* @return array
* @throws Exception
*/
public function findAll(): array
{
try {
$sql = "SELECT * FROM `product`";
$result = $this->database->executeQuery($sql);
$products = [];
while ($row = $result->fetch_object()) {
$categoryQueries = $this->container->get("Jarenal\App\Model\CategoryQueries");
$category = $categoryQueries->findById((int)$row->category_id);
$currentProduct = $this->container->get("Jarenal\App\Model\Product");
$currentProduct->setId((int)$row->id)
->setName($row->name)
->addCategory($category)
->setPrice((float)$row->price)
->setDescription($row->description);
$products[] = $currentProduct;
}
return $products;
} catch (Exception $ex) {
}
}
/**
* @param int $id
* @return Product|null
* @throws Exception
*/
public function findById(int $id): ?Product
{
try {
$sql = "SELECT * FROM `product` WHERE `id`=%s";
$result = $this->database->executeQuery($sql, [$id]);
$row = $result->fetch_object();
if ($row) {
$categoryQueries = $this->container->get("Jarenal\App\Model\CategoryQueries");
$category = $categoryQueries->findById((int)$row->category_id);
$product = $this->container->get("Jarenal\App\Model\Product");
$product->setId((int)$row->id)
->setName($row->name)
->addCategory($category)
->setPrice((float)$row->price)
->setDescription($row->description);
return $product;
} else {
return null;
}
} catch (Exception $ex) {
throw $ex;
}
}
}
|
JavaScript
|
UTF-8
| 897 | 2.84375 | 3 |
[] |
no_license
|
const modalOverlay = document.querySelector('.modal-overlay');
const cards = document.querySelectorAll('.card');
const closeModal = document.querySelector('.close-modal');
cards.forEach(card =>
card.addEventListener('click', () => {
modalOverlay.classList.add('active');
modalOverlay.querySelector('iframe').src = `https://www.youtube.com/embed/${getURL(card)}`;
}))
closeModal.addEventListener('click', () => {
modalOverlay.classList.remove('active');
modalOverlay.querySelector('iframe').src = "";
});
const getURL = (card) => card.querySelector('img').src.split("/")[4];
/*
const infos = [];
cards.forEach(card => {
infos.push([
card.querySelector("img").src,
card.querySelector(".card__content").innerText,
card.querySelector(".card__info").innerText.split("\n")[0],
card.querySelector(".card__info").innerText.split("\n")[2],
])
}
);
console.log(JSON.stringify(infos))
*/
|
Java
|
UTF-8
| 1,748 | 2.34375 | 2 |
[] |
no_license
|
package com.changhong.system.web.facade.assember;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.util.StringUtils;
import com.changhong.common.repository.EntityLoadHolder;
import com.changhong.system.domain.app.AppStrategy;
import com.changhong.system.domain.app.AppStrategyBox;
import com.changhong.system.web.facade.dto.AppStrategyBoxDTO;
public class AppStrategyBoxWebAssember {
public static AppStrategyBox toAppStrategyBoxDomain(AppStrategyBoxDTO dto){
AppStrategyBox appStrategyBox = null;
if(dto==null) return null;
if(StringUtils.hasText(dto.getUuid())){
appStrategyBox = (AppStrategyBox)EntityLoadHolder.getUserDao().findByUuid(dto.getUuid(),AppStrategyBox.class);
appStrategyBox.setMacNumber(dto.getMacNumber());
appStrategyBox.setStrategyUuid(dto.getStrategyUuid());
}else
appStrategyBox = new AppStrategyBox(dto.getStrategyUuid(), dto.getMacNumber());
return appStrategyBox;
}
public static AppStrategyBoxDTO toAppStrategyBoxDTO(AppStrategyBox appStrategyBox){
String uuid = appStrategyBox.getUuid();
String strategyUuid = appStrategyBox.getStrategyUuid();
String macNumber = appStrategyBox.getMacNumber();
AppStrategyBoxDTO appStrategyBoxDTO = new AppStrategyBoxDTO(uuid, strategyUuid, macNumber);
return appStrategyBoxDTO;
}
public static List<AppStrategyBoxDTO> toAppStrategyBoxDTOList(List<AppStrategyBox> appStrategyBoxs){
List<AppStrategyBoxDTO> dtos = new ArrayList<AppStrategyBoxDTO>();
if(appStrategyBoxs!=null){
for(AppStrategyBox loop:appStrategyBoxs){
dtos.add(toAppStrategyBoxDTO(loop));
}
}
return dtos;
}
}
|
C
|
UTF-8
| 4,288 | 2.734375 | 3 |
[] |
no_license
|
#ifndef PROC_H
#define PROC_H
#include "../settings.h"
/**
* @brief show Proc status
*/
enum cpuState : char {
OFF = 0,
ASSEMBLING,
EXECUTE,
BROKEN
};
/**
* @brief errors in stack funcions
*
* @param line ptr to string begin
* @param strlen number of letters in string
*/
enum StackError : char {
// [ ########### GENERAL ############ ]
noErr = 0,
// [ ############ STACK ############# ]
badCap = 1 << 2,
badSz = 1 << 3,
dataErr = 1 << 4,
structPtrErr = 1 << 5
};
/**
* @brief errors in proc funcions
*
* @param line ptr to string begin
* @param strlen number of letters in string
*/
enum class EXECUTE_ERROR : char {
noErr = 0,
// [ FUNC ]
argErr,
// [ PROC STRUCT ]
ramNullptr,
ramOverflow,
// [ STACK ERRORS ]
stackNullptr,
StackOverflow,
stackEmpty,
// [ STACK ERRORS ]
codeNullptr,
regNullptr,
badSntx,
// [ RUNTIME PROCESS ]
commandsOverflow
};
#include "../stack/stack.h"
#include "../asm/asm.h"
// [ ############## STRUCTS ################ ]
/**
* @brief memory struct. In CPU_32 we use like a RAM
*
* @param data ptr to proc data
* @param index index of element in data
*/
struct Mem {
char *data;
size_t index;
};
/**
* @brief we set what follow to funcion in DSL
*
* @param w_... = [ w.ith_ {Adres, Value, Registerб Label} ]
*/
struct{
unsigned char wArgVal:5;
unsigned char wVal:1;
unsigned char wReg:1;
unsigned char wLab:1;
} cmdFlags;
/**
* @brief CPU_32 struct
*
* @param state :: status of work CPU_32 DECLARED in M_CPUx32.h as enum
* @param ram :: RAM structure DECLARED in M_CPUx32.h as struct
* @param stack :: stack structure DECLARED in ../stack/stack.h as struct
*
* @param code :: pointer to executecode
* @param reg :: reg struct DECLARED in M_CPUx32.h
* @param ip :: executeble code index
*/
struct CPU_32 {
size_t state = -1;
Mem ram = {};
Stack stack = {};
char* code = nullptr;
float reg[NREGS] = {};
int ip = {};
};
// [ ######## DEFINES ################################### ]
#define NEXTIP prt + 1
#define NOERR 0
#define ARGPTR argument
#define ARG (*ARGPTR)
#define PRINTF(arg) printf("OUT: %d", arg)
#define HLT return EXECUTE_ERROR::noErr
#define JMP(arg) prt += arg
#define JMP_ABS(arg) prt = arg
#define SCANF(argptr) scanf("%d ", argptr)
#define OUTC(arg) printf("%c", (char)arg);
#define PAUSE getchar();
#define SLEEP(arg) tsleep(arg);
// #### [ SUBORDINARY ################################ ]
/**
* @brief CPU_Introduce CPU_32 program
*/
void CP_Intro();
/**
* @brief stop program work in small period of time
*
* @param time value of stop period
*/
void Tsleep(int time);
/**
* @brief slow putting chars of string [use tsleep to do it]
*
* @param line ptr to string begin
* @param strlen number of letters in string
*/
void SlowLine(char *line, size_t strlen);
/**
* @brief slow erase after string pring
*
* @param strlen number of symbols that we want to dell
*/
void SlowErase(char *line, size_t strlen);
/**
* @brief calloc RAM and watch if smth went wrong
*
* @param ram RAM of proc
*/
EXECUTE_ERROR RAM_Init(Mem* ram);
/**
* @brief calloc stackData and watch if smth went wrong
*
* @param ram stack of proc
*/
EXECUTE_ERROR stackInit(Stack* stack);
// [ #### PREPARING ################################## ]
/**
* @brief load the program for CPU_32 & watch if smt went wrong
*
* @param proc struct of proc
* @param exe_txt name of program
* @param ASM_DATA assembler struct
*/
EXECUTE_ERROR CP_Compile_Txt(CPU_32 *proc, char *exe_txt, ASM_DATA *asmData);
/**
* @brief load the program for CPU_32 & watch if smt went wrong
*
* @param proc struct of proc
*/
EXECUTE_ERROR CP_DataCtor(CPU_32 *proc);
// [ #### EXECUTING ################################## ]
/**
* @brief load the program for CPU_32 & watch if smt went wrong
*
* @param proc struct of proc
*/
EXECUTE_ERROR Execute(FILE *bexe, CPU_32 *proc, size_t fsize);
#endif//PROC_H
|
Shell
|
UTF-8
| 171 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
#saving the given text file as a variable
text=$1
#grabbing the html stuff
bits=$2
#target file name
target=$3
cat $2_header.html $1 $2_footer.html > $target
|
Python
|
UTF-8
| 875 | 2.78125 | 3 |
[] |
no_license
|
import RPi.GPIO as GPIO
import time
dac = [26, 19, 13, 6, 5, 11, 9, 10]
bits = len(dac)
levels = 2 ** bits
max_voltage = 3.3
def decimal_to_binary(number):
return [int(i) for i in bin(number)[2:].zfill(len(dac))]
def decimal_to_dac(value):
signal = decimal_to_binary(value)
GPIO.output(dac, signal)
return signal
GPIO.setmode(GPIO.BCM)
GPIO.setup(dac, GPIO.OUT, initial = GPIO.LOW)
try:
while True:
for i in range(256):
decimal_to_dac(i)
time.sleep(0.002)
print(i)
for i in range(254, 0, -1):
decimal_to_dac(i)
time.sleep(0.002)
print(i)
except KeyboardInterrupt:
print('The program was stopped by the keyboatd')
else:
print('No exceptions')
finally:
GPIO.output(dac, GPIO.LOW)
GPIO.cleanup(dac)
print('Cleanup completed')
|
Java
|
UTF-8
| 1,498 | 2.078125 | 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 pe.com.syscenterlife.dao.venta;
import java.util.List;
import org.springframework.stereotype.Repository;
import pe.com.syscenterlife.SysDataAccess;
import pe.com.syscenterlife.modelo.VentClientes;
/**
*
* @author edwil
*/
@Repository
public class VclientesDaoImpl extends SysDataAccess<Integer, VentClientes> implements VclientesDaoI{
@SuppressWarnings("unchecked")
@Override
public List<VentClientes> listarEntidad() {
return getListAll(); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<VentClientes> listarEntidadDato(String dato) {
return (List<VentClientes>)sessionFactory.getCurrentSession()
.createQuery("SELECT p from VentClientes p WHERE CONCAT(p.idventa,' ', p.idMovVnt) LIKE ?1 ")
.setParameter(1, "%"+dato+"%")
.list();
}
@Override
public VentClientes buscarEntidadId(int id) {
return getById(id);
}
@Override
public void guardarEntidad(VentClientes vclientes) {
savev(vclientes);
}
@Override
public void eliminarEntidad(int id) {
delete(id);
}
@Override
public void modificarEntidad(VentClientes vclientes) {
update(vclientes);
}
}
|
C
|
UTF-8
| 1,431 | 3.40625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <error.h>
void *clean(void *arg)
{
printf("cleanup:%s \n",(char *)arg);
return (void *)0;
}
void * thr_fn1(void *arg)
{
printf("thread 1 start \n");
pthread_cleanup_push((void*)clean,"thread 1 first handler");
pthread_cleanup_push((void*)clean,"thread 1 second handler");
printf("thread 1 push complete\n");
if(arg)
{
pthread_exit(NULL);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void *) 1;
}
void *thr_fn2(void * arg)
{
printf("thread 2 start \n");
pthread_cleanup_push((void*)clean,"thread 2 first handler");
pthread_cleanup_push((void*)clean,"thread 2 second handler");
printf("thread 2 push complete\n");
if(arg)
{
return ((void*)2);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void *) 2;
}
int main()
{
int err;
pthread_t tid1, tid2;
void *tret;
err = pthread_create(&tid1,NULL,thr_fn1,(void*)1);
if(err != 0)
{
perror("create pthread 1 error \n");
return -1;
}
err = pthread_create(&tid2,NULL,thr_fn2,(void*)1);
if(err != 0)
{
perror("create pthread 2 error \n");
return -1;
}
err = pthread_join(tid1, &tret);
if(err != 0)
{
perror("join thread 1 error \n");
}
printf("thread 1 exit code %d \n",(int) tret);
err = pthread_join(tid2, &tret);
if(err != 0)
{
perror("join thread 2 error \n");
}
printf("thread 2 exit code %d \n",(int) tret);
return 1;
}
|
Rust
|
UTF-8
| 2,930 | 2.6875 | 3 |
[
"MPL-2.0"
] |
permissive
|
use super::InternalEvent;
use crate::tls::TlsError;
use metrics::counter;
#[derive(Debug)]
pub struct TcpSocketConnectionEstablished {
pub peer_addr: Option<std::net::SocketAddr>,
}
impl InternalEvent for TcpSocketConnectionEstablished {
fn emit_logs(&self) {
if let Some(peer_addr) = self.peer_addr {
debug!(message = "Connected.", %peer_addr);
} else {
debug!(message = "Connected.", peer_addr = "unknown");
}
}
fn emit_metrics(&self) {
counter!("connection_established_total", 1, "mode" => "tcp");
}
}
#[derive(Debug)]
pub struct TcpSocketConnectionFailed<E> {
pub error: E,
}
impl<E> InternalEvent for TcpSocketConnectionFailed<E>
where
E: std::error::Error,
{
fn emit_logs(&self) {
error!(message = "Unable to connect.", error = %self.error);
}
fn emit_metrics(&self) {
counter!("connection_failed_total", 1, "mode" => "tcp");
}
}
#[derive(Debug)]
pub struct TcpSocketConnectionShutdown;
impl InternalEvent for TcpSocketConnectionShutdown {
fn emit_logs(&self) {
debug!(message = "Received EOF from the server, shutdown.");
}
fn emit_metrics(&self) {
counter!("connection_shutdown_total", 1, "mode" => "tcp");
}
}
#[derive(Debug)]
pub struct TcpSocketConnectionError {
pub error: TlsError,
}
impl InternalEvent for TcpSocketConnectionError {
fn emit_logs(&self) {
match self.error {
// Specific error that occures when the other side is only
// doing SYN/SYN-ACK connections for healthcheck.
// https://github.com/timberio/vector/issues/7318
TlsError::Handshake { ref source }
if source.code() == openssl::ssl::ErrorCode::SYSCALL
&& source.io_error().is_none() =>
{
debug!(message = "Connection error, probably a healthcheck.", error = %self.error, internal_log_rate_secs = 10);
}
_ => {
warn!(message = "Connection error.", error = %self.error, internal_log_rate_secs = 10)
}
}
}
fn emit_metrics(&self) {
counter!("connection_errors_total", 1, "mode" => "tcp");
}
}
#[derive(Debug)]
pub struct TcpSocketError {
pub error: std::io::Error,
}
impl InternalEvent for TcpSocketError {
fn emit_logs(&self) {
debug!(message = "TCP socket error.", error = %self.error);
}
fn emit_metrics(&self) {
counter!("connection_errors_total", 1, "mode" => "tcp");
}
}
#[derive(Debug)]
pub struct TcpSendAckError {
pub error: std::io::Error,
}
impl InternalEvent for TcpSendAckError {
fn emit_logs(&self) {
warn!(message = "Error writing acknowledgement, dropping connection.", error = %self.error);
}
fn emit_metrics(&self) {
counter!("connection_send_ack_errors_total", 1, "mode" => "tcp");
}
}
|
C++
|
UTF-8
| 741 | 2.796875 | 3 |
[] |
no_license
|
//
// Created by Admin on 11/19/2018.
//
#include "../blocklib/SHA256Hasher.hpp"
#include "../blocklib/POWMiner.hpp"
#include "../blocklib/BlockChain.hpp"
using namespace std;
int main()
{
int32_t difficulty = 3;
BlockChain<SHA256Hasher, POWMiner> chain = BlockChain<SHA256Hasher, POWMiner>(3);
cout << "Add new block" << endl;
chain.AppendBlock("Bob gave Alice 1E");
cout << "Add new block" << endl;
chain.AppendBlock("Alice gave Bob a cat");
cout << "Add new block" << endl;
chain.AppendBlock("John gave Mary a Parrot");
cout << "Add new block" << endl;
chain.AppendBlock("John gave Jill 5B");
chain.PrintChain();
//cout << "Press any key to exit" << endl;
//cin.get();
return 0;
}
|
JavaScript
|
UTF-8
| 1,678 | 4.71875 | 5 |
[] |
no_license
|
/**
Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.
insert(val): Inserts an item val to the collection.
remove(val): Removes an item val from the collection if present.
getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.
*/
/**
* Initialize your data structure here.
*/
var RandomizedCollection = function() {
this.set = [];
};
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
* @param {number} val
* @return {boolean}
*/
RandomizedCollection.prototype.insert = function(val) {
var check = false;
if (this.set.indexOf(val) === -1) {
check = true;
}
this.set.push(val);
return check;
};
/**
* Removes a value from the set. Returns true if the set contained the specified element.
* @param {number} val
* @return {boolean}
*/
RandomizedCollection.prototype.remove = function(val) {
var index = this.set.indexOf(val);
if (index === -1) {
return false;
}
this.set.splice(index, 1);
return true;
};
/**
* Get a random element from the set.
* @return {number}
*/
RandomizedCollection.prototype.getRandom = function() {
return this.set[Math.floor(this.set.length * Math.random())];
};
/**
* Your RandomizedCollection object will be instantiated and called as such:
* var obj = Object.create(RandomizedCollection).createNew()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/
|
PHP
|
UTF-8
| 1,534 | 2.671875 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: sanokouhei
* Date: 2017/12/24
* Time: 13:28
*/
namespace Conversation;
class IntentionConfigLoader
{
/**
* @param Configure $configure
*
* @return IntentionProvider
*/
public static function load($configure)
{
$intention_groups = [];
$config_intention_groups = $configure->read('Intention');
foreach ($config_intention_groups as $config_intention_group) {
$intentions = [];
$config_actions = $config_intention_group['actions'];
foreach ($config_actions as $config_action) {
$class_name = $config_action['class'];
if ( ! class_exists($class_name)) {
continue;
}
$class = new $class_name(
$config_action['name'],
isset($config_action['label']) ? $config_action['label'] : null
);
if ( ! ($class instanceof AbstractIntentionHandler)) {
continue;
}
$intentions[] = $class;
}
if (empty($intentions)) {
continue;
}
$intention_groups[] = new IntentionGroup(
$config_intention_group['id'],
$intentions,
isset($config_intention_group['label']) ? $config_intention_group['label'] : null
);
}
return new IntentionProvider($intention_groups);
}
}
|
Markdown
|
UTF-8
| 878 | 3.484375 | 3 |
[] |
no_license
|
### 139. Word Break
-----
  给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
  字典中没有重复的单词,拆分时可以重复使用字典中的单词。
-----
#### 正解一 DP
  dp[i]:字符串 s 的前 i 个字符组成的子串 s[0..i-1] 能否拆分成若干个字典中出现的单词。
  因此要枚举 s[0..i-1] 中的分割点 j ,看 s[0..j-1] 组成的字符串是否合法,即 dp[j];以及 s[j..i-1] 字符串是否合法。
  状态转移方程:dp[i] = dp[j] && check(s[j..i−1])
  剪枝:枚举时可将 j 从 i - 1 开始由大到小遍历,当 s[j..i−1] 的长度 i - j 已经大于字典里最长的单词的长度,就结束遍历。
|
JavaScript
|
UTF-8
| 1,015 | 2.765625 | 3 |
[] |
no_license
|
'use strict';
const ValueObject = require('./ValueObject');
/**
* The AuthResult is a DTO that contains the result of an authentication request.
* It holds the generated token and metadata about the course of authentication:
* whether the token generated is final and what the next step is if not.
* @extends ValueObject
* @property {string} token - The generated token, in string format.
* @property {boolean} final - Whether the token is final (i.e. allows logging on to the target system).
* @property {?string[]} next - The next possible methods of authentication. Only one should be selected by the requester.
*/
class AuthResult extends ValueObject {
constructor({ token, final = true, next = null }) {
token = String(token);
final = Boolean(final);
if (!token || (!final && (!next || !Array.isArray(next) || next.length === 0))) {
throw new Error('Invalid AuthResult data passed to the constructor');
}
super({ token, final, next });
}
}
module.exports = AuthResult;
|
PHP
|
UTF-8
| 2,775 | 2.921875 | 3 |
[] |
no_license
|
<?php
require_once 'php/model/glossaire.php';
// DEBUG
// print_r($glossaire);
// on crée une fonction qui prend en paramètre un tableau
function displayRandomTerm($array)
{
// on stocke la longueur du tableau dans une variable
$length = count($array);
// Utilisation de la fonction PHP mt_rand() pour générer un nombre aléatoire
// https://www.php.net/manual/fr/function.mt-rand.php
$index = mt_rand(0, $length - 1);
// DEBUG
// echo '<pre>';
// print_r($array[$index]['title']);
// echo '<br>';
// print_r($array[$index]['description']);
// echo '</pre>';
// on sélection dans le tableau l'élément (un tableau associatif) qui a l'index qu'on vient de générer et on stocke la valeur de chaque clé dans une variable pour plus de facilité
$title = $array[$index]['title'];
$description = $array[$index]['description'];
// on prépare le code HTML à afficher
$html =
<<<OUTPUT
<div class="container">
<div class="card border-primary mb-3" style="max-width: 20rem;">
<div class="card-header">{$title}</div>
<div class="card-body">
<p class="card-text">{$description}</p>
</div>
</div>
</div>
OUTPUT;
echo $html;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Glossaire des termes OPQUAST</title>
<!-- intégration du CDN de la librairie CSS Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<!-- code de la navbar récuréré sur bootswtach.com : https://bootswatch.com/ -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">RANDOMIZE ME</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor02">
<form class="form-inline my-2 my-lg-0">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Afficher un terme aléatoire</button>
</form>
</div>
</nav>
<?php
// on invoque la fonction où on en a besoin
displayRandomTerm($glossaire);
?>
</body>
</html>
|
Java
|
UTF-8
| 2,207 | 3.328125 | 3 |
[] |
no_license
|
import java.util.*;
import java.io.*;
class Score
{
String date;
Integer score;
Score(String d, int s)
{
date = d;
score = s;
}
public String getDate()
{
return date;
}
public Integer getScore()
{
return score;
}
public String toString()
{
return date + " " + score;
}
}
public class TestMap
{
ArrayList<Score> sl1 = new ArrayList<Score>();
ArrayList<Score> sl2 = new ArrayList<Score>();
TreeMap<String,ArrayList<Score>> Bowler = new TreeMap<String, ArrayList<Score>>();
class DateCompare implements Comparator<Score>
{
public int compare(Score one, Score two)
{
return one.date.compareTo(two.date);
}
}
public static void main(String[] args)
{
new TestMap().go();
}
public void go()
{
sl1.add(new Score("2016-01-01",250));
sl1.add(new Score("2016-02-01",270));
sl1.add(new Score("2016-03-01",256));
sl1.add(new Score("2016-04-01",236));
sl1.add(new Score("2015-12-31",244));
sl2.add(new Score("2016-01-01",230));
sl2.add(new Score("2016-02-01",240));
sl2.add(new Score("2016-03-01",266));
sl2.add(new Score("2016-04-01",246));
sl2.add(new Score("2016-05-01",276));
sl2.add(new Score("2015-12-01",248));
sl2.add(new Score("2015-11-01",250));
DateCompare dc =new DateCompare();
Collections.sort(sl1,dc);
Collections.sort(sl2,dc);
Bowler.put("Danny", sl1);
Bowler.put("Jack", sl2);
Iterator<String> iterator = Bowler.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
int size = Bowler.get(key).size();
System.out.println("Bowler's name: " + key);
System.out.println("Bowler's game record: " + Bowler.get(key));
System.out.println("Number of game: " + Bowler.get(key).size());
System.out.println("The average score: " + getAverage(Bowler.get(key)));
System.out.println("Date of the last game: " + Bowler.get(key).get(size-1).getDate());
System.out.println("Score of the last game: " + Bowler.get(key).get(size-1).getScore());
}
}
double getAverage(ArrayList<Score> sl)
{
int sum = 0;
double average;
int size = sl.size();
for(int i=0; i<size;i++)
{
sum += sl.get(i).getScore();
}
average = sum/size;
return average;
}
}
|
C#
|
UTF-8
| 874 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factory
{
public class CreadorTipoPago : ICreadorTipoPago
{
private Pedido pedido;
public CreadorTipoPago(Pedido _pedido)
{
this.pedido = _pedido;
}
public IRealizadorPago CrearModalidadPago()
{
ICreadorPago creadorPago = null;
switch (this.pedido.Modalidad)
{
case Pago.Modalidad.Efectivo:
creadorPago = new CreadorPagoEfectivo(this.pedido);
break;
case Pago.Modalidad.Tarjeta:
creadorPago = new CreadorPagoTarjeta(this.pedido);
break;
}
return creadorPago.CrearModalidadPago();
}
}
}
|
Java
|
UTF-8
| 4,298 | 2.5 | 2 |
[
"MIT"
] |
permissive
|
package com.arassec.igor.simulation.job;
import com.arassec.igor.application.simulation.JobSimulator;
import com.arassec.igor.application.simulation.SimulationResult;
import com.arassec.igor.core.model.job.Job;
import com.arassec.igor.core.model.job.execution.JobExecution;
import com.arassec.igor.core.model.trigger.EventTrigger;
import com.arassec.igor.core.util.event.JobTriggerEvent;
import com.arassec.igor.simulation.IgorSimulationProperties;
import com.arassec.igor.simulation.job.strategy.SimulationStrategy;
import com.arassec.igor.simulation.job.strategy.SimulationStrategyFactory;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Predicate;
/**
* A {@link JobSimulator} that runs the jobs in simulation mode.
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class StandardJobSimulator implements JobSimulator {
/**
* Contains the currently simulated jobs, indexed by their ID.
*/
@Getter
private final List<Job> runningSimulations = Collections.synchronizedList(new LinkedList<>());
/**
* Simulation configuration properties.
*/
private final IgorSimulationProperties simulationProperties;
/**
* A factory for {@link SimulationStrategy} instances.
*/
private final SimulationStrategyFactory simulationStrategyFactory;
/**
* {@inheritDoc}
*/
@Async
@Override
public Future<Map<String, SimulationResult>> simulateJob(Job job) {
return CompletableFuture.supplyAsync(() -> {
var jobExecution = new JobExecution();
runningSimulations.add(job);
var simulationStrategy = simulationStrategyFactory.determineSimulationStrategy(job);
Map<String, SimulationResult> simulationResults = simulationStrategy.simulate(job, jobExecution);
runningSimulations.remove(job);
return simulationResults;
});
}
/**
* {@inheritDoc}
*/
@Override
public void cancelAllSimulations(String jobId) {
List<Job> jobsToCancel = runningSimulations.stream()
.filter(simulatedJob -> simulatedJob.getId().equals(jobId))
.toList();
jobsToCancel.forEach(Job::cancel);
}
/**
* Listens for job trigger events and starts processing in the simulated job.
*
* @param jobTriggerEvent The event containing additional data.
*/
@EventListener
public void onJobTriggerEvent(JobTriggerEvent jobTriggerEvent) {
runningSimulations.stream()
.filter(job -> job.getId().equals(jobTriggerEvent.getJobId()))
.filter(job -> job.getTrigger() instanceof EventTrigger)
.filter(job -> ((EventTrigger) job.getTrigger()).getSupportedEventType().equals(jobTriggerEvent.getEventType()))
.forEach(job -> ((EventTrigger) job.getTrigger()).processEvent(jobTriggerEvent.getEventData()));
}
/**
* Cancels simulations that haven't received any input data for a configurable amount of time.
*/
@Scheduled(fixedRate = 1000)
public void cancelStaleSimulations() {
Predicate<Job> isStale = job -> {
if (job.getCurrentJobExecution() == null) {
return true;
}
Instant started = job.getCurrentJobExecution().getStarted();
var now = Instant.now();
var time = Duration.between(started, now);
return time.toSeconds() >= simulationProperties.getTimeout();
};
List<Job> staleSimulations = runningSimulations.stream()
.filter(isStale)
.toList();
staleSimulations.forEach(job -> {
log.debug("Cancelling simulation of job '" + job.getId() + "' due to timeout!");
job.cancel();
});
}
}
|
C++
|
UTF-8
| 1,054 | 2.765625 | 3 |
[] |
no_license
|
//
// Created by hoho on 2019-07-08.
//
#include "Code_15664.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#define MAX 9
using namespace std;
int N_15664, M_15664;
int inputArr_15664[MAX];
vector<int> targetVector_15664;
set<vector<int>> outputSet_15664;
void reculsive_15664(int index, int count) {
targetVector_15664.resize(M_15664);
if (index == M_15664) {
outputSet_15664.insert(targetVector_15664);
return;
} else if (count > N_15664 - 1) {
return;
}
targetVector_15664[index] = inputArr_15664[count];
reculsive_15664(index + 1, count + 1);
reculsive_15664(index, count + 1);
}
void method_15664() {
cin >> N_15664 >> M_15664;
for (int i = 0; i < N_15664; i++) {
cin >> inputArr_15664[i];
}
sort(inputArr_15664, inputArr_15664 + N_15664);
reculsive_15664(0, 0);
for(vector<int> i : outputSet_15664){
for(int j : i){
cout << j << " ";
}
cout << "\n";
}
}
|
Java
|
UTF-8
| 3,055 | 2.296875 | 2 |
[] |
no_license
|
package ph.txtdis.fx.control;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import ph.txtdis.util.ClientTypeMap;
@Scope("prototype")
@Component("appButton")
public class AppButton //
extends Button {
@Autowired
private ClientTypeMap typeMap;
private String text, color, tooltip;
private int size;
private boolean isUnicode;
public AppButton build() {
setOnEnterKeyPressed();
setTooltip();
setText();
setStyle();
return this;
}
private void setOnEnterKeyPressed() {
setOnKeyPressed(e -> fire(e));
}
private void setTooltip() {
if (tooltip != null)
setTooltip(new ToolTip(tooltip));
}
private void setText() {
if (isUnicode)
text = typeMap.icon(text);
setText(text);
}
private void setStyle() {
String style = textButtonStyle();
if (text == null || isUnicode)
style = iconButtonStyle();
setStyle(style);
}
private void fire(KeyEvent e) {
if (e.getCode() == KeyCode.ENTER)
fire();
}
private String textButtonStyle() {
return " -fx-font-size: " + textSize() + "pt;";
}
private String iconButtonStyle() {
return " -fx-font: " + iconSize() + " 'txtdis'; " + color() + "-fx-padding: 0; " + buttonSize();
}
private int textSize() {
return size == 0 ? 11 : size;
}
private int iconSize() {
return size == 0 ? 24 : size;
}
private String color() {
return color == null ? "" : "-fx-text-fill: " + color + "; ";
}
private String buttonSize() {
int s = iconSize() * 2 - 2;
return " -fx-min-width: " + s + "; -fx-max-width: " + s + "; -fx-min-height: " + s + "; -fx-max-height: " + s +
";";
}
public AppButton color(String color) {
this.color = color;
return this;
}
public void disable() {
disableProperty().unbind();
disableProperty().set(true);
}
public void disableIf(ObservableValue<Boolean> b) {
disableProperty().unbind();
disableProperty().bind(b);
}
public void enable() {
disableProperty().unbind();
disableProperty().set(false);
}
public AppButton fontSize(int size) {
this.size = size;
return this;
}
public AppButton icon(String unicode) {
isUnicode = true;
return text(unicode);
}
public AppButton text(String text) {
this.text = text;
return this;
}
public AppButton large(String text) {
this.text = text;
this.size = 14;
HBox.setMargin(this, new Insets(0, 0, 0, 10));
return this;
}
public void onAction(EventHandler<ActionEvent> e) {
setOnAction(e);
}
public AppButton tooltip(String tooltip) {
this.tooltip = tooltip;
return this;
}
}
|
C
|
UTF-8
| 209 | 2.84375 | 3 |
[] |
no_license
|
// ARQUIVO COPIADO DO AVA
#include<stdio.h>
#include<stdlib.h>
main() {
int cont;
for(cont=0;cont<30;cont++) {
printf("Exibindo o valor de cont %d\n",cont);
}
system("pause");
}
|
Java
|
UTF-8
| 843 | 2.109375 | 2 |
[] |
no_license
|
package edu.sjsu.models;
import java.util.ArrayList;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface UserDao extends CrudRepository<User, Long> {
@Query(value = "SELECT * FROM users u WHERE u.email=?1", nativeQuery = true)
User getUserByEmail(String email);
@Query(value = "select * from users where userid=?1 and sessionid=?2", nativeQuery = true)
User getUserByUseridAndSessionid(long userid, long sessionid);
@Query(value = "select * from users where name LIKE %?1%", nativeQuery = true)
ArrayList<User> SearchUserName(String string);
@Query(value = "select * from users", nativeQuery = true)
ArrayList<User> getAllUsers();
}
|
Python
|
UTF-8
| 6,204 | 2.734375 | 3 |
[] |
no_license
|
import math
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import mnist
def random_mini_batches(X, Y, mini_batch_size = 64):
m = X.shape[0]
mini_batches = []
permutation = list(np.random.permutation(m))
shuffled_X = X[permutation,:]
shuffled_Y = Y[permutation,:].reshape((m,Y.shape[1]))
num_complete_minibatches = int(math.floor(m/mini_batch_size))
for k in range(0, int(num_complete_minibatches)):
mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def predict(X, parameters):
W1 = tf.convert_to_tensor(parameters["W1"])
b1 = tf.convert_to_tensor(parameters["b1"])
W2 = tf.convert_to_tensor(parameters["W2"])
b2 = tf.convert_to_tensor(parameters["b2"])
W3 = tf.convert_to_tensor(parameters["W3"])
b3 = tf.convert_to_tensor(parameters["b3"])
params = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2,
"W3": W3,
"b3": b3}
x = tf.placeholder("float", [12288, 1])
z3 = forward_propagation_for_predict(x, params)
p = tf.argmax(z3)
sess = tf.Session()
prediction = sess.run(p, feed_dict = {x: X})
return prediction
def forward_propagation_for_predict(X, parameters):
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
W3 = parameters['W3']
b3 = parameters['b3']
Z1 = tf.add(tf.matmul(W1, X), b1)
A1 = tf.nn.relu(Z1)
Z2 = tf.add(tf.matmul(W2, A1), b2)
A2 = tf.nn.relu(Z2)
Z3 = tf.add(tf.matmul(W3, A2), b3)
return Z3
def convert_to_one_hot(Y, C):
Y = np.eye(C)[Y.reshape(-1)]
return Y
def load_mnist_data():
x_train = mnist.train_images()
y_train = mnist.train_labels()
x_test = mnist.test_images()
y_test = mnist.test_labels()
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = (x_train / 255)
x_test = (x_test / 255)
x_train = x_train.reshape((-1,28,28,1))
x_test = x_test.reshape((-1,28,28,1))
y_train = convert_to_one_hot(y_train, 10)
y_test = convert_to_one_hot(y_test, 10)
return x_train[:5000], y_train[:5000], x_test, y_test
def create_placeholders(n_H, n_W, n_C, n_y):
X = tf.placeholder(tf.float32,shape=(None, n_H, n_W, n_C))
Y = tf.placeholder(tf.float32,shape=(None, n_y))
return X, Y
def initialize_parameters():
W1 = tf.get_variable("W1",[3,3,1,16],initializer = tf.contrib.layers.xavier_initializer())
W2 = tf.get_variable("W2",[3,3,16,32],initializer = tf.contrib.layers.xavier_initializer())
FW3 = tf.get_variable("FW3",[2048, 32],initializer = tf.contrib.layers.xavier_initializer())
Fb3 = tf.get_variable("Fb3",[1, 32],initializer = tf.zeros_initializer())
FW4 = tf.get_variable("FW4",[32, 10],initializer = tf.contrib.layers.xavier_initializer())
Fb4 = tf.get_variable("Fb4",[1, 10],initializer = tf.zeros_initializer())
parameters = {"W1": W1, "W2": W2, "FW3": FW3, "Fb3": Fb3, "FW4": FW4, "Fb4": Fb4}
return parameters
def forward_propagation(X, parameters):
W1 = parameters['W1']
W2 = parameters['W2']
FW3 = parameters['FW3']
Fb3 = parameters['Fb3']
FW4 = parameters['FW4']
Fb4 = parameters['Fb4']
Z1 = tf.nn.conv2d(X,W1,strides=[1,1,1,1], padding='VALID')
A1 = tf.nn.relu(Z1)
Z2 = tf.nn.conv2d(A1,W2,strides=[1,1,1,1], padding='VALID')
A2 = tf.nn.relu(Z2)
P1 = tf.nn.max_pool(A2,ksize= [1,3,3,1], strides=[1,3,3,1], padding= 'SAME')
F = tf.contrib.layers.flatten(P1)
Z3 = tf.add(tf.matmul(F, FW3), Fb3)
A3 = tf.nn.relu(Z3)
Z4 = tf.add(tf.matmul(A3,FW4), Fb4)
return Z4
def compute_cost(Z3, Y):
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = Z3, labels = Y)) # axis = -1, Last dim is the class dim
return cost
X_train, Y_train, X_test, Y_test = load_mnist_data()
(m, n_H, n_W, n_C) = X_train.shape
n_y = 10
costs = []
learning_rate = 0.009
num_epochs = 20
minibatch_size = 32
print_cost = True
tf.reset_default_graph()
X, Y = create_placeholders(n_H, n_W, n_C, n_y)
parameters = initialize_parameters()
Z4 = forward_propagation(X,parameters)
cost = compute_cost(Z4,Y)
optimizer = tf.train.GradientDescentOptimizer(learning_rate= learning_rate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(num_epochs):
epoch_cost = 0.
num_minibatches = int(m / minibatch_size)
minibatches = random_mini_batches(X_train, Y_train, minibatch_size)
for minibatch in minibatches:
(minibatch_X, minibatch_Y) = minibatch
_ , minibatch_cost = sess.run([optimizer,cost],feed_dict= {X :minibatch_X, Y : minibatch_Y})
epoch_cost += minibatch_cost / num_minibatches
if print_cost == True and epoch % 1 == 0:
print ("Cost after epoch %i: %f" % (epoch, epoch_cost))
if print_cost == True and epoch % 1 == 0:
costs.append(epoch_cost)
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per fives)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
parameters = sess.run(parameters)
print ("Parameters have been trained!")
correct_prediction = tf.equal(tf.argmax(Z4,1), tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train}))
print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))
#
# 20 epochs, learning_rate = 0.009, Batch size = 32
# Train Accuracy 95,
# Test Accuracy 92
|
Markdown
|
UTF-8
| 2,016 | 3.71875 | 4 |
[] |
no_license
|
The questions will be posted as homework.
However, for this assignment specifically,
you are allowed to work in pairs or small groups.
These programs should be written in Scheme.
# Questions
Everyone knows that grading is done via random number generation.
The trick is figuring out the correct distribution to use.
You are going to write code that simulates grades for various types of
coursework.
1. First, try to make an easy assignment as follows.
Write a function (`grade1`) that:
* generates a random number between 88 and 95
* assigns a letter grade according to a simple scale with no +/- grading
(A is 90 or above, B is 80 - 89, etc.)
You will want to use the `random` function.
When passed one argument `x`,
the function `random` returns a random integer in the half-open range `[0, x)`.
2. Next, you get grumpy because you are thinking of how Game of Thrones ended.
Make an extremely hard exam with scores between 8 and 30.
Assign letter grades as before.
However, you should write your function in such a way that your grading logic
could be reused even if the score distribution changed
(i.e., as a helper function).
Call the function `grade2`.
3. To make your grading process more efficient in the future,
you need to make your program more flexible.
Make a function that can create your future grading functions.
Create a single function (`grade3`) that
* takes two arguments, the high and low grades for the assignment
* returns a function that accepts no arguments and outputs letter grades
for random scores between the low and high grades (inclusive)
Test it out on a few ranges.
Remember -- you are not directly generating a grade here.
You are returning a function that generates grades.
4. Write a function to evaluate the expression
```
a + (b % c)*5*d - (5*d)**(b % c)
```
where `**` denotes exponentiation (`expt` in Scheme).
Notice that `(b % c)` and `5*d` both appear twice in the expression.
Write your function so that the values are computed just once.
(Hint: remember `let`)
|
C#
|
UTF-8
| 1,676 | 3.453125 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
public class Node<T> : IEnumerable<T>, IComparable<Node<T>> where T : IComparable<T>
{
public Node(T value)
{
this.Value = value;
this.Parent = null;
this.LeftChild = null;
this.RightChild = null;
}
public T Value { get; set; }
public Node<T> Parent { get; set; }
public Node<T> LeftChild { get; set; }
public Node<T> RightChild { get; set; }
public override string ToString()
{
return this.Value.ToString();
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public int CompareTo(Node<T> other)
{
return this.Value.CompareTo(other.Value);
}
public override bool Equals(object obj)
{
Node<T> other = (Node<T>)obj;
return this.CompareTo(other) == 0;
}
public IEnumerator<T> GetEnumerator()
{
if (this.LeftChild != null)
{
foreach (var child in this.LeftChild)
yield return child;
}
yield return this.Value;
if (this.RightChild != null)
{
foreach (var child in this.RightChild)
yield return child;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public void EachInOrder(Action<T> action)
{
if (this.LeftChild != null)
{
this.LeftChild.EachInOrder(action);
}
action(this.Value);
if (this.RightChild != null)
{
this.RightChild.EachInOrder(action);
}
}
}
|
Java
|
UTF-8
| 419 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.daniel_araujo.byteringbuffer;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class PeekCallbackTracker implements ByteRingBuffer.PeekCallback {
public final List<byte[]> calls = new ArrayList<>();
@Override
public void borrow(ByteBuffer chunk) {
byte[] arr = new byte[chunk.remaining()];
chunk.get(arr);
calls.add(arr);
}
}
|
JavaScript
|
UTF-8
| 2,097 | 3.875 | 4 |
[] |
no_license
|
//El resultado es undefined, porque la variable no está declarada
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
// Declara las variables
// Hay 5 tipos de datos
var a = "Wilt"; //texto
var b = 3; //número
var c = true; //boolean
var d = undefined; //null
var e = null; //indefinido
// Imprime los valores correctos en consola
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
// Ojo: undefined no es igual a null
console.log(d === e)
//Objetos
var obj = {
numero: 10,
texto: "nuevo texto",
booleano: true
};
console.log(obj);
//Los objetos pueden tener otros objetos dentro
var objPadre = {
nombre: "Wilt",
edad: 44,
casado: true,
objHijo: {
nombre: "Tomás",
edad: 2
},
ubicacion: {
pais: "Colombia",
ciudad: "Medellín",
direccion: "Transversal 53A #65-70",
edificio: "Madrid Aptos"
}
};
console.log("objPadre: ", objPadre);
console.log("objPadre.nombre: ", objPadre.nombre);
console.log("objPadre.objHijo: ", objPadre.objHijo);
console.log("objPadre.objHijo.nombre: ", objPadre.objHijo.nombre)
console.log("objPadre.ubicacion.direccion: ", objPadre.ubicacion.direccion);
// También se pueden agregar propiedades a un objeto
objPadre.objHijo.nacionalidad = "Colombiano";
console.log("objPadre.objHijo: ", objPadre.objHijo);
console.log("objPadre.objHijo.nacionalidad: ", objPadre.objHijo.nacionalidad);
// Se puede crear un objeto que haga referencia al objeto interno
var objHijo = objPadre.objHijo;
objHijo.genero = "Masculino";
console.log("objHijo.genero: ", objHijo.genero);
console.log("objPadre.objHijo: ", objPadre.objHijo);
// Notación de corchetes
console.log("objPadre['nombre']: ", objPadre["nombre"]);
console.log("objPadre['ubicacion']['pais']: ", objPadre["ubicacion"]["pais"]);
// También se pueden utilizar campos
campoNombre = "nombre";
campoPais = "pais"
console.log("objPadre[campoNombre]: ", objPadre[campoNombre]);
console.log("objPadre['ubicacion'][campoPais]: ", objPadre["ubicacion"][campoPais]);
|
TypeScript
|
UTF-8
| 872 | 2.6875 | 3 |
[] |
no_license
|
let gridcontainer: HTMLElement = document.getElementById("admingrid");
let images: NodeListOf<HTMLImageElement> = gridcontainer.querySelectorAll("img");
let imageurls: string[] = JSON.parse(sessionStorage.getItem("images"));
for (let index: number = 0; index < images.length; index++) {
const image: HTMLImageElement = images[index] as HTMLImageElement;
image.setAttribute("onclick", `changeimage(${index})`);
showimage(index);
}
function changeimage(index: number): void {
let input: string = prompt("Bitte geben sie die URL des Bildes an");
if (input != null) {
imageurls[index] = input;
sessionStorage.setItem("images", JSON.stringify(imageurls));
showimage(index);
}
}
function showimage(index: number): void {
const image: HTMLImageElement = images[index] as HTMLImageElement;
image.src = imageurls[index];
}
|
C#
|
UTF-8
| 4,430 | 2.578125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
namespace LuisAndQandA1.Dialogs
{
[Serializable]
public class CoordinatedHRLinksDialog : IDialog<bool> //IDialog<object>
{
public async Task StartAsync(IDialogContext context)
{
//OPTION 1 - WAITS FOR A MESSAGE
//context.Wait(this.MessageReceivedAsync);
//OPTION 2 - GOES DIRECTLY INTO SHOWING A MESSAGE
await this.NoMessageNeededAsync(context);
}
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var reply = context.MakeMessage();
reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
reply.Attachments = GetCardsAttachments();
await context.PostAsync(reply);
//context.Wait(this.MessageReceivedAsync);
//WAIT FOR 1 SECOND
System.Threading.Thread.Sleep(1000);
context.Done(true);
}
public virtual async Task NoMessageNeededAsync(IDialogContext context)
{
var reply = context.MakeMessage();
reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
reply.Attachments = GetCardsAttachments();
await context.PostAsync(reply);
//context.Wait(this.MessageReceivedAsync);
//WAIT FOR 1 SECOND
System.Threading.Thread.Sleep(1000);
context.Done(true);
}
private static IList<Attachment> GetCardsAttachments()
{
return new List<Attachment>()
{
GetThumbnailCard(
"Company HR Policy",
"Human Resources Policies",
"Contoso's one-stop shop for all HR policies and links. All guides are tailored to each of the regional Contoso offices. Also, you can find links to the new employee orientation guides here. Look here first!",
new CardImage(url: "https://www.shrm.org/_layouts/15/SHRM.Core/design/images/SHRMLogo.svg"),
new CardAction(ActionTypes.OpenUrl, "Learn more", value: "https://www.shrm.org/pages/default.aspx")),
GetThumbnailCard(
"Insurance Election Schedule",
"Human resource policies",
"The new year is just around the corner - don't forget to choose your insurance provider and policy! Each link describes each policy in depth. You can also find your last year's elections here.",
new CardImage(url: "http://static.weboffice.uwa.edu.au/visualid/graphics/uwacrest.png"),
new CardAction(ActionTypes.OpenUrl, "Learn more", value: "http://www.hr.uwa.edu.au/policies/policies/a-z")),
GetThumbnailCard(
"Remote Working Tools",
"Human resource policies",
"15% of Contoso's employees are remote workers - here's a list of the best tools to use when you're on the road.",
new CardImage(url: "https://www.shrm.org/_layouts/15/SHRM.Core/design/images/SHRMLogo.svg"),
new CardAction(ActionTypes.OpenUrl, "Learn more", value: "https://www.shrm.org/pages/default.aspx")),
};
}
private static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction)
{
var heroCard = new HeroCard
{
Title = title,
Subtitle = subtitle,
Text = text,
Images = new List<CardImage>() { cardImage },
Buttons = new List<CardAction>() { cardAction },
};
return heroCard.ToAttachment();
}
private static Attachment GetThumbnailCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction)
{
var heroCard = new ThumbnailCard
{
Title = title,
Subtitle = subtitle,
Text = text,
Images = new List<CardImage>() { cardImage },
Buttons = new List<CardAction>() { cardAction },
};
return heroCard.ToAttachment();
}
}
}
|
Markdown
|
UTF-8
| 3,956 | 3.140625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# How To use Multi Materials
A multi-material is used to apply different materials to different parts of the same object as you can see below

To be able to define a multi-materials you first have to define some standard materials:
```javascript
var material0 = new BABYLON.StandardMaterial("mat0", scene);
material0.diffuseColor = new BABYLON.Color3(1, 0, 0);
material0.bumpTexture = new BABYLON.Texture("normalMap.jpg", scene);<br/>
var material1 = new BABYLON.StandardMaterial("mat1", scene);
material1.diffuseColor = new BABYLON.Color3(0, 0, 1);
var material2 = new BABYLON.StandardMaterial("mat2", scene);
material2.emissiveColor = new BABYLON.Color3(0.4, 0, 0.4);</pre>
```
Then you can create a multi-material in order to gather them all:
```javascript
var multimat = new BABYLON.MultiMaterial("multi", scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
multimat.subMaterials.push(material2);
```
You are now able to affect the multi-material to your mesh:
```javascript
var sphere = BABYLON.Mesh.CreateSphere("Sphere0", 16, 3, scene);
sphere.material = multimat;
```
But if you do that, you will see that the sphere will only use the first submaterial (the red bumped one). This is because by default a mesh is is designed to use only one material.
You can specify which part of the mesh uses a specific material by using the _subMeshes_ property. By default, every mesh comes with only one submesh that cover the entire mesh.
To define multiple submeshes, you just have to use this code:
```javascript
sphere.subMeshes = [];
var verticesCount = sphere.getTotalVertices();
new BABYLON.SubMesh(0, 0, verticesCount, 0, 900, sphere);
new BABYLON.SubMesh(1, 0, verticesCount, 900, 900, sphere);
new BABYLON.SubMesh(2, 0, verticesCount, 1800, 2088, sphere);
```
In this case, you will have 3 parts:
* One starting from index 0 to index 900
* One starting from index 900 to index 1800
* One starting from index 1800 to index 3880
A submesh is defined with:
* The index of the material to use (this index is used to find the correct material Inside the _subMaterials_ collection of a multi-material)
* The index of the first vertex and the count of vertices used (To optimize things for collisions for instance)
* Index of the first indice to use and indices count
* The parent mesh
So with the code above, you can use the first material on the top part of the sphere, the second material on the middle part and the last material on the bottom part of the sphere.
* [Playground Example - MultiMaterial](https://www.babylonjs-playground.com/#2Q4S2S#268)
## With Merged Meshes
When you [merge meshes](/how_to/How_to_Merge_Meshes) together with the final parameter (`multiMultiMaterial`) set to true the subMeshes array is automatically created with all merging meshes' subMeshes. Each subMesh's material is also included in the resulting mesh's new multiMaterial. This feature ignores the parameter (`subdivideWithSubMeshes`).
* [Playground Example - MultiMaterial with Merged Meshes using multiMultiMaterials](https://playground.babylonjs.com/#INZ0Z0#59)
When you [merge meshes](/how_to/How_to_Merge_Meshes) together with the second to last parameter (`subdivideWithSubMeshes`) set to true, but the last parameter (`multiMultiMaterial`) left as false, the subMeshes array is automatically created with each merging mesh as a submesh of the new mesh. You must assign the correct subMesh index to the correct material index.
When you form `mergedMesh` by merging meshes in this array order [mesh1, mesh2], and the multiMaterials subMaterials array contains materials in the order [mat1, mat2] then for the subMesh from `mesh2` to have material `mat2` you need to set
```javascript
mergedMesh.subMeshes[1].materialIndex = 1;
```
* [Playground Example - MultiMaterial with Merged Meshes](https://playground.babylonjs.com/#INZ0Z0#6)
|
JavaScript
|
UTF-8
| 2,058 | 2.53125 | 3 |
[] |
no_license
|
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
$(document).ready(function () {
var currentUser = $('.share-track').attr('data-current-user');
var selectedUser = void 0;
console.log(currentUser, selectedUser, 'current and selected users');
function setGetData() {
selectedUser = $('select[name="share-track"] :selected').attr('value');
return {
action: 'seeRecommendations',
current: currentUser,
selected: selectedUser
};
}
// function placeData (element, data) {
// console.log(element);
// $('<h3></h3>', {
// text: 'Artist: ' + data.artist + '; Album: ' + data.album,
// }).appendTo(element);
// }
function placeData(element, data) {
console.log('one');
var container = $('<div></div>', {}).appendTo(element);
$('<h3></h3>', {
text: 'Artist: ' + data.artist
}).appendTo(container);
$('<h3></h3>', {
text: 'Album: ' + data.album
}).appendTo(container);
}
function getRecommendedList() {
$.ajax({
type: 'GET',
url: './endpoints/homePage.php',
dataType: 'json',
data: setGetData(),
success: function success(data) {
console.log(data, 'data');
console.log(typeof data === 'undefined' ? 'undefined' : _typeof(data));
data.forEach(function (elem) {
placeData('.results', elem);
});
}
}).fail(function () {
console.log('Something went wrong');
});
}
$('input[name="shares"]').on('click', function () {
console.log('change');
$('.results').empty();
getRecommendedList();
});
});
|
Java
|
UTF-8
| 1,181 | 2.109375 | 2 |
[] |
no_license
|
package com.infore.service;
import java.util.List;
import com.infore.model.UserInfo;
import com.infore.model.dto.UserInfoDto;
/**
* @desc .
* @author Created by Cai.xu
* @date 2017/6/30-上午9:44
*/
public interface UserInfoService extends BaseService<UserInfoDto> {
/**
* 检查登录信息
* @param loginName
* @param pwd
* @return
*/
public UserInfo checkUser(String loginName, String pwd);
/**
* 查询所有的人员信息
* @return List<UserInfo>
*/
public List<UserInfo> selectAllUsers();
/**
* 查询通讯录中的展示信息
* @return List<UserInfo>
*/
List<UserInfo> selectContacts();
/**
* 新增人员前先检测用户名是否可用
* @return UserInfo
*/
public UserInfo selectByUserNo(String user_no);
/**
* 根据用户信息id修改密码
* @param id
* @param password
* @return
*/
public int modifyPwdById(UserInfoDto userInfoDto);
/**
* 根据用户信息id查询用户的所有信息
* @param id
* @return UserInfoDto
*/
public UserInfoDto selectById(int id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.