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
|
---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 143 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
<?php
$nums =range(0,10);
//print_r($nums);
foreach($nums as $chave => &$valor){
$valor *= 10;
echo $valor."\n";
}
print_r($nums);
?>
|
JavaScript
|
UTF-8
| 3,702 | 2.546875 | 3 |
[] |
no_license
|
const _ = require('lodash');
const Q = require('q');
const Queue = require('./queue.model');
//membuat function
exports.index = function (req, res) {
// http://localhost:5000/api/queues?page=1&limit=10
let page = Number(req.query.page) || 1,
limit = Number(req.query.limit) || 10,
skip = (page - 1) * limit;
let query = {
code: {
$regex: req.query.code || '',
$options: 'i'
}
};
//proses async
Q.all([
Queue.count(query), //total data
Queue.find(query).sort('timeCome').populate('patient').skip(skip).limit(limit) //jumlah data
])
.spread(function (total, queues) {
res.status(200).json({
total,
queues
});
})
.catch(function (err) {
res.status(500).send(err);
});
};
exports.search = function (req, res) {
//http://localhost:5000/api/jobs/search?value=xdfgchgvjh
Queue.find({
name: {
$regex: req.query.value,
$options: 'i'
}
}).exec(function (err, queues) {
if (err) return res.status(500).send(err);
res.status(200).json(queues);
});
};
exports.show = function (req, res) {
//http://localhost:5000/api/queues/234567890
Queue.findOne({
_id: req.params.id
}).populate('patient').exec(function (err, queue) {
if (err) return res.status(500).send(err);
if (!queue) return res.status(404).json({
message: 'Queue Not Found! '
});
res.status(200).json(queue);
});
};
exports.create = function (req, res) {
// Lakukan pengecekan bahwa Patient yang sudah booking tidak bisa booking lagi.
Queue.create(req.body, function (err, queue) {
if (err) return res.status(500).send(err);
res.status(201).send(queue);
});
};
exports.checkIn = function (req, res) {
if (!req.params.id) return res.status(400).json({
message: "Params ID is Required!"
});
Queue.findOne({
_id: req.params.id
}).exec(function (err, queue) {
if (err) return res.status(500).send(err);
if (!queue) return res.status(404).json({
message: 'Appointment not Found!'
});
queue.hasCome = true;
queue.save(function (err) {
if (err) return res.status(500).send(err);
return res.status(200).json({
message: 'Appointment was Saved & Patient has Come!'
});
});
});
};
exports.update = function (req, res) {
//http://localhost:5000/api/queues/234567890
if (req.body._id) delete req.body._id;
Queue.findOne({
_id: req.params.id
}).exec(function (err, queue) {
if (err) return res.status(500).send(err);
if (!queue) return res.status(404).json({
message: 'Queue Not Found! '
});
let updated = _.merge(queue, req.body);
updated.save(function (err) {
if (err) return res.status(500).send(err);
res.status(200).json({
massage: 'Queue Updated',
queue: updated
});
});
});
}
exports.destroy = function (req, res) {
Queue.findOne({
_id: req.params.id
}).exec(function (err, queue) {
if (err) return res.status(500).send(err);
if (!queue) return res.status(404).json({
message: 'Queue Not Found! '
});
queue.remove(function (err) {
if (err) return res.status(500).send(err);
res.status(200).json({
massage: 'Job Deleted!'
});
});
});
}
|
Python
|
UTF-8
| 181 | 4.125 | 4 |
[] |
no_license
|
55.Write a program to calculate product of digits of a number.
SOL:
n=int(input("Enter any number:"))
s=1
while n!=0:
i=n%10
s=s*i
n=int(n/10)
print("Sum of numbers is :",s)
|
Java
|
UTF-8
| 667 | 2.859375 | 3 |
[] |
no_license
|
package game;
import java.util.ArrayList;
public class Monster extends Creature{
private String name;
private int serial;
private int id;
private ArrayList<CreatureAction> creatureaction = null;
public Monster(){
}
public void setID(int room, int _serial){
id = room;
serial = _serial;
}
public void setCreatureAction(CreatureAction _creatureaction){
if (creatureaction == null){
creatureaction = new ArrayList<CreatureAction>();
}
creatureaction.add(_creatureaction);
}
public ArrayList<CreatureAction> getCreatureAction(){
return creatureaction;
}
}
|
JavaScript
|
UTF-8
| 3,086 | 2.671875 | 3 |
[] |
no_license
|
import {Point} from '../src/Point';
import {PointVisibilityMapRouteOptimizer} from '../src/PointVisibilityMapRouteOptimizer'
describe("PointVisibilityMapRouteOptimizer.optimize", function() {
it("does no optimization if no points are visible to each other", function() {
const route = [
new Point(0, 0),
new Point(100, 200),
new Point(200, 300),
];
const arePointsVisibleToEachOther = function(_ptA, _ptB) {
return false;
};
PointVisibilityMapRouteOptimizer.optimize(route, arePointsVisibleToEachOther);
expect(route.length).toBe(3);
expect(route[0].getX()).toBe(0);
expect(route[0].getY()).toBe(0);
expect(route[1].getX()).toBe(100);
expect(route[1].getY()).toBe(200);
expect(route[2].getX()).toBe(200);
expect(route[2].getY()).toBe(300);
});
it("does no optimization for 0 points", function() {
const route = [
];
const arePointsVisibleToEachOther = function(_ptA, _ptB) {
return true;
};
PointVisibilityMapRouteOptimizer.optimize(route, arePointsVisibleToEachOther);
expect(route.length).toBe(0);
});
it("does no optimization for 1 point", function() {
const route = [
new Point(100, 200),
];
const arePointsVisibleToEachOther = function(_ptA, _ptB) {
return true;
};
PointVisibilityMapRouteOptimizer.optimize(route, arePointsVisibleToEachOther);
expect(route.length).toBe(1);
expect(route[0].getX()).toBe(100);
expect(route[0].getY()).toBe(200);
});
it("does no optimization for 2 points", function() {
const route = [
new Point(0, 0),
new Point(100, 200),
];
const arePointsVisibleToEachOther = function(_ptA, _ptB) {
return true;
};
PointVisibilityMapRouteOptimizer.optimize(route, arePointsVisibleToEachOther);
expect(route.length).toBe(2);
expect(route[0].getX()).toBe(0);
expect(route[0].getY()).toBe(0);
expect(route[1].getX()).toBe(100);
expect(route[1].getY()).toBe(200);
});
it("does optimization of 3 points where 1st and 3rd are visible to each other", function() {
const route = [
new Point(0, 0),
new Point(100, 200),
new Point(200, 300),
];
const arePointsVisibleToEachOther = function(_ptA, _ptB) {
if(_ptA.isEqual(new Point(0, 0)) && _ptB.isEqual(new Point(200, 300))) {
return true;
}
return false;
};
PointVisibilityMapRouteOptimizer.optimize(route, arePointsVisibleToEachOther);
expect(route.length).toBe(2);
expect(route[0].getX()).toBe(0);
expect(route[0].getY()).toBe(0);
expect(route[1].getX()).toBe(200);
expect(route[1].getY()).toBe(300);
});
});
|
JavaScript
|
UTF-8
| 6,299 | 2.65625 | 3 |
[] |
no_license
|
import {
runnerObject,
isJuniorOrOlder
} from "../helpers/runnerHelper";
import {
nationObject,
unknownNation
} from "../helpers/nationHelper";
import {
relayResultObject,
individualResultObject
} from "../helpers/resultHelper";
import {
individualEntryObject
} from "../helpers/entryHelper";
import {
eventObject,
teamObject,
unknownTeam
} from "../helpers/eventHelper";
import {
itemInArray,
ensureArray,
isVacantRunner
} from "../helpers/helper";
function processRunner(runner, teams, nations) {
// Make sure that the team excists, if runner has no team assisiation he should get unknown team
let team = unknownTeam()
if (runner.Organisation) {
team = teamObject(runner.Organisation);
if (itemInArray(teams, runner.Organisation.OrganisationId)) {
teams.push(team);
}
} else if (itemInArray(teams, 0)) {
teams.push(team);
}
// Not all nationalities are propperly mapped up.
// We have to make differentiate between totaly missing countries,
// countris with only id and propper countries.
if (runner.Person.Nationality) {
if (runner.Person.Nationality.Country) {
if (itemInArray(
nations,
runner.Person.Nationality.Country.CountryId.value
)) {
nations.push(nationObject(runner.Person.Nationality));
}
} else {
if (itemInArray(
nations,
runner.Person.Nationality.CountryId.value
)) {
nations.push(unknownNation(runner.Person.Nationality.CountryId.value));
}
}
} else {
nations.push(unknownNation());
}
const processedRunner = runnerObject(runner);
return {
processedRunner,
team
};
}
function processEvent(data) {
let event = null;
const nations = [];
const teams = [];
const runners = [];
if (data.ClassResult) {
event = eventObject(data.Event, data.ClassResult);
data.ClassResult.forEach(_class => {
const __class = {
id: _class.EventClass.EventClassId,
name: _class.EventClass.Name
};
ensureArray(_class.PersonResult).forEach(runner => {
if (runner.Person.PersonId) {
let {
processedRunner,
team
} = processRunner(runner, teams, nations);
let result = runner.Result;
// If the race is multi day we need to send in a different form of event data
// TODO: process result data from each day indivually
if (event.eventForm == "IndMultiDay") {
result = runner.RaceResult.Result;
}
processedRunner.results.push(
individualResultObject(result, event.id, team.id, __class)
);
if (
itemInArray(runners, processedRunner.id) &&
!isVacantRunner(processedRunner) &&
isJuniorOrOlder(processedRunner.birthYear, event.startDate)
) {
runners.push(processedRunner);
}
}
});
});
} else {
event = eventObject(data.Event, data.EventClassList.EventClass);
ensureArray(data.EventEntries.Entry).forEach(runner => {
const _runner = runner.Competitor;
if (_runner.Person.PersonId) {
const {
processedRunner,
team
} = processRunner(_runner, teams, nations);
processedRunner.entries.push(
individualEntryObject(event, team.id, runner.EntryClass.EventClassId)
);
if (
itemInArray(runners, processedRunner.id) &&
!isVacantRunner(processedRunner) &&
isJuniorOrOlder(processedRunner.birthYear, event.startDate)
) {
runners.push(processedRunner);
}
}
});
}
return {
event,
teams,
nations,
runners
};
}
function processRelayEvent(data) {
let event = null;
const nations = [];
const teams = [];
const runners = [];
if (data.ClassResult) {
const event = eventObject(data.Event, data.ClassResult);
if (data.ClassResult) {
data.ClassResult.forEach(_class => {
const __class = {
id: _class.EventClass.EventClassId,
name: _class.EventClass.Name
};
_class.TeamResult.forEach(team => {
const _team = teamObject(team.Organisation);
if (team.Organisation.OrganisationId && itemInArray(teams, _team.id)) {
teams.push(_team);
}
team.TeamMemberResult.forEach(runner => {
if (
runner.Person.Nationality &&
itemInArray(
nations,
runner.Person.Nationality.Country.CountryId.value
)
) {
nations.push(nationObject(runner.Person.Nationality));
}
const _runner = runnerObject(runner);
const result = relayResultObject(runner, event.id, _team.id, __class);
_runner.results.push(result);
if (
!isVacantRunner(_runner) &&
isJuniorOrOlder(_runner.birthYear, event.startDate)
) {
runners.push(_runner);
}
});
});
});
}
} else {
event = eventObject(data.Event, data.EventClassList.EventClass);
ensureArray(data.EventEntries.Entry).forEach(_team => {
console.log(_team.EntryClass);
const __team = teamObject(_team);
if (_team.OrganisationId && itemInArray(teams, __team.id)) {
teams.push(__team);
}
ensureArray(_team.TeamCompetitor).forEach(runner => {
if (runner.Person) {
if (runner.Person.PersonId) {
const {
processedRunner,
team
} = processRunner(runner, teams, nations);
processedRunner.entries.push(
individualEntryObject(event, team.id, _team.EntryClass.EventClassId)
);
if (
itemInArray(runners, processedRunner.id) &&
!isVacantRunner(processedRunner) &&
isJuniorOrOlder(processedRunner.birthYear, event.startDate)
) {
runners.push(processedRunner);
}
}
}
});
});
}
return {
event,
teams,
nations,
runners
};
}
export {
processRelayEvent,
processEvent
};
|
PHP
|
UTF-8
| 6,648 | 3.203125 | 3 |
[] |
no_license
|
<?php
require_once(__DIR__."/../data/TaskDBContext.php");
/**
* Handles Tasks operations.
*
* @author Yesid Perea
**/
class Task
{
private $id;
private $description;
private $userId;
private $messages;
private $error;
private $tasks;
private $dbContext;
/**
* Constructor of the class
*/
public function __construct($apiKey = null)
{
$this->error = false;
$this->messages = array();
$this->dbContext = new TaskDBContext();
}
/**
* Set the value of id
*
* @return self
*/
public function setId($id)
{
if (empty($id))
{
$this->error = true;
$this->messages[] = "Id required.";
return;
}
$this->id = $id;
}
/**
* Get the value of id
*/
public function getId()
{
return $this->id;
}
/**
* Get the value of description
*/
public function getDescription()
{
return $this->description;
}
/**
* Set the value of description
*
* @param description of the task.
* @return self
*/
public function setDescription($description)
{
if (empty($description))
{
$this->error = true;
$this->messages[] = "Field description required.";
return;
}
$this->description = $description;
}
/**
* Set the value of user id
*
* @param userid of the owner of the task.
* @return self
*/
public function setUserId($userId)
{
if (empty($userId))
{
$this->error = true;
$this->messages[] = "User Id required.";
return;
}
$this->userId = $userId;
}
/**
* Get the value of user id
*/
public function getUserId()
{
return $this->userId;
}
/**
* Get the value of Messages
*/
public function getMessages()
{
return !empty($this->messages) ? $this->messages: array();
}
/**
* Get the tasks
*/
public function getTasks()
{
return !empty($this->tasks) ? $this->tasks: array();
}
/**
* Creates a task.
*
* @param description Task description.
* @return task Task object.
*/
public function create($description, $userId)
{
$this->setDescription($description);
$this->setUserId($userId);
if (!$this->error)
{
$result = $this->dbContext->create($description, $userId);
$this->id = $result;
$this->messages[] = "Last record Id: {$this->id}";
}
return json_encode($result, JSON_PRETTY_PRINT);
}
/**
* Updates a task.
*
* @param id Task id.
* @param description Task description.
* @return task Task updated.
*/
public function update($id, $description, $userId)
{
$this->setId($id);
$this->setDescription($description);
$this->setUserId($userId);
if (!$this->error)
{
$result = $this->dbContext->update($id, $description, $userId);
$this->messages[] = "{$result} records updated.";
}
return json_encode($result, JSON_PRETTY_PRINT);
}
/**
* Deletes a task for given Id and User Id.
*
* @param id Task id.
* @return task Task deleted with the result message.
*/
public function delete($id, $userId)
{
$this->setId($id);
$this->setUserId($userId);
if (!$this->error)
{
$result = $this->dbContext->delete($id, $userId);
$this->messages[] = "{$result} records deleted.";
$this->id = null;
}
return json_encode($result, JSON_PRETTY_PRINT);
}
/**
* Get a task for a given Id and User Id.
*
* @param id Task id.
* @return task Task for the Id given.
*/
public function get($id, $userId)
{
$this->setId($id);
$this->setUserId($userId);
$results = array();
if (!$this->error) {
$results = $this->dbContext->read($id, $userId);
if(count($results) > 0)
{
$result = $results[0];
$this->description = $result['description'];
}
else
{
$this->messages[] = "No records found for Id: $id.";
}
}
return json_encode($results, JSON_PRETTY_PRINT);
}
/**
* Get the tasks associated to the User Id.
*
* @return tasks Collection of Tasks.
*/
public function getAll($userId)
{
$this->setUserId($userId);
$result = array();
if (!$this->error)
{
$result = $this->dbContext->readAll($userId);
if(count($result) == 0)
{
$this->messages[] = "No records found.";
}
}
return json_encode($result, JSON_PRETTY_PRINT);
}
/**
* Get the task statistics for all users.
*
* @return statistics Collection of Tasks statistics.
*/
public function getStatistics()
{
$result = array();
if (!$this->error)
{
$result = $this->dbContext->readStats();
if(count($result) == 0)
{
$this->messages[] = "No records found.";
}
}
return json_encode($result, JSON_PRETTY_PRINT);
}
}
?>
|
Python
|
UTF-8
| 2,832 | 4.375 | 4 |
[] |
no_license
|
'''
the Question:
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node's key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
Create a class that converts the number into a node in the tree (every node should have left child,
right child and the value of the node "child can be none").
The class should have a function that inserts a new node to the binary tree. And another function
that prints the final binary tree (tree should be printed from left to the write {left-root-right})
Examples:
10 15
5 11 ➞ [3, 5, 6, 10, 11] 7 18 ➞ [5, 9, 7, 15, 17, 18, 19]
3 6 5 9 17 19
root()=Node(10) -> 10 is the root of the tree (first node in the top)
root.insert(5)
root.insert(11)
root.insert(3)
root.insert(6)
root.PrintTree() -> [3, 5, 6, 10, 11]
root.data -> 10
root.left.data -> 5
root.right.data -> 11
'''
class Node:
tree=[]
# crate node for number every nood have left childe and right chile and data
def __init__(self, data):
self.left = None
self.right = None
self.data = data
Node.tree.clear()
def insert(self, data):
# Compare the new value with the parent node
if self.data:
# check for the new value if it bigger than the root if it true then check if the root have a left chiled
# if not have make this data a new node as aleft node for the root and this node have a left and right
# if the root already have aleft so it recall the func insert but this time to left node to cheack agine
# if the new inert data is smaller than that nood or not and the same for the right
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
# cheak the object left childe if it has left child recall the func to cheak again if it have left etc...
# if it not have it print the data of that node
if self.left:
self.left.PrintTree()
Node.tree.append(self.data)
if self.right:
self.right.PrintTree()
return Node.tree
|
C++
|
UTF-8
| 1,209 | 2.921875 | 3 |
[] |
no_license
|
#pragma once
#include "Window.h"
#include <functional>
#include <vector>
class InputManager
{
public:
// Was a key pressed?
static bool GetKeyPressed(char key);
// Is a key held down?
static bool GetKeyDown(char key);
static int GetMouseX();
static int GetMouseY();
static float GetMouseXDelta();
static float GetMouseYDelta();
static float GetScrollX();
static float GetScrollY();
// Link the input manager to a window
static void LinkWindow(Window *w);
// Called from window manager
static void SetKeyPressed(char key);
static void SetScrollX(float xscrl);
static void SetScrollY(float yscrl);
static void UpdateLastMousePosition();
static void FlushKeyPressArray();
static void ResizeWindowEvent(int x, int y);
template<class T> static void AddResizeWindowCallback(T* const object, void(T::* const mf)(int, int))
{
using namespace std::placeholders;
resizeWindowCallbacks.emplace_back(std::bind(mf, object, _1, _2));
}
private:
static bool keyPressed[];
static bool keyDown[];
static int mouseX, mouseY;
static int lastX, lastY;
static float scrollX, scrollY;
static Window* window;
static std::vector<std::function<void(int, int)>> resizeWindowCallbacks;
};
|
C++
|
UTF-8
| 2,878 | 3.203125 | 3 |
[] |
no_license
|
#include "computer1.h"
#include "game.h"
#include "map.h"
#include <cstdlib>
#include <iostream>
using namespace std;
/**
*
*/
Computer1::Computer1()
{
xPoint = 0;
yPoint = 0;
xVelocity = 0;
yVelocity = 0;
carNumber = 0;
}
void Computer1::createLoc(Game& game)
{
int tofind;
if (carNumber == 1 )
tofind = -11;
else if (carNumber == 2)
tofind = -12;
else if (carNumber == 3)
tofind =-13;
int spotfound;
vector<int> aLocation= game.getMap().searchListLocation(tofind);
for (std::vector<int>::const_iterator i = aLocation.begin(); i != aLocation.end(); ++i)
{
//std::cout << *i << " ";
spotfound = *i;
}
//cout << spotfound << endl;
setX(spotfound, game);
//cout << xPoint << endl;
setY(spotfound, game);
}
void Computer1::setX(int spot, Game& game)
{
//cout << "Made it to xTerms" << endl;
//cout << "We have " << game.getMap().getCol() << " Columns" << endl;
//cout << "There are " << game.getMap().getRows() << " Rows" << endl;
int xComparer = 0;
for (int x =0; x<= game.getMap().getCol(); x++)
{
xComparer = x;
//cout << "The x inside the forloop is XXXXXXXXXXX " << x << endl;
for (int y=0; y < game.getMap().getRows(); y++)
{
//cout << "The Value of Y " << y << endl;
//cout << "Value we are looking for is " << spot
//<< "\nxComparer= "
//<< xComparer << "\n\n";
if (spot == xComparer)
{
//cout << "We have a MATCH!!!\n";
//cout << x << endl;
xPoint = x;
xComparer =xComparer+ game.getMap().getCol();
}
else
xComparer =xComparer+ game.getMap().getCol();
}
}
}
void Computer1::setY(int spot, Game& game)
{
//cout << "In the setY" << endl;
int yVar= game.getMap().getCol()*game.getMap().getRows();
for (int x =0; x< game.getMap().getRows(); x++)
{
//cout << "The yVar value from inside the first while loop " << yVar << "\n\n";
for (int y=0; y < game.getMap().getCol(); y++)
{
yVar--;
//cout << "The yVar value from inside the second while loop " << yVar << endl;
if (spot == yVar)
{
//cout << "Found match " << yVar << endl;
//cout << "We are turning " << x <<endl;
yPoint = x;
}
}
}
}
/**
*
*/
void Computer1::getMove(Game& game, int& column, int& row) {
}
int Computer1::getX()
{
return xPoint;
}
int Computer1::getY()
{
return yPoint;
}
int Computer1::getXVel()
{
return xVelocity;
}
int Computer1::getYVel()
{
return yVelocity;
}
void Computer1::addCarNum(int number)
{
carNumber = number;
}
|
C++
|
UTF-8
| 5,905 | 3.59375 | 4 |
[] |
no_license
|
#include <iostream>
#include <cstring>
#include "postfixGenerator.h"
#include "myStack.h"
using namespace std;
postfixGenerator::postfixGenerator()
{
//Setting infix and postfix strings to empty expressions.
infix = "";
postfix = "";
}
void postfixGenerator::getInfix(string x)
{
//For class objects to work with multiple expressions,
//every time we get a new infix expression we set postfix
//back to an empty expression.
infix = x;
postfix = "";
}
string postfixGenerator::showInfix()
{
return infix; //Returns our infix expression.
}
string postfixGenerator::showPostfix()
{
convertToPostfix(); //To get a postfix string before returning it.
return postfix;
}
void postfixGenerator::convertToPostfix()
{
//NOTE: In the comments, there might be an "a.", or "b.",
//or "b.1." or something to that effect. These are the points hit
//for the programming challenge according to Prog. challenge # 9
//of chapter 7 of the Data Structures Book, pg. 449
//a. Initialize stack
myStack<string> postfixStack; //Stack holding operators.
bool onlyLeftParenth; //Used for 2 cases involving parenthesis
string sym; //To hold the operator or operand we're currently looking at.
for(int i = 0; i< infix.size(); i++)
{
//b. Get the symbol, sym from infix.
sym = infix[i]; //sym will hold the ith character of
//the infix string.
if(sym != "+" && sym != "-" && sym != "/"
&& sym != "*" && sym != "(" && sym != ")") //b.1. If sym is an operand.
{
postfix.append(sym); //Put operands in the postfix string.
}
if(sym == "(") // b.2. If sym is "("
{
postfixStack.push(sym); //push sym into the stack.
}
if( sym == ")") //b.3. If sym is ")"
{
onlyLeftParenth = false;
if(!postfixStack.isEmptyStack())
{
//Pop and append all the symbols from the stack until the MOST
//RECENT left parenthesis, "(". Meaning at the end of this, the stack could
//still hold multiple "(" parentheses.
while(!postfixStack.isEmptyStack() && onlyLeftParenth == false)
{
if(postfixStack.top() != "(") //popping and appending until we hit a "("
{
postfix.append(postfixStack.top());
postfixStack.pop();
}
else //We've reahed a "("
{
postfixStack.pop(); //Pop the instance of "(" out.
onlyLeftParenth = true; //We've popped and appended everything
//within a single "( )" in the expression.
}
}
}
}
if(sym == "+" || sym == "-" || sym == "*" || sym == "/") //b.4. If sym is an operator
{
//b.4.1. pop and append all the operators that are above the most recent "(" AND have
//precedence greater than or = to sym.
onlyLeftParenth = false;
if(!postfixStack.isEmptyStack()) //I'm not sure if I need this if statement.
{
//We pop until the stack is empty or until we've reached a "("
while(!postfixStack.isEmptyStack() && onlyLeftParenth == false)
{
if( postfixStack.top()!= "(")
{
//+ and - are the lowest end precedence
if(sym == "+" || sym == "-")
{
postfix.append(postfixStack.top());
postfixStack.pop();
}
else if(sym == "*" || sym == "/")
{
//If the next thing in the stack has greater or equal precedence to sym.
if(postfixStack.top() == "*" || postfixStack.top() == "/" )
{
postfix.append(postfixStack.top());
postfixStack.pop();
}
else
{
//This variable name might be misleading. What's actually happening
//is if we have a + or - at the top of the stack, then that is
//lower precedence than sym's * or /. SO, since we're only supposed
//to pop and append things that have GREATER or EQUAL precedence to
//sym until the left parenthesis, we're done here.
onlyLeftParenth = true;
}
}
}
else
{
//We've hit an instance of "('
onlyLeftParenth = true;
}
}
}
//b.4.2.
//Since we've popped and appended everything we need to,
//we can now push whatever operator sym is into the stack.
postfixStack.push(sym); //push sym into the stack.
}
}
//c.
//After processing infix, some operators might be left in the stack.
//Pop and append to postfix string everything from the stack.
while(!postfixStack.isEmptyStack())
{
postfix.append(postfixStack.top());
postfixStack.pop();
}
}
postfixGenerator::~postfixGenerator()
{
//dtor
}
|
Java
|
UTF-8
| 1,900 | 2.359375 | 2 |
[] |
no_license
|
package it.trackerchallenge.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import it.trackerchallenge.entity.User;
import it.trackerchallenge.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userService;
private Logger log = LoggerFactory.getLogger(this.getClass());
@PostMapping("/login-user")
public String login(@RequestParam String email, @RequestParam String password, Model model, HttpServletRequest request) {
User loggedUser = userService.login(email, password);
if (loggedUser == null) {
model.addAttribute("error", "wrong credentials");
return "login";
}
model.addAttribute("loggedUser",loggedUser);
request.getSession().setAttribute("loggedUser", loggedUser);
return "index";
}
@PostMapping("/signin-user")
public String signIn(User user, Model model) {
userService.insertUser(user);
model.addAttribute("confirmation", "Your account has been registred correctly");
return "login";
}
@PostMapping("/edit-user")
public String edit(User user, Model model, HttpServletRequest request) {
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("loggedUser");
user.setEmail(userSession.getEmail());
userService.updateUser(userSession.getId(), user);
model.addAttribute("editOk", "Your account has been updated");
return "index";
}
@PostMapping("/logout-user")
public String logout(HttpServletRequest request) {
request.getSession().invalidate();
return "login";
}
}
|
Python
|
UTF-8
| 1,939 | 3.25 | 3 |
[] |
no_license
|
from tkinter import *
import game as g
import tkinter.messagebox
class MainGame:
"""class with "start game" window"""
def __init__(self):
self._window_config()
def _window_config(self):
root = Tk()
root.title("made by Sakevich")
root.geometry('300x200')
# creating and showing Label widget on the screen
Label1 = Label(root, text="Welcome to the game!")
Label1.pack()
# creating a menu and submenu
main_menu = Menu()
file_menu = Menu(tearoff=0)
file_menu.add_command(label="New", command=self._new_game)
main_menu.add_cascade(label="File", menu=file_menu)
main_menu.add_cascade(label="Exit", command=quit)
root.config(menu=main_menu)
# creating button widgets
button1 = Button(root, text="Start", command=self._game, bg="yellow", width=12, height=2)
button1.pack()
button2 = Button(root, text="Rules", command=self._game_rules, bg="yellow", width=12, height=2)
button2.pack()
self._Button1 = button1
self._Button2 = button2
self._root = root
root.mainloop()
def _game(self):
"""imports information from game.py and displays new window with the game field """
top = Toplevel()
top.title("Game")
self._Button1.configure(state=DISABLED)
g.GameField(top)
top.resizable(width=False, height=False)
def _new_game(self):
"""restarts new game"""
self._Button1.configure(state=ACTIVE)
def _game_rules(self):
tkinter.messagebox.showinfo(title="RULES", message="Мета: очистити поле від всіх фігур\n Як грати: за допомогою кліку мишки поміняй місцями будь-які 2 фігури\n Виконавець: Сакевич Михайло К11")
MainGame()
|
Markdown
|
UTF-8
| 4,311 | 3.296875 | 3 |
[] |
no_license
|
OK Coders: Lesson 4 Exercises
====
Complete all homework assignments before coming to the next class or as otherwise instructed.
## Create an express app for bootstrap practice
**Create a new express app**
Similar to the previous homework assignment, create a new Express web application. Do not reuse previous express applications. The intent is to practice using the command line and creating applications from scratch quickly.
**Grab the html from this repository**
Copy all the html files from the public directory in this repository into the public directory of your express application. Actually, for this lesson you could create the html files from scratch, because the html files in this repository are empty placeholders.
**Install bootstrap**
Download the bootstrap files and place them into the correct directories. Remember to use the *javascripts* instead of *js* and *stylesheets* instead of *css* directories in your express application.
**Create a web site**
For this assignment you will create the files from scratch. I've added an empty file for each page. You will generate all the html. Base your html on the Bootstrap Basic Template we used in class, but don't forget to correct the `link` and `script` tags.
The site should have the following characteristics:
**Navigation and container**
Each page should have a working bootstrap-based *navigation bar* with links to all the other pages that also indicates the current page. Each page should also have a *container* div that contains the rest of the page.
**Index.html**
The index is the front landing page for the site. Use the *jumbotron* component and *panels* to highlight features of the site. Make up marketing copy (text) for a data analysis firm and add images.
**About.html**
Create an about page that describes the business and the team. Add images for team members. The images should be circles, but don't edit square images. Use bootstrap's support for making a rectangular image appear circular. Again, make up the copy (text contents).
**Signup.html**
Create a sign up page for the firm's product. Create a form using bootstrap's form classes. Your sign up form should require an email address and password. No username and no password confirmation field. Include a signup button. Center the form on the page so that it doesn't take up the entire width.
**Reports.html**
The reports page uses bootstrap's *grid system* for layout. This is where your customers go to view the data reports available to them. Use bootstrap's grid system to create a two column layout. The left column is the sidebar (width:4) that contains a *list group* component. The right column is the main content area (width:8) and should include a sample report or chart. If you're feeling brave, try incorporating one of the examples from [D3.js](http://d3js.org/), even if you don't understand javascript yet.
## Review css selectors and properties
Mozilla has excellent css documention. Review the properties list and make sure you understand selectors. We'll be using them with JavaScript as well.
[Mozilla's CSS Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference): The goto reference for css questions.
[Code Academy CSS Practice](http://www.codecademy.com/tracks/web): Practice html and css at Code Academy.
## Review the command line and git
Two free books on the command line and on git were mentioned in class. Consider these books textbooks and study them.
[The Linux Command Line, by William Shots](http://linuxcommand.org/tlcl.php) : Read past the first four chapters. Start to get into the advanced material likes pipes and redirection.
[Pro Git](http://git-scm.com/book) : Make sure you have read the first two chapters, Getting Started and Git Basics, and begin working on branching in chapter three.
## Keep learning JavaScript
We start JavaScript programming next week! Make sure you come to class prepared. We will use the excellent and free [Eloquent JavaScript](http://eloquentjavascript.net/) for this class.
Read and practice with the first four chapters by the beginning of next week. Don't put this off!
If you would like additional JavaScript practice, sign up for a free account at [Code Academy](http://www.codecademy.com/) and begin working through their JavaScript lessons.
|
Ruby
|
UTF-8
| 1,095 | 4.25 | 4 |
[] |
no_license
|
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# output array
a.each {|x| puts x}
# output only if greater than 5
a.each {|x| puts x if x > 5}
# odd numbers only
a.each {|x| puts x if x % 2 != 0}
# append 11 to end of array
a.push 11 ## or can use a << 11
# prepend 0 to beginning of array
a.unshift 0
# remove 11 and append 3
a.pop
a << 3
# only unique elements of array but without modifying no bang, bang is exclamation mark and actually modifies the array
puts a.uniq
# hash in newer syntax
h = {a:1, b:2, c:3, d:4}
# hash in 1.8 syntax
h_1_8 = {:a => 1, :b => 2, :c => 3, :d => 4}
# get value of b key, newer syntax creates key as symbol, need to use colon to reference
puts h.select {|k,v| k == :b}
# add e/5 key value to hash
h.store(:e, 5) # with this syntax, apparently can't use e:5, colon before e to designate key as symbol
h.delete_if {|k,v| v < 3.5}
puts h
# add an array to a hash
h.store(:f, ['one', 'two', 'three'])
# vice versa, add a hash to an array - this actually contains an array within a hash within an array
string_arr = ['one', 'two', 'three']
string_arr << h
puts string_arr
|
Python
|
UTF-8
| 586 | 3.125 | 3 |
[] |
no_license
|
import os
import matplotlib.pyplot as plt
class RunningAverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, momentum=0.99):
self.momentum = momentum
self.reset()
def reset(self):
self.val = None
self.avg = 0
def update(self, val):
if self.val is None:
self.avg = val
else:
self.avg = self.avg * self.momentum + val * (1 - self.momentum)
self.val = val
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
|
Python
|
UTF-8
| 2,072 | 2.703125 | 3 |
[] |
no_license
|
import numpy
import cv2
from matplotlib import pyplot
from matplotlib.widgets import Button, Slider
import sys
sys.path.append("../library/")
import image_correction as ic
if len(sys.argv) != 2:
# http://stackoverflow.com/questions/2949974/how-to-exit-a-program-sys-stderr-write-or-print
sys.exit("Error: Num arguments should be 2. Actual arguments are "+len(sys.argv));
# Reading file names
input_file = sys.argv[1]
# Reading input image
img = cv2.imread(input_file)
print img.shape
rows,cols,ch = img.shape
threshold = 200
radius = 3
output = ic.InvDiffOfGaussian(img, radius, threshold)
# Start the ui loop
fig = pyplot.figure()
ax = fig.add_subplot(111)
fig1 = ax.imshow(output, cmap = 'gray', interpolation = 'bicubic')
# def onclick(event):
# print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
# event.button, event.x, event.y, event.xdata, event.ydata)
# cid = fig.canvas.mpl_connect('button_press_event', onclick)
# Updating threshold and radius
axcolor = 'lightgoldenrodyellow'
axthreshold = pyplot.axes([0.12, 0.04, 0.65, 0.03], axisbg=axcolor)
sthreshold = Slider(axthreshold, 'Threshold', 100, 255, valinit=threshold)
axradius = pyplot.axes([0.12, 0.01, 0.65, 0.03], axisbg=axcolor)
sradius = Slider(axradius, 'Radius', 1, 10, valinit=radius)
def update(val):
radius = sradius.val
threshold = sthreshold.val
output = ic.InvDiffOfGaussian(img, radius, threshold)
#fig1.draw()
ax.imshow(output, cmap = 'gray', interpolation = 'bicubic')
fig.canvas.draw_idle()
#print (sthreshold.val, sradius.val, radius, threshold)
sthreshold.on_changed(update)
sradius.on_changed(update)
# Do the actual processing
def on_button_press(event):
print (radius, threshold)
output = ic.InvDiffOfGaussian(img, radius, threshold)
ax.imshow(output, cmap = 'gray', interpolation = 'bicubic')
#print event
process = pyplot.axes([0.01, 0.01, 0.1, 0.075])
bprocess = Button(process, 'Process')
bprocess.on_clicked(on_button_press)
pyplot.xticks([]), pyplot.yticks([]) # to hide tick values on X and Y axis
pyplot.show()
|
C++
|
UTF-8
| 1,021 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
void printPath(vector<int>& path){
for(int i=0;i<path.size();i++){
cout<<path[i];
}
cout<<endl;
}
bool safe(int x,int y,vector<vector<bool> >& visited){
if(x>=0&&x<=visited.size()-1&&y>=0&&y<=visited[0].size()&&!visited[x][y]){
return true;
}
return false;
}
void findPath(vector<vector<bool> >& visited,int x,int y,int *n_path){
//cout<<"find("<<x<<","<<y<<")"<<endl;
if(x==visited.size()-1&&y==visited[0].size()-1){
*n_path = *n_path+1;
return;
}
visited[x][y] = true;
if(safe(x+1,y,visited)){
findPath(visited,x+1,y,n_path);
}
if(safe(x,y+1,visited)){
findPath(visited,x,y+1,n_path);
}
visited[x][y] = false;
}
int main() {
//code
int t;
cin>>t;
while(t--){
int m,n;
cin>>m>>n;
int npaths = 0;
vector<vector<bool> > visited(m,vector<bool>(n,false));
findPath(visited,0,0,&npaths);
cout<<npaths<<endl;
}
return 0;
}
|
Ruby
|
UTF-8
| 817 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
require 'basilico/event_handler.rb'
module Basilico
extend self
EVENTS = %w{start interrupt interrupt_over reset resume end break_end every}
def handlers
@event_handlers ||= []
end
def add_handler(klass)
handlers << klass
end
def run_all(event, *vars)
options = parse_variables(vars.flatten)
handlers.each do |handler|
next unless handler.handles?(event)
handler.new.send(event, options)
end
end
private
def self.parse_variables(vars)
vars.inject({}) do |hash, pair|
key, value = pair.split("=")
value = value.to_i if value =~ /\A\d+\Z/ and key != "title"
hash[key] = value
hash
end
end
end
# Load all handlers
Dir[File.join(File.dirname(__FILE__), "..", "event_handlers", "*.rb")].each do |handler|
require(handler)
end
|
JavaScript
|
UTF-8
| 1,166 | 3.546875 | 4 |
[] |
no_license
|
/**
* @param {number[][]} triangle
* @return {number}
*/
var minimumTotal = function(triangle) {
if (!triangle || !triangle[0]) {
return 0;
}
let min = triangle[0][0];
for (let i = 1; i < triangle.length; i++) {
let length = triangle[i].length;
min = Infinity;
for (let j = 0; j < length; j++) {
if (j == 0) {
triangle[i][0] += triangle[i - 1][0];
}
else if (j == length - 1) {
triangle[i][j] += triangle[i - 1][j - 1];
}
else {
triangle[i][j] += Math.min(triangle[i - 1][j - 1], triangle[i - 1][j]);
}
min = Math.min(triangle[i][j], min);
}
}
return min;
};
var minimumTotal = function(triangle) {
if (!triangle || !triangle[0]) {
return 0;
}
const N = triangle.length - 1;
const dp = triangle[N]
for (let i = triangle.length - 2; i >= 0; i--) {
const length = triangle[i].length;
for (let j = 0; j < length; j++) {
dp[j] = triangle[i][j] + Math.min(dp[j], dp[j + 1]);
}
}
return dp[0];
};
|
Markdown
|
UTF-8
| 9,717 | 2.53125 | 3 |
[] |
no_license
|
# IbookerEditorAndroidK
书客编辑器安卓Kotlin版。
>作者:邹峰立,微博:zrunker,邮箱:zrunker@yahoo.com,微信公众号:书客创作,个人平台:[www.ibooker.cc](www.ibooker.cc)。
>本文选自[书客创作](www.ibooker.cc)平台第131篇文章。[阅读原文](http://www.ibooker.cc/article/131/detail) , [书客编辑器安卓Kotlin版 - 体验版下载](https://www.pgyer.com/LPzU)

书客编辑器是一款基于Markdown标记语言的开源的富文本编辑器,它以简易的操作界面和强大的功能深受广大开发者的喜爱。正如官方所说:现在的版本不一定是最好的版本,却是最好的开源版本。官方地址:[editor.ibooker.cc](editor.ibooker.cc)。
下面针对书客编辑器安卓Kotlin版,进行详解说明。
### 效果图
在进行讲解之前,首先看一下书客编辑器安卓版的效果图:

### 一、引入资源
引入书客编辑器安卓Kotlin版的方式有很多,这里主要提供两种方式:
1、在build.gradle文件中添加以下代码:
```
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
```
```
dependencies {
compile 'com.github.zrunker:IbookerEditorAndroidK:v1.0.1'
}
```
2、在maven文件中添加以下代码:
```
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
```
```
<dependency>
<groupId>com.github.zrunker</groupId>
<artifactId>IbookerEditorAndroidK</artifactId>
<version>v1.0.1</version>
</dependency>
```
### 二、使用
书客编辑器安卓版简易所在就是只需要简单引入资源之后,可以直接进行使用。因为书客编辑器安卓版不仅仅提供了功能实现,还提供了界面。所以使用过程中,连界面绘制都不用了。
**界面分析**
书客编辑器安卓版界面大致分为三个部分,即编辑器顶部,内容区(编辑区+预览区)和底部(工具栏)。

首先在布局文件中引入书客编辑器安卓版控件,如布局文件为activity_main.xml,只需要在该文件内添加以下代码即可:
```
<?xml version="1.0" encoding="utf-8"?>
<cc.ibooker.ibookereditorklib.IbookerEditorView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ibookereditorview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
实际上IbookerEditorView继承LinearLayout,所以它具备LinearLayout的一切功能。
### 三、功能介绍
根据轮廓图可以看出,书客编辑器安卓版布局只有三个部分,所以关于书客编辑器安卓版功能模块也就分三个部分对外提供使用,即修改哪一个布局模块就是对于哪一个功能模块。
**顶部功能模块**
书客编辑器安卓版顶部实际上是采用IbookerEditorTopView控件进行呈现,所以要实现顶部相关控件功能首先要获取该控件。

书客编辑器安卓版顶部界面图,从左到右分别对应返回(back),撤销(undo),重做(redo),编辑模式(edit),预览模式(preview),帮助(help),关于(about)。知道每个按钮对应的功能,所以就可以去修改或完善相关实现过程。
例如修改返回按钮一些属性,可以使用一下代码:
```
// 设置书客编辑器顶部布局相关属性
ibookerEditorView.ibookerEditorTopView?.setBackImgVisibility(View.VISIBLE)?.setHelpIBtnVisibility(View.VISIBLE)
```
当然也可以通过IbookerEditorTopView获取相关控件,然后针对该控件进行逐一处理:
```
ibookerEditorView.ibookerEditorTopView?.backImg?.visibility = View.VISIBLE
```
这里只是使用返回按钮进行举例说,其他按钮使用规则更返回按钮一样。
**中间功能模块**
书客编辑器安卓版中间区域又分为两个部分,分别是编辑部分和预览部分,所以要修改相关功能就要获取到相关部分的控件。其中编辑部分由IbookerEditorEditView控件进行呈现,预览部分由IbookerEditorPreView控件进行呈现。
例如修改编辑部分相关属性,可以使用如下代码:
```
// 设置书客编辑器中间布局相关属性
ibookerEditorView.ibookerEditorVpView?.editView?.setIbookerEdHint("书客编辑器")?.setIbookerBackgroundColor(Color.parseColor("#DDDDDD"))
```
编辑部分并不是只有一个控件,所以也可以获取相关控件,然后针对特定控件进行逐一操作:
```
ibookerEditorView.ibookerEditorVpView?.editView?.ibookerEd?.setText("书客编辑器")
```
```
// 执行预览功能
ibookerEditorView.ibookerEditorVpView?.preView?.ibookerHtmlCompile("预览内容")
```
**底部功能模块**
书客编辑器安卓版,底部为工具栏,由IbookerEditorToolView进行呈现。
工具栏一共提供了30多种功能,每一个按钮对应一个功能。各个控件分别为:
```
boldIBtn, italicIBtn, strikeoutIBtn, underlineIBtn, capitalsIBtn,
uppercaseIBtn, lowercaseIBtn, h1IBtn, h2IBtn,
h3IBtn, h4IBtn, h5IBtn, h6IBtn, linkIBtn, quoteIBtn,
codeIBtn, imguIBtn, olIBtn, ulIBtn, unselectedIBtn,
selectedIBtn, tableIBtn, htmlIBtn, hrIBtn, emojiIBtn;
```
所以要修改底部相关属性,首先要获取到IbookerEditorToolView控件,然后对该控件进行操作。
```
// 设置书客编辑器底部布局相关属性
ibookerEditorView.ibookerEditorToolView?.setEmojiIBtnVisibility(View.GONE)
```
当然底部一共有30多个控件,也可以直接获取到相关控件,然后该控件进行操作,如:
```
ibookerEditorView.ibookerEditorToolView?.emojiIBtn?.visibility = View.GONE
```
**补充功能:按钮点击事件监听**
这里的按钮点击事件监听主要是针对顶部布局按钮和底部布局按钮。
顶部部分按钮点击事件监听,需要实现IbookerEditorTopView.OnTopClickListener接口,而每个按钮点击通过对应Tag来判断,具体代码如下:
```
// 顶部按钮点击事件监听
override fun onTopClick(tag: Any) {
if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IMG_BACK) {// 返回
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_UNDO) {// 撤销
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_REDO) {// 重做
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_EDIT) {// 编辑
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_PREVIEW) {// 预览
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_HELP) {// 帮助
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_ABOUT) {// 关于
}
}
```
其中IMG_BACK、IBTN_UNDO等变量是由IbookerEditorEnum枚举类提供。
底部部分按钮点击事件监听,需要实现IbookerEditorToolView.OnToolClickListener接口,而每个按钮点击通过对应Tag来判断,具体代码如下:
```
// 工具栏按钮点击事件监听
override fun onToolClick(tag: Any) {
if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_BOLD) {// 加粗
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_ITALIC) {// 斜体
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_STRIKEOUT) {// 删除线
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_UNDERLINE) {// 下划线
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_CAPITALS) {// 单词首字母大写
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_UPPERCASE) {// 字母转大写
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_LOWERCASE) {// 字母转小写
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_H1) {// 一级标题
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_H2) {// 二级标题
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_H3) {// 三级标题
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_H4) {// 四级标题
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_H5) {// 五级标题
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_H6) {// 六级标题
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_LINK) {// 超链接
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_QUOTE) {// 引用
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_CODE) {// 代码
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_IMG_U) {// 图片
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_OL) {// 数字列表
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_UL) {// 普通列表
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_UNSELECTED) {// 复选框未选中
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_SELECTED) {// 复选框选中
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_TABLE) {// 表格
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_HTML) {// HTML
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_HR) {// 分割线
} else if (tag == IbookerEditorEnum.TOOLVIEW_TAG.IBTN_EMOJI) {// emoji表情
}
}
```
其中IBTN_BOLD、IBTN_ITALIC等变量是由IbookerEditorEnum枚举类提供。
[Github地址](https://github.com/zrunker/IbookerEditorAndroidK/)
[阅读原文](http://www.ibooker.cc/article/131/detail)
----------

|
Go
|
UTF-8
| 582 | 3.140625 | 3 |
[] |
no_license
|
package pizza
type Pizza struct {
toppings []string
}
func (pizza Pizza) addToppingMethod(topping string) Pizza {
return Pizza{
toppings: append(pizza.toppings, topping),
}
}
func (pizza Pizza) PublicAddToppingMethod(topping string) Pizza {
return Pizza{
toppings: append(pizza.toppings, topping),
}
}
func addToppingBareFunction(pizza Pizza, topping string) Pizza {
return Pizza{
toppings: append(pizza.toppings, topping),
}
}
func PublicAddToppingBareFunction(pizza Pizza, topping string) Pizza {
return Pizza{
toppings: append(pizza.toppings, topping),
}
}
|
Java
|
ISO-8859-1
| 1,919 | 3.125 | 3 |
[] |
no_license
|
package controller;
import java.util.concurrent.Semaphore;
public class Threads extends Thread{
private int sld;
private int cod;
private int val;
private int cont;
private Semaphore [] sqDep;
private Conta conta[];
private int pos;
private static int transac;
public Threads(int pos, int cod, int sld, int val, int cont, Semaphore sqDep[], Conta [] conta) {
this.cod = cod;
this.sld = sld;
this.val = val;
this.cont = cont;
this.sqDep = sqDep;
this.conta = conta;
this.pos = pos;
}
public void run() {
try {
sqDep[cont].acquire();
fazTransacao();
transac ++;
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
mostraResultado();
sqDep[cont].release();
}
}
public void fazTransacao() {
conta[pos].setConta(cod);
conta[pos].setValor(val);
conta[pos].setSaldo(sld);
if (conta[pos].getValor() >= 0) {
conta[pos].setSaldo(conta[pos].getValor() + conta[pos].getSaldo());
}
else {
conta[pos].setSaldo(conta[pos].getSaldo() - conta[pos].getValor());
}
}
public void mostraResultado() {
if (transac == 20) {
for (int i = 0; i < 20; i ++) {
if (conta[i].getValor() >= 0) {
System.out.println("Transao realizada: Depsito");
System.out.println("Conta: " + conta[i].getConta() + " | Saldo anterior R$ " + (conta[i].getSaldo() - conta[i].getValor()) +
" | Valor do depsito R$ " + conta[i].getValor() + " | Saldo atual R$ " + conta[i].getSaldo() + "\n");
}
else {
conta[i].setValor(conta[i].getValor() * -1);
System.out.println("Transao realizada: Saque");
System.out.println("Conta: " + conta[i].getConta() + " | Saldo anterior R$ " + (conta[i].getSaldo() + conta[i].getValor()) +
" | Valor do saque R$ " + conta[i].getValor() + " | Saldo atual R$" + conta[i].getSaldo() +"\n");
}
}
}
}
}
|
JavaScript
|
UTF-8
| 1,320 | 3.796875 | 4 |
[] |
no_license
|
var letters = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z"
];
var wins = 0;
var losses = 0;
var computerPick;
var humanPick;
var guess = [];
var guessLeft = 9;
guessGame();
function guessGame() {
computerPick = letters[Math.floor(Math.random() * 26)];
console.log(computerPick);
getguess();
function getguess() {
document.onkeyup = function(event) {
var humanPick = event.key;
guess.push(humanPick.toUpperCase());
console.log(humanPick);
if (humanPick.toUpperCase() === computerPick) {
guessLeft = 9;
wins++;
document.getElementById("wins").innerHTML = "Wins: " + wins;
reset();
} else calcLosses();
};
}
function calcLosses() {
document.getElementById("guess").innerHTML = "Your Guesses:" + guess;
guessLeft--;
document.getElementById("guessLeft").innerHTML = "Guess left: " + guessLeft;
if (guessLeft === 0) {
alert("Computer Letter is " + computerPick);
losses++;
document.getElementById("losses").innerHTML = "Losses: " + losses;
reset();
} else getguess();
}
function reset() {
guess = [];
guessLeft = 9;
guessGame();
}
}
|
Java
|
UTF-8
| 205 | 2.015625 | 2 |
[] |
no_license
|
package archivos.pilas;
import mis.clases.Comprobante;
public interface IPila {
public void apilar(Comprobante item);
public Comprobante desapilar();
public boolean estaVacia();
}
|
TypeScript
|
UTF-8
| 539 | 3.390625 | 3 |
[] |
no_license
|
// https://leetcode-cn.com/problems/unique-binary-search-trees/
let temp: Array<number> = []
export function numTrees(n: number): number {
temp = new Array(n+1).fill(0)
return count(1, n)
};
function count(start: number, end: number): number {
if (start > end) {
return 1
}
if (temp[end-start]) {
return temp[end-start]
}
let total = 0
for (let i = start; i <= end; i++) {
let left = count(start, i-1)
let right = count(i+1, end)
total += left * right
}
temp[end-start] = total
return total
}
|
C#
|
UTF-8
| 586 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
namespace WpfApp1
{
class program
{
static void Main(string[] args)
{
string w = Console.ReadLine();
Console.WriteLine(w + 's');
Console.ReadLine();
}
static int Max(int a, int b)
{
if (a <= b) return b;
else return a;
}
static int Min(int a,int b)
{
if (a == Max(a, b)) return b;
else return a;
}
}
}
|
JavaScript
|
UTF-8
| 511 | 2.5625 | 3 |
[] |
no_license
|
import express from 'express';
const server = express();
let port = 8080;
let host = "localhost";
server.use(express.static('.'));
// Basic Response with a message
server.get(['/echo','/echo/:message'], (req,res) => {
let messageReceived = req.params.message || "No Message Received";
console.info("Message Received: " + messageReceived);
res.send({
message: messageReceived
})
});
server.listen(port,host, () => {
console.info("Echo Server listening on port ", host, port);
});
|
Markdown
|
UTF-8
| 3,175 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
---
slug: contest-entries-get-creative-with-gingerbread
title: "Contest entries get creative with gingerbread"
date: January 01 2020
---
<p>There are gingerbread bakers and gingerbread artists.</p>
<p>And then there are gingerbread overachievers.</p>
<p>
The group representing Focus the Region, the annual teach-in on climate
change, fits into the latter category. The faculty and staff members and the
single student on the team came up with a “house” they called CandyLEED
Campus. Apparently, Leadership in Energy and Environmental Design (LEED®) is
flexible enough to apply to all building types – gingerbread as well as wood
and cement.
</p>
<p>
Their entry earned enough credits to be awarded a platinum rating, using such
things as skylights made from salvaged hard candy, melted and cooled into
sheets, a garden with drip irrigation, chocolate bar solar panels and a living
sweets roof. And they had a LEED®-accredited professional on hand.
</p>
<p>
For their efforts, Team Focus the Region took first place in CSUMB’s seventh
annual gingerbread house contest on Dec. 10. They were awarded a tin of butter
cookies, a pizza party for 10 (courtesy of Sodexo) and possession of the
trophy until next year’s competition.
</p>
<p>
The contest drew nine teams representing several dozen employees. Each group
was given a kit consisting of the basic pieces and encouraged to let their
imaginations run wild.
</p>
<p>
A panel was invited to judge the entries. Judges included Ken Turgen of Wald,
Runke and Dost architects, and chair of the Marina Planning Commission; Julie
Ann Lozano of Monterey Bay Office Systems; Charles Wesley of Sodexo catering;
and former CSUMB staff member Courtney Kuhn of Quail Lodge.
</p>
<p>
The judges selected the top three finishers. Those who attended the staff and
faculty holiday party on Dec. 10 were invited to cast their vote for the
People’s Choice Award. The team representing Student Housing and Residential
Life took that honor with their model of Chocolate Mountain from the CandyLand
board game.
</p>
<p>
All nine entries were displayed in the lobby of the University Center during
the party, and then went to local community organizations for display.
</p>
<p>
<em
>(Note: More photos can be viewed
<a href="https://www.flickr.com/photos/csumb/sets/72157625472252033/">here</a
>.)</em
>
</p>
<p>Winning teams:</p>
<p>
• <strong>First-place</strong>: Team CandyLEED Campus; team leader Dan
Fernandez, team members Brad Barbeau, Duane Lindsay, Kevin Miller, Laura Lee
Lienk, Mark Lasnik, Megan Tolbert, Rebecca Kersnar and Sarah Dahlen.
</p>
<p>
• <strong>Second-place</strong>: Team Big Daddy Canes from Facilities Services
and Operations; team leader Susie Hernandez, team members Wendy Rutledge,
Jennifer Benallal, Alfredo Corona, Doug Lazzaroni, Andy Sierra, Benny Sanchez,
Tony Cabeca, Augie Eclarin, Lloyd Eads
</p>
<p>
• <strong>Third-place</strong>: University Police Department; team leader
Claudia Velazquez, team members Lupe Cabeca, Maria Amezquita, Nicki Hodges,
Stacie Russo, Christine Pressas Cesar Velazquez
</p>
<p>
<strong>People’s Choice Award</strong>: Student Housing and Residential Life;
team leader Melody Rico, team members Alexandra Froehlich, Andrea
Dominguez-Blanco, Antoinette Olano-Defensor, Gayleene Badiango-Rullan,
Jennifer Plueard, Priscilla Alvarez, Tom Burns
</p>
|
Python
|
UTF-8
| 2,294 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
@testModuleNameCodeCoverage.AddMethodTesting
@testModuleNameCodeCoverage.AddPropertyTesting
class testClassName(unittest.TestCase):
###################################
# Tests of class methods #
###################################
def testmethod_name(self):
# Tests the method_name method of the ClassName class
# - Test all permutations of "good" argument-values:
# - Test all permutations of each "bad" argument-value
# set against "good" values for the other arguments:
self.fail('testmethod_name is not yet implemented')
###################################
# Tests of class properties #
###################################
# def testproperty_name(self):
# # Tests the property_name property of the ClassName class
# # - Assert that the getter is correct:
# self.assertEqual(
# ClassName.property_name.fget,
# ClassName._get_property_name,
# 'ClassName.property_name is expected to use the '
# '_get_property_name method as its getter-method'
# )
# # - If property_name is not expected to be publicly settable,
# # the second item here (ClassName._set_property_name) should
# # be changed to None, and the failure message adjusted
# # accordingly:
# # - Assert that the setter is correct:
# self.assertEqual(
# ClassName.property_name.fset,
# ClassName._set_property_name,
# 'ClassName.property_name is expected to use the '
# '_set_property_name method as its setter-method'
# )
# # - If property_name is not expected to be publicly deletable,
# # the second item here (ClassName._del_property_name) should
# # be changed to None, and the failure message adjusted
# # accordingly:
# # - Assert that the deleter is correct:
# self.assertEqual(
# ClassName.property_name.fdel,
# ClassName._del_property_name,
# 'ClassName.property_name is expected to use the '
# '_del_property_name method as its deleter-method'
# )
LocalSuite.addTests(
unittest.TestLoader().loadTestsFromTestCase(
testClassName
)
)
|
Java
|
UTF-8
| 503 | 2.015625 | 2 |
[
"MIT"
] |
permissive
|
package kr.pe.nuti.home.api.pack.todo.domain;
import kr.pe.nuti.home.api.core.annotation.TrackLog;
import kr.pe.nuti.home.api.pack.todo.enumeration.TodoState;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Data
@Entity(name = "todo_item")
@TrackLog
public class TodoItem {
@Id
@Column(name = "idx")
private Long idx;
private String title;
private String content;
@Column(name = "state")
private TodoState state;
}
|
Markdown
|
UTF-8
| 602 | 2.59375 | 3 |
[] |
no_license
|
# Lecture 12
*29/10/2019*
## Pipelined Control
- Control signals are derived from instruction
- Start with execution stage
### Design
- If a sequence has many dependencies, it may need to forward data.
- Forwarding implies reading ALU operands from a source other than the register file.
### When to forward
- Data hazards when 2nd next instruction, it has to be read from the memory write back.
- Or else it has to be forwarded from Exclusoing memory for next instruction
- If theres an overwrite of a register during the pipeline, forward the most recent value (In the execution memory stage)
|
C#
|
UTF-8
| 3,989 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using TestGenerator.business;
using TestGenerator.data.model;
using TestGenerator.DataAccessLayer;
using static System.Windows.Forms.ListViewItem;
namespace TestGenerator.presentation
{
public partial class FormAdmin : Form
{
public FormAdmin()
{
InitializeComponent();
}
private void FormAdmin_Load(object sender, EventArgs e)
{
populateRolesComboBox();
populateUsersList();
}
private void populateRolesComboBox()
{
//Get the roles for add a new user ...
RoleBusiness userRoles = new RoleBusiness();
List<RolesDataModel> usersRolesList = userRoles.readAll();
//Set the display member and value memebr / admin = 1
comboBoxUserRoles.DisplayMember = "Text";
comboBoxUserRoles.ValueMember = "Value";
List<ComboboxItem> list = new List<ComboboxItem>();
ComboboxItem item = new ComboboxItem();
for (var i = 0; i < usersRolesList.Count; i++)
{
item = new ComboboxItem();
item.Text = usersRolesList[i].Role_name;
item.Value = usersRolesList[i].Role_id;
list.Add(item);
}
comboBoxUserRoles.DataSource = list; // Bind combobox to a datasource
}
private void populateUsersList()
{
//Get all users
UserBusiness userBusiness = new UserBusiness();
UserDataGateway userGateway = new UserDataGateway();
List<UserDataModel> usersToShow = userGateway.readAll();
//preapre list view
listViewUsers.Items.Clear();
listViewUsers.View = View.Details;
listViewUsers.Columns.Add("Display Name", 350);
listViewUsers.Columns.Add("Username", 180);
listViewUsers.Columns.Add("User Type", 120);
foreach (UserDataModel user in usersToShow)
{
ListViewItem item = new ListViewItem();
item.Text = user.Display_name.ToString();
item.SubItems.Add(user.Display_name.ToString());
item.SubItems.Add(user.Role_name.ToString());
listViewUsers.Items.Add(item);
}
}
private void buttonAddUser_Click(object sender, EventArgs e)
{
//Check the role
RoleBusiness userRoles = new RoleBusiness();
List<RolesDataModel> usersRolesList = userRoles.readAll();
UserBusiness userToAdd = new UserBusiness(textBoxUserName.Text, textBoxUserPassword.Text, textBoxUserDisplayName.Text, Int16.Parse(comboBoxUserRoles.SelectedValue.ToString()));
//Show buttons
uiAddingUser();
if (userToAdd.createUser())
{
labelCreateUserMessage.Text = "User created.";
//Populate the suers list
populateUsersList();
}
else
{
labelCreateUserMessage.Text = "User already exists.";
}
}
private void uiAddingUser()
{
//Preapre the label
labelCreateUserMessage.Visible = true;
//Preapre the clear button
buttonClearForm.Visible = true;
}
private void buttonClearForm_Click(object sender, EventArgs e)
{
textBoxUserDisplayName.Text = "";
textBoxUserName.Text = "";
textBoxUserPassword.Text = "";
buttonClearForm.Visible = false;
labelCreateUserMessage.Visible = false;
}
private void button3_Click(object sender, EventArgs e)
{
}
}
}
|
Java
|
UTF-8
| 368 | 2.828125 | 3 |
[] |
no_license
|
package interfaceSegregationPrinciple.withUsePrinciple;
/**
* Created by h.elahi on Dec, 2020
*/
public class SmartPhone implements PublicTechnology,SpecialTechnology {
@Override
public void GPS() {
System.out.println("SmartPhone has GPS");
}
@Override
public void Radio() {
System.out.println("SmartPhone has Radio");
}
}
|
C++
|
UTF-8
| 13,395 | 2.703125 | 3 |
[] |
no_license
|
/*** Included Header Files ***/
#include "CoreProject.h"
#include "CoreObject.h"
#include "CoreAttribute.h"
#include "CoreMetaProject.h"
#include "CoreMetaObject.h"
// --------------------------- Private CoreProject Functions ---------------------------
CoreProject::CoreProject(CoreMetaProject* &coreMetaProject, ICoreStorage* &storage)
: _storage(storage), _coreMetaProject(coreMetaProject), _isDirty(false), _objectHash(), _transactionList()
{
ASSERT( coreMetaProject != NULL );
ASSERT( storage != NULL );
}
std::string CoreProject::GetFirstToken(const std::string &connection)
{
// Get a local copy
std::string con = connection;
// Find the equals
size_t pos = con.find('=');
// If there is an =, get just the string to that point
if( pos != std::string::npos )
con.resize(pos);
// Find the semicolon
pos = con.find(';');
// If there is a ;, get just the string to that point
if( pos != std::string::npos )
con.resize(pos);
// Return what is left
return con;
}
void CoreProject::RegisterObject(const Uuid &uuid, CoreObjectBase *object) throw()
{
// Check some things
ASSERT( this->_storage != NULL );
ASSERT( uuid != Uuid::Null() );
ASSERT( object != NULL );
// Must not find object already in the hash
ASSERT( this->_objectHash.find(uuid) == this->_objectHash.end() );
// Insert the object into the hash
this->_objectHash.insert( std::make_pair(uuid, object) );
}
void CoreProject::UnregisterObject(const Uuid &uuid) throw()
{
ASSERT( this->_storage != NULL );
ASSERT( uuid != Uuid::Null() );
// Is the pair in the hash?
ObjectHashIterator objIter = this->_objectHash.find(uuid);
if( objIter != this->_objectHash.end() )
{
// Remove the object from the hash
this->_objectHash.erase( objIter );
return;
}
// Really should assert here. Should never have issues
ASSERT(false);
}
ICoreStorage* CoreProject::SetStorageObject(const Uuid &uuid) throw()
{
// Try to open the object at the storage level
Result_t result = this->_storage->OpenObject(uuid);
// Really should be good here
ASSERT( result == S_OK );
return this->_storage;
}
void CoreProject::RegisterTransactionItem(CoreAttributeBase* attribute) throw()
{
// Make sure we are in a transaction
ASSERT( !this->_transactionList.empty() );
// Add this attribute to the list of changes
this->_transactionList.front().attributes.push_back(attribute);
}
// --------------------------- Public CoreProject Functions ---------------------------
CoreProject::~CoreProject()
{
// Do some checks before we leave (pretty much everything has to be empty)
if( !this->_objectHash.empty() )
{
std::cout << "Forgotten Objects in CoreProject ObjectHash: " << this->_objectHash.size() << std::endl;
ObjectHash::iterator hashIter = this->_objectHash.begin();
while (hashIter != this->_objectHash.end())
{
CoreObjectBase* objBase = hashIter->second;
CoreMetaObject* metaObj;
objBase->MetaObject(metaObj);
std::string name, metaName;
metaObj->GetName(metaName);
Result_t result = this->BeginTransaction(true);
ASSERT( result == S_OK );
result = objBase->GetAttributeValue(ATTRID_NAME, name);
if ( result != S_OK )
{
std::cout << metaObj;
name = "";
}
result = this->CommitTransaction();
ASSERT( result == S_OK );
std::cout << "\tForgotten Object: (" << metaName << ") named " << name << ".\n";
++hashIter;
}
}
ASSERT( this->_transactionList.empty() );
// Delete any storage
if (this->_storage != NULL) delete this->_storage;
// Delete the CoreMetaProject
if (this->_coreMetaProject != NULL) delete this->_coreMetaProject;
this->_coreMetaProject = NULL;
}
const Result_t CoreProject::Create(const std::string &connection, CoreMetaProject* coreMetaProject, CoreProject* &project) throw()
{
if( connection == "" ) return E_NAMEMISSING;
if( coreMetaProject == NULL ) return E_META_NOTOPEN;
// What type of file are we trying to open
std::string con = CoreProject::GetFirstToken(connection);
ICoreStorage* coreStorage = NULL;
if( con == "MGA" )
{
// Clean up the filename
std::string cleanFileName = connection;
cleanFileName.erase(0, 4);
// Create the CoreStorage for the project
Result_t retVal = ICoreStorage::Create(con, cleanFileName, coreMetaProject, coreStorage);
if ( retVal != S_OK )
{
delete coreMetaProject;
return retVal;
}
}
if( coreStorage == NULL )
{
// Do something to signal a failure to create CoreStorage
delete coreMetaProject;
return E_UNKNOWN_STORAGE;
}
// Create the new CoreProject
project = new CoreProject(coreMetaProject, coreStorage);
ASSERT( project != NULL );
return S_OK;
}
const Result_t CoreProject::Open(const std::string &connection, CoreMetaProject* coreMetaProject, CoreProject* &project) throw()
{
if( connection == "" ) return E_NAMEMISSING;
if( coreMetaProject == NULL ) return E_META_NOTOPEN;
// Now figure out what CoreStorage to use
std::string con = CoreProject::GetFirstToken(connection);
ICoreStorage* coreStorage = NULL;
if( con == "MGA" )
{
// Clean up the filename
std::string cleanFileName = connection;
cleanFileName.erase(0, 4);
// Open the CoreStorage for the project
Result_t retVal = ICoreStorage::Open(con, cleanFileName, coreMetaProject, coreStorage);
if ( retVal != S_OK )
{
delete coreMetaProject;
return retVal;
}
}
// Make sure we have a valid storage object
if( coreStorage == NULL )
{
// Do something to signal a failure to create CoreStorage
delete coreMetaProject;
return E_UNKNOWN_STORAGE;
}
// Create the new CoreProject
project = new CoreProject(coreMetaProject, coreStorage);
ASSERT( project != NULL );
return S_OK;
}
const Result_t CoreProject::Save(const std::string &filename, const bool &force) throw()
{
if( filename == "" ) return E_NAMEMISSING;
if( !this->_transactionList.empty() ) return E_TRANSACTION;
ASSERT( this->_storage != NULL );
// Ask the coreStorage to save itself
return this->_storage->Save(filename, force);
}
const Result_t CoreProject::BeginTransaction(const bool &readOnly) throw()
{
ASSERT( this->_storage != NULL );
// Make sure a read-write transaction is not being requested nested inside of a read-only
if( !this->_transactionList.empty() && this->_transactionList.front().readOnly && !readOnly) return E_READONLY;
// Start the transaction at the storage level
this->_storage->BeginTransaction();
// Create the new transaction item and put it on top of the list
this->_transactionList.push_front( Transaction() );
// Set the transaction read/write type
this->_transactionList.front().readOnly = readOnly;
return S_OK;
}
const Result_t CoreProject::CommitTransaction(void) throw()
{
ASSERT( this->_storage != NULL );
if( this->_transactionList.empty() ) return S_OK;
// Is this a nested commit transaction
if( this->_transactionList.size() > 1 )
{
// Get the transaction and remove it from the list
Transaction transaction = this->_transactionList.front();
this->_transactionList.pop_front();
// Get the parent transaction
Transaction &parentTransaction = this->_transactionList.front();
// Append nested transaction onto end of parent transaction
parentTransaction.createdObjects.splice(parentTransaction.createdObjects.begin(), transaction.createdObjects);
parentTransaction.attributes.splice(parentTransaction.attributes.begin(), transaction.attributes);
parentTransaction.deletedObjects.splice(parentTransaction.deletedObjects.begin(), transaction.deletedObjects);
}
// This is a final commit
else
{
// Get the transaction and process
Transaction &transaction = this->_transactionList.front();
// Don't need to worry about CreateObjects since they are already in storage)
transaction.createdObjects.clear();
// Go through all attribute changes and write into storage
std::list<CoreAttributeBase*>::iterator attrIter = transaction.attributes.begin();
while( attrIter != transaction.attributes.end() )
{
// Force it to write to storage and condense its values list
(*attrIter)->CommitTransaction();
++attrIter;
}
// Go through all object deletes and write into storage
std::list<Uuid>::iterator deletedIter = transaction.deletedObjects.begin();
while( deletedIter != transaction.deletedObjects.end() )
{
// Set storage to this object and delete it
Result_t result = this->_storage->OpenObject(*deletedIter);
ASSERT( result == S_OK );
result = this->_storage->DeleteObject();
ASSERT( result == S_OK );
// Move on to the next deleted object
++deletedIter;
}
// Commit the transaction in storage
this->_storage->CommitTransaction();
// Remove the final transaction
this->_transactionList.pop_front();
ASSERT( this->_transactionList.empty() );
}
// All is good
return S_OK;
}
const Result_t CoreProject::AbortTransaction(void) throw()
{
ASSERT( this->_storage != NULL );
if( this->_transactionList.empty() ) return S_OK;
// Get the transaction and process
Transaction &transaction = this->_transactionList.front();
// Go through all attribute changes and abort them
std::list<CoreAttributeBase*>::iterator attrIter = transaction.attributes.begin();
while( attrIter != transaction.attributes.end() )
{
// Revert this value change in the attribute
(*attrIter)->AbortTransaction();
++attrIter;
}
// Nothing needs to be done for deleted since they are reconnected via attribute reversions
transaction.deletedObjects.clear();
// Go through all created objects and delete from storage
std::list<Uuid>::iterator createdIter = transaction.createdObjects.begin();
while( createdIter != transaction.createdObjects.end() )
{
// Set storage to this object and delete it
Result_t result = this->_storage->OpenObject(*createdIter);
ASSERT( result == S_OK );
result = this->_storage->DeleteObject();
ASSERT( result == S_OK );
// Move on to the next created object
++createdIter;
}
// Remove the transaction and move on
this->_transactionList.pop_front();
// If this was the last transaction, call AbortTransaction on storage
if (this->_transactionList.empty()) this->_storage->AbortTransaction();
// All is good
return S_OK;
}
const Result_t CoreProject::Object(const Uuid &uuid, CoreObject &object) throw()
{
if( uuid == Uuid::Null() ) return E_INVALID_USAGE;
if( this->_transactionList.empty() ) return E_TRANSACTION;
// Have we already fetched this object
ObjectHashIterator objectIter = this->_objectHash.find(uuid);
if( objectIter != this->_objectHash.end() )
{
ASSERT( objectIter->second != NULL );
// Create a CoreObject(smart pointer) for the object
object = CoreObject(objectIter->second);
}
// Otherwise, we have to instantiate this object (this will register it to the project)
else
{
Result_t result = CoreObjectBase::Create(this, uuid, object);
if( result != S_OK ) return result;
}
ASSERT( object != NULL );
return S_OK;
}
const Result_t CoreProject::CreateObject(const MetaID_t &metaID, CoreObject &object) throw()
{
if( metaID == METAID_NONE ) return E_INVALID_USAGE;
// Must be in a write transaction
if( this->_transactionList.empty() ) return E_TRANSACTION;
if( this->_transactionList.front().readOnly ) return E_READONLY;
// Create an object of the specified MetaID (call to ICoreStorage)
Uuid uuid = Uuid::Null();
Result_t result = this->_storage->CreateObject(metaID, uuid);
ASSERT( result == S_OK && uuid != Uuid::Null() );
// Now create the corresponding CoreObjectBase and CoreObject pointer
result = CoreObjectBase::Create(this, uuid, object);
if( result != S_OK )
{
// Delete that object from storage
Result_t tmpResult = this->_storage->DeleteObject();
ASSERT( tmpResult == S_OK );
return result;
}
ASSERT( object != NULL );
// Add the object into the created objects list of the transaction
this->_transactionList.front().createdObjects.push_back( uuid );
return S_OK;
}
const Result_t CoreProject::RootObject(CoreObject &coreObject) throw()
{
// Get the root object from the storage
Uuid uuid = Uuid::Null();
Result_t result = this->_storage->RootUuid(uuid);
ASSERT( result == S_OK );
ASSERT( uuid != Uuid::Null() );
return this->Object(uuid, coreObject);
}
const Result_t CoreProject::DeleteObject(const Uuid &uuid) throw()
{
if( uuid == Uuid::Null() ) return E_INVALID_USAGE;
// Must be in a write transaction
if( this->_transactionList.empty() ) return E_TRANSACTION;
if( this->_transactionList.front().readOnly ) return E_READONLY;
// Is this object in the objectHash? Don't allow delete if so
if( this->_objectHash.find(uuid) != this->_objectHash.end() ) return E_LOCK_VIOLATION;
// Open the object with the specified Uuid (call to ICoreStorage)
Result_t result = this->_storage->OpenObject(uuid);
if( result != S_OK ) return result;
// Now delete it in storage
result = this->_storage->DeleteObject();
if( result != S_OK ) return result;
// Add object to deleted objects list of the transaction
this->_transactionList.front().deletedObjects.push_back(uuid);
return S_OK;
}
|
C#
|
UTF-8
| 10,076 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using FastMember;
using Semicolon.Attributes;
using Semicolon.Binding;
using Semicolon.Exceptions;
using Semicolon.Extensions;
// ReSharper disable ArgumentsStyleLiteral
namespace Semicolon
{
/// <summary>
/// This is the main parser class. New this one up, passing as <typeparamref name="TRow"/> the type you want to represent each row of data to extract.
/// Please note that the type does not have to bind to ALL columns of the CSV data, but all columns (configured with <see cref="CsvColumnAttribute"/>
/// on properties with public setters) MUST be resolveable from the column name configured.
/// </summary>
public class Parser<TRow>
{
readonly Options _options;
readonly TypeAccessor _accessor = TypeAccessor.Create(typeof(TRow));
/// <summary>
/// Creates the parser with default options
/// </summary>
public Parser() : this(null)
{
}
/// <summary>
/// Creates the CSV parser using the given <paramref name="options"/>. If no options are given, <see cref="Options.Default"/> will be used
/// </summary>
public Parser(Options options) => _options = options ?? Options.Default();
/// <summary>
/// Parses the given CSV string
/// </summary>
public IEnumerable<TRow> ParseCsv(string csv)
{
if (csv == null) throw new ArgumentNullException(nameof(csv));
using (var reader = new StringReader(csv))
{
foreach (var row in ParseCsv(reader))
{
yield return row;
}
}
}
/// <summary>
/// Parses CSV from the given <paramref name="textReader"/>
/// </summary>
public IEnumerable<TRow> ParseCsv(TextReader textReader)
{
if (textReader == null) throw new ArgumentNullException(nameof(textReader));
var headers = GetHeaders(textReader);
var rowParser = GetRowparser(headers);
while (true)
{
var line = textReader.ReadLine();
if (line == null) yield break;
var values = SplitLine(line);
yield return rowParser(values);
}
}
string[] GetHeaders(TextReader textReader)
{
if (_options.Headers.Any()) return _options.Headers.ToArray();
var line = textReader.ReadLine()
?? throw new FormatException($"Expected the first line to contain a '{_options.ColumnSeparator}'-separated list of column headers");
if (string.IsNullOrWhiteSpace(line))
{
throw new FormatException("The first line of the CSV text was empty. Please make the necessary trimming of the CSV text, before passing it to the parser");
}
var headers = SplitLine(line)
.Select(text => text.Trim())
.ToArray();
return headers;
}
string[] SplitLine(string line)
{
var values = line.Split(new[] { _options.ColumnSeparator }, StringSplitOptions.None);
if (_options.ValueDelimiter != null)
{
return values
.Select(value => value.TrimOne(_options.ValueDelimiter.Value))
.ToArray();
}
return values;
}
Func<string[], TRow> GetRowparser(string[] headers)
{
Member[] GetMembersForHeader(string header) => _accessor.GetMembers()
.Where(m => m.HasAttribute<CsvColumnAttribute>(c => IsColumnMatch(header, c.Name)))
.ToArray();
var members = headers.Select(GetMembersForHeader).ToList();
var propertiesWithoutCsvColumns = _accessor.GetMembers()
.Select(m => new
{
Member = m,
CsvColumnAttribute = m.GetAttribute<CsvColumnAttribute>()
})
.Where(a => a.CsvColumnAttribute != null)
.Where(a => !headers.Any(nameFromCsvHeader => IsColumnMatch(nameFromCsvHeader, a.CsvColumnAttribute.Name)))
.ToList();
if (propertiesWithoutCsvColumns.Any())
{
throw new ArgumentException($@"Cannot parse CSV into {typeof(TRow)}, because the CSV data lacks columns for the following properties:
{string.Join(Environment.NewLine, propertiesWithoutCsvColumns.Select(p => $" {p.Member.Name}: CSV column '{p.CsvColumnAttribute.Name}'"))}
The CSV data contains the following columns:
{string.Join(Environment.NewLine, headers.Select(name => $" {name}"))}
Please ensure that all CSV columns referenced from the row type can be resolved from the CSV passed to the parser.");
}
TRow CreateNew()
{
try
{
return (TRow)_accessor.CreateNew();
}
catch (Exception exception)
{
throw new ApplicationException($"Could not create instance of {typeof(TRow)}", exception);
}
}
var getters = members
.Select(memberForHeader =>
{
return memberForHeader
.Select(member =>
{
var customBinderType = member.GetAttribute<CsvColumnAttribute>().Binder;
var binder = customBinderType != null
? GetCustomBinderInstance(customBinderType)
: Predefined.GetBinderOrNull(member.Type)
?? throw new ArgumentException($"Sorry, don't know how to bind property {member.Name} of type {member.Type}");
return new { Member = member, Binder = GetValueGetter(binder, member) };
})
.ToArray();
})
.ToArray();
return values =>
{
var row = CreateNew();
try
{
var maxIndex = Math.Min(values.Length, getters.Length);
for (var index = 0; index < maxIndex; index++)
{
var textValue = values[index];
var gettersForThisValue = getters[index];
foreach (var getter in gettersForThisValue)
{
var member = getter.Member;
var binder = getter.Binder;
var name = member.Name;
var objectValue = binder(textValue, _options.CultureInfo);
try
{
_accessor[row, name] = objectValue;
}
catch (ArgumentOutOfRangeException exception) when (exception.ParamName == "name")
{
throw new CsvParserException($@"Error when setting property {name} = {textValue}
This is probably an indication that the property does not have a public setter.
Bound properties must have a public setter, so Semicolon can set their values.", exception);
}
catch (Exception exception)
{
throw new CsvParserException($"Error when setting property {name} = {textValue}", exception);
}
}
}
return row;
}
catch (Exception exception)
{
throw new CsvParserException($@"Error when binding CSV values
{string.Join(Environment.NewLine, values.Select(v => $" {v}"))}
to instance of {typeof(TRow)}", exception);
}
};
}
static Func<string, CultureInfo, object> GetValueGetter(IBinder binder, Member member)
{
return (value, culture) =>
{
try
{
return binder.GetValue(culture, value);
}
catch (FormatException exception)
{
throw new FormatException(
$"Could not parse the value '{value}' into {member.Type} using the culture {culture}",
exception);
}
};
}
static IBinder GetCustomBinderInstance(Type customBinderType)
{
try
{
var binder = (IBinder)TypeAccessor.Create(customBinderType).CreateNew();
return binder;
//return (value, culture) =>
//{
// try
// {
// return binder.GetValue(culture, value);
// }
// catch (Exception exception)
// {
// throw new FormatException(
// $"Could not bind value '{value}' using instance of custom binder {binder.GetType()}",
// exception);
// }
//};
}
catch (Exception exception)
{
throw new ArgumentException(
$"Could not create custom binder of type {customBinderType}. Please note that custom binders must implement IBinder and have a default constructor to work.",
exception);
}
}
static bool IsColumnMatch(string headerFromCsv, string nameFromAttribute) => nameFromAttribute == headerFromCsv;
}
}
|
Java
|
MacCentralEurope
| 9,010 | 2.546875 | 3 |
[] |
no_license
|
package projetsystemC;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Fenetre extends JFrame implements ChangeListener{
public static final long serialVersionUID = 1L;
public static Fenetre f =null;
public static int periode;
//public static JButton ButtonLancement=new JButton("Lancer Simulation");
public static Container contenant=null;
public static JPanel pane = new JPanel();
public static Vector<String> vectdonnee;
//public static Cursor curseur=null;
public static JSlider slider = new JSlider(JSlider.VERTICAL,3000,20000,4000);
public static JTextArea echo = new JTextArea();
public static JTextArea textArea = new JTextArea();
public Fenetre(){
super();
construction();//On initialise notre fentre
}
private void construction(){
ImageIcon monIcon= new ImageIcon("iconeprojet.png");
setIconImage(monIcon.getImage());
setTitle("Simulation du Bloc de gestion des concurrences BGC"); //On donne un titre l'application
setSize(970,660); //On donne une taille notre fentre
setLocationRelativeTo(null); //On centre la fentre sur l'cran
setResizable(true); //On interdit le redimensionnement de la fentre
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //On dit l'application de se fermer lors du clic sur la croix
slider.setValue(10000);
periode = slider.getValue();
//slider.setValue(periode);
slider.addChangeListener(this);
// ButtonLancement.addActionListener(this);
}
public void stateChanged(ChangeEvent ce){
periode = slider.getValue();
System.out.print("------->"+periode);
//String str = Integer.toString(value);
// label.setText(str);
}
public static Vector<String> executer(String command) {
Vector<String> OutPut =new Vector<String>();
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
String temp ="";
int i =0;
while ((line = input.readLine()) != null) {
if(line.startsWith("Decision finale")){//i==27){
//System.out.println((line));//.split(" : ")[1]));//.split(" vert")[0]);
OutPut.add(0, (String)(line.split(" : ")[1]));//.split(" vert")[0];
System.out.println(OutPut);
echo.setText(line); }
if(i>=20){temp += line+"\n";}
//System.out.println("ligne "+i+" = "+line);
i=i+1; }
//echo.setText(temp);
OutPut.add(1,(String)temp);
} catch (IOException ex) { }
return OutPut; }
public static void commanderfeux(String cmd,String res){
String O="", E="", N="", S ="" ;
if(cmd.contains("feux1")){O ="vert"; E ="rouge" ;
N="rouge"; S="rouge";}
if(cmd.contains("feux2")){ O ="rouge" ; E ="vert" ;
N="rouge"; S="rouge";}
if(cmd.contains("feux3")){ O ="rouge" ; E ="rouge" ;
N="vert"; S="rouge";}
if(cmd.contains("feux4")){ O ="rouge" ; E ="rouge" ;
N="rouge"; S="vert";}
pane= new FeuxTricolore(O,E,N,S);
pane.setSize(970, 660);
FlowLayout fl =null ;
pane.setLayout(fl);
textArea.setBounds(125, 85, 460, 250);
textArea.setFont(new Font("Serif", Font.BOLD, 12));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setText(res);
textArea.setAutoscrolls(true);
textArea.setEditable (false);
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.RED);
/* JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// areaScrollPane.setPreferredSize(new Dimension(250, 250));
*/
// ButtonLancement.setBounds(730,500,150, 30);
slider.setBounds(840, 60, 45, 360);
echo.setBounds(230, 500, 500, 50);
echo.setEditable (false);
echo.setBackground(Color.green);
echo.setLineWrap (true);
echo.setAutoscrolls(true);
echo.setFont(new Font("Serif", Font.BOLD, 26));
echo.setForeground(Color.BLACK);
slider.setMinorTickSpacing(100);
slider.setMajorTickSpacing(100);
slider.setPaintTicks(true);
slider.setSnapToTicks(false);
slider.setPaintTrack(true);
slider.setPaintLabels(false);
slider.setToolTipText("valeur :"+periode);
//pane.add(ButtonLancement);
pane.add(slider);
pane.add(echo);
// pane.add(areaScrollPane);
pane.add(textArea);
//f.add(ButtonLancement);
//f.add(slider);
f.setContentPane(pane);
f.setVisible(true);
// Pour attendre 4secondes
try {
Thread.sleep(periode);//4000
} catch (InterruptedException e) { }
// passage a l'orange :
if(O=="vert"){
pane= new FeuxTricolore("orange",E,N,S);}
if(E=="vert"){
pane= new FeuxTricolore(O,"orange",N,S);}
if(N=="vert"){
pane= new FeuxTricolore(O,E,"orange",S);}
if(S=="vert"){
pane= new FeuxTricolore(O,E,N,"orange");}
chargerGUI(res);
f.setContentPane(pane);
f.setVisible(true);
f.repaint();
try {
Thread.sleep(periode/3);//4000
} catch (InterruptedException e) { }
}
public static Vector<String> Lirefichier(String chemin){
Vector<String> chaine= new Vector<String>();
String fichier =chemin;
//lecture du fichier texte
try{
InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String ligne;
while ((ligne=br.readLine())!=null){
//System.out.println(ligne);
chaine.add(ligne);
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
return chaine;
}
public static void lancersimulation(Vector<String> vect){
for(int i=0;i<vect.size();i++){
echo.setText((String)vect.get(i)+"\n");
System.out.print((String)vectdonnee.get(i)+"\n");
String temp ="cmd /c CoeurBGC.exe ".concat((String)vect.get(i));
//appel a la methode executer
Vector<String> resexecu = executer(temp);
//System.out.print(temp+"\n");
// System.out.print(rescmd+"\n");
commanderfeux((String)resexecu.elementAt(0),(String)resexecu.elementAt(1));
//}
}
}
public static void execution(String[] args){
f = new Fenetre();
vectdonnee = Lirefichier("fichier_Donnee_BGC_projet_SystemC.txt");
System.out.print(vectdonnee+"\n");
lancersimulation(vectdonnee);
f.setVisible(true);
}
public static void chargerGUI(String res){
pane.setSize(970, 660);
FlowLayout fl =null ;
pane.setLayout(fl);
textArea.setBounds(125, 85, 460, 250);
textArea.setFont(new Font("Serif", Font.BOLD, 12));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setText(res);
textArea.setAutoscrolls(true);
textArea.setEditable (false);
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.RED);
/* JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// areaScrollPane.setPreferredSize(new Dimension(250, 250));
*/
// ButtonLancement.setBounds(730,500,150, 30);
slider.setBounds(840, 60, 45, 360);
echo.setBounds(230, 500, 500, 50);
echo.setEditable (false);
echo.setBackground(Color.green);
echo.setLineWrap (true);
echo.setAutoscrolls(true);
echo.setFont(new Font("Serif", Font.BOLD, 26));
echo.setForeground(Color.BLACK);
slider.setMinorTickSpacing(100);
slider.setMajorTickSpacing(100);
slider.setPaintTicks(true);
slider.setSnapToTicks(false);
slider.setPaintTrack(true);
slider.setPaintLabels(false);
slider.setToolTipText("valeur :"+periode);
//pane.add(ButtonLancement);
pane.add(slider);
pane.add(echo);
// pane.add(areaScrollPane);
pane.add(textArea);
}
public static void main(String[] args) throws IOException{
execution(args);
}
}
|
Java
|
UTF-8
| 5,647 | 1.976563 | 2 |
[
"CC-PDDC",
"CC0-1.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"CDDL-1.0",
"GCC-exception-3.1",
"MIT",
"EPL-1.0",
"Classpath-exception-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-jdom",
"CDDL-1.1",
"BSD-2-Clause",
"LicenseRef-scancode-unknown"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.service.provider;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.service.api.records.Artifact;
import org.apache.hadoop.yarn.service.api.records.ConfigFile;
import org.apache.hadoop.yarn.service.utils.ServiceUtils;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.apache.hadoop.yarn.service.conf.YarnServiceConstants.CONTENT;
public abstract class AbstractClientProvider {
public AbstractClientProvider() {
}
/**
* Generates a fixed format of application tags given one or more of
* application name, version and description. This allows subsequent query for
* an application with a name only, version only or description only or any
* combination of those as filters.
*
* @param appName name of the application
* @param appVersion version of the application
* @param appDescription brief description of the application
* @return
*/
public static final Set<String> createApplicationTags(String appName,
String appVersion, String appDescription) {
Set<String> tags = new HashSet<>();
tags.add(ServiceUtils.createNameTag(appName));
if (appVersion != null) {
tags.add(ServiceUtils.createVersionTag(appVersion));
}
if (appDescription != null) {
tags.add(ServiceUtils.createDescriptionTag(appDescription));
}
return tags;
}
/**
* Validate the artifact.
* @param artifact
*/
public abstract void validateArtifact(Artifact artifact, String compName,
FileSystem fileSystem) throws IOException;
protected abstract void validateConfigFile(ConfigFile configFile,
String compName, FileSystem fileSystem) throws IOException;
/**
* Validate the config files.
* @param configFiles config file list
* @param fs file system
*/
public void validateConfigFiles(List<ConfigFile> configFiles, String compName,
FileSystem fs) throws IOException {
Set<String> destFileSet = new HashSet<>();
for (ConfigFile file : configFiles) {
if (file.getType() == null) {
throw new IllegalArgumentException("File type is empty");
}
ConfigFile.TypeEnum fileType = file.getType();
if (fileType.equals(ConfigFile.TypeEnum.TEMPLATE)) {
if (StringUtils.isEmpty(file.getSrcFile()) &&
!file.getProperties().containsKey(CONTENT)) {
throw new IllegalArgumentException(MessageFormat.format("For {0} " +
"format, either src_file must be specified in ConfigFile," +
" or the \"{1}\" key must be specified in " +
"the 'properties' field of ConfigFile. ",
ConfigFile.TypeEnum.TEMPLATE, CONTENT));
}
} else if (fileType.equals(ConfigFile.TypeEnum.STATIC) || fileType.equals(
ConfigFile.TypeEnum.ARCHIVE)) {
if (!file.getProperties().isEmpty()) {
throw new IllegalArgumentException(String
.format("For %s format, should not specify any 'properties.'",
fileType));
}
String srcFile = file.getSrcFile();
if (srcFile == null || srcFile.isEmpty()) {
throw new IllegalArgumentException(String.format(
"For %s format, should make sure that srcFile is specified",
fileType));
}
FileStatus fileStatus = fs.getFileStatus(new Path(srcFile));
if (fileStatus != null && fileStatus.isDirectory()) {
throw new IllegalArgumentException("srcFile=" + srcFile +
" is a directory, which is not supported.");
}
}
if (!StringUtils.isEmpty(file.getSrcFile())) {
Path p = new Path(file.getSrcFile());
if (!fs.exists(p)) {
throw new IllegalArgumentException(
"Specified src_file does not exist on " + fs.getScheme() + ": "
+ file.getSrcFile());
}
}
if (StringUtils.isEmpty(file.getDestFile())) {
throw new IllegalArgumentException("dest_file is empty.");
}
if (destFileSet.contains(file.getDestFile())) {
throw new IllegalArgumentException(
"Duplicated ConfigFile exists: " + file.getDestFile());
}
destFileSet.add(file.getDestFile());
java.nio.file.Path destPath = Paths.get(file.getDestFile());
if (!destPath.isAbsolute() && destPath.getNameCount() > 1) {
throw new IllegalArgumentException("Non-absolute dest_file has more " +
"than one path element");
}
// provider-specific validation
validateConfigFile(file, compName, fs);
}
}
}
|
Python
|
UTF-8
| 339 | 2.78125 | 3 |
[] |
no_license
|
from PIL import Image
import os, sys
import kmeans
try:
filename = sys.argv[1]
except IndexError:
filename = raw_input("Enter a filename: ")
try:
img = Image.open(filename)
except IOError:
print "Unable to read file - check spelling."
sys.exit()
bw = img.convert('L')
k = raw_input("enter a k value: ")
kmeans.kmeans(bw,k)
|
SQL
|
UTF-8
| 2,533 | 3.28125 | 3 |
[] |
no_license
|
/* Процедура удаления старых записей из таблицы DWH.BCL_STOREDBLOB и очистки ТП */
create or replace procedure DWH.STORED_DEL_VAL_p
as
begin
delete from DWH.STOREDBLOB where created < add_months(sysdate, -12*6); -- удаляет старые данные старше 6 лет с момента запуска;
commit;
execute immediate 'alter table DWH.STOREDBLOB enable row movement'; -- в случае если таблица заблокирована для передвижения записей необходимо разблокировать
execute immediate 'alter table DWH.STOREDBLOB shrink space'; -- очищает табл пространство
execute immediate 'alter table DWH.STOREDBLOB disable row movement'; -- включает обратно блокировку
end;
/
/* Само задание для запуска процедуры очистки таблицы */
BEGIN
SYS.DBMS_SCHEDULER.DROP_JOB
(job_name => 'DWH.STORED_DEL_VAL');
END;
/
BEGIN
SYS.DBMS_SCHEDULER.CREATE_JOB
(
job_name => 'DWH.STORED_DEL_VAL'
,start_date => TO_TIMESTAMP_TZ('2016/08/20 11:11:48.677000 +05:00','yyyy/mm/dd hh24:mi:ss.ff tzr')
,repeat_interval => 'FREQ=MONTHLY; BYDAY=-1SUN' -- выполняется каждое последнее воскресенье
,end_date => TO_TIMESTAMP_TZ('2020/08/21 00:00:00.000000 +05:00','yyyy/mm/dd hh24:mi:ss.ff tzr')
,job_class => 'DEFAULT_JOB_CLASS'
,job_type => 'STORED_PROCEDURE'
,job_action => 'DWH.STORED_DEL_VAL_P'
,comments => NULL
);
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'RESTARTABLE'
,value => FALSE);
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'LOGGING_LEVEL'
,value => SYS.DBMS_SCHEDULER.LOGGING_RUNS);
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE_NULL
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'MAX_FAILURES');
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE_NULL
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'MAX_RUNS');
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'STOP_ON_WINDOW_CLOSE'
,value => FALSE);
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'JOB_PRIORITY'
,value => 3);
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE_NULL
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'SCHEDULE_LIMIT');
SYS.DBMS_SCHEDULER.SET_ATTRIBUTE
( name => 'DWH.STORED_DEL_VAL'
,attribute => 'AUTO_DROP'
,value => FALSE);
END;
|
C#
|
UTF-8
| 4,610 | 2.59375 | 3 |
[] |
no_license
|
namespace Cq.Miniserver
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class Server
{
private TcpListener listener;
private Queue<string> logQueue;
public Server()
{
this.listener = new TcpListener(
IPAddress.Parse(ConfigurationManager.AppSettings["ip"]),
int.Parse(ConfigurationManager.AppSettings["port"]));
this.logQueue = new Queue<string>();
Console.WriteLine("Service started: {0}", this.listener.LocalEndpoint);
this.listener.Start();
this.ProcessLoop();
this.ProcessLog();
this.ProcessStorage();
}
private void ProcessStorage()
{
ThreadPool.QueueUserWorkItem(
delegate
{
while (true)
{
ServiceCall.Objects.Save();
Thread.Sleep(10000);
}
});
}
private void ProcessLog()
{
ThreadPool.QueueUserWorkItem(
delegate
{
while (true)
{
if (this.logQueue.Count > 0)
{
Console.WriteLine(this.logQueue.Dequeue());
}
Thread.Sleep(10);
}
});
}
private void ProcessLoop()
{
ThreadPool.QueueUserWorkItem(
delegate
{
try
{
while (true)
{
this.ProcessClient(this.listener.AcceptTcpClient());
}
}
catch (Exception ex)
{
Console.WriteLine("[{0}] {1}", DateTime.Now.ToLongTimeString(), ex.Message);
}
});
}
private const int RequestBufferSize = 1024 * 1024;
private void ProcessClient(TcpClient client)
{
ThreadPool.QueueUserWorkItem(
delegate
{
var stream = client.GetStream();
var log = string.Format("[{0}] ", DateTime.Now.ToLongTimeString());
try
{
var requestBuffer = new byte[RequestBufferSize];
var length = stream.Read(requestBuffer, 0, RequestBufferSize);
if (length == RequestBufferSize)
{
Console.WriteLine("Request too big");
this.SendResponse(stream, Response.GetErrorResponse());
}
if (length > 0)
{
var request = new Request(requestBuffer, length);
log += string.Format("> {0} {1} ", request.Method, request.Path);
var response = new Response(request);
log += string.Format("< {0} {1} {2}", response.StatusCode, response.ContentType, response.ContentLength);
this.SendResponse(stream, response);
}
else
{
log += "Empty request";
this.SendResponse(stream, Response.GetErrorResponse());
}
}
catch (Exception ex)
{
try
{
this.SendResponse(stream, Response.GetErrorResponse());
}
catch { }
Console.WriteLine("Error: {0}", ex.Message);
}
this.logQueue.Enqueue(log);
stream.Dispose();
});
}
private void SendResponse(Stream stream, Response response)
{
var header = response.Header;
stream.Write(header, 0, header.Length);
if (response.Content != null)
{
stream.Write(response.Content, 0, response.Content.Length);
}
}
}
}
|
Markdown
|
UTF-8
| 748 | 2.515625 | 3 |
[] |
no_license
|
# Motivação
Atualmente, não há nenhuma forma de saber de antemão quais refeições estarão disponíveis nos restaurantes universitários. Estudantes gostariam de ter uma forma simples e rápida de acessar o cardápio do dia, sem precisar pegar a fila do RU (sem sequer saber se gosta ou não da comida do dia).
Além disso, seria conveniente saber o tamanho da fila antes de ir ao restaurante universitário. Por exemplo, caso a fila esteja grande, um estudante pode optar por comer em outro lugar para não chegar atrasado na próxima aula.
Visando resolver estes problemas, a aplicação RUFBA foi concebida para dar aos estudante um acesso fácil ao cardápio do restaurante, sem depender da colaboração da empresa responsável.
|
Java
|
UTF-8
| 2,689 | 2.171875 | 2 |
[] |
no_license
|
package br.com.rtools.relatorios.dao;
import br.com.rtools.principal.DB;
import br.com.rtools.utilitarios.Debugs;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.persistence.Query;
public class RelatorioFechamentoBaileDao extends DB {
public List<Vector> listaEventoBaile(Integer id_evento_baile) {
String text
= " -- RelatorioFechamentoBaileDao->listaEventoBaile() \n "
+ "SELECT \n "
+ " v.dt_emissao AS emissao,\n "
+ " PO.DS_NOME AS operador, \n "
+ " p.id AS codigo, \n "
+ " p.ds_nome AS convidado, \n "
+ " st.ds_descricao AS status, \n "
+ " nr_mesa AS mesa, \n "
+ " nr_convite as convite, \n "
+ " mv.dt_vencimento as vencimento, \n "
+ " b.dt_baixa as pagamento, \n "
+ " mv.nr_valor_baixa as valor, \n "
+ " pu.ds_nome as caixa, \n "
+ " v.ds_obs as obs, \n "
+ " ese.id_servicos as servico_id \n "
+ " FROM eve_evento_baile AS eb \n "
+ "INNER JOIN eve_evento AS e ON e.id = eb.id_evento \n "
+ "INNER JOIN eve_desc_evento AS de ON de.id = e.id_descricao_evento \n "
+ " LEFT JOIN eve_venda AS v ON v.id_evento = e.id \n "
+ " LEFT JOIN seg_usuario AS uo ON uo.id = v.id_usuario \n "
+ " LEFT JOIN pes_pessoa AS po ON po.id = uo.id_pessoa \n "
+ " LEFT JOIN pes_pessoa AS p ON p.id = v.id_pessoa \n "
+ " LEFT JOIN eve_evento_baile_mapa AS m ON m.id_venda = v.id \n "
+ " LEFT JOIN eve_evento_baile_convite AS c ON c.id_venda = v.id \n "
+ " LEFT JOIN eve_status AS st on st.id = v.id_status \n "
+ " LEFT JOIN fin_movimento AS mv ON mv.id = m.id_movimento OR mv.id = c.id_movimento \n "
+ " LEFT JOIN fin_baixa AS b ON b.id = mv.id_baixa \n "
+ " LEFT JOIN seg_usuario AS u ON u.id = b.id_usuario \n "
+ " LEFT JOIN pes_pessoa AS pu ON pu.id = u.id_pessoa \n "
+ " LEFT JOIN eve_evento_servico AS ese ON ese.id = v.id_evento_servico \n "
+ "WHERE eb.id = " + id_evento_baile + " \n "
+ "ORDER BY nr_mesa, nr_convite ";
try {
Debugs.put("habilitaDebugQuery", text);
Query query = getEntityManager().createNativeQuery(text);
return query.getResultList();
} catch (Exception e) {
e.getMessage();
}
return new ArrayList();
}
}
|
TypeScript
|
UTF-8
| 455 | 2.96875 | 3 |
[] |
no_license
|
export interface IDeviceTypeReducer {
deviceType: string
}
const initState: IDeviceTypeReducer = { deviceType: "iPhone" }
export const deviceTypeReducer = (state: IDeviceTypeReducer = initState, action: any) => {
switch (action.type) {
case "SET_DEVICE_TYPE":
case "INIT_APP":
return {
...state,
deviceType: action.payload.deviceType
}
default: return state
}
}
|
Python
|
UTF-8
| 1,049 | 3.6875 | 4 |
[] |
no_license
|
# 백준 10971 외판원 순회2
# 앞서서 풀었던 35_2 [차이를 최대로]와 같이 순열 알고리즘으로 풀 수 있을 것으로 예상됨
# + 두 도시 사이에 길이 없는 경우(0)에도 return 해야 함
n = 3
a = [[0, 10, 15],[5, 0, 9],[6, 13, 0]]
picked = []
result =[]
def sum(a, n, picked):
add = 0
for i in range(n):
add += a[picked[i][0], picked[i][1]]
return add
def dfs(a, iD, jD, picked, n):
# a: 소스 배열
# depth: 탐색 깊이
# picked: 선택된 경로
# n: 선택되야 하는 경로의 숫자(도시 개수와 동일)
# return 조건: 두 도시사이에 길이 없다 or n만큼 다 선택했다
if (iD == n-1 and jD == n-1) or len(picked) == n-1:
picked.append([jD, picked[0][0]])
tmp = sum(a, n, picked)
result.append(tmp)
return
for i in range(iD, n): # i의 깊이
for j in range(jD, n): # j의 깊이
if a[i][j]!=0:
picked.append([i,j])
print(picked)
else:
dfs(a, iD, jD+1, picked, n)
dfs(a, iD+1 , jD, picked, n)
dfs(a, 0, 0, picked, n)
print(result)
|
Java
|
UTF-8
| 2,187 | 2.953125 | 3 |
[] |
no_license
|
package com.example.tarasantoshchuk.translator.history.translations;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.LinkedList;
public class TranslationHistory implements Serializable, Parcelable{
private static final int MAX_SIZE = 50;
private LinkedList<TranslationInfo> list;
public TranslationHistory() {
list = new LinkedList<TranslationInfo>();
}
private TranslationHistory(Parcel source) {
this();
int size = source.readInt();
for(int i = 0; i < size; i++) {
list.addLast(
(TranslationInfo)source.readParcelable(TranslationInfo.class.getClassLoader()));
}
}
public void add(TranslationInfo tInfo) {
/**
* check for duplicates
*/
for(TranslationInfo info: list) {
if(info.equals(tInfo)) {
list.remove(info);
break;
}
}
/**
* remove oldest translation info, if we exceed max size of list
*/
if(list.size() == MAX_SIZE) {
list.removeLast();
}
list.addFirst(tInfo);
}
public void clear() {
list.clear();
}
public TranslationInfo get(int position) {
return list.get(position);
}
public int size() {
return list.size();
}
public static final Parcelable.Creator<TranslationHistory> CREATOR =
new Parcelable.Creator<TranslationHistory>() {
@Override
public TranslationHistory createFromParcel(Parcel source) {
return new TranslationHistory(source);
}
@Override
public TranslationHistory[] newArray(int size) {
return new TranslationHistory[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(list.size());
for(TranslationInfo tInfo: list) {
dest.writeParcelable(tInfo, 0);
}
}
}
|
TypeScript
|
UTF-8
| 2,052 | 2.9375 | 3 |
[] |
no_license
|
function click(x: number, y: number);
function gesture(duration: number, ...points);
function sleep(ms: number);
function toast(msg: string);
function exit();
interface Point {
x: number;
y: number;
}
//app
interface Intent {
action: string;//android.intent.action.
packageName: string;
className: string;
}
namespace app {
function launch(packageName: string);
function launchPackage(packageName: string);
function currentPackage(): string;
function startActivity(name: string)
function intent(options: Intent);
}
namespace engines {
function myEngine();
}
//images
type Color = number
class AutoImage {
getHeight(): number;
pixel(x: number, y: number): Color
}
function requestScreenCapture(): boolean;
function captureScreen(): AutoImage;
/**
* 区域找色
* @param img
* @param color
* @param x
* @param y
*/
function findColorInRegion(img: AutoImage, color: Color | string, x: number, y: number, width?: number, height?: number, threshold?: number);
namespace images {
function findColor(image, color, options)
function findMultiColors(img: AutoImage, firstColor, colors, options?):Point;
}
class colors {
/**
*
* @param alpha
* @param red
* @param green
* @param blue
*/
static argb(alpha, red, green, blue);
/**
*
* @param color1
* @param color2
* @param threshold 颜色相似度临界值,默认为4。取值范围为0~255。这个值越大表示允许的相似程度越小,如果这个值为0,则两个颜色相等时该函数才会返回true。
* @param algorithm
*/
static isSimilar(color1: Color, color2: Color, threshold?: number, algorithm?): boolean;
static toString(color: Color): string;
}
class device {
static width: number;
static height: number;
}
namespace ui {
function run(cb: Function);//Android的runOnUiThread
}
//悬浮窗
class FloatyWindow {
}
namespace floaty {
function window(layout: string): FloatyWindow;
function closeAll();
}
|
PHP
|
UTF-8
| 1,694 | 2.640625 | 3 |
[] |
no_license
|
<?php
namespace App\Libs;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
/**
* 用户相关接口请求
*/
class User extends Base
{
public $client;
protected $error = null;
protected function __construct()
{
$this->client = (new Client());
}
/**
* 设置错误信息
* @param string $msg [description]
*/
protected function setError($msg = '')
{
$this->error = $msg;
Log::error($msg);
return false;
}
/**
* 获取错误信息
* @return [type] [description]
*/
public function getError()
{
return $this->error;
}
/**
* 确认用户secureCode 是否合法
* @param [type] $uid [description]
* @param [type] $secureCode [description]
* @return [type] [description]
*/
public function checkUserSecureCode($uid, $secureCode)
{
// Log::info(config('services.user'));
$url = config('services.user.' . env('APP_ENV')) . 'login/checkSecureCode?PFServer=bbex&uid=' . $uid . '&secureCode=' . $secureCode;
try {
$client = $this->client->get($url);
$res = json_decode($client->getBody()->getContents(), true);
// Log::info("checkUserSecureCode uid:" . $uid . " res:" , $res);
if ($res && $res['code'] == 0) {
return isset($res['data']) ? $res['data'] : $res;
}
} catch (\Exception $e) {
$this->setError('url: ' . $url . "\n[" . __METHOD__ . '] error: ' . $e->getMessage());
}
return false;
}
}
|
Python
|
UTF-8
| 6,486 | 2.890625 | 3 |
[] |
no_license
|
import pygame
import argparse
import sys
import json
import pytuio as tuio
screenwidth = 800
screenheight = 600
fullscreen_width = 0
fullscreen_height = 0
config = json.load(open("config.json"))
def init_tuio(args):
tracking = tuio.Tracking(args.ip,args.port)
print("loaded profiles:", tracking.profiles.keys())
print("list functions to access tracked objects:", tracking.get_helpers())
return tracking
def pygame_init():
pygame.display.init()
global fullscreen_width
fullscreen_width = pygame.display.Info().current_w
global fullscreen_height
fullscreen_height = pygame.display.Info().current_h
size = screenwidth, screenheight
screen = pygame.display.set_mode(size)
screen = pygame.display.set_mode([fullscreen_width,fullscreen_height], flags=pygame.FULLSCREEN)
return screen
def checkCollision(pos1, dia1, pos2, dia2):
dx = pos1[0] - pos2[0]
dy = pos1[1] - pos2[1]
# L2-norm
return dx**2 + dy**2 <= (dia1+dia2)**2
def pos2px(x,y):
return (int(fullscreen_width *x), int(fullscreen_height*y))
def getVelocity(oldpos, newpos):
direction = [oldpos[0] - newpos[0], oldpos[1] - newpos[1]] # delta
magnitude = (direction[0]**2 + direction[1]**2)**(0.5)
if magnitude == 0:
return [0,0]
direction[0] /= magnitude
direction[1] /= magnitude
return direction, magnitude
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="convert shape to geojson")
parser.add_argument('--ip', type=str, default=config["tuio_host"],help="the IP address of the tuio host. If omitted, read from config.json")
parser.add_argument('--port', type=int, default=int(config["tuio_port"]),help="the port of the tuio host. If omitted, read from config.json")
parser.add_argument('--updates', type=int, default=1,help="number of TUIO updates per frame")
args = parser.parse_args()
# initialise
tracking = init_tuio(args)
screen = pygame_init()
isFullscreen = True
black = 0, 0, 0
player1id = 1
player2id = 2
ballPos = [int(fullscreen_width/2), int(fullscreen_height/2)]
ballSpeed = [0, 0]
ballDiameter = 20
player1pos = (0,0)
player1speed = 0
player2pos = (0, int(fullscreen_height/2) )
player2speed = 0
player1score = 0
player2score = 0
playerDiameter = 70
collision = False
pygame.font.init()
# pick a font
myfont = pygame.font.Font("comic.ttf", 40)
clock = pygame.time.Clock()
clock.tick()
while True:
deltatime = clock.tick()
# handle objects
for i in range(args.updates):
tracking.update()
for obj in tracking.objects():
if obj.id == player1id:
_, player1speed = getVelocity(player1pos,pos2px(obj.xpos, obj.ypos))
if deltatime > 0:
player1speed /= deltatime
player1pos = pos2px(obj.xpos, obj.ypos)
if obj.id == player2id:
_, player2speed = getVelocity(player2pos,pos2px(obj.xpos, obj.ypos))
if deltatime > 0:
player2speed /= deltatime
player2pos = pos2px(obj.xpos, obj.ypos)
#update ball
ballPos[0] = int(ballPos[0] + ballSpeed[0]*0.1 * deltatime)
ballPos[1] = int(ballPos[1] + ballSpeed[1]*0.1 * deltatime)
# if deltatime > 0:
# ballSpeed[0] += -ballSpeed[0] * 0.9 / deltatime
# ballSpeed[1] += -ballSpeed[1] * 0.9 / deltatime
# drawing
screen.fill(black)
pygame.draw.circle(screen, (255,0,0), player1pos, playerDiameter)
pygame.draw.circle(screen, (0,0,255), player2pos , playerDiameter)
pygame.draw.circle(screen, (255,255,255), ballPos , 20)
# print score
# apply it to text on a label
label = myfont.render(str(player1score), 1, (255,0,0))
# put the label object on the screen at right edge
screen.blit(label, (fullscreen_width - 100, 10))
# apply it to text on a label
label = myfont.render(str(player2score), 1, (0,0,255))
# put the label object on the screen at left edge
screen.blit(label, (10, 10))
pygame.display.flip()
# check ball contact
ballmagnitude = (ballSpeed[0]**2+ballSpeed[1]**2)**0.5
if checkCollision(player1pos, playerDiameter, ballPos, ballDiameter):
#p1 hit ball
vector, _ = getVelocity(player1pos, ballPos)
magnitude = ballmagnitude+player1speed
ballSpeed = [vector[0]*-magnitude, vector[1]*-magnitude]
collision = True
elif checkCollision(player2pos, playerDiameter, ballPos, ballDiameter):
#p2 hit ball
vector, _ = getVelocity(player2pos, ballPos)
magnitude = ballmagnitude+player2speed
ballSpeed = [vector[0]*-magnitude, vector[1]*-magnitude]
collision = True
else:
collision = False
# scoring i.e. hitting left or right screen edge
if ballPos[0] < 0:
player1score += 1
ballPos = [int(fullscreen_width/2), int(fullscreen_height/2)]
ballSpeed = [0,0]
elif ballPos[0] > fullscreen_width:
player2score += 1
ballPos = [int(fullscreen_width/2), int(fullscreen_height/2)]
ballSpeed = [0,0]
# bouncing i.e. hitting top or bottom screen edge
if ballPos[1] < 0:
ballSpeed[1] *= -0.8
elif ballPos[1] > fullscreen_height:
ballSpeed[1] *= -0.8
# Keyboard input
keys = [] # reset input
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
keys = pygame.key.get_pressed()
if keys != []:
if keys[pygame.K_ESCAPE]:
sys.exit()
# toggle fullscreen mode
if keys[pygame.K_SPACE]:
if not isFullscreen:
screen = pygame.display.set_mode([fullscreen_width,fullscreen_height], flags=pygame.FULLSCREEN)
else:
screen = pygame.display.set_mode([screenwidth, screenheight])
isFullscreen = not isFullscreen
if keys[pygame.K_RETURN]:
ballPos = [int(fullscreen_width/2), int(fullscreen_height/2)]
ballSpeed = [0,0]
|
JavaScript
|
UTF-8
| 1,157 | 2.546875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
import React from "react";
class Card extends React.Component {
render() {
let {card} = this.props;
let imgUrl = card.getImgUrl();
let isRaised = card.getIsRaised();
let isPlayable = card.getIsPlayable();
let style = card.getStyle();
let styles = {};
if(style) {
styles.left = style.left ? style.left + "px" : '';
styles.bottom = style.bottom ? style.bottom + "px" : '';
styles.transform = style.rot ? "rotate(" + style.rot + "deg)" : '';
}
if(isRaised) {
let raisingDistance = 30;
styles.bottom = (style.bottom + raisingDistance) + "px";
}
return (
<div className={"card-wrapper"}>
<img
className={"card " + (this.props.isActive ? "raisable " : '') + (isPlayable ? "playable " : '')}
src={imgUrl}
style={styles}
onClick={this.props.isActive ? () => this.props.onCardClick(this.props.card) : null}
/>
</div>
);
}
}
export default Card;
|
Java
|
TIS-620
| 1,496 | 2.09375 | 2 |
[] |
no_license
|
package selenium.facebook.begin.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.*;
import selenium.automation.utilities.FirefoxUtil;
import selenium.facebook.elements.*;
public class fbLoginSimpleTest {
public WebDriver driver;
@BeforeClass
public void setup() {
driver = FirefoxUtil.getDriver("C:\\SeleniumDriver\\geckodriver_v016.exe");
}
@AfterClass
public void tearDown() {
driver.close();
}
@BeforeMethod
@AfterMethod
@Test
public void loadPage() {
String expected = "Facebook - кѤҹ";
String actual = driver.getTitle();
Assert.assertEquals(expected, actual);
}
@Test(dependsOnMethods="loadPage")
public void filloutEmailField() {
String strInput = "clbsqatester@gmail.com";
WebElement inpField = driver.findElement(By.cssSelector(elFacebookLogin.cssEmail));
inpField.sendKeys(strInput);
String expected = strInput;
String actual = inpField.getAttribute("value");
Assert.assertEquals(expected, actual);
}
@Test(dependsOnMethods="loadPage")
public void filloutPasswordField() {
String strInput = "clbs1234";
WebElement inpField = driver.findElement(By.cssSelector(elFacebookLogin.cssPassword));
inpField.sendKeys(strInput);
String expected = strInput;
String actual = inpField.getAttribute("value");
Assert.assertEquals(expected, actual);
}
}
|
Python
|
UTF-8
| 1,784 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""Controller for sharing Omada API coordinators between platforms."""
from functools import partial
from tplink_omada_client.devices import OmadaSwitch, OmadaSwitchPortDetails
from tplink_omada_client.omadasiteclient import OmadaSiteClient
from homeassistant.core import HomeAssistant
from .coordinator import OmadaCoordinator
async def _poll_switch_state(
client: OmadaSiteClient, network_switch: OmadaSwitch
) -> dict[str, OmadaSwitchPortDetails]:
"""Poll a switch's current state."""
ports = await client.get_switch_ports(network_switch)
return {p.port_id: p for p in ports}
class OmadaSiteController:
"""Controller for the Omada SDN site."""
def __init__(self, hass: HomeAssistant, omada_client: OmadaSiteClient) -> None:
"""Create the controller."""
self._hass = hass
self._omada_client = omada_client
self._switch_port_coordinators: dict[
str, OmadaCoordinator[OmadaSwitchPortDetails]
] = {}
@property
def omada_client(self) -> OmadaSiteClient:
"""Get the connected client API for the site to manage."""
return self._omada_client
def get_switch_port_coordinator(
self, switch: OmadaSwitch
) -> OmadaCoordinator[OmadaSwitchPortDetails]:
"""Get coordinator for network port information of a given switch."""
if switch.mac not in self._switch_port_coordinators:
self._switch_port_coordinators[switch.mac] = OmadaCoordinator[
OmadaSwitchPortDetails
](
self._hass,
self._omada_client,
f"{switch.name} Ports",
partial(_poll_switch_state, network_switch=switch),
)
return self._switch_port_coordinators[switch.mac]
|
C++
|
UTF-8
| 759 | 2.828125 | 3 |
[] |
no_license
|
#include "DifferentialEvolution/DifferentialEvolution.h"
double Griewangk(const std::vector<double> &x){
double sum1 = 0.0;
double prod1 = 1.0;
for (auto i = 0; i < x.size(); ++i){
sum1 += pow(x[i], 2);
prod1 *= cos(x[i]/sqrt(i+1));
}
auto f = sum1/4000.0 - prod1 + 1;
return f;
}
using namespace DifferentialEvolution;
int main(){
for (std::size_t D: {20})//,20,30,40})
{
bounds_type bounds;
for (auto i = 0; i < D; ++i){
bounds.push_back(std::make_pair(-10,10));
}
DifferentialEvolutionOptimizer de(Griewangk, bounds, D*5);
auto &config = de.get_config();
config.epsilon_ftol = 1e-6;
de.optimize(12000);
}
return EXIT_SUCCESS;
}
|
Python
|
UTF-8
| 516 | 2.625 | 3 |
[] |
no_license
|
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as WD
from selenium.webdriver.common.by import By
WaitTime = 15
def answered(d,Question_Num): # here d is the driver and the second parameter is Question number
WaitFor = WD(d,WaitTime)
answer_element = WaitFor.until(EC.presence_of_element_located((By.NAME,"answer" + str(Question_Num))))
if "Correct." in answer_element.get_attribute("value"):
return True
else:
return False
|
SQL
|
UHC
| 2,830 | 4.5 | 4 |
[] |
no_license
|
--join2
(1) oracle;
select buyer_id, buyer_name, prod_id, prod_name
from prod, buyer
where prod.prod_buyer = buyer.buyer_id;
join2 Ǽ ϴ sql
--1 :
select count(*)
from
(select buyer_id, buyer_name, prod_id, prod_name
from prod, buyer
where prod.prod_buyer = buyer.buyer_id); --ĥ : inline-view ʿѰ Ȯض
--2
select count(*)
from prod, buyer
where prod.prod_buyer = buyer.buyer_id;
buyer_name Ǽ ȸ ۼ
select buyer_name, count(*)
from prod, buyer
where prod.prod_buyer = buyer.buyer_id --join
group by buyer.buyer_name; --group
--join3
select mem_id, mem_name, prod_id, prod_name, cart_qty
FROM member, cart, prod
where cart.cart_member = member.mem_id and cart.cart_prod = prod.prod_id;
SELECT member.mem_id, member.mem_name, prod.prod_id, prod.prod_name, cart.cart_qty
FROM member join cart on(member.mem_id = cart.cart_member)
join prod on (cart.cart_prod = prod.prod_id);
select *
from
(select deptno, count(*)
from emp
group by deptno)
where deptno = 30;
select deptno, count(*)
from emp
group by deptno
having deptno = 30;
select deptno, count(*)
from emp
where deptno = 30
group by deptno;
--join4~7
select *
from customer;
cid : customer id
cnm : customer number
select *
from product;
pid : product id
pnm : product number
select *
from cycle;
cycle : ֱ
cid :
pid :
day : (Ͽ-1,-2,ȭ-3...)
cnt :
--join4
select customer.cid, customer.cnm, cycle.pid, cycle.day, cycle.cnt
from customer, cycle
where customer.cid = cycle.cid
and customer.cnm in('brown','sally');
select customer.cid, cnm, pid, day, cnt
from customer, cycle
where customer.cid = cycle.cid
and customer.cnm in('brown','sally');
select cid, cnm, pid, day, cnt
from customer natural join cycle
where customer.cnm in('brown','sally');
--join5
select customer.cid, customer.cnm, cycle.pid, product.pnm, cycle.day, cycle.cnt
from customer, cycle, product
where customer.cid = cycle.cid
and cycle.pid = product.pid
and customer.cnm in('brown','sally');
--join6
select customer.cid, customer.cnm, cycle.pid, product.pnm, sum(cnt) as cnt
from customer, cycle, product
where customer.cid = cycle.cid and cycle.pid = product.pid
group by customer.cid, customer.cnm, cycle.pid, product.pnm, cycle.cnt;
--count(cnt) -> cnt null
--count(*) -> null ְ
--join7
select product.pid, product.pnm, sum(cnt) as cnt
from product, cycle
where product.pid = cycle.pid
group by product.pid, product.pnm;
select a.pid, b.pnm, a.cnt
from
(select pid, sum(cnt) as cnt
from cycle
group by cycle.pid) a, product b
where a.pid = b.pid;
|
Java
|
UTF-8
| 1,674 | 2.375 | 2 |
[] |
no_license
|
package com.mcdonalds.app.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.ensighten.Ensighten;
public class PagerIndicatorGroup extends RadioGroup {
private final Context mContext;
public PagerIndicatorGroup(Context context) {
super(context);
this.mContext = context;
}
public PagerIndicatorGroup(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
}
private int getResourceId(int index) {
Ensighten.evaluateEvent(this, "getResourceId", new Object[]{new Integer(index)});
return getResources().getIdentifier("page_indicator_" + index, "id", this.mContext.getPackageName());
}
public void select(int index) {
Ensighten.evaluateEvent(this, "select", new Object[]{new Integer(index)});
check(getResourceId(index));
}
private void hideAll() {
Ensighten.evaluateEvent(this, "hideAll", null);
for (int i = 0; i < getChildCount(); i++) {
RadioButton radio = (RadioButton) findViewById(getResourceId(i));
if (radio != null) {
radio.setVisibility(8);
}
}
}
public void setCount(int count) {
Ensighten.evaluateEvent(this, "setCount", new Object[]{new Integer(count)});
hideAll();
setVisibility(0);
for (int i = 0; i < count; i++) {
RadioButton radio = (RadioButton) findViewById(getResourceId(i));
if (radio != null) {
radio.setVisibility(0);
}
}
}
}
|
JavaScript
|
UTF-8
| 2,158 | 3.359375 | 3 |
[] |
no_license
|
"using strict"
class Book {
constructor(img, name, author, genre, year, rating)
{
this._img = img;
this._name = name;
this._author = author;
this._genre = genre;
this._year = year;
this._rating = rating;
}
getImg(){
return this._img;
}
getName(){
return this._name;
}
getAuthor(){
return this._name;
}
getGenre(){
return this._genre;
}
getYear(){
return this._year;
}
getRating(){
return this._rating;
}
setName(name){
this._name = name;
}
setAuthor(author){
this._author = author;
}
setGenre(genre){
this._genre = genre;
}
setYear(year){
this._year = year;
}
setRating(rating){
this._rating = rating;
}
getBookRow(){
let secElem = document.createElement("section");
let imgElem = document.createElement("img");
let pElem = document.createElement("p");
imgElem.src = this._img;
pElem.innerHTML = "<b>" + this._name + "</b>" + " by " + this._author + ". Genre: " + this._genre +
". Written: " + this._year + ". Rated: " + this._rating + ".";
secElem.append(imgElem);
secElem.append(pElem);
return secElem;
}
}
let headElem = document.createElement("h1");
headElem.innerHTML = "Books";
let contentDiv = document.getElementById("content");
bookArr = [];
bookArr.push(new Book("images/cWeb.jpg","Charlotte's Web", "E.B. White", "Children's Literature", 1952, 4));
bookArr.push(new Book("images/fahrenheit451.jpg","Fahrenheit 451", "Ray Bradbury", "Utopian and Dystopian Fiction", 1953, 2));
bookArr.push(new Book("images/green-eggs.jpg","Green Eggs and Ham", "Dr. Seuss", "Children's Literature", 1960 , 5));
bookArr.push(new Book("images/harryPot.jpg","Harry Potter and the Deathly Hallows", "JK Rowling", "Young Adult Fiction", 2007, 4));
bookArr.push(new Book("images/hunger-games.jpg","The Hunger Games", "Suzanne Collins", "Utopian and Dystopian Fiction", 2008, 5));
contentDiv.append(headElem);
for (i of bookArr) {
contentDiv.append(i.getBookRow());
}
|
PHP
|
UTF-8
| 1,460 | 2.84375 | 3 |
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
<?php
namespace SerBinario\SAD\Bundle\UserBundle\RN;
use SerBinario\SAD\Bundle\UserBundle\DAO\UserDAO;
use SerBinario\SAD\Bundle\UserBundle\Entity\User;
/**
* Description of UserRN
*
* @author andrey
*/
class UserRN
{
/**
*
* @var type
*/
private $userDAO;
/**
*
* @param UserDAO $userDAO
*/
public function __construct(UserDAO $userDAO)
{
$this->userDAO = $userDAO;
}
/**
*
* @param User $user
* @return User
*/
public function save(User $user)
{
$result = $this->userDAO->save($user);
return $result;
}
/**
*
* @param User $user
* @return User
*/
public function update(User $user)
{
$result = $this->userDAO->update($user);
return $result;
}
/**
*
* @param type $id
* @return type
*/
public function findById($id)
{
$result = $this->userDAO->findById($id);
return $result;
}
/**
*
* @param type $param
* @return type
*/
public function findByEmailOrUsename($param)
{
$result = $this->userDAO->findByEmailOrUsename($param);
return $result;
}
/**
*
* @return type
*/
public function ultimoRegistro()
{
$result = $this->userDAO->ultimoRegistro();
return $result;
}
}
|
Java
|
UTF-8
| 1,997 | 2.8125 | 3 |
[] |
no_license
|
/**
*
*/
package servidor.lock.deadlock.impl;
import java.lang.Thread.State;
import java.util.Set;
import servidor.lock.deadlock.PrevencionDeadLock;
import servidor.transaccion.FabricaTransactionManager;
import servidor.transaccion.Transaccion;
import servidor.transaccion.TransactionManager;
/**
* Algoritmo de prevencion que se fija en la fecha de creacion de las distintas transacciones
* y sigue el sistema Caution-Waiting para elegir a una victima.
* Si existe una transaccion que sostiene un lock sobre un elemento deseado por otra,
* y la primera ademas se encuentra esperando por algun otro lock, entonces la segunda muere. En caso contrario, la segunda espera.
*/
public final class PDL_CautionWaiting implements PrevencionDeadLock {
/**
* Variable con el administrador de transacciones para obtener las distintas transacciones involucradas.
*/
private TransactionManager transactionManager = FabricaTransactionManager.dameInstancia();
/**
* @see servidor.lock.deadlock.PrevencionDeadLock#elegirVictima(servidor.transaccion.Transaccion.ID, java.util.Set)
*/
public Transaccion.ID elegirVictima(Transaccion.ID idActual, Set<Transaccion.ID> conjuntoTransacciones) {
Transaccion ti = this.transactionManager.dameTransaccion(idActual);
if (ti == null) {
// no hay transaccion en progreso => imposible comprobar deadlock
return null;
}
// si Tj espera algo de Tk entonces Ti aborta. Si Tj no espera a nadie entonces Ti espera.
for (Transaccion.ID idTxConflictiva : conjuntoTransacciones) {
Transaccion tj = this.transactionManager.dameTransaccion(idTxConflictiva);
// caution waiting: solamente muere si la otra esta esperando tambien.
if (tj.threadPropietario().getState().equals(State.WAITING)) {
return idActual;
}
}
// ninguna Transaccion cumple la condicion => la actual se encola y espera
return null;
}
}
|
Python
|
UTF-8
| 387 | 3.296875 | 3 |
[
"Apache-2.0"
] |
permissive
|
class C1(object):
__slots__ = "s1";
class C2(C1):
__slots__ = "s2";
class C3(C2):
pass
o1 = C1()
o2 = C2()
o3 = C3()
print o1.__slots__ # prints s1
print o2.__slots__ # prints s2
print o3.__slots__ # prints s2
o1.s1 = 11
o2.s1 = 21
o2.s2 = 22
o3.s1 = 31
o3.s2 = 32
o3.a = 5
import copy
p3 = copy.copy(o3)
print "p3=", p3.s1
print "p3=", p3.s2
print "p3=", p3.a
|
C#
|
UTF-8
| 803 | 3.765625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
namespace Framework.Patterns.Container
{
/// <summary>
/// Extension methods for <see cref="IEnumerable{T}"/>
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Runs a for each loop on each item of an <see cref="IEnumerable{T}"/>
/// </summary>
/// <typeparam name="T">Type in the container</typeparam>
/// <param name="container">Container</param>
/// <param name="action">lambda to perform on each object of <see cref="container"/></param>
public static void ForEach<T>(this IEnumerable<T> container, Action<T> action)
{
foreach(var item in container)
{
action(item);
}
}
}
}
|
TypeScript
|
UTF-8
| 852 | 2.875 | 3 |
[] |
no_license
|
export const UrlGetLocationInfo = "https://api.weather.gov/points/";//following lat and lon
export const Locations = {
WASHINGTON:"Washington",
MINNEAPOLIS:"Minneapolis",
MIAMI: "Miami",
SEATTLE: "Seattle"
}
export interface ILocationInfo {
id: string;
city: string;
geo: string;
}
export const LocationInfo : ILocationInfo[] = [
{id:'WASHINGTON', city:"Washington", geo:'38.8894,-77.0352'},
{id:'MINNEAPOLIS', city:"Minneapolis", geo:'45.0137,-93.2605'},
{id:'MIAMI', city:"Miami", geo:'25.7723,-80.1918'},
{id:'SEATTLE', city:"Seattle", geo: '47.594,-122.0324'}
]
export const getCity = (location: string): string =>{
const info = getInfo(location);
return info ? info.city : '';
}
export const getInfo = (location: string): any =>{
return LocationInfo.find(l => l.id === location);
}
|
Swift
|
UTF-8
| 5,642 | 2.546875 | 3 |
[] |
no_license
|
//
// UIDraggableView.swift
// Friends List Cleaner
//
// Created by Simen Johannessen on 15/10/14.
// Copyright (c) 2014 Simen Johannessen. All rights reserved.
//
import Foundation
import UIKit
import Photos
func d2r(degrees : Double) -> Double {
return degrees * M_PI / 180.0
}
protocol DraggableDelegate {
func didDropOnKeep(_: UIDraggableView)
func didDropOnTrash(_: UIDraggableView)
func isBeingDragged(_: UIDraggableView)
func isBeingTapped(_: UIImageView)
}
class UIDraggableView : UIView {
let openCenterRight: CGPoint
let openCenterLeft: CGPoint
let imageAsset: PHAsset
var originalCenter: CGPoint
var lastLocation: CGPoint
var isDragging: Bool = false
var diffX: Double
var diffY: Double
var leftImage: UIButton
var rightImage: UIButton
var backgroundImage: UIImageView
var dateLabel: UILabel
var delegate:DraggableDelegate?
init(frame:CGRect, openCenterRight: CGPoint, openCenterLeft: CGPoint, backgroundImage: UIImageView,
imageAsset: PHAsset,
originalCenter: CGPoint) {
self.openCenterRight = openCenterRight
self.openCenterLeft = openCenterLeft
self.originalCenter = originalCenter
self.diffX = 0.0
self.diffY = 0.0
self.lastLocation = CGPointMake(0,0)
let width: CGFloat = 130
let height: CGFloat = 65
let adjustmentWidth: CGFloat = 15
let adjustmentHeight: CGFloat = 35
self.leftImage = UIButton(frame: CGRectMake(adjustmentWidth, adjustmentHeight, width, height))
self.leftImage.setTitle("KEEP", forState: UIControlState.Normal)
self.leftImage.transform = CGAffineTransformMakeRotation(-0.2)
self.leftImage.alpha = 0
self.leftImage.layer.borderColor = GREEN_COLOR_DARK.CGColor
self.leftImage.setTitleColor(GREEN_COLOR_DARK, forState: UIControlState.Normal)
self.leftImage.layer.borderWidth = 4.0
self.leftImage.titleLabel?.font = UIFont.systemFontOfSize(40)
self.leftImage.layer.cornerRadius = 6.0
self.rightImage = UIButton(frame: CGRectMake(frame.width - width - adjustmentWidth - 8, adjustmentHeight, width + 20, height))
self.rightImage.setTitle("TRASH", forState: UIControlState.Normal)
self.rightImage.setTitleColor(RED_DIVERSE_COLOR, forState: UIControlState.Normal)
self.rightImage.transform = CGAffineTransformMakeRotation(0.2)
self.rightImage.alpha = 0
self.rightImage.layer.borderColor = RED_DIVERSE_COLOR.CGColor
self.rightImage.layer.borderWidth = 4.0
self.rightImage.titleLabel?.font = UIFont.systemFontOfSize(40)
self.rightImage.layer.cornerRadius = 6.0
self.imageAsset = imageAsset
self.backgroundImage = backgroundImage
self.dateLabel = UILabel()
super.init(frame: frame)
self.backgroundColor = UIColor.blackColor()
backgroundImage.frame = CGRectMake(0, 0, frame.width, frame.height - 20)
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
backgroundImage.clipsToBounds = true
self.addSubview(backgroundImage)
self.addSubview(self.leftImage)
self.addSubview(self.rightImage)
}
required init?(coder aDecoder: NSCoder) {
fatalError( "NSCoding not supported")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let touch = touches.first!
self.lastLocation = touch.locationInView(self)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
let touch = touches.first!
let touchLocation = touch.locationInView(self)
var frame = self.frame
frame.origin.x = frame.origin.x + touchLocation.x - self.lastLocation.x
frame.origin.y = frame.origin.y + touchLocation.y - self.lastLocation.y
self.frame = frame
let alphaPictureLeft = (self.center.x - self.originalCenter.x) / 100
let alphaPictureRight = (self.originalCenter.x - self.center.x) / 100
self.leftImage.alpha = alphaPictureLeft
self.rightImage.alpha = alphaPictureRight
self.delegate?.isBeingDragged(self)
self.isDragging = true
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
if (self.isDragging == false) {
self.delegate?.isBeingTapped(self.backgroundImage)
}
else {
let touch = touches.first
let touchLocation = self.center
if (touchLocation.x >= self.openCenterRight.x) {
self.delegate?.didDropOnKeep(self)
}
else if (touchLocation.x <= self.openCenterLeft.x) {
self.delegate?.didDropOnTrash(self)
}
else {
self.animateBackToStartPosition()
}
}
self.isDragging = false
}
func animateBackToStartPosition() {
UIView.animateWithDuration(0.25,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 1.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
self.center = self.originalCenter
self.alpha = 1.0
self.leftImage.alpha = 0
self.rightImage.alpha = 0
},
completion: nil)
}
}
|
C#
|
UTF-8
| 817 | 2.515625 | 3 |
[] |
no_license
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using EF.Data;
using System.Data.Entity.ModelConfiguration.Configuration;
using System;
namespace EF.Data.Mapping
{
public class AttachmentMap : EntityTypeConfiguration<Attachment>
{
public AttachmentMap()
{
this.HasKey(p => p.Id);
//property
Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.Name).HasMaxLength(500);
Property(t => t.Url).HasMaxLength(500);
Property(t => t.AddedDateTime).IsRequired();
Property(t => t.ModifiedDateTime).IsRequired();
//relation
//table
ToTable("Attachment");
}
}
}
|
C++
|
UTF-8
| 759 | 3.078125 | 3 |
[] |
no_license
|
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int binarysearch(int arr[], int n, int key){
int s = 0;
int e = n;
while(s<=e){
int mid = (s+e)/2;
if (arr[mid]==key){
return mid;
}
else if(arr[mid]>key){
e = mid-1;
return e;
}
else{
e = mid+1;
return e;
}
}
return -1;
}
int main(){
int arr[10] = {12,29,7,2,98,37,90,28,9,76};
// int size = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+10);
for (int i = 0; i < 10; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
int key;
cout<<"Enter key ";
cin>>key;
cout<<binarysearch(arr, 10,key);
}
|
Markdown
|
UTF-8
| 7,236 | 3 | 3 |
[] |
no_license
|
# Enoncé
L'objectif de cet exercice est de manipuler une liste simplement
chainée de cellules contenant un entier. Une liste sera ici
représentée par un pointeur vers sa première cellule, la tête de
liste.
On fournit ici la structure de donnée représentant une cellule, un
programme de test (`main`) ainsi que les prototypes des fonctions à
implémenter, à savoir:
1. L'insertion d'une valeur en tête de liste ;
2. L'insertion d'une valeur en queue de liste ;
3. La suppression d'une liste de la première occurrence d'une valeur
donnée ;
4. L'affichage des cellules d'une liste sur la sortie standard.
Le comportement attendu pour chaque fonction à implémenter est décrit
en commentaires au dessus de chacune d'entre elles.
*Remarque :* dans quel ordre écrire ces fonctions?
Il est important de compiler et tester au fur et à mesure que vous
developpez, le plus tôt possible (et surtout pas tout coder avant
même d'essayer de compiler. Echec quasi-garanti).
Ici 1. permet de construire une liste et 4. de l'afficher. Avec ça,
vous aurez rapidement un programme certes incomplet mais qui fonctionne!
En plus vous réglerez d'éventuels problèmes de compréhension sur comment manipuler
les structures en jeu, et les fonctions suivantes seront beaucoup
plus simples à écrire.
(Cas contraire: imaginez que ayez écrit tout le code avec un couac
sur l'utilisation de la structure. Une fois le problème résolu, vous
devrez reprendre toutes les autres fonctions...)
Le point de départ pour cet exercice (squelette de code, énoncé) se
trouve dans `exercices/base/listes/`.
# Indices
<details>
<summary>Cliquez ici pour révéler des indices sur cet exercice.</summary>
<br>
* Le mot-clé `NULL` désigne un pointeur nul. C'est pratique pour
trouver la fin de ma liste.
* Ma tête de liste n'a pas été modifiée après un appel à
`inserer_tete` ? Ca ne vous rappelle pas `echanger_faux` vu dans la
fiche passage de paramètre du kit de démarrage ?
</details>
# Compétences
* Structures
* Passage de paramètre par copie
* Passage de la valeur d'une variable
* Passage de l'adresse d'une variable
* Opérateur adresse de
* Opérateur d'indirection
* Fonction taille mémoire d'un type de donnée
* Allocation de mémoire dynamique type de donnée simple
* Libération de mémoire
* Pointeurs de structures
* Listes chainées
# Difficulté
:star: :star:
# Correction
<details>
<summary>Cliquez ici pour révéler la correction de l'exercice.</summary>
#### Corrigé du fichier Makefile
```make
CC=gcc
CFLAGS=-std=c99 -Wall -Wextra -g
all: listes
.PHONY: clean
clean:
rm -f *~ *.o listes
rm -rf *.dSYM # mac-erie
```
#### Corrigé du fichier listes.c
```c
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <assert.h>
/* Structure de données décrivant un élément d'une liste. */
struct cellule
{
/* La valeur d'une cellule est un entier. */
uint32_t val;
/* Pointeur vers la cellule suivant dans la liste. */
struct cellule *suiv;
};
/*
Affiche sur la sortie standard les valeurs des cellules de la liste
pointée par l.
*/
static void afficher(struct cellule *l)
{
/* A implémenter! */
while (l != NULL) {
printf("%i -> ", l->val);
l = l->suiv;
}
printf("FIN\n");
}
/*
Crée une nouvelle cellule contenant la valeur v et l'insère en tête
de la liste pointée par pl.
*/
static void inserer_tete(struct cellule **pl, uint32_t v)
{
/* A implémenter! */
/*
Rappel : une liste est définie comme un pointeur vers la première
cellule. Comme cette fonction modifie la liste (la première cellule),
la fonction appelante doit passer l'adresse de la liste pour pouvoir
observer les changements (cf fiche passage de paramètres du kit de
démarrage). Ainsi pl contient l'adresse de la liste et *pl désigne la
liste (cad l'adresse de la première cellule).
*/
/*
On alloue une nouvelle cellule, qui sera la tête de la nouvelle liste.
L'opérateur sizeof calcule le nombre d'octet à allouer pour le type
voulu.
*/
struct cellule *liste = malloc(sizeof(struct cellule));
/*Programmation défensive : on vérification que malloc s'est bien passé*/
assert(liste != NULL);
/* On fixe les valeurs de cette cellule. */
liste->val = v;
liste->suiv = *pl;
/* On fait pointer l'argument pl vers la nouvelle liste */
*pl = liste;
}
/*
Crée une nouvelle cellule contenant la valeur v et l'insère en queue
de la liste pointée par pl.
*/
static void inserer_queue(struct cellule **pl, uint32_t v)
{
/* A implémenter! */
/*
Cette fonction prend en argument un pointeur sur la liste, car cette
dernière change dans le cas de l'insertion de la première cellule.
On place une sentinelle de manière à gérer à l'identique tous les cas
incluant le cas liste vide. Le champ suiv de notre sentinelle sera la
liste que l'on voudra retourner.
*/
struct cellule sent = { -1, *pl };
struct cellule *queue = &sent;
/* On parcourt la liste jusqu'à la dernière cellule */
while (queue->suiv != NULL) {
queue = queue->suiv;
}
/* Allocation et insertion de la cellule */
queue->suiv = malloc(sizeof(struct cellule));
assert(queue->suiv != NULL);
queue->suiv->val = v;
queue->suiv->suiv = NULL;
/* On fait pointer l'argument pl vers la nouvelle liste */
*pl = sent.suiv;
}
/*
Supprime de la liste pointée par pl la première occurrence de cellule
contenant la valeur v.
*/
static void supprimer_premiere_occurrence(struct cellule **pl, uint32_t v)
{
/* A implémenter! */
/*
Cette fonction prend en argument un pointeur sur la liste, car cette
dernière change lorsqu'on supprime la première cellule.
*/
struct cellule sent = { -1, *pl };
struct cellule *p = &sent;
/*
En C, les conditions sont évaluées séquentiellement. L'expression à
droite d'une condition logique && n'est évaluée que si l'expression à
gauche est vraie.
*/
while (p->suiv != NULL && p->suiv->val != v) {
p = p->suiv;
}
/* Cas occurence trouvée */
if (p->suiv != NULL) {
/*
On rechaine les 2 cellules de la liste entourant l'occurrence et on
libère la cellule trouvée.
*/
struct cellule *style = p->suiv;
p->suiv = style->suiv;
free(style);
}
*pl = sent.suiv;
}
int main(void)
{
struct cellule *liste = NULL;
for (uint32_t i = 6; i < 10; i++) {
inserer_queue(&liste, i);
afficher(liste);
}
for (uint32_t i = 5; i > 0; i--) {
inserer_tete(&liste, i);
afficher(liste);
}
/*
Initialisation du générateur de nombres aléatoires
(nécessaire pour que rand() retourne des valeurs différentes à chaque
exécution du programme).
*/
srand(time(NULL));
while (liste != NULL) {
supprimer_premiere_occurrence(&liste, rand() % 10);
afficher(liste);
}
return EXIT_SUCCESS;
}
```
</details>
|
C#
|
UTF-8
| 2,352 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace RealWorldStocks.Core.Models
{
public class YahooStocksService
{
public async Task<ObservableCollection<StockSnapshot>> GetSnapshotsAsync(string[] symbols)
{
var client = new HttpClient();
var yahooData = await client.GetAsync(
string.Format("http://finance.yahoo.com/d/quotes.csv?s={0}&f=snol1vpc1p2ghyra2j1abe8", string.Join("+", symbols)));
var csv = await yahooData.Content.ReadAsStringAsync();
csv = csv.TrimEnd('\r', '\n');
var snapshots = from line in csv.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
let columns = Regex.Split(line, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)").Select(s => s.Replace("\"", "")).ToList()
select new StockSnapshot
{
Symbol = columns[0],
Company = columns[1],
OpeningPrice = columns[2].ConvertTo<decimal>(),
LastPrice = columns[3].ConvertTo<decimal>(),
Volume = columns[4].ConvertTo<int>(),
PreviousClose = columns[5].ConvertTo<decimal>(),
DaysChange = columns[6].ConvertTo<decimal>(),
DaysChangePercentFormatted = columns[7],
LowPrice = columns[8].ConvertTo<decimal>(),
HighPrice = columns[9].ConvertTo<decimal>(),
DivAndYield = columns[10],
PERatio = columns[11].ConvertTo<decimal>(),
AverageVolume = columns[12].ConvertTo<int>(),
MarketCap = columns[13],
Ask = columns[14],
Bid = columns[15],
// TODO: Figure out correct param for below
OneYearEstimate = columns[16].ConvertTo<decimal>(),
};
return new ObservableCollection<StockSnapshot>(snapshots);
}
}
}
|
Java
|
UTF-8
| 305 | 1.835938 | 2 |
[] |
no_license
|
package com.green.bank.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoanModel {
String accountNo;
int loanAmount;
String status;
String fName;
String lName;
String address;
String email;
}
|
Python
|
UTF-8
| 2,356 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#coding:utf-8
import sys
sys.path.append('../')
import numpy as np
from StableDog import preprocessing
data = np.array([[ 3, -1.5, 2, -5.4],
[ 0, 4, -0.3, 2.1],
[ 1, 3.3, -1.9, -4.3]])
print(data)
# 均值移除
data_standardized = preprocessing.meanRemoval(data, True)
print("\n均值移除后数据:\n", data_standardized)
# 缩放数据
data_scaled = preprocessing.scaling(data, -1, 1) # 缩放数据到[-1,1]
print("\n缩放后数据:\n", data_scaled)
# 归一化数据
data_normalized = preprocessing.normalization(data, 'l1') # 独立归一化每一个样本
print("\nL1归一化后数据(独立归一化每一个样本):\n", data_normalized)
data_normalized = preprocessing.normalization(data, 'l1', 0) # 归一化每一维特征
print("\nL1归一化后数据(归一化每一维特征):\n", data_normalized)
# 二值化数据
data_binarized = preprocessing.binarization(data, 0.0) # 以0为界限划分
print("\n二值化后数据:\n", data_binarized)
# 独热编码
train_data = np.array([[0, 2, 1, 12],
[1, 3, 5, 3],
[2, 3, 2, 12],
[1, 2, 4, 3]])
one_hot_encoder = preprocessing.OneHotEncoder(train_data) # 构建编码器
data = [[2, 3, 4, 3]]
encoded_vector = preprocessing.oneHotEncoding(data, one_hot_encoder)
print("\n数据:\n", data)
print("\n独热编码后数据:\n", encoded_vector)
# 便签编码
label_classes = ['audi', 'ford', 'audi', 'toyota', 'ford', 'bmw']
label_encoder = preprocessing.LabelEncoder(label_classes)
labels = ['toyota', 'ford', 'audi', 'ford']
encoded_labels = preprocessing.labelEncoding(labels, label_encoder)
print("\n原始标签 =", labels)
print("编码后的标签 =", encoded_labels)
encoded_labels = [2, 1, 0, 3, 1]
decoded_labels = preprocessing.labelDecoding(encoded_labels, label_encoder)
print("\n编码后的标签 =", encoded_labels)
print("解码后的标签 =", decoded_labels)
print("\n重新创建编码器...")
label_classes = ['audi', 'ford', 'audi', 'toyota', 'ford', 'bmw']
label_encoder = preprocessing.LabelEncoder()
preprocessing.createAndEncoding(label_classes, label_encoder)
labels = ['toyota', 'ford', 'audi', 'ford']
encoded_labels = preprocessing.labelEncoding(labels, label_encoder)
print("原始标签 =", labels)
print("编码后的标签 =", encoded_labels)
|
JavaScript
|
UTF-8
| 2,231 | 3.375 | 3 |
[] |
no_license
|
$(document).ready(function(){
$("button").on("click", getWeatherData);
})
function getWeatherData(){
var zip = $(".zipcode").val();
$.ajax({
url: "https://api.openweathermap.org/data/2.5/forecast",
method: "GET",
data: {
APPID: "e41600df5a54dc35fc4a1b2fd4b91136",
units: "imperial",
zip: zip
},
success: makeFiveDayForecast
})
}
function makeFiveDayForecast(response){
var weatherData = response.list;
var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
$(".city-name").text(response.city.name)
var weatherByDay = {};
var currentDay = new Date(weatherData[0].dt*1000).getDay();
for(var i = 0; i < weatherData.length; i++){
var dayNum = new Date(weatherData[i].dt*1000).getDay();
if(!weatherByDay[dayNum]){
var weatherIconUrl = getWeatherIconUrl(weatherData[i].weather[0].icon);
weatherByDay[dayNum] = {
tempList: [weatherData[i].main.temp],
weatherIcon: `http://openweathermap.org/img/wn/${weatherIconUrl}@2x.png`
}
} else {
weatherByDay[dayNum].tempList.push(weatherData[i].main.temp)
}
}
$(".weather-container").empty()
for(var dayIndex = 0; dayIndex < 5; dayIndex++){
var avgDayTemp = `${parseInt(avgArray(weatherByDay[currentDay].tempList))}°F`
makeWeatherItem(daysOfWeek[currentDay], weatherByDay[currentDay].weatherIcon, avgDayTemp);
currentDay = moveToNextDay(currentDay);
}
}
function getWeatherIconUrl(iconCode){
return iconCode.slice(0, iconCode.length-1) + "d";
}
function moveToNextDay(dayNum){
return (dayNum + 1) % 7;
}
function makeWeatherItem(day, image, temp){
var weatherItem = $("<div>").addClass("day-weather");
var dateElem = $("<p>").addClass("date").text(day);
var weatherIcon = $("<img>").addClass("weather-icon").attr("src", image);
var tempElem = $("<p>").addClass("temp").text(temp);
weatherItem.append(dateElem, weatherIcon, tempElem);
$(".weather-container").append(weatherItem)
}
function avgArray(arr){
return arr.reduce((total,item) => total + item) / arr.length;
}
|
SQL
|
UTF-8
| 281 | 2.515625 | 3 |
[] |
no_license
|
CREATE DATABASE Players;
USE Players;
CREATE TABLE Players(
Username varchar(20) PRIMARY KEY,
Password varchar(20) NOT NULL,
ID float,
Email varchar(50),
Name varchar(20),
Score int
);
Insert into Players Values ('test','pass',1,'mas2g2@mail.missouri.edu','Test',0);
SELECT * FROM Players;
|
PHP
|
UTF-8
| 1,338 | 3.09375 | 3 |
[] |
no_license
|
<?php
/**
*
*
* @link ${GITHUB_URL} Source code
*/
namespace Sta\Entity;
abstract class AbstractQueryResult
{
public function __construct(array $initialData = array())
{
foreach ($initialData as $attr => $value) {
$this->set($attr, $value);
}
}
public function get($attributeName)
{
$method = 'get' . ucfirst($attributeName);
if (is_callable(array($this, $method))) {
return $this->$method();
}
$method = 'is' . ucfirst($attributeName);
if (is_callable(array($this, $method))) {
return $this->$method();
}
throw new \Sta\Entity\Exception\InvalidArgument('Não existe um método para retornar o valor do atributo: "'
. $attributeName . '"');
}
/**
* @ignore
* @param string $attributeName
* @param $value
*
* @throws \Sta\Entity\Exception\InvalidArgument
*/
public function set($attributeName, $value)
{
$method = 'set' . ucfirst($attributeName);
if (is_callable(array($this, $method))) {
$this->$method($value);
return;
}
throw new \Sta\Entity\Exception\InvalidArgument('Não existe um método para definir o valor do atributo: "'
. $attributeName . '"');
}
}
|
C++
|
UTF-8
| 2,652 | 3.09375 | 3 |
[] |
no_license
|
#include "Vector.h"
#include "Vertex.h"
#include <vector>
#include <string>
#include <iostream>
#include <limits>
#include <assert.h>
#ifndef FACE_H
#define FACE_H
class Line{
public:
Line(){
m_StartPoint[3] = 1;
}
~Line(){;}
Vector4f getPoint(float _t) const{
Vector4f ret = m_StartPoint + m_Direction * _t;
ret[3] = 1;
return ret;
}
Vector4f m_StartPoint;
Vector4f m_Direction;
};
class Triangle{
public:
Triangle(){};
~Triangle(){};
void print(){
m_V1.Print();
m_V2.Print();
m_V3.Print();
}
int m_iShadingGroup;
Vector4i m_V1; // coord/texture/normal
Vector4i m_V2;
Vector4i m_V3;
inline static Vector4d toBaryCentric(const Vector4f& _a,
const Vector4f& _b, const Vector4f& _c,
const Vector4f& _p){
Vector4d ret;
Vector4f edge1 = _b - _a;
Vector4f edge2 = _c - _a;
Vector4f N = edge1.cross(edge2);
double area2 = N.magnitude();
Vector4f vp0 = _p - _a;
Vector4f vp1 = _p - _b;
Vector4f vp2 = _p - _c;
Vector4f edge3 = _c - _b;
Vector4f C;
C = edge1.cross(vp0);
ret[0] = C.magnitude()/area2;
C = (edge3).cross(vp1);
ret[1] = C.magnitude()/area2;
C = (-edge2).cross(vp2);
ret[2] = C.magnitude()/area2;
return ret;
}
inline static float getSurfaceIntersect(const Vector4f& _a,
const Vector4f& _b, const Vector4f& _c,
const Line& L){
Vector4f v0 = _b-_a;
Vector4f v1 = _c-_a;
Vector4f Norm = v0.cross(v1);
float d = Norm.dot(_a);
float t = (d - Norm.dot(L.m_StartPoint))/Norm.dot(L.m_Direction);
return t;
}
inline static Vector4f getPlanarNormal(const Vector4f& _a,
const Vector4f& _b, const Vector4f& _c){
Vector4f v0 = _b-_a;
Vector4f v1 = _c-_a;
Vector4f Norm = v0.cross(v1);
Norm.Normalize();
assert(Norm[3] == 0);
return Norm;
}
inline static bool isIntersect(const Vector4d& _barycorrd){
if((_barycorrd[0] < 0.0) || (_barycorrd[1] < 0.0) || (_barycorrd[2] < 0.0) ||
std::fabs(_barycorrd[0] + _barycorrd[1] + _barycorrd[2]- 1.0) >
0.01){
return false;
}
else{
return true;
}
}
inline static Vector4f Interpolate_Barycentric(const Vector4f& _a,
const Vector4f& _b, const Vector4f& _c,
const Vector4f& _barry){
//std::cout<<"wow"<<std::endl;
Vector4f ret = _a * _barry[0] + _b * _barry[1] + _c * _barry[2];
//ret.Normalize();
return ret;
//std::cout<<"wow"<<std::endl;
}
};
#endif
|
Java
|
UTF-8
| 1,117 | 2.296875 | 2 |
[] |
no_license
|
package com.yl.myokgodemo.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.yl.myokgodemo.R;
import com.yl.myokgodemo.global.App;
/**
* Description: 所以界面的基类
* Copyright : Copyright (c) 2017
* Author : yl
* Date : 2017/9/30
*/
public class BaseActivity extends AppCompatActivity {
private App mApp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//打开一个activity就添加一个
mApp = (App) getApplication();
mApp.addActivity(this);
setContentView(R.layout.activity_base);
}
//返回键
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
//销毁时调用
@Override
protected void onDestroy() {
super.onDestroy();
mApp.removeActivity(this);
System.gc();
}
/**
* 替代findviewById方法
*/
protected <T extends View> T find(int id) {
return (T) findViewById(id);
}
}
|
C#
|
UTF-8
| 932 | 2.90625 | 3 |
[] |
no_license
|
static void Main(string[] args)
{
var path = Directory.EnumerateFiles(@"C:\Program Files (x86)\Stuff\Noodles", "*.config", SearchOption.AllDirectories);
foreach (var xmlfile in path)
{
var doc = XDocument.Load(xmlfile );
var endpointsToUpdate = doc
.Descendants("endpoint")
.Where(x => new Uri((string)x.Attribute("address")).Host != "localhost")
.ToArray();
// skip if there is nothing to update
if (!endpointsToUpdate.Any()) return;
foreach (var endpoint in endpointsToUpdate)
{
string address = (string)endpoint.Attribute("address");
string pattern = "//[^:]+";
address = Regex.Replace(address, pattern, "//" + GetIPAddress(Dns.GetHostName()));
endpoint.Attribute("address").SetValue(address);
}
doc.Save(xmlfile );
}
}
|
Markdown
|
UTF-8
| 617 | 2.765625 | 3 |
[] |
no_license
|
# Dasher3D
Once a colleague of mine thought aloud "How would a 3D Boulder Dash game look like?". I thought to give a try...
To test, install .apk file (in Installable file folder) to your Android device. Then play with Daydream, Cardboard, or by just looking around with Magic Window option.
Object of the game: Find all the diamonds, but don't get hit by a stone.
Hints:
Tap (or with cardboard say something to tap) to destroy sand & move around. You can see the map below you (and change the floor the map shows).
To get to next floor you'll need to climb the ladders, i.e. touch the ladders in the upper floor.
|
Markdown
|
UTF-8
| 723 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
---
tags :
- JavaScript
---
[[Object.defineProperty]]
1. Proxy 的优势如下: Proxy 可以直接监听对象而非属性; Proxy 可以直接监听数组的变化;
Proxy 有多达 13 种拦截方法,不限于 apply、ownKeys、deleteProperty、has等等是Object.defineProperty 不具备的;
Proxy返回的是一个新对象,我们可以只操作新的对象达到目的,而Object.defineProperty 只能遍历对象属性直接修改;
Proxy 作为新标准将受到浏览器厂商重点持续的性能优化,也就是传说中的 新标准的性能红利;
2. Object.defineProperty 的优势如下: 兼容性好,支持 IE9,而 Proxy 的存在浏览器兼容性问题,而且无法用 polyfill。
|
Java
|
UTF-8
| 179 | 1.789063 | 2 |
[] |
no_license
|
package filepanel;
import java.awt.event.MouseEvent;
/**
* Created by andrey on 3/26/16.
*/
public interface FileViewPanel {
void createPanel();
void updatePanel();
}
|
C#
|
UTF-8
| 3,111 | 2.578125 | 3 |
[] |
no_license
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// 이벤트의 베이스 클래스.
public class EventBase {
protected GameObject data_holder;
// ================================================================ //
public EventBase() {}
public virtual void initialize() {}
public virtual void start() {}
public virtual void execute() {}
public virtual void end() {}
public virtual void onGUI() {}
// 이벤트 실행 중?.
public virtual bool isInAction()
{
return(false);
}
protected Vector3 get_locator_position(string locator)
{
Vector3 pos = this.data_holder.transform.FindChild(locator).position;
return(pos);
}
};
// 이벤트 관리.
public class EventRoot : MonoBehaviour {
protected EventBase next_event = null; // 실행할 이벤트.
protected EventBase current_event = null; // 실행 중인 이벤트.
// ================================================================ //
// MonoBehaviour에서 상속.
void Start()
{
}
void Update()
{
// 이벤트 종료.
if(this.current_event != null) {
if(!this.current_event.isInAction()) {
this.current_event.end();
this.current_event = null;
}
}
// 이벤트 시작.
if(this.current_event == null) {
if(this.next_event != null) {
this.current_event = this.next_event;
this.current_event.initialize();
this.current_event.start();
this.next_event = null;
}
}
// 이벤트 실행.
if(this.current_event != null) {
this.current_event.execute();
}
}
void OnGUI()
{
if(this.current_event != null) {
this.current_event.onGUI();
}
}
// ================================================================ //
// 이벤트를 시작한다.
public T startEvent<T>() where T : EventBase, new()
{
T new_event = null;
if(this.next_event == null) {
new_event = new T();
this.next_event = new_event;
}
return(new_event);
}
public EventBase getCurrentEvent()
{
return(this.current_event);
}
public T getCurrentEvent<T>() where T : EventBase
{
T ev = null;
if(this.current_event != null) {
ev = this.current_event as T;
}
return(ev);
}
#if false
public T getEventData<T>() where T : MonoBehaviour
{
T event_data = this.gameObject.GetComponent<T>();
return(event_data);
}
#endif
#if false
// 이벤트 박스를 전부 액티브로 한다.
public void activateEventBoxAll()
{
EventBoxLeave[] boxes = this.getEventBoxes();
foreach(var box in boxes) {
box.activate();
}
}
#endif
#if false
// 이벤트 박스를 전부 슬립으로 한다.
public void deactivateEventBoxAll()
{
EventBoxLeave[] boxes = this.getEventBoxes();
foreach(var box in boxes) {
box.deactivate();
}
}
#endif
// ================================================================ //
// 인스턴스.
private static EventRoot instance = null;
public static EventRoot get()
{
if(EventRoot.instance == null) {
EventRoot.instance = GameObject.Find("EventRoot").GetComponent<EventRoot>();
}
return(EventRoot.instance);
}
}
|
JavaScript
|
UTF-8
| 985 | 3.078125 | 3 |
[] |
no_license
|
//create scene
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera.position.z = 50;
//add shape
const geometry = new THREE.TorusGeometry(10, 5, 16, 100);
const material = new THREE.MeshStandardMaterial({
color: 0xc68958
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
//add lighting
const pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(25, 25, 25);
const ambientLight = new THREE.AmbientLight(0xffffff);
scene.add(pointLight, ambientLight)
//render scene
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
cube.rotation.z += 0.01;
renderer.render(scene, camera);
}
animate();
|
C++
|
UTF-8
| 15,230 | 2.8125 | 3 |
[] |
no_license
|
#include "TcpWebServer.h"
void main()
{
WSAData wsaData;
if (NO_ERROR != WSAStartup(MAKEWORD(2, 2), &wsaData))
{
cout << "Time Server: Error at WSAStartup()\n";
return;
}
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == listenSocket)
{
cout << "Time Server: Error at socket(): " << WSAGetLastError() << endl;
WSACleanup();
return;
}
sockaddr_in serverService;
serverService.sin_family = AF_INET;
serverService.sin_addr.s_addr = INADDR_ANY;
serverService.sin_port = htons(LISTEN_PORT);
if (SOCKET_ERROR == bind(listenSocket, (SOCKADDR *)&serverService, sizeof(serverService)))
{
cout << "Time Server: Error at bind(): " << WSAGetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
return;
}
if (SOCKET_ERROR == listen(listenSocket, 5))
{
cout << "Time Server: Error at listen(): " << WSAGetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
return;
}
addSocket(listenSocket, LISTEN);
while (true)
{
fd_set waitRecv;
FD_ZERO(&waitRecv);
for (int i = 0; i < MAX_SOCKETS; i++)
{
if ((sockets[i].recv == LISTEN) || (sockets[i].recv == RECEIVE))
FD_SET(sockets[i].id, &waitRecv);
}
fd_set waitSend;
FD_ZERO(&waitSend);
for (int i = 0; i < MAX_SOCKETS; i++)
{
if (sockets[i].send == SEND)
FD_SET(sockets[i].id, &waitSend);
}
int nfd;
nfd = select(0, &waitRecv, &waitSend, NULL, NULL);
if (nfd == SOCKET_ERROR)
{
cout << "Server: Error at select(): " << WSAGetLastError() << endl;
WSACleanup();
return;
}
for (int i = 0; i < MAX_SOCKETS && nfd > 0; i++)
{
if (FD_ISSET(sockets[i].id, &waitRecv))
{
nfd--;
switch (sockets[i].recv)
{
case LISTEN:
acceptConnection(i);
break;
case RECEIVE:
receiveMessage(i);
break;
}
}
}
for (int i = 0; i < MAX_SOCKETS && nfd > 0; i++)
{
if (FD_ISSET(sockets[i].id, &waitSend))
{
nfd--;
switch (sockets[i].send)
{
case SEND:
time_t now;
time(&now);
if (now - sockets[i].timeEntered > THREE_MINUTES)
{
closesocket(sockets[i].id);
removeSocket(i);
}
else
sendMessage(i);
break;
}
}
}
}
cout << "Server: Closing Connection.\n";
closesocket(listenSocket);
WSACleanup();
}
bool addSocket(SOCKET id, int what)
{
for (int i = 0; i < MAX_SOCKETS; i++)
{
if (sockets[i].recv == EMPTY)
{
sockets[i].id = id;
sockets[i].recv = what;
sockets[i].send = IDLE;
sockets[i].len = 0;
socketsCount++;
return (true);
}
}
return (false);
}
void removeSocket(int index)
{
sockets[index].recv = EMPTY;
sockets[index].send = EMPTY;
socketsCount--;
}
void acceptConnection(int index) // index probably be 0 - its the only one listenSocket we created and add first to the sockets array
{
SOCKET id = sockets[index].id;
struct sockaddr_in from; // Address of sending partner
int fromLen = sizeof(from);
SOCKET msgSocket = accept(id, (struct sockaddr *)&from, &fromLen);
if (INVALID_SOCKET == msgSocket)
{
cout << "Server: Error at accept(): " << WSAGetLastError() << endl;
return;
}
cout << "Server: Client " << inet_ntoa(from.sin_addr) << ":" << ntohs(from.sin_port) << " is connected." << endl;
unsigned long flag = 1;
if (ioctlsocket(msgSocket, FIONBIO, &flag) != 0)
{
cout << "Server: Error at ioctlsocket(): " << WSAGetLastError() << endl;
}
if (addSocket(msgSocket, RECEIVE) == false)
{
cout << "\t\tToo many connections, dropped!\n";
closesocket(id);
}
return;
}
void receiveMessage(int index)
{
SOCKET msgSocket = sockets[index].id;
int len = sockets[index].len;
int bytesRecv = recv(msgSocket, &sockets[index].buffer[len], sizeof(sockets[index].buffer) - len, 0);
if (SOCKET_ERROR == bytesRecv)
{
cout << "Server: Error at recv(): " << WSAGetLastError() << endl;
closesocket(msgSocket);
removeSocket(index);
return;
}
if (bytesRecv == 0)
{
closesocket(msgSocket);
removeSocket(index);
return;
}
else
{
sockets[index].buffer[len + bytesRecv] = '\0';
cout << "Server: Recieved: " << bytesRecv << " bytes of \"" << &sockets[index].buffer[len] << "\" message.\n";
sockets[index].len += bytesRecv;
if (sockets[index].len > 0)
{
if (strncmp(sockets[index].buffer, "GET", 3) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = GET;
memcpy(sockets[index].buffer, &sockets[index].buffer[3], sockets[index].len - 3);
sockets[index].len -= 3;
sockets[index].buffer[sockets[index].len] = '\0';
time(&sockets[index].timeEntered);
return;
}
if (strncmp(sockets[index].buffer, "HEAD", 4) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = HEAD;
memcpy(sockets[index].buffer, &sockets[index].buffer[4], sockets[index].len - 4);
sockets[index].len -= 4;
sockets[index].buffer[sockets[index].len] = '\0';
time(&sockets[index].timeEntered);
return;
}
if (strncmp(sockets[index].buffer, "OPTIONS", 7) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = OPTIONS;
memcpy(sockets[index].buffer, &sockets[index].buffer[7], sockets[index].len - 7);
sockets[index].len -= 7;
sockets[index].buffer[sockets[index].len] = '\0';
time(&sockets[index].timeEntered);
return;
}
if (strncmp(sockets[index].buffer, "PUT", 3) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = PUT;
memcpy(sockets[index].buffer, &sockets[index].buffer[3], sockets[index].len - 3);
sockets[index].len -= 3;
sockets[index].buffer[sockets[index].len] = '\0';
time(&sockets[index].timeEntered);
return;
}
if (strncmp(sockets[index].buffer, "POST", 4) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = POST;
memcpy(sockets[index].buffer, &sockets[index].buffer[4], sockets[index].len - 4);
sockets[index].len -= 4;
sockets[index].buffer[sockets[index].len] = '\0';
time(&sockets[index].timeEntered);
return;
}
if (strncmp(sockets[index].buffer, "DELETE", 6) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = DELET_RESOURCE;
memcpy(sockets[index].buffer, &sockets[index].buffer[6], sockets[index].len - 6);
sockets[index].len -= 6;
sockets[index].buffer[sockets[index].len] = '\0';
time(&sockets[index].timeEntered);
return;
}
if (strncmp(sockets[index].buffer, "TRACE", 5) == 0)
{
sockets[index].send = SEND;
sockets[index].sendSubType = TRACE;
time(&sockets[index].timeEntered);
return;
}
sockets[index].send = SEND;
sockets[index].sendSubType = INVALID_REQUEST;
time(&sockets[index].timeEntered);
return;
}
}
}
void sendMessage(int index)
{
SOCKET msgSocket = sockets[index].id;
int bytesSent = 0, logSize = 0, phySize = 255;
char* sendBuff = (char*)malloc(sizeof(char)*phySize);
char tmpBuffer[MAX_STR_LEN];
char filePath[MAX_STR_LEN];
char fileType[20];
char language[5];
char currTimeStr[50];
getTimeStr(currTimeStr);
char *fileName;
int fileLen, numOfLines;
char fileLenStr[20];
if (sockets[index].sendSubType == GET || sockets[index].sendSubType == HEAD)
{
strcpy(tmpBuffer, sockets[index].buffer + 2);
fileName = tmpBuffer;
fileName = strtok(fileName, " ");
getFileType(fileName, fileType);
getLangQueryString(fileName, language);
if (strcmp(language, "NONE") != 0 && strcmp(language, "he") != 0 && strcmp(language, "en") != 0)
objectNotFound(sendBuff, currTimeStr);
else
{
if (strcmp(language, "he") == 0)
strcpy(filePath, HE_PUBLIC_FILES);
else
strcpy(filePath, EN_PUBLIC_FILES);
strcpy(filePath + strlen(filePath), fileName);
FILE* fp = fopen(filePath, "r");
if (fp == NULL)
objectNotFound(sendBuff, currTimeStr);
else
{
fseek(fp, 0, SEEK_END);
fileLen = ftell(fp);
fseek(fp, 0, SEEK_SET);
numOfLines = getNumOfLines(fp);
fileLen -= numOfLines;
_itoa(fileLen, fileLenStr, 10);
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s%s", OK_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH,
fileLenStr, NEWLINE, strcmp(fileType, "html") == 0 ? CONTENT_TYPE_HTML : CONTENT_TYPE_TXT, NEWLINE, NEWLINE);
logSize = strlen(sendBuff);
if (sockets[index].sendSubType == GET)
{
readFromFile(&sendBuff, fp , &logSize, &phySize);
}
fclose(fp);
}
}
}
else if (sockets[index].sendSubType == OPTIONS)
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s%s",
OK_MSG, NEWLINE, ALLOW_OPTIONS, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE, CONTENT_TYPE_HTML, NEWLINE, NEWLINE);
}
else if (sockets[index].sendSubType == PUT)
{
FILE* fp;
strcpy(tmpBuffer, sockets[index].buffer + 2);
fileName = tmpBuffer;
fileName = strtok(fileName, " ");
getFileType(fileName, fileType);
getLangQueryString(fileName, language);
strcpy(filePath, EN_PUBLIC_FILES);
strcpy(filePath + strlen(filePath), fileName);
char bodyBuff[MAX_STR_LEN] = "\0";
getBodyContent(sockets[index].buffer, bodyBuff);
fp = fopen(filePath, "r");
if (fp == NULL)
{
fp = fopen(filePath, "w");
if (fp != NULL) // create new file , code 201
{
if (strlen(bodyBuff) == 0)
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
NO_CONTENT_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE,
strcmp(fileType, "html") == 0 ? CONTENT_TYPE_HTML : CONTENT_TYPE_TXT, NEWLINE, NEWLINE);
}
else
{
fprintf(fp, "%s", bodyBuff);
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
CREATED_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE,
strcmp(fileType, "html") == 0 ? CONTENT_TYPE_HTML : CONTENT_TYPE_TXT, NEWLINE, NEWLINE);
}
fclose(fp);
}
else // can not open/create file , code 501
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
NOT_IMPLEMENTED_MSG, NEWLINE, currTimeStr, NEWLINE, NEWLINE, CONTENT_LENGTH0, NEWLINE,
strcmp(fileType, "html") == 0 ? CONTENT_TYPE_HTML : CONTENT_TYPE_TXT, NEWLINE, NEWLINE);
}
}
else // file exist , update the file , code 200
{
fclose(fp);
fp = fopen(filePath, "w");
if (strlen(bodyBuff) == 0) // no body, code 204
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
NO_CONTENT_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE,
strcmp(fileType, "html") == 0 ? CONTENT_TYPE_HTML : CONTENT_TYPE_TXT, NEWLINE, NEWLINE);
}
else
{
fprintf(fp, "%s", bodyBuff);
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
OK_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE,
strcmp(fileType, "html") == 0 ? CONTENT_TYPE_HTML : CONTENT_TYPE_TXT, NEWLINE, NEWLINE);
}
fclose(fp);
}
}
else if (sockets[index].sendSubType == POST)
{
char bodyBuff[MAX_STR_LEN];
getBodyContent(sockets[index].buffer, bodyBuff);
cout << "Clinet POST: " << bodyBuff << endl;
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
OK_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE, CONTENT_TYPE_HTML, NEWLINE, NEWLINE);
}
else if (sockets[index].sendSubType == DELET_RESOURCE)
{
int hasBeenDeletedHe, hasBeenDeletedEn;
strcpy(tmpBuffer, sockets[index].buffer + 2);
fileName = tmpBuffer;
fileName = strtok(fileName, " ");
strcpy(filePath, HE_PUBLIC_FILES);
strcpy(filePath + strlen(filePath), fileName);
hasBeenDeletedHe = remove(filePath);
strcpy(filePath, EN_PUBLIC_FILES);
strcpy(filePath + strlen(filePath), fileName);
hasBeenDeletedEn = remove(filePath);
if (hasBeenDeletedHe != 0 && hasBeenDeletedEn != 0)
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s", NO_CONTENT_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0,
NEWLINE, CONTENT_TYPE_HTML, NEWLINE, NEWLINE);
}
else
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s", OK_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE,
CONTENT_TYPE_HTML, NEWLINE, NEWLINE);
}
}
else if (sockets[index].sendSubType == TRACE)
{
int len = strlen(sockets[index].buffer);
_itoa(len, fileLenStr, 10);
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s%s", OK_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH, fileLenStr,
NEWLINE, CONTENT_TYPE_TRACE, NEWLINE, NEWLINE);
logSize = strlen(sendBuff);
if (logSize + len > phySize)
{
phySize *= 2;
sendBuff = (char*)realloc(sendBuff, sizeof(char)*phySize);
}
strcat(sendBuff, sockets[index].buffer);
strcat(sendBuff, NEWLINE);
logSize = strlen(sendBuff);
sendBuff = (char*)realloc(sendBuff, sizeof(char)*logSize + 1);
sendBuff[logSize] = '\0';
}
else if (sockets[index].sendSubType == INVALID_REQUEST)
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s", INVALID_REQUEST_TYPE_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE,
CONTENT_TYPE_HTML, NEWLINE, NEWLINE);
}
bytesSent = send(msgSocket, sendBuff, (int)strlen(sendBuff), 0);
if (SOCKET_ERROR == bytesSent)
{
cout << "TCP Server: Error at send(): " << WSAGetLastError() << endl;
return;
}
cout << "TCP Server: Sent: " << bytesSent << "\\" << strlen(sendBuff) << " bytes of \"" << sendBuff << "\" message.\n";
free(sendBuff);
sockets[index].send = IDLE;
}
void getTimeStr(char* bufferTime)
{
strcpy(bufferTime, DATE_MSG);
struct tm *currTime;
time_t localTime;
localTime = time(&localTime);
strcpy(bufferTime + strlen(bufferTime), ctime(&localTime));
bufferTime[strlen(bufferTime) - 1] = '\0';
}
void getLangQueryString(char* fileName, char* language)
{
char* quertStr = fileName;
quertStr = strtok(quertStr, "?");
quertStr = strtok(NULL, "?");
if (quertStr == NULL)
strcpy(language, "NONE");
else
strcpy(language, quertStr + 5);
}
void getFileType(char* fileName, char* fileType)
{
char tmpFileName[MAX_STR_LEN];
strcpy(tmpFileName, fileName);
char* quertStr = tmpFileName;
quertStr = strtok(quertStr, ".");
quertStr = strtok(NULL, "?");
strcpy(fileType, quertStr);
}
void readFromFile(char** sendBuff, FILE* fp, int* logSize, int* phySize)
{
char letter;
char line[100];
while (!feof(fp))
{
if (*logSize + 100 > *phySize)
{
*phySize *= 2;
*sendBuff = (char*)realloc(*sendBuff, sizeof(char)*(*phySize));
}
fgets(line, 100, fp);
strcat(*sendBuff, line);
*logSize = strlen(*sendBuff);
}
*sendBuff = (char*)realloc(*sendBuff, sizeof(char)*((*logSize) + 1));
(*sendBuff)[*logSize] = '\0';
}
int getNumOfLines(FILE* fp)
{
char letter;
int numOfLines = 0;
while (!feof(fp))
{
letter = fgetc(fp);
if (letter == '\n')
numOfLines++;
}
fseek(fp, 0, SEEK_SET);
return numOfLines;
}
void getBodyContent(char* recvBuffer, char* bodyBuffer)
{
printf("%s \n", recvBuffer);
if (strlen(recvBuffer) < 4) {
cout << "Error at sendBuff\n";
}
char doubleNewLine[4] = { '\r','\n','\r','\n' };
int doubleNewLineIndex = 0;
int resIndex = -1;
while (recvBuffer[doubleNewLineIndex + 4] != '\0')
{
if (strncmp(recvBuffer + doubleNewLineIndex, doubleNewLine, 4) == 0)
{
resIndex = doubleNewLineIndex;
break;
}
doubleNewLineIndex++;
}
if (resIndex != -1)
strcpy(bodyBuffer, recvBuffer + doubleNewLineIndex + 4);
}
void objectNotFound(char* sendBuff, char* currTimeStr)
{
sprintf(sendBuff, "%s%s%s%s%s%s%s%s%s",
NOT_FOUND_MSG, NEWLINE, currTimeStr, NEWLINE, CONTENT_LENGTH0, NEWLINE, CONTENT_TYPE_HTML, NEWLINE, NEWLINE);
}
|
JavaScript
|
UTF-8
| 1,011 | 2.828125 | 3 |
[] |
no_license
|
export default function reducer(state={
markets: [],
fetching: false,
fetched: false,
error: null
}, action) {
switch(action.type) {
case "FETCH_MARKETS": {
return {...state, fetching: true}
}
case "FETCH_MARKETS_REJECTED": {
return {...state, fetching: false, error: action.payload}
}
case "FETCH_MARKETS_FULFILLED": {
return {
...state,
fetching: false,
fetched: true,
markets: action.payload
}
}
case "ADD_MARKET": {
return {
...state,
markets: [...state.markets, action.payload]
}
}
case "UPDATE_MARKET": {
const { id, title, icon, urlTitle } = action.payload
const newMarkets = [...state.markets]
const marketToUpdate = newMarkets.findIndex(market => market.id === id)
newMarkets[marketToUpdate] = action.payload
return {
...state,
markets: newMarkets
}
}
case "DELETE_MARKET": {
return {
...state,
markets: state.markets.filter(market => market.id !== action.payload)
}
}
}
return state
}
|
JavaScript
|
UTF-8
| 2,058 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
var CONSTANT = require('./util').CONSTANT;
function User(socket) {
this.socket = socket;
this.id = socket.id;
this.name = 'rename';
this.rooms = {};
this.current = null;
}
// user life cycle management
User.prototype.setName = function(name) {
var cleanName = name.replace(/[^a-z0-9\s]/gi,'');
if (cleanName && cleanName.length <= CONSTANT.MAX_CHAR) {
this.name = cleanName;
this.updateUser();
return true;
}
return false;
};
User.prototype.addRoom = function(room, joinType) {
if (!this.rooms[room]) {
this.rooms[room] = joinType;
// join room after add
this.joinRoom(room);
this.updateUser();
return true;
}
return false;
};
User.prototype.removeRoom = function(room) {
if (this.rooms[room]) {
// when removing the room we are currently in, make sure to leave the room beforehand
if (room === this.current) {
this.leaveRoom(room);
}
delete this.rooms[room];
this.updateUser();
return true;
}
return false;
};
User.prototype.joinRoom = function(room) {
if (this.rooms[room] && this.current !== room) {
if (this.current !== null) {
// leave old room
this.leaveRoom(this.current);
}
// join new room
this.socket.join(room);
this.current = room;
this.updateUser();
return true;
}
return false;
}
User.prototype.leaveRoom = function(room) {
if (this.rooms[room] && this.current === room) {
this.socket.leave(room);
this.current = null;
this.updateUser(true);
return true;
}
return false;
};
User.prototype.disconnect = function(room) {
// on disconnect, leave all rooms
Object.keys(this.rooms).forEach(function(name) {
room.leaveUser(name, this);
}, this);
};
User.prototype.updateUser = function(emptyView) {
this.socket.emit('_user_state', this.retrieveUserState());
if (emptyView) {
this.socket.emit('_room_state', {
users: [],
players: [],
supply: {},
trash: null
});
}
};
User.prototype.retrieveUserState = function() {
return {
name: this.name,
rooms: this.rooms,
current: this.current
};
};
module.exports = User;
|
C#
|
UTF-8
| 1,566 | 2.53125 | 3 |
[] |
no_license
|
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
public sealed class ValidateActionParameters_WebApiActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
var descriptor = context.ActionDescriptor;
if (descriptor != null)
{
var modelState = context.ModelState;
foreach (var parameterDescriptor in descriptor.GetParameters())
{
EvaluateValidationAttributes(
suppliedValue: context.ActionArguments[parameterDescriptor.ParameterName],
modelState: modelState,
parameterDescriptor: parameterDescriptor
);
}
}
base.OnActionExecuting(context);
}
static private void EvaluateValidationAttributes(HttpParameterDescriptor parameterDescriptor, object suppliedValue, ModelStateDictionary modelState)
{
var parameterName = parameterDescriptor.ParameterName;
parameterDescriptor
.GetCustomAttributes<object>()
.OfType<ValidationAttribute>()
.Where(x => !x.IsValid(suppliedValue))
.ForEach(x => modelState.AddModelError(parameterName, x.FormatErrorMessage(parameterName)));
}
}
|
Python
|
UTF-8
| 3,879 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import urllib
def Box_Character(img):
# Import Photo
# path = r'Z:\caseyduncan\Casey Duncan\CSM Grad School Work\2019\Fall\CSCI 575B - Machine Learning\ML Project\Data\Data - Equations\eqn_test3.jpg'
# img = cv2.imread(path)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Convert to gray
# Threshold & Morpholigical Close
ret2,th2 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
kernel = np.ones((2,2),np.uint8)
closing = cv2.morphologyEx(th2, cv2.MORPH_CLOSE, kernel)
# Find Characters (contours)
contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Find position of Bounding Box around each Contours
chars_bb = []
for cnt in contours:
cnt = cnt.reshape((cnt.shape[0],cnt.shape[2]))
left_tc = np.amin(cnt, axis=0)
right_bc = np.amax(cnt, axis=0)
min_x = left_tc[0]
max_x = right_bc[0]
min_y = left_tc[1]
max_y = right_bc[1]
chars_bb.append([min_x,min_y,max_x,max_y])
# Find characters that are made of multiple contours (for example: "=" or "i")
chars_bb_new = chars_bb.copy()
for i in range(len(chars_bb)-1):
cnt_i = chars_bb[i]
i=0
for j in range(i+1,len(chars_bb)):
cnt_j = chars_bb[j]
cent_i = cnt_i[0]+(cnt_i[2] - cnt_i[0])/2
cent_j = cnt_j[0]+(cnt_j[2] - cnt_j[0])/2
if cnt_j == cnt_i:
pass
elif abs(cent_i - cent_j) <= 20:
min_x = min(cnt_j[0],cnt_i[0])
min_y = min(cnt_j[1],cnt_i[1])
max_x = max(cnt_j[2],cnt_i[2])
max_y = max(cnt_j[3],cnt_i[3])
vals_new = [min_x,min_y,max_x,max_y]
chars_bb_new.append(vals_new)
if i == 0:
chars_bb_new.remove(cnt_i)
i=i+1
# Delete near duplicate contours
# (for example: sometimes the dot on an "i" is thought of as two contours)
chars_bb_new2 = chars_bb_new.copy()
for i in range(len(chars_bb_new)-1):
cnt_i = chars_bb_new[i]
for j in range(i+1,len(chars_bb_new)):
cnt_j = chars_bb_new[j]
cent_i = cnt_i[0]+(cnt_i[2] - cnt_i[0])/2
cent_j = cnt_j[0]+(cnt_j[2] - cnt_j[0])/2
area_i = (cnt_i[2] - cnt_i[0])*(cnt_i[3] - cnt_i[1])
area_j = (cnt_j[2] - cnt_j[0])*(cnt_j[3] - cnt_j[1])
if cnt_j == cnt_i:
pass
elif (abs(cent_i - cent_j) <= 20):
if area_i > area_j:
if cnt_j in chars_bb_new2:
chars_bb_new2.remove(cnt_j)
elif area_i < area_j:
if cnt_i in chars_bb_new2:
chars_bb_new2.remove(cnt_i)
# Delete duplicates contours
chars_bb = []
for i in chars_bb_new2:
if i not in chars_bb:
chars_bb.append(i)
# Order Characters from left to right
chars_bb.sort()
# Draw bounding box around character
#cv2.imshow('image', img)
#cv2.waitKey(0); cv2.destroyAllWindows(); cv2.waitKey(1)
# for cnt in chars_bb:
# min_x = cnt[0]
# max_x = cnt[2]
# min_y = cnt[1]
# max_y = cnt[3]
# cv2.rectangle(img,(min_x,min_y),(max_x,max_y),(0,0,255),1)
# cv2.imshow('image', img)
# cv2.waitKey(0); cv2.destroyAllWindows(); cv2.waitKey(1)
# Save each character as its own image in a vector of images
X_input = np.empty((0,45,45),dtype=np.float16)
for cnt in chars_bb:
size_x = 45
size_y = 45
pad = 3
min_x = cnt[0]-pad
max_x = cnt[2]+pad
min_y = cnt[1]-pad
max_y = cnt[3]+pad
if (max_x - min_x) > size_x:
size_x = max_x - min_x
if (max_y - min_y) > size_y:
size_y = max_y - min_y
img_i = np.zeros((size_y,size_x), np.uint8)
img_i[:,:] = 255
start_x = int(0.5*(size_x-(max_x - min_x)))
end_x = start_x + (max_x - min_x)
start_y = int(0.5*(size_y-(max_y - min_y)))
end_y = start_y + (max_y - min_y)
img_i[start_y:end_y,start_x:end_x] = gray[min_y:max_y,min_x:max_x]
img_i = cv2.resize(img_i,(45,45))
X_input = np.append(X_input, [img_i],axis = 0) #might need to change
#for x in X_input:
#cv2.imshow('image', x)
#cv2.waitKey(0); cv2.destroyAllWindows(); cv2.waitKey(1)
return X_input
|
Java
|
UTF-8
| 14,670 | 1.914063 | 2 |
[
"Apache-2.0"
] |
permissive
|
import com.kitfox.svg.SVGDiagram;
import com.kitfox.svg.SVGException;
import com.kitfox.svg.SVGUniverse;
import org.lwjgl.glg2d.GLGraphics2D;
import org.lwjgl.glg2d.GLUtils;
import org.lwjgl.glg2d.bridge.Lwjgl3GL2;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.awt.AWTGLCanvas;
import org.lwjgl.opengl.awt.GLData;
import org.lwjgl.opengl.awt.MyPlatformMacOSXGLCanvas;
import javax.swing.JFrame;
import java.awt.AWTException;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.BufferCapabilities;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Panel;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferStrategy;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glViewport;
public final class AWTHello {
private static final int InitialWidth = 800;
private static final int InitialHeight = 600;
private static final boolean AWT_ONLY = false;
private float scaleX = 1f;
private float scaleY = 1f;
private int logicalWidth = 800;
private int logicalHeight = 600;
private GLGraphics2D g;
private Lwjgl3GL2 gl;
private boolean shown;
private boolean running = false;
private double angle;
private SVGDiagram diagram;
private void run() {
Frame frame = new JFrame("AWT test");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
GLData data = new GLData();
// data.majorVersion = 2;
// data.minorVersion = 0;
data.swapInterval = 1;
data.profile = GLData.Profile.COMPATIBILITY;
data.samples = 4;
SVGUniverse universe = new SVGUniverse();
URI svg = universe.loadSVG(getURL("robot.svg"));
diagram = universe.getDiagram(svg);
diagram.setIgnoringClipHeuristic(true);
// frame.add(new Component() {
// @Override
// public Dimension getPreferredSize() {
// return new Dimension(800, 600);
// }
//
// @Override
// public void paint(Graphics g0) {
// Graphics2D g = (Graphics2D) g0;
// g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON);
//
//
// drawRotatedRectangle(g, angle, 100, 100, 50, 50);
// angle += 1f / 60f;
//
//
// try {
// diagram.render(g);
// } catch (SVGException e) {
// e.printStackTrace();
// }
// }
// });
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
running = false;
frame.dispose();
// System.exit(0);
}
});
if (AWT_ONLY) {
// Component panel = frame.add(new Component() {
// });
// panel.setPreferredSize(new Dimension(800, 600));
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
BufferCapabilities caps = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration()
.getBufferCapabilities();
try {
frame.createBufferStrategy(2, caps);
} catch (AWTException e) {
throw new RuntimeException(e);
}
BufferStrategy strategy = frame.getBufferStrategy();
running = true;
Runnable loop = new Runnable() {
public void run() {
if (!running) return;
do {
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.clearRect(0, 0, frame.getWidth(), frame.getHeight());
g.setClip(0, 0, frame.getWidth(), frame.getHeight());
drawRotatedRectangle(g, angle, 400, 300, 50, 50);
AffineTransform af = new AffineTransform();
af.translate(100, 100);
af.rotate(angle, 100, 100);
g.setTransform(af);
try {
diagram.render(g);
//
// af.translate(100, 100);
// g.setTransform(af);
//
// diagram.render(g);
} catch (SVGException e) {
e.printStackTrace();
}
// g.setColor(Color.GRAY);
// g.drawRect(0, 0, 500, 500);
// g.setColor(Color.BLACK);
// g.drawLine(50, 50, 200, 50);
// Dispose the graphics
g.dispose();
} while (running && strategy.contentsRestored());
angle += 1f / 60f;
// Display the buffer
strategy.show();
EventQueue.invokeLater(this);
}
};
EventQueue.invokeLater(loop);
// new Thread(() -> {
// while (running) {
// // Prepare for rendering the next frame
// // ...
//
// // Render single frame
// do {
// // The following loop ensures that the contents of the drawing buffer
// // are consistent in case the underlying surface was recreated
// do {
// // Get a new graphics context every time through the loop
// // to make sure the strategy is validated
// Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
//
// g.clearRect(0, 0, panel.getWidth(), panel.getHeight());
//
// g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON);
//
// drawRotatedRectangle(g, angle, 100, 100, 50, 50);
// angle += 1f / 60f;
//
// try {
// diagram.render(g);
// } catch (SVGException e) {
// e.printStackTrace();
// }
//
//
// // g.setColor(Color.GRAY);
// // g.drawRect(0, 0, 500, 500);
// // g.setColor(Color.BLACK);
// // g.drawLine(50, 50, 200, 50);
//
// // Dispose the graphics
// g.dispose();
//
// // Repeat the rendering if the drawing buffer contents
// // were restored
// } while (running && strategy.contentsRestored());
//
// // Display the buffer
// strategy.show();
//
// // Repeat the rendering if the drawing buffer was lost
// } while (running && strategy.contentsLost());
// }
// }).start();
return;
}
MyAWTGLCanvas canvas = new MyAWTGLCanvas(data);
canvas.setPreferredSize(new Dimension(InitialWidth, InitialHeight));
// canvas.setPreferredSize(new Dimension(WIDTH + 1, HEIGHT + 1));
frame.add(canvas);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
// System.out.println("windowOpened " + Thread.currentThread().getId());
canvas.render();
}
// @Override
// public void windowStateChanged(WindowEvent e) {
// System.out.println(e);
// canvas.reset();
// }
});
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
canvas.render();
}
@Override
public void componentShown(ComponentEvent e) {
System.out.println("componentShown " + Thread.currentThread().getId());
canvas.render();
}
@Override
public void componentHidden(ComponentEvent e) {
shown = false;
}
});
frame.setBackground(Color.BLACK);
frame.pack();
frame.setLocationRelativeTo(null);
try {
EventQueue.invokeAndWait(() -> {
frame.setVisible(true);
});
} catch (InterruptedException | InvocationTargetException e) {
e.printStackTrace();
System.exit(-1);
}
frame.transferFocus();
// canvas.setPreferredSize(new Dimension(WIDTH, HEIGHT));
// frame.pack();
// frame.setLocationRelativeTo(null);
System.out.println("main " + Thread.currentThread().getId());
Runnable renderLoop = new Runnable() {
public void run() {
if (!canvas.isValid()) {
return;
}
canvas.render();
EventQueue.invokeLater(this);
}
};
EventQueue.invokeLater(renderLoop);
// while (true) {
// canvas.render();
// }
}
private static void drawRotatedRectangle(Graphics2D g, double angle, double x, double y, double w, double h) {
Rectangle2D r = new Rectangle2D.Double(-.5 * w, -.5 * h, w, h);
Path2D.Double path = new Path2D.Double();
path.append(r, false);
AffineTransform t = new AffineTransform();
t.translate(x, y);
t.rotate(angle);
path.transform(t);
g.draw(path);
}
public static void main(String[] args) {
new AWTHello().run();
}
private final class MyAWTGLCanvas extends AWTGLCanvas {
double dx;
double angle;
Stroke stroke;
public MyAWTGLCanvas(GLData data) {
super(data);
platformCanvas = new MyPlatformMacOSXGLCanvas();
float[] scale = GLUtils.getScale(new float[2]);
scaleX = scale[0];
scaleY = scale[1];
MyPlatformMacOSXGLCanvas.scaleX = scaleX;
MyPlatformMacOSXGLCanvas.scaleY = scaleY;
// frame.addKeyListener(new KeyAdapter() {
// @Override
// public void keyPressed(KeyEvent e) {
// context = 0;
// initCalled = false;
// }
// });
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// context = 0;
// render();
}
@Override
public void componentShown(ComponentEvent e) {
// render();
}
});
dx = 0.;
angle = 0.;
stroke = new BasicStroke(3);
}
public void initGL() {
System.out.println("initGL");
GL.createCapabilities();
gl = new Lwjgl3GL2();
g = new GLGraphics2D(gl, WIDTH, HEIGHT);
// Set the clear color
// glClearColor(0.0f, 0f, 0f, 0.0f);
//
// Stroke stroke = new BasicStroke(3);
//
// double dx = 0.;
// double angle = 0.;
//
// GLFW.glfwGetFramebufferSize(window, tmpBuffer, tmpBuffer2);
// int backBufferWidth = tmpBuffer.get(0);
// int backBufferHeight = tmpBuffer2.get(0);
//
// GLFW.glfwGetWindowSize(window, tmpBuffer, tmpBuffer2);
// logicalWidth = tmpBuffer.get(0);
// logicalHeight = tmpBuffer2.get(0);
//
// glViewport(0, 0, backBufferWidth, backBufferHeight);
//
// GL20.glMatrixMode(GL20.GL_PROJECTION);
// GL20.glLoadIdentity();
// GL20.glOrtho(0, logicalWidth, 0, logicalHeight, -1, 1);
}
public void paintGL() {
// System.out.println("paintGL");
// logicalWidth = tmpBuffer.get(0);
// logicalHeight = tmpBuffer2.get(0);
// int backBufferWidth = 1600;
// int backBufferHeight = 1200;
//
// glViewport(0, 0, backBufferWidth, backBufferHeight);
// glViewport(0, 0, 400, 300);
// glViewport(0, 0, WIDTH, HEIGHT);
// glViewport(0, 0, 800, 600);
logicalWidth = getWidth();
logicalHeight = getHeight();
// System.out.println(logicalWidth + ":" + logicalHeight);
int surfaceWidth = (int) (logicalWidth * scaleX + 0.5);
int surfaceHeight = (int) (logicalHeight * scaleY + 0.5);
glViewport(0, 0, surfaceWidth, surfaceHeight);
g.setSize(logicalWidth, logicalHeight, surfaceWidth, surfaceHeight);
g.active();
g.setDefaultState();
g.setClip(0, 0, logicalWidth, logicalHeight);
// glViewport(0, 0, logicalWidth, logicalHeight);
// GL20.glMatrixMode(GL20.GL_PROJECTION);
// GL20.glLoadIdentity();
// GL20.glOrtho(0, logicalWidth, 0, logicalHeight, -1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
// try (MemoryStack ignore = stackPush()) {
// FloatBuffer buffer = stackMallocFloat(3 * 2);
// buffer.put(-0.5f).put(-0.5f);
// buffer.put(+0.5f).put(-0.5f);
// buffer.put(+0.0f).put(+0.5f);
// buffer.flip();
// int vbo = GL15C.glGenBuffers();
// GL15C.glBindBuffer(GL_ARRAY_BUFFER, vbo);
// GL15C.glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);
// }
//
// glEnableClientState(GL_VERTEX_ARRAY);
// glVertexPointer(2, GL_FLOAT, 0, 0L);
//
// GL11C.glDrawArrays(GL_TRIANGLES, 0, 3);
drawRotatedRectangle(g, angle, 100, 100, 50, 50);
angle += 1f / 60f;
// g.setColor(Color.WHITE);
g.setStroke(stroke);
// g.drawRect(100 + (int) dx, 100, 50, 50);
g.draw(new Rectangle2D.Double(75 + dx, 75, 50, 50));
dx += 1f / 60f * 8;
// g.fillRect(100, 100, 50, 50);
g.draw(new Ellipse2D.Double(200, 200, 500, 500));
drawRotatedRectangle(g, angle * 2., 100 + dx, 100, 200, 200);
drawSVG(g);
// g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 13));
// g.drawString("Hello OpenGL", 100, 100);
swapBuffers();
}
public void reset() {
context = 0;
}
}
private void drawSVG(GLGraphics2D g) {
try {
diagram.render(g);
} catch (SVGException e) {
throw new RuntimeException(e);
}
}
/**
* Returns an image resource.
*
* @param filename the filename of the image to load
* @return the loaded image
*/
public static URL getURL(String filename) {
URL url = AWTHello.class.getClassLoader().getResource(filename);
if (url == null) {
throw new RuntimeException("Could not load image because of invalid filename: " + filename);
}
return url;
}
}
|
Python
|
UTF-8
| 1,735 | 3.296875 | 3 |
[] |
no_license
|
"""This module content the Movie class definition
"""
import webbrowser
class Movie():
"""This class provides a way to store movie related information
This class was made to populate the fresh_tomatoes web page.
Every movie will have the basic information of the movie,
including a poster and a trailer in a video.
"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
def __init__(self,
movie_title,
movie_storyline="No storyline found",
poster_image="https://upload.wikimedia.org/"
"wikipedia/commons/a/ac/No_image_available.svg",
trailer_youtube="https://www.youtube.com/"
"watch?v=IYnsfV5N2n8"):
"""Constructor
Args:
movie_title (str): the name of the movie
movie_storyline (str): the description of the story.
By default: "No storyline found",
poster_image (str): the image of the main poster of the movie.
By default: a "no image available" image
trailer_youtube (str): the trailer of the movie in youtube.
It has to be the complete url.
By default: ASDF Movie 1
TODO:make a default video with 20 seconds of "no trailer available"
"""
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
"""
Open the trailer of the movie in a web browser.
This trailer has to be previously set in "trailer_youtube_url"
"""
webbrowser.open(self.trailer_youtube_url)
|
C#
|
UTF-8
| 2,802 | 2.640625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trapper : Piece
{
public int minimumRange = 3;
public override List<Vector2Int> MoveLocations(Vector2Int gridPoint)
{
int usableMovementPoints;
List<Vector2Int> locations = new List<Vector2Int>();
List<Vector2Int> directions = new List<Vector2Int>(nonDiagonalDirections);
Vector2Int originalPosition;
originalPosition = new Vector2Int(gridPoint.x + 0, gridPoint.y + 0);
locations.Add(originalPosition);
usableMovementPoints = movementPoints;
while (usableMovementPoints > 0)
{
int forsize = locations.Count;
for (int i = 0; i < forsize; i++)
{
foreach (Vector2Int dir in directions)
{
Vector2Int nextGridPoint = new Vector2Int(locations[i].x + dir.x, locations[i].y + dir.y);
if (locations.Contains(nextGridPoint) == false && GameManager.gameManagerInstance.NoPieceAt(nextGridPoint))
{
locations.Add(nextGridPoint);
}
}
}
usableMovementPoints--;
}
return locations;
}
public override List<Vector2Int> AttackLocations(Vector2Int gridPoint)
{
List<Vector2Int> locations = new List<Vector2Int>();
List<Vector2Int> directions = new List<Vector2Int>(nonDiagonalDirections);
directions.AddRange(diagonalDirections);
foreach (Vector2Int dir in directions)
{
for (int i = 1; i < attackRange; i++)
{
Vector2Int nextGridPoint = new Vector2Int(gridPoint.x + i * dir.x, gridPoint.y + i * dir.y);
if (i > minimumRange)
{
locations.Add(nextGridPoint);
}
if (GameManager.gameManagerInstance.PieceAtGrid(nextGridPoint))
{
break;
}
}
}
return locations;
}
public List<Vector2Int> TrapLocations(Vector2Int gridPoint)
{
List<Vector2Int> locations = new List<Vector2Int>();
List<Vector2Int> directions = new List<Vector2Int>(nonDiagonalDirections);
foreach (Vector2Int dir in directions)
{
for (int i = 1; i < attackRange; i++)
{
Vector2Int nextGridPoint = new Vector2Int(gridPoint.x + i * dir.x, gridPoint.y + i * dir.y);
locations.Add(nextGridPoint);
if (GameManager.gameManagerInstance.PieceAtGrid(nextGridPoint))
{
break;
}
}
}
return locations;
}
}
|
Python
|
UTF-8
| 3,755 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
# This Script for generating Tables
# Steps:
# [1] Get The Table Title
# [2] Get The Table Cells width
# [3] Get The Table Column Names
# [4] Get The Table Cells Data
# ==========================================================
# Import Print Function
from __future__ import print_function
def calc_space_before(word,cell_length):
# Get Total width of cell
# Sub The Length of word
# Return the value devided by 2
return int((cell_length - len(word))/2)
def Cells_Line(columns_width,cell_line = "-",cells_seperator="+"):
# Printing The Cell Tob Line
for i in columns_width:
print(cells_seperator + (cell_line * i), end="")
# Closing Row Line
print(cells_seperator)
def calc_space_after(word,cell_length):
return int(int(cell_length) - (int((cell_length - len(word))/2) + len(word)))
def table_generator(title,columns_width,columns_names,columns_data,Space = " ",cell_line = "-",cells_seperator="+",data_seperator = "|"):
""" This Function For Generating Tables """
# Converting Title To String
title = str(title)
# Converting Columns Width to integer
try:
for i in range(len(columns_width)):
columns_width[i] = int(columns_width[i])
except ValueError:
print("[-] Columns width must be integer values")
# Converting Columns Data to String
try:
for i in range(len(columns_data)):
for j in range(len(columns_data[i])):
columns_data[i][j] = str(columns_data[i][j])
except TypeError:
print("[-] Data Must be in string type")
# Caching The total Width From Columns Widthes
total_width = 0
for i in columns_width:
total_width += i
if len(title) >= total_width:
columns_width[-1] = columns_width[-1] + (len(title)- total_width) + 2
total_width = len(title) + len(columns_width) + 1
else:
total_width += (len(columns_width)-1)
# Printing Table Header
print(cells_seperator + (cell_line * total_width) + cells_seperator)
# Printing The Title
print(data_seperator + (Space * calc_space_before(title,total_width)) + title + (Space * calc_space_after(title,total_width)) + data_seperator)
# Printing The Columns Titles Tob Line
Cells_Line(columns_width,cell_line,cells_seperator)
# Printing Columns Names
for i in range(len(columns_width)):
print(data_seperator + (Space * calc_space_before(columns_names[i],columns_width[i])) + columns_names[i] + (Space * calc_space_after(columns_names[i],columns_width[i])) , end="")
print(data_seperator)
# Printing The Columns Titles Bottom Line
Cells_Line(columns_width,cell_line,cells_seperator)
# Printing Table Data
for i in range(len(columns_data)):
for j in range(len(columns_data[i])):
print(data_seperator +(Space * calc_space_before(columns_data[i][j],columns_width[j])) + columns_data[i][j] + (Space * calc_space_after(columns_data[i][j],columns_width[j])), end="")
print(data_seperator)
# Printing The Seperator Line
Cells_Line(columns_width,cell_line,cells_seperator)
# ==================== End Of Table Generator Function ============
title = "Table Name Table Name Table Name Table Name Table Name Table Name Table Name Table Name Table Name Table Name Table Name Table Name"
columns_width = [7,41,9,15,9,9,9,9,9,8]
columns_names = ["ID","Fullname","Class","Degree","X","XX","XXX","xxxx","xxxx","xxxxx"]
columns_data = list()
for i in range(10):
columns_data.append([(i+1),str("Mostafa " + str(i) + " Mahmoud"),"A",i*5,"x","xx","xxx","xxxx","xxxxx","xxxxxx"])
table_generator(title, columns_width, columns_names, columns_data)
|
Markdown
|
UTF-8
| 6,293 | 3.5625 | 4 |
[] |
no_license
|
相信下面的代码很眼熟吧
```javascript
const a = '23333';
if (a === '23333' || a === '33333' || a === '43333' || a === '53333') {
console.log(1);
}
```
如果a的值有更多可能呢?或许可以这样写:
```javascript
const a = '23333';
const compare = ['23333', '33333', '43333', '53333']
if (compare.includes(a)) {
console.log(1);
}
```
有没有觉得好多了?实际上可能平常困扰更多的是大量的if-else的使用,其实这也是有办法简化的。
例如这样的判断:
```javascript
const state = 'a';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
if (state === 'a') {
add('state1');
go('state1')
} else if (state === 'b') {
add('state2');
go('state2')
} else if (state === 'c') {
add('state3');
go('state3')
} else if (state === 'd') {
add('state4');
go('state4')
} else if (state === 'e') {
add('state5');
go('state5')
}
```
可以使用switch替换如下:
```javascript
const state = 'a';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
switch (state) {
case 'a':
add('state1');
go('state1');
break;
case 'b':
add('state2');
go('state2');
break;
case 'c':
add('state3');
go('state3');
break;
case 'd':
add('state4');
go('state4');
break;
case 'e':
add('state5');
go('state5');
break;
}
```
好像没有太大的变化…别着急,其实像这样的一元条件判断可以通过object对象或者Map对象存储达到降低代码的冗杂度。具体怎么做呢?请看一下下面两种写法:
```javascript
const state = 'a';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
const handle = {
'a': 'state1',
'b': 'state2',
'c': 'state3',
'd': 'state4',
'e': 'state5'
};
add(handle[state]);
go(handle[state]);
```
```javascript
const state = 'a';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
const map = new Map([
['a', 'state1'],
['b', 'state2'],
['c', 'state3'],
['d', 'state4'],
['e', 'state5']]);
add(map.get(state));
go(map.get(state));
```
这样代码是不是感觉简洁多了?如果是更复杂的判断情况呢?比如下面的:
```javascript
const state = 'a';
const author = 'me';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
if (author === 'me') {
if (state === 'a') {
add('state1');
go('state1')
} else if (state === 'b') {
add('state2');
go('state2')
} else if (state === 'c') {
add('state3');
go('state3')
} else if (state === 'd') {
add('state4');
go('state4')
} else if (state === 'e') {
add('state5');
go('state5')
}
} else if (author === 'you') {
if (state === 'a') {
add('state11');
go('state11')
} else if (state === 'b') {
add('state22');
go('state22')
} else if (state === 'c') {
add('state33');
go('state33')
} else if (state === 'd') {
add('state44');
go('state44')
} else if (state === 'e') {
add('state55');
go('state55')
}
}
```
上面的有两个判断条件,我们称为二元条件判断。这种情况又该怎么处理呢?请看下面的写法:
```javascript
const state = 'a';
const author = 'me';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
const handle = {
'me_a': 'state1',
'me_b': 'state2',
'me_c': 'state3',
'me_d': 'state4',
'me_e': 'state5',
'you_a': 'state11',
'you_b': 'state22',
'you_c': 'state33',
'you_d': 'state44',
'you_e': 'state55'
};
add(handle[`${author}_${state}`]);
go(handle[`${author}_${state}`]);
```
这次通过字符串拼接和对象存储,实现了二元条件的判断简化。当然也可以用Map对象来做容器,这里我就不演示了。
其实这个并不是最好的方法,或许对于二元条件判断来说可以接受,但是如果是三元判断甚至更多呢?总不能因为es6的模版字符串好用而无脑使用字符串拼接吧。
这个时候Map对象的优势就体现出来了,我们都知道Map对象的key可以是任何值。利用这个特性我们可以通过Map对象作为容器管理多元判断。具体怎么做呢?请看下面的代码:
```javascript
const state = 'a';
const author = 'me';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
const map = new Map([
[{state: 'a', author: 'me'}, 'state1'],
[{state: 'b', author: 'me'}, 'state2'],
[{state: 'c', author: 'me'}, 'state3'],
[{state: 'd', author: 'me'}, 'state4'],
[{state: 'e', author: 'me'}, 'state5'],
[{state: 'a', author: 'you'}, 'state11'],
[{state: 'b', author: 'you'}, 'state22'],
[{state: 'c', author: 'you'}, 'state33'],
[{state: 'd', author: 'you'}, 'state44'],
[{state: 'e', author: 'you'}, 'state55'],
]);
const item = [...map].filter(([key, value]) => key.state === state && key.author === author );
const [key, value] = item[0];
add(value);
go(value);
```
那么这样就够了吗?其实有了Map对象做容器后,我们可以实现更复杂的多元判断管理。
比如,某几个状态( state = b || c || d || e 同时 author = me)会执行相同的函数,此时引入正则即可实现这样的多元判断简化,如下:
```javascript
const state = 'c';
const author = 'me';
function add(param) {
console.log(param);
}
function go(param) {
console.warn(param);
}
const map = new Map([
[/^a_me$/, 'state1'],
[/^b|c|d|e_me$/, 'state2'],
[/^a_you$/, 'state11'],
[/^b_you$/, 'state22'],
[/^c_you$/, 'state33'],
[/^d_you$/, 'state44'],
[/^e_you$/, 'state55'],
]);
const item = [...map].filter(([key, value]) => key.test(`${state}_${author}`) );
const [key, value] = item[0];
add(value);
go(value);
```
有没有一种再也不会被大量的if-else困扰的感觉?2333...
|
PHP
|
UTF-8
| 1,313 | 2.65625 | 3 |
[] |
no_license
|
<?php
session_start();
require("config.php");
$req =$bdd->prepare('SELECT * FROM users WHERE email= :email');
$req->execute(array(
'email' => $_POST['email']));
$result =$req->fetch();
if($result){
header('Location:index.php?error=1');
}
else{
if(isset($_POST['password']) AND $_POST['password'] == $_POST['confirmPassword'] AND !empty($_POST['password']) AND !empty($_POST['email']) AND !empty($_POST['firstname']) AND !empty($_POST['lastname']) AND !empty($_POST['job']))
{
//Hachage du password
$_POST['password'] = sha1($_POST['password']);
//Insertion
$req = $bdd->prepare('INSERT INTO users (firstname, lastname, email, password, job, date_create) VALUES (:firstname, :lastname, :email, :password, :job, NOW() )');
$req->execute(array(
':firstname' =>$_POST['firstname'],
':lastname' =>$_POST['lastname'],
':email' =>$_POST['email'],
':password' =>$_POST['password'],
':job' =>$_POST['job']
));
$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];
$_SESSION['job'] = $_POST['job'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['author'] = $_POST['firstname'].' '.$_POST['lastname'];
header('Location:index.php');
}
else
{
echo "Tous les champs sont obligatoires";
}
}
?>
|
Java
|
UTF-8
| 79 | 1.90625 | 2 |
[] |
no_license
|
package prototype;
public interface MailSender {
void send(Mail mail);
}
|
Go
|
UTF-8
| 2,365 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package keeper_test
import (
"testing"
"github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
)
func TestGetLastTokenizeShareRecordId(t *testing.T) {
_, app, ctx := createTestInput(t)
lastTokenizeShareRecordID := app.StakingKeeper.GetLastTokenizeShareRecordID(ctx)
require.Equal(t, lastTokenizeShareRecordID, uint64(0))
app.StakingKeeper.SetLastTokenizeShareRecordID(ctx, 100)
lastTokenizeShareRecordID = app.StakingKeeper.GetLastTokenizeShareRecordID(ctx)
require.Equal(t, lastTokenizeShareRecordID, uint64(100))
}
func TestGetTokenizeShareRecord(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels, _ := generateAddresses(app, ctx, 2)
owner1, owner2 := addrDels[0], addrDels[1]
tokenizeShareRecord1 := types.TokenizeShareRecord{
Id: 0,
Owner: owner1.String(),
ModuleAccount: "test-module-account-1",
Validator: "test-validator",
}
tokenizeShareRecord2 := types.TokenizeShareRecord{
Id: 1,
Owner: owner2.String(),
ModuleAccount: "test-module-account-2",
Validator: "test-validator",
}
tokenizeShareRecord3 := types.TokenizeShareRecord{
Id: 2,
Owner: owner1.String(),
ModuleAccount: "test-module-account-3",
Validator: "test-validator",
}
err := app.StakingKeeper.AddTokenizeShareRecord(ctx, tokenizeShareRecord1)
require.NoError(t, err)
err = app.StakingKeeper.AddTokenizeShareRecord(ctx, tokenizeShareRecord2)
require.NoError(t, err)
err = app.StakingKeeper.AddTokenizeShareRecord(ctx, tokenizeShareRecord3)
require.NoError(t, err)
tokenizeShareRecord, err := app.StakingKeeper.GetTokenizeShareRecord(ctx, 2)
require.NoError(t, err)
require.Equal(t, tokenizeShareRecord, tokenizeShareRecord3)
tokenizeShareRecord, err = app.StakingKeeper.GetTokenizeShareRecordByDenom(ctx, tokenizeShareRecord2.GetShareTokenDenom())
require.NoError(t, err)
require.Equal(t, tokenizeShareRecord, tokenizeShareRecord2)
tokenizeShareRecords := app.StakingKeeper.GetAllTokenizeShareRecords(ctx)
require.Equal(t, len(tokenizeShareRecords), 3)
tokenizeShareRecords = app.StakingKeeper.GetTokenizeShareRecordsByOwner(ctx, owner1)
require.Equal(t, len(tokenizeShareRecords), 2)
tokenizeShareRecords = app.StakingKeeper.GetTokenizeShareRecordsByOwner(ctx, owner2)
require.Equal(t, len(tokenizeShareRecords), 1)
}
|
Python
|
UTF-8
| 8,412 | 2.65625 | 3 |
[] |
no_license
|
import numpy
import torch
import torch.nn as nn
class ActorCriticDiscrete(nn.Module):
def __init__(self, hyperParameters):
super(ActorCriticDiscrete, self).__init__()
self.__device = hyperParameters.device
# actor mean range -1 to 1
self.__actorNet = nn.Sequential(
nn.Linear(hyperParameters.stateDimension, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, hyperParameters.actionDimension),
nn.Softmax(dim=-1)
).to(self.__device)
# critic
self.__criticNet = nn.Sequential(
nn.Linear(hyperParameters.stateDimension, 256),
nn.Tanh(),
nn.Linear(256, 128),
nn.Tanh(),
nn.Linear(128, 64),
nn.Tanh(),
nn.Linear(64, 1)
).to(self.__device)
def forward(self):
raise NotImplementedError
def setStateDict(self,actorCriticStateDict):
if isinstance(actorCriticStateDict,dict):
tensorDict={}
for key, value in actorCriticStateDict.items():
tensorDict[key] = torch.from_numpy(value).to(self.__device)
actorCriticStateDict = tensorDict
elif isinstance(actorCriticStateDict,str):
actorCriticStateDict = torch.load(actorCriticStateDict)
else:
raise TypeError("actorCriticStateDict msut be a dictionary or a string!")
self.load_state_dict(actorCriticStateDict)
def selectAction(self, state):
state = torch.FloatTensor(state).to(self.__device)
actionProbs = self.__actorNet(state)
actionDistribution = torch.distributions.Categorical(actionProbs)
action = actionDistribution.sample()
return action.detach().cpu().numpy(), actionDistribution.log_prob(action).detach().cpu().numpy()
def evaluate(self, state, action):
actionProbs = self.__actorNet(state)
actionDistribution = torch.distributions.Categorical(actionProbs)
actionLogProbs = actionDistribution.log_prob(action)
entropyDistribution = actionDistribution.entropy()
stateValue = self.__criticNet(state)
return actionLogProbs, torch.squeeze(stateValue), entropyDistribution
class ActorCriticContinuous(nn.Module):
def __init__(self, hyperParameters):
super(ActorCriticContinuous, self).__init__()
self.__device = hyperParameters.device
# actor mean range -1 to 1
self.__actorNet = nn.Sequential(
nn.Linear(hyperParameters.stateDimension, 256),
nn.LeakyReLU(),
nn.Linear(256, 128),
nn.LeakyReLU(),
nn.Linear(128, 64),
nn.LeakyReLU(),
nn.Linear(64, hyperParameters.actionDimension),
nn.LeakyReLU()
).to(self.__device)
# critic
self.__criticNet = nn.Sequential(
nn.Linear(hyperParameters.stateDimension, 256),
nn.LeakyReLU(),
nn.Linear(256, 128),
nn.LeakyReLU(),
nn.Linear(128, 64),
nn.LeakyReLU(),
nn.Linear(64, 1)
).to(self.__device)
self.__actionVariance = torch.full((hyperParameters.actionDimension,), hyperParameters.actionSTD*hyperParameters.actionSTD).to(self.__device)
def forward(self):
raise NotImplementedError
def setStateDict(self,actorCriticStateDict):
if isinstance(actorCriticStateDict,dict):
tensorDict={}
for key, value in actorCriticStateDict.items():
tensorDict[key] = torch.from_numpy(value).to(self.__device)
actorCriticStateDict = tensorDict
elif isinstance(actorCriticStateDict,str):
actorCriticStateDict = torch.load(actorCriticStateDict)
else:
raise TypeError("actorCriticStateDict msut be a dictionary or a string!")
self.load_state_dict(actorCriticStateDict)
def selectAction(self, state):
state = torch.FloatTensor(state).to(self.__device)
actionMean = self.__actorNet(state)
actionVarianceMatrix = torch.diag(self.__actionVariance).to(self.__device)
actionDistribution = torch.distributions.MultivariateNormal(actionMean,actionVarianceMatrix)
action = actionDistribution.sample()
return action.detach().cpu().numpy(), actionDistribution.log_prob(action).detach().cpu().numpy()
def evaluate(self, state, action):
actionMean = self.__actorNet(state)
actionVariance = self.__actionVariance.expand_as(actionMean)
actionVarianceMatrix = torch.diag_embed(actionVariance).to(self.__device)
actionDistribution = torch.distributions.MultivariateNormal(actionMean, actionVarianceMatrix)
actionLogProbs = actionDistribution.log_prob(action)
entropyDistribution = actionDistribution.entropy()
stateValue = self.__criticNet(state)
return actionLogProbs, torch.squeeze(stateValue), entropyDistribution
class PPO:
def __init__(self, hyperParameters):
self.__device=hyperParameters.device
self.__epsilonClip = hyperParameters.epsilonClip
self.__updateEpochs = hyperParameters.updateEpochs
self.__gamma = hyperParameters.gamma
self.policyAlgorithm = ActorCriticContinuous if hyperParameters.actionContinuous else ActorCriticDiscrete
self.actorCritic = self.policyAlgorithm(hyperParameters)
self.__optimizer = torch.optim.Adam(self.actorCritic.parameters(), lr=hyperParameters.lr, betas=hyperParameters.betas)
# self.optimizer = torch.optim.SGD(self.actorCritic.parameters(), lr=hyperParameters.lr, momentum=0.5, weight_decay=0.001)
self.__MseLoss = nn.MSELoss()
def __convertListToTensor(self,list):
numpyArray = numpy.stack(list)
arrayShape = numpyArray.shape
return torch.from_numpy(numpyArray.reshape(-1)).reshape(arrayShape).float().to(self.__device)
def getStateDict(self):
return {key:value.cpu().numpy() for key, value in self.actorCritic.state_dict().items()}
def saveModel(self,directory):
torch.save(self.actorCritic.state_dict(), directory)
def update(self, stateRepository):
# Monte Carlo estimate of state rewards:
rewards = []
discounted_reward = 0
for reward, terminalStatus in zip(reversed(stateRepository.rewards), reversed(stateRepository.terminalStatus)):
if terminalStatus:
discounted_reward = 0
discounted_reward = reward + (self.__gamma * discounted_reward)
rewards.insert(0, discounted_reward)
# Normalizing the rewards:
rewards = torch.tensor(rewards).float().to(self.__device)
rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-5)
# convert list to tensor
with torch.no_grad():
statesOld = self.__convertListToTensor(stateRepository.states)
actionsOld = self.__convertListToTensor(stateRepository.actions)
logProbsOld = self.__convertListToTensor(stateRepository.actionLogProbs)
# Optimize actorCritic for K epochs:
for _ in range(self.__updateEpochs):
# Evaluating old actions and values :
actionLogProbs, stateValues, entropyDistribution = self.actorCritic.evaluate(statesOld, actionsOld)
# Finding the ratio (pi_theta / pi_theta__old):
ratios = torch.exp(actionLogProbs - logProbsOld.detach())
# Finding Surrogate Loss:
advantages = rewards - stateValues.detach()
surr1 = ratios * advantages
surr2 = torch.clamp(ratios, 1-self.__epsilonClip, 1+self.__epsilonClip) * advantages
loss = -torch.min(surr1, surr2) + 0.5*self.__MseLoss(stateValues, rewards) - 0.01*entropyDistribution
# take gradient step
self.__optimizer.zero_grad()
loss.mean().backward()
self.__optimizer.step()
|
C#
|
UTF-8
| 689 | 3.5 | 4 |
[] |
no_license
|
class ProductComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;
return x.Code == y.Code && (x.Name.Equals(y.Name, StringComparison.InvariantCultureIgnoreCase));
}
public int GetHashCode(Product product)
{
var hashProductName = product.Name == null ? 0 : product.Name.ToLower().GetHashCode();
var hashProductCode = product.Code.GetHashCode();
return hashProductName ^ hashProductCode;
}
}
|
C++
|
UTF-8
| 3,002 | 3.453125 | 3 |
[] |
no_license
|
//#include <iostream>
//#include <string>
//#include <vector>
//#include <queue>
//
//using namespace std;
//
//struct TreeNode
//{
// int val;
// TreeNode* left;
// TreeNode* right;
// TreeNode(int x) : val(x), left(nullptr), right(nullptr)
// {
//
// }
//};
//
//void inorderTraversal(TreeNode* root, TreeNode* pre, int& minVal)
//{
//
// if (root->left)
// inorderTraversal(root->left, pre, minVal);
//
// if (pre)
// minVal = min(minVal, abs(root->val - pre->val));
// pre = root;
//
// if (root->right)
// inorderTraversal(root->right, pre, minVal);
//}
//
//int getMinimumDifference2(TreeNode* root)
//{
// int minVal = INT_MAX;
// TreeNode* pre = nullptr;
// inorderTraversal(root, pre, minVal);
//
// return minVal;
//}
//
//void helper(TreeNode* root, int& minVal)
//{
// if (!root)
// return;
//
// if (root->left)
// {
// TreeNode* tmp = root->left;
// while (tmp->right)
// tmp = tmp->right;
//
// minVal = min(minVal, root->val - tmp->val);
// helper(root->left, minVal);
// }
//
// if (root->right)
// {
// TreeNode* tmp = root->right;
// while (tmp->left)
// tmp = tmp->left;
//
// minVal = min(minVal, tmp->val - root->val);
// helper(root->right, minVal);
// }
//}
//
//int getMinimumDifference(TreeNode* root)
//{
// int minVal = INT_MAX;
// helper(root, minVal);
//
// return minVal;
//}
//
//TreeNode* createBinaryTree(const vector<string>& nums)
//{
// if (nums.empty())
// return nullptr;
//
// TreeNode* root = new TreeNode(stoi(nums[0]));
// queue<TreeNode*> q;
// q.emplace(root);
// TreeNode* pCurrent = nullptr;
//
// int startIndex = 1;
// int nextLevelIndex = 2;
// int restIndex = nums.size() - 1;
//
// while (restIndex > 0)
// {
// for (int i = startIndex; i < startIndex + nextLevelIndex; i += 2)
// {
// if (i >= nums.size())
// return root;
//
// pCurrent = q.front();
// q.pop();
//
// if (nums[i] != "null")
// {
// pCurrent->left = new TreeNode(stoi(nums[i]));
// q.emplace(pCurrent->left);
// }
//
// if (i + 1 >= nums.size())
// return root;
//
// if (nums[i + 1] != "null")
// {
// pCurrent->right = new TreeNode(stoi(nums[i + 1]));
// q.emplace(pCurrent->right);
// }
// }
//
// startIndex += nextLevelIndex;
// restIndex -= nextLevelIndex;
// nextLevelIndex = q.size() * 2;
// }
//
// return root;
//}
//
//void testGetMinimumDifference()
//{
// vector<string> nums1 = { "1", "null", "3", "2" };
// TreeNode* root1 = createBinaryTree(nums1);
// cout << getMinimumDifference(root1) << endl;
//}
//
//int main()
//{
// testGetMinimumDifference();
//
// getchar();
// return 0;
//}
|
JavaScript
|
UTF-8
| 1,207 | 2.5625 | 3 |
[
"Unlicense"
] |
permissive
|
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const { newsFragmentsUserConfig } = require("../config");
const { checkFragmentsFolder } = require("../helpers");
const availableFragmentTypes = newsFragmentsUserConfig.fragmentsTypes.map(
function (el) {
return el.extension;
}
);
module.exports.create = function (inputs, flags) {
const fragmentType = inputs[1];
let fragmentText = inputs[2] || "";
let message = "";
if (!availableFragmentTypes.includes(fragmentType)) {
message = chalk`Fragment type {red ${fragmentType}} is invalid.
Choose one of available fragment types: {green ${availableFragmentTypes}}`;
process.stdout.write(message);
return message;
}
const fragmentsFolder = newsFragmentsUserConfig.fragmentsFolder;
const filename = path.join(fragmentsFolder, `${+new Date()}.${fragmentType}`);
checkFragmentsFolder(fragmentsFolder);
if (fragmentText.length > 0 && !fragmentText.endsWith(".")) {
fragmentText = `${fragmentText}.`;
}
fs.writeFileSync(filename, fragmentText);
message = `Fragment ${filename} created with success!`;
process.stdout.write(chalk.green(message));
return message;
};
|
Ruby
|
UTF-8
| 1,920 | 3.171875 | 3 |
[] |
no_license
|
#!/usr/bin/ruby
$dir = 'models'
$models = []
def file_to_obj(filename)
ret = {}
ret[:model] = {}
char = filename.scan(/[0-9][[0-9]*_]+[0-9]+.res$/)[0].split('_')
ret[:model][:neuron]=filename.scan(/\[.*\]/)[0][1..-2].split('_').map(&:to_i)
ret[:model][:eta] = char[-2].to_f / 10.0
ret[:model][:momentom] = char[-1].to_f / 10.0
ret[:data] = {}
ret[:data][:raw] = []
File.open(filename,'r'){|f|
while (line=f.gets) != nil
e_val = line.split(' ').first.to_f
ret[:data][:raw] << e_val
end
}
ret[:data][:max] = ret[:data][:raw].max
ret
end
def print_model(e)
"#{e[:model][:neuron].join(',')} #{e[:model][:eta]} #{e[:model][:momentom]}: #{e[:data][:max]}"
end
def simple_statistics
puts "Best rate of all: #{print_model($models.max_by{|c| c[:data][:max]})}"
puts "Best eta of each:"
$models.sort_by!{|c|-c[:data][:max]}
$models.group_by{|c|c[:model][:neuron]}.each{|model,models|
max = models.max_by{|c|c[:data][:max]}
puts " Best eta of #{model}: eta=#{max[:model][:eta]} mom=#{max[:model][:momentom]}"
}
end
def output_csv
puts '"neuron","eta","momentum",' + (1..20).to_a.map{|c|c*1000}.join(',')
$models.sort_by{|c|c[:model][:neuron].to_s+c[:model][:eta].to_s}.each{|f|
puts "\"#{f[:model][:neuron]}\",\"#{f[:model][:eta]}\",\"#{f[:model][:momentom]}\"" + f[:data][:raw].join(',')
}
end
def help
puts <<HELP
=====================================================
usage: ./analyze_models.rb command
avalid commands are:
s : output simple statistics
csv : output e_val in csv format of each model
=====================================================
HELP
exit
end
def load_files
Dir.chdir($dir)
Dir.glob("*.res").each{|filename|
$models << file_to_obj(filename)
}
end
def main
help if ARGV.size != 1
load_files
case ARGV[0]
when 's';simple_statistics
when 'csv';output_csv
end
end
main
|
JavaScript
|
UTF-8
| 631 | 2.546875 | 3 |
[] |
no_license
|
const baseUrl = 'http://localhost:8080/api/v1'
export const getAllSongs = () => {
return fetch(baseUrl + '/playlist')
.then(res => res.json())
.catch(error => console.error(error));
}
export const postNewSong = (song) => {
return fetch(baseUrl + '/playlist', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(song)
})
.then(res => res.json())
.catch(error => console.error(error));
}
export const removeSongFromQueue = (songId) => {
fetch(`${baseUrl}/playlist/${songId}`, {
method: 'DELETE'
})
.catch(error => console.error(error));
}
|
Java
|
UTF-8
| 1,086 | 1.976563 | 2 |
[
"MIT"
] |
permissive
|
package oith.ws.dom.hcm.prl;
import oith.ws.dom.hcm.core.Period;
import javax.validation.constraints.NotNull;
import org.springframework.data.mongodb.core.mapping.Document;
import oith.ws.dom.core.AbstDocProcessAudit;
import oith.ws.dom.core.User;
import oith.ws.dom.hcm.pmis.Emp;
import org.springframework.data.mongodb.core.mapping.DBRef;
@Document(collection = "ProcessedPrl")
public class ProcessedPrl extends AbstDocProcessAudit {
@NotNull
@DBRef
private Emp emp;
@NotNull
@DBRef
private Period period;
private Double netPay;
public ProcessedPrl(User user) {
super(user);
}
public Double getNetPay() {
return netPay;
}
public void setNetPay(Double netPay) {
this.netPay = netPay;
}
public Emp getEmp() {
return emp;
}
public void setEmp(Emp emp) {
this.emp = emp;
}
public Period getPeriod() {
return period;
}
public void setPeriod(Period period) {
this.period = period;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.