file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
39k
| suffix
large_stringlengths 0
36.1k
| middle
large_stringlengths 0
29.4k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
create.js | var middleware = require('../../middleware')
;
function handler (req, res, next) {
var profile = { };
res.send(200, res.profile);
next( );
return;
}
var endpoint = {
path: '/users/:user/create'
, method: 'get'
, handler: handler
};
module.exports = function configure (opts, server) {
function mount (server) { | var mandatory = middleware.mandatory(opts, server);
endpoint.middleware = mandatory.concat(userInfo);
function updateUser (req, res, next) {
var profile = { };
var name = req.params.user;
var update = req.params;
server.updateUser(name, update, {save:false, create:true}, function (result) {
server.log.debug('UPDATED user', arguments);
res.profile = result;
next( );
});
}
endpoint.mount = mount;
return endpoint;
};
module.exports.endpoint = endpoint; | server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler);
}
var userInfo = middleware.minUser(opts, server); | random_line_split |
create.js | var middleware = require('../../middleware')
;
function handler (req, res, next) {
var profile = { };
res.send(200, res.profile);
next( );
return;
}
var endpoint = {
path: '/users/:user/create'
, method: 'get'
, handler: handler
};
module.exports = function configure (opts, server) {
function mount (server) {
server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler);
}
var userInfo = middleware.minUser(opts, server);
var mandatory = middleware.mandatory(opts, server);
endpoint.middleware = mandatory.concat(userInfo);
function updateUser (req, res, next) |
endpoint.mount = mount;
return endpoint;
};
module.exports.endpoint = endpoint;
| {
var profile = { };
var name = req.params.user;
var update = req.params;
server.updateUser(name, update, {save:false, create:true}, function (result) {
server.log.debug('UPDATED user', arguments);
res.profile = result;
next( );
});
} | identifier_body |
create.js | var middleware = require('../../middleware')
;
function handler (req, res, next) {
var profile = { };
res.send(200, res.profile);
next( );
return;
}
var endpoint = {
path: '/users/:user/create'
, method: 'get'
, handler: handler
};
module.exports = function configure (opts, server) {
function | (server) {
server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler);
}
var userInfo = middleware.minUser(opts, server);
var mandatory = middleware.mandatory(opts, server);
endpoint.middleware = mandatory.concat(userInfo);
function updateUser (req, res, next) {
var profile = { };
var name = req.params.user;
var update = req.params;
server.updateUser(name, update, {save:false, create:true}, function (result) {
server.log.debug('UPDATED user', arguments);
res.profile = result;
next( );
});
}
endpoint.mount = mount;
return endpoint;
};
module.exports.endpoint = endpoint;
| mount | identifier_name |
api.ts | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the project repository.
// ==LICENSE-END==
import { TApiMethod, TApiMethodName } from "readium-desktop/common/api/api.type";
import { TMethodApi } from "readium-desktop/common/api/methodApi.type";
import { TModuleApi } from "readium-desktop/common/api/moduleApi.type";
import { apiActions } from "readium-desktop/common/redux/actions";
// eslint-disable-next-line local-rules/typed-redux-saga-use-typed-effects
import { put } from "redux-saga/effects";
/**
*
* api function to dispatch an api request in redux-saga.
* should be call with yield* to delegate to another generator
*
* @param apiPath name of the api
* @param requestId id string channel
* @param requestData typed api parameter
*/
export function | <T extends TApiMethodName>(
apiPath: T,
requestId: string,
...requestData: Parameters<TApiMethod[T]>
) {
const splitPath = apiPath.split("/");
const moduleId = splitPath[0] as TModuleApi;
const methodId = splitPath[1] as TMethodApi;
return put(apiActions.request.build(requestId, moduleId, methodId, requestData));
}
| apiSaga | identifier_name |
api.ts | // Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the project repository.
// ==LICENSE-END==
import { TApiMethod, TApiMethodName } from "readium-desktop/common/api/api.type";
import { TMethodApi } from "readium-desktop/common/api/methodApi.type";
import { TModuleApi } from "readium-desktop/common/api/moduleApi.type";
import { apiActions } from "readium-desktop/common/redux/actions";
// eslint-disable-next-line local-rules/typed-redux-saga-use-typed-effects
import { put } from "redux-saga/effects";
/**
*
* api function to dispatch an api request in redux-saga.
* should be call with yield* to delegate to another generator
*
* @param apiPath name of the api
* @param requestId id string channel
* @param requestData typed api parameter
*/
export function apiSaga<T extends TApiMethodName>(
apiPath: T,
requestId: string,
...requestData: Parameters<TApiMethod[T]>
) {
const splitPath = apiPath.split("/");
const moduleId = splitPath[0] as TModuleApi;
const methodId = splitPath[1] as TMethodApi;
return put(apiActions.request.build(requestId, moduleId, methodId, requestData));
} | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements. | random_line_split |
|
api.ts | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the project repository.
// ==LICENSE-END==
import { TApiMethod, TApiMethodName } from "readium-desktop/common/api/api.type";
import { TMethodApi } from "readium-desktop/common/api/methodApi.type";
import { TModuleApi } from "readium-desktop/common/api/moduleApi.type";
import { apiActions } from "readium-desktop/common/redux/actions";
// eslint-disable-next-line local-rules/typed-redux-saga-use-typed-effects
import { put } from "redux-saga/effects";
/**
*
* api function to dispatch an api request in redux-saga.
* should be call with yield* to delegate to another generator
*
* @param apiPath name of the api
* @param requestId id string channel
* @param requestData typed api parameter
*/
export function apiSaga<T extends TApiMethodName>(
apiPath: T,
requestId: string,
...requestData: Parameters<TApiMethod[T]>
) | {
const splitPath = apiPath.split("/");
const moduleId = splitPath[0] as TModuleApi;
const methodId = splitPath[1] as TMethodApi;
return put(apiActions.request.build(requestId, moduleId, methodId, requestData));
} | identifier_body |
|
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
}
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
} | Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
} |
// echo incoming bytes back
match stream.write(&mut buf) { | random_line_split |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() |
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
}
// echo incoming bytes back
match stream.write(&mut buf) {
Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
} | identifier_body |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
}
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn | (mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
}
// echo incoming bytes back
match stream.write(&mut buf) {
Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| handle_client | identifier_name |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
}
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
}
// echo incoming bytes back
match stream.write(&mut buf) {
Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => |
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
} | conditional_block |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used in conjunction with the geomodel library for doing
# proximity based searches
from google.appengine.ext.db import GeoPt
from geo import geotypes
# HttpResponse is what all Django-based views must return
# to render the output. In our web application the
# _json* methods build and return HttpResponse objects
# for rendering JSON dat
from django.http import HttpResponse
# For encoding Python objects into JSON strings
from django.utils import simplejson
# Our datastore models
from model import *
# For handling user sessions
from appengine_utilities.sessions import Session
# Provides the sha1 module we use for hashing passwords
import hashlib
# The Python loggin module. We use the basicConfig method
# to setup to log to the console (or GoogleAppEngineLauncher
# logs screen)
import logging
logging.basicConfig(level=logging.DEBUG)
##
# CONSTANTS
##
"""
The email address to send from. See the Notes section of the README
for more information on what to set this to.
"""
SENDER_EMAIL_ADDRESS = "VALID@APPENGINE_ADDRESS.COM"
##
# UTILITY METHODS
##
def _hash_password(password):
"""
Returns a sha1-hashed version of the given plaintext password.
"""
return hashlib.sha1(password).hexdigest()
def _json_response(success=True, msg="OK", **kwargs):
"""
Helper method to build an HTTPResponse with a stock
JSON object.
@param success=True: indicates success or failure of the API method
@param msg: string with details on success or failure
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# build up the response data and convert it to a string using the
# simplejson module
response_data = dict(success=success, msg=msg)
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
# All views must return a valid HttpResponse object so build it and
# set the JSON string and mimetype indicating that the result is
# JSON
return HttpResponse(response_string, mimetype="application/json")
def _json_unauthorized_response(**kwargs):
"""
Helper method to build an HTTPResponse with a stock JSON object
that represents unauthorized access to an API method.
NOTE: Always returns success=false and msg="Unauthorized"
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# Same process as _json_response method, accept always return false and
# an Unauthorized message with a status code of 401
response_data = dict(success=False, msg="Unauthorized")
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
return HttpResponse(response_string, status=401, mimetype="application/json")
##
# DECORATORS
#
# For more information about decorators in Python see:
#
# http://www.python.org/dev/peps/pep-0318/
# http://wiki.python.org/moin/PythonDecorators
# http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
# Google...
##
# Usage: @validate_request(method, p1, p2, ...)
def validate_request(method, *params):
"""
Decorator for validating the required request method for an API call as
well as enforcing any required parameters in the request. If either the
method or parameter checks fail a stock failure JSON object is returned
with the exact issue in the msg field. If all checks pass then the
API call proceeds.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# check the required method
if request.method == method:
# check that each parameter exists and has a value
for param in params:
value = request.REQUEST.get(param, "")
if not value:
# failed parameter check
return _json_response(success=False,
msg="'%s' is required." % param)
# return the original API call through
return view_func(request, *args, **kwargs)
else:
# failed method check
return _json_response(success=False,
msg="%s requests are not allowed." % request.method)
return _view
return _dec
# Usage: @validate_session()
def validate_session():
"""
Decorator for validating that a user is authenticated by checking the
session for a user object. If this fails the stock json_unauthorized_response
is returned or else the API call is allowed to proceed.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# get the session and check for a user, fail if it doesn't exist
if Session().get("user") is None:
# failed request
return _json_unauthorized_response()
# return the original API call through
return view_func(request, *args, **kwargs)
return _view
return _dec
##
# API METHODS
##
@validate_session()
@validate_request("POST", "question", "latitude", "longitude", "pay_key")
def ask(request):
"""
API Method - /ask
Creates a new Question and adds it to the datastore
@method POST
@param question: the text of the question
@param latitude: latitude of the location
@param longitude: longitude of the location
@param pay_key: the pay key from a successful PayPal purchase
@returns stock success or failure JSON response along with
the question and user objects.
"""
# authenticated user
user = Session().get("user")
# required parameters
question = request.REQUEST.get("question")
latitude = float(request.REQUEST.get("latitude"))
longitude = float(request.REQUEST.get("longitude"))
pay_key = request.REQUEST.get("pay_key")
# Using the PayKey you could validate it using PayPal APIs
# to confirm that a user paid and the transaction is complete.
# This is left up to the curious coder to implement :)
# Create the question with the required fields and tie it | q = Question(question=question,
location=GeoPt(latitude, longitude),
user=user)
q.update_location()
q.put()
# return stock JSON with the Question object details
return _json_response(question=q.to_json(), user=user.to_json())
@validate_session()
@validate_request("POST", "question_id", "answer")
def answer(request):
"""
API Method - /answer
Creates a new Answer object and adds it to the datastore. Validates
that the question exists and does not have an accepted answer before
accepting the answer.
This method also takes care of sending the owner of the question
an email saying a new answer has been given with the answer in the
body of the message.
@method POST
@param question_id: id of an existing question
@param answer: the text for the answer to a question
@returns one answer object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
question_id = int(request.REQUEST.get("question_id"))
answer = request.REQUEST.get("answer")
# find the question associated with the question_id parameter
question = Question.get_by_id(question_id)
# no question with the given id
if question is None:
return _json_response(success=False, msg="Question does not exist.")
# question has already been answered
if question.closed:
return _json_response(success=False, msg="Question has an accepted answer and is now closed.")
# create a new answer and save it to the datastore
a = Answer(user=user,
question=question,
answer=answer)
a.put()
# send an email to the owner of the question
question_owner_email = question.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=question_owner_email,
subject="Your question has a new answer!",
body="""
This is to inform you that one of your questions has
received a new answer.
Your question:
%s
The answer:
%s
Regards,
Inquire Application
""" % (question.question, answer))
# return stock JSON with details of the answer object
return _json_response(answer=a.to_json())
@validate_session()
@validate_request("POST", "answer_id")
def accept(request):
"""
API Method - /accept
Accepts an answer for a question. The question must be owned by the
current authenticated user accepting the question and not already
have an accepted answer.
This method also takes care of sending the owner of the answer
an email saying their answer was accepted. The accepted answer
owner will also be given one karma point.
@method POST
@param answer_id: id of the answer being accepted
@returns stock JSON object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
answer_id = int(request.REQUEST.get("answer_id"))
# find the answer associated with the answer_id
answer = Answer.get_by_id(answer_id)
# no answer with the given id
if answer is None:
return _json_response(success=False, msg="Answer does not exist.")
# associated question
question = answer.question
# make sure the question for this answer is owned by this user
question = answer.question
if question.user.key().id() != user.key().id():
return _json_response(success=False, msg="You must be the owner of the question to accept an answer.")
# also make sure the question is not already answered
if question.closed:
return _json_response(success=False, msg="Question already has an accepted answer.")
# change the accepted flag of the answer and save it.
answer.accepted_answer = True
answer.put()
# close the question and save it
question.closed = True
question.put()
# update the answer owner's karma points
answer.user.karma += 1
answer.user.put()
# send an email to the address assigned to the answer
answer_owner_email = answer.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=answer_owner_email,
subject="Your answer was accepted!",
body="""
This is to inform you that one of your answers has
been accepted! You have been given one karma point.
The question you answered:
%s
Your answer:
%s
Regards,
Inquire Application
""" % (question.question, answer.answer))
# return stock success JSON
return _json_response()
@validate_session()
@validate_request("GET", "question_id")
def answers(request):
"""
API Method - /answers
Returns a list of answers for a given question id.
@method GET
@param question_id: The question id to retrieve answers for
@returns list of answer objects
"""
# required parameters
question_id = int(request.GET.get("question_id"))
# retrieve the matching question
question = Question.get_by_id(question_id)
if question is None:
return _json_response(success=False,
msg="Question does not exist!")
return _json_response(answers=[a.to_json() for a in question.answer_set])
@validate_session()
@validate_request("GET", "latitude", "longitude")
def questions(request):
"""
API Method - /questions
Returns a list of questions that are within geographical proximity
to the passed in latitude/longitude.
@method GET
@param latitude: latitude of the location
@param longitude longitude of the location
@optional max_results: max number of questions to return, default=25
@optional max_distance: max distance to search in miles
@returns list of question objects
"""
# required parameters
latitude = float(request.GET.get("latitude"))
longitude = float(request.GET.get("longitude"))
# defines the center of our proximity search
# geotypes.Point provided by geomodel project
center = geotypes.Point(latitude, longitude)
# default
max_results = int(request.GET.get("max_results", 25)) # 25 results default
max_distance = int(request.GET.get("max_distance", 50)) # 50 mile default
# convert miles to kilometers
max_distance = 1000*max_distance/0.621371192
# Get all unclosed questions within the proximity max_distance and
# limit to max_results
base_query = Question.all().filter("closed =", False)
questions = Question.proximity_fetch(base_query,
center,
max_results=max_results,
max_distance=max_distance)
return _json_response(questions=[q.to_json() for q in questions])
@validate_request("POST", "email", "password")
def register(request):
"""
API Method - /register
Creates a new user and adds it to the datastore. If a user already
exists with the given email address the request fails and an
appropriate JSON response is returned.
@method POST
@param email: email address for the user
@param password: password for the user
@returns newly created user object or failure JSON
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
#
users = User.all()
users.filter("email =", email)
if users.count() != 0:
return _json_response(success=False,
msg="Email address already exists.", users=users.count())
password = _hash_password(password)
new_user = User(email=email, password=password)
new_user.put()
return _json_response()
def logout(request):
"""
API Method - /logout
Destroys the active user's session object. Any further use of
protected API methods will require a new session via the auth
API.
@method GET
@returns stock JSON response
"""
# delete session and return stock JSON response with a msg
# indicating the user has logged out
session = Session()
session.delete()
return _json_response(msg="User has been logged out.")
@validate_request("POST", "email", "password")
def auth(request):
"""
API Method - /auth
If credentials are correct a new session is created for this
user which authorizes them to use protected API methods.
@method POST
@param email: user's email address
@param password: user's password
@returns stock JSON response
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
# hash the password
password = _hash_password(password)
# Look up a User object that matches the email/password
users = User.all()
users \
.filter("email =", email) \
.filter("password =", password)
# No user found, return a failure message
if users.count() == 0:
return _json_response(success=False,
msg="Email or password is invalid.")
# Somehow more than one client with the same user/password have
# been created, which should never happen. Error out here.
if users.count() > 1:
return _json_response(details=None,
success=False,
msg="Internal security error. Contact an administrator")
# Pull the User from the datastore
user = users.get()
# Build a new session object and store the user
session = Session()
session["user"] = user
# return stock JSON with user details
return _json_response(user=user.to_json())
# Utility method for generating random questions around a
# given point. The point is currently Apple's headquarters
# so this works well with testing with the simulator.
def randomize(request):
import random
# location to generate questions around
near_lat, near_lon = 37.331693, -122.030457
# ~50 miles
dx = 50.0/69.0
# Number of questions to generate
num_questions = 10
# Possible users to assign questions to. These
# users will be looked up by the email addresses
# supply in this list and they must exist
email_accounts = ["[email protected]", "[email protected]"]
# no more editing
# look up the user objects associated with the
# given email addresses
users = []
for email in email_accounts:
user = User.all().filter("email =", email).get()
if user is not None:
users.append(user)
# return false if there were no user objects found
if not users:
return _json_response(success=False, msg="No users found")
# generate num_questions random questions around the given
# point (near_lat, near_lon) within some distance dx and
# assigning a random user to the question
for i in range(num_questions):
lat = random.uniform(near_lat-dx, near_lat+dx)
lon = random.uniform(near_lon-dx, near_lon+dx)
user = random.sample(users, 1)[0]
q = Question(user=user,
question="Question %d" % i,
location=db.GeoPt(lat, lon))
q.update_location()
q.put()
# return true
return _json_response() | # to the authenticated user | random_line_split |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used in conjunction with the geomodel library for doing
# proximity based searches
from google.appengine.ext.db import GeoPt
from geo import geotypes
# HttpResponse is what all Django-based views must return
# to render the output. In our web application the
# _json* methods build and return HttpResponse objects
# for rendering JSON dat
from django.http import HttpResponse
# For encoding Python objects into JSON strings
from django.utils import simplejson
# Our datastore models
from model import *
# For handling user sessions
from appengine_utilities.sessions import Session
# Provides the sha1 module we use for hashing passwords
import hashlib
# The Python loggin module. We use the basicConfig method
# to setup to log to the console (or GoogleAppEngineLauncher
# logs screen)
import logging
logging.basicConfig(level=logging.DEBUG)
##
# CONSTANTS
##
"""
The email address to send from. See the Notes section of the README
for more information on what to set this to.
"""
SENDER_EMAIL_ADDRESS = "VALID@APPENGINE_ADDRESS.COM"
##
# UTILITY METHODS
##
def _hash_password(password):
"""
Returns a sha1-hashed version of the given plaintext password.
"""
return hashlib.sha1(password).hexdigest()
def _json_response(success=True, msg="OK", **kwargs):
|
def _json_unauthorized_response(**kwargs):
"""
Helper method to build an HTTPResponse with a stock JSON object
that represents unauthorized access to an API method.
NOTE: Always returns success=false and msg="Unauthorized"
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# Same process as _json_response method, accept always return false and
# an Unauthorized message with a status code of 401
response_data = dict(success=False, msg="Unauthorized")
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
return HttpResponse(response_string, status=401, mimetype="application/json")
##
# DECORATORS
#
# For more information about decorators in Python see:
#
# http://www.python.org/dev/peps/pep-0318/
# http://wiki.python.org/moin/PythonDecorators
# http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
# Google...
##
# Usage: @validate_request(method, p1, p2, ...)
def validate_request(method, *params):
"""
Decorator for validating the required request method for an API call as
well as enforcing any required parameters in the request. If either the
method or parameter checks fail a stock failure JSON object is returned
with the exact issue in the msg field. If all checks pass then the
API call proceeds.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# check the required method
if request.method == method:
# check that each parameter exists and has a value
for param in params:
value = request.REQUEST.get(param, "")
if not value:
# failed parameter check
return _json_response(success=False,
msg="'%s' is required." % param)
# return the original API call through
return view_func(request, *args, **kwargs)
else:
# failed method check
return _json_response(success=False,
msg="%s requests are not allowed." % request.method)
return _view
return _dec
# Usage: @validate_session()
def validate_session():
"""
Decorator for validating that a user is authenticated by checking the
session for a user object. If this fails the stock json_unauthorized_response
is returned or else the API call is allowed to proceed.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# get the session and check for a user, fail if it doesn't exist
if Session().get("user") is None:
# failed request
return _json_unauthorized_response()
# return the original API call through
return view_func(request, *args, **kwargs)
return _view
return _dec
##
# API METHODS
##
@validate_session()
@validate_request("POST", "question", "latitude", "longitude", "pay_key")
def ask(request):
"""
API Method - /ask
Creates a new Question and adds it to the datastore
@method POST
@param question: the text of the question
@param latitude: latitude of the location
@param longitude: longitude of the location
@param pay_key: the pay key from a successful PayPal purchase
@returns stock success or failure JSON response along with
the question and user objects.
"""
# authenticated user
user = Session().get("user")
# required parameters
question = request.REQUEST.get("question")
latitude = float(request.REQUEST.get("latitude"))
longitude = float(request.REQUEST.get("longitude"))
pay_key = request.REQUEST.get("pay_key")
# Using the PayKey you could validate it using PayPal APIs
# to confirm that a user paid and the transaction is complete.
# This is left up to the curious coder to implement :)
# Create the question with the required fields and tie it
# to the authenticated user
q = Question(question=question,
location=GeoPt(latitude, longitude),
user=user)
q.update_location()
q.put()
# return stock JSON with the Question object details
return _json_response(question=q.to_json(), user=user.to_json())
@validate_session()
@validate_request("POST", "question_id", "answer")
def answer(request):
"""
API Method - /answer
Creates a new Answer object and adds it to the datastore. Validates
that the question exists and does not have an accepted answer before
accepting the answer.
This method also takes care of sending the owner of the question
an email saying a new answer has been given with the answer in the
body of the message.
@method POST
@param question_id: id of an existing question
@param answer: the text for the answer to a question
@returns one answer object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
question_id = int(request.REQUEST.get("question_id"))
answer = request.REQUEST.get("answer")
# find the question associated with the question_id parameter
question = Question.get_by_id(question_id)
# no question with the given id
if question is None:
return _json_response(success=False, msg="Question does not exist.")
# question has already been answered
if question.closed:
return _json_response(success=False, msg="Question has an accepted answer and is now closed.")
# create a new answer and save it to the datastore
a = Answer(user=user,
question=question,
answer=answer)
a.put()
# send an email to the owner of the question
question_owner_email = question.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=question_owner_email,
subject="Your question has a new answer!",
body="""
This is to inform you that one of your questions has
received a new answer.
Your question:
%s
The answer:
%s
Regards,
Inquire Application
""" % (question.question, answer))
# return stock JSON with details of the answer object
return _json_response(answer=a.to_json())
@validate_session()
@validate_request("POST", "answer_id")
def accept(request):
"""
API Method - /accept
Accepts an answer for a question. The question must be owned by the
current authenticated user accepting the question and not already
have an accepted answer.
This method also takes care of sending the owner of the answer
an email saying their answer was accepted. The accepted answer
owner will also be given one karma point.
@method POST
@param answer_id: id of the answer being accepted
@returns stock JSON object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
answer_id = int(request.REQUEST.get("answer_id"))
# find the answer associated with the answer_id
answer = Answer.get_by_id(answer_id)
# no answer with the given id
if answer is None:
return _json_response(success=False, msg="Answer does not exist.")
# associated question
question = answer.question
# make sure the question for this answer is owned by this user
question = answer.question
if question.user.key().id() != user.key().id():
return _json_response(success=False, msg="You must be the owner of the question to accept an answer.")
# also make sure the question is not already answered
if question.closed:
return _json_response(success=False, msg="Question already has an accepted answer.")
# change the accepted flag of the answer and save it.
answer.accepted_answer = True
answer.put()
# close the question and save it
question.closed = True
question.put()
# update the answer owner's karma points
answer.user.karma += 1
answer.user.put()
# send an email to the address assigned to the answer
answer_owner_email = answer.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=answer_owner_email,
subject="Your answer was accepted!",
body="""
This is to inform you that one of your answers has
been accepted! You have been given one karma point.
The question you answered:
%s
Your answer:
%s
Regards,
Inquire Application
""" % (question.question, answer.answer))
# return stock success JSON
return _json_response()
@validate_session()
@validate_request("GET", "question_id")
def answers(request):
"""
API Method - /answers
Returns a list of answers for a given question id.
@method GET
@param question_id: The question id to retrieve answers for
@returns list of answer objects
"""
# required parameters
question_id = int(request.GET.get("question_id"))
# retrieve the matching question
question = Question.get_by_id(question_id)
if question is None:
return _json_response(success=False,
msg="Question does not exist!")
return _json_response(answers=[a.to_json() for a in question.answer_set])
@validate_session()
@validate_request("GET", "latitude", "longitude")
def questions(request):
"""
API Method - /questions
Returns a list of questions that are within geographical proximity
to the passed in latitude/longitude.
@method GET
@param latitude: latitude of the location
@param longitude longitude of the location
@optional max_results: max number of questions to return, default=25
@optional max_distance: max distance to search in miles
@returns list of question objects
"""
# required parameters
latitude = float(request.GET.get("latitude"))
longitude = float(request.GET.get("longitude"))
# defines the center of our proximity search
# geotypes.Point provided by geomodel project
center = geotypes.Point(latitude, longitude)
# default
max_results = int(request.GET.get("max_results", 25)) # 25 results default
max_distance = int(request.GET.get("max_distance", 50)) # 50 mile default
# convert miles to kilometers
max_distance = 1000*max_distance/0.621371192
# Get all unclosed questions within the proximity max_distance and
# limit to max_results
base_query = Question.all().filter("closed =", False)
questions = Question.proximity_fetch(base_query,
center,
max_results=max_results,
max_distance=max_distance)
return _json_response(questions=[q.to_json() for q in questions])
@validate_request("POST", "email", "password")
def register(request):
"""
API Method - /register
Creates a new user and adds it to the datastore. If a user already
exists with the given email address the request fails and an
appropriate JSON response is returned.
@method POST
@param email: email address for the user
@param password: password for the user
@returns newly created user object or failure JSON
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
#
users = User.all()
users.filter("email =", email)
if users.count() != 0:
return _json_response(success=False,
msg="Email address already exists.", users=users.count())
password = _hash_password(password)
new_user = User(email=email, password=password)
new_user.put()
return _json_response()
def logout(request):
"""
API Method - /logout
Destroys the active user's session object. Any further use of
protected API methods will require a new session via the auth
API.
@method GET
@returns stock JSON response
"""
# delete session and return stock JSON response with a msg
# indicating the user has logged out
session = Session()
session.delete()
return _json_response(msg="User has been logged out.")
@validate_request("POST", "email", "password")
def auth(request):
"""
API Method - /auth
If credentials are correct a new session is created for this
user which authorizes them to use protected API methods.
@method POST
@param email: user's email address
@param password: user's password
@returns stock JSON response
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
# hash the password
password = _hash_password(password)
# Look up a User object that matches the email/password
users = User.all()
users \
.filter("email =", email) \
.filter("password =", password)
# No user found, return a failure message
if users.count() == 0:
return _json_response(success=False,
msg="Email or password is invalid.")
# Somehow more than one client with the same user/password have
# been created, which should never happen. Error out here.
if users.count() > 1:
return _json_response(details=None,
success=False,
msg="Internal security error. Contact an administrator")
# Pull the User from the datastore
user = users.get()
# Build a new session object and store the user
session = Session()
session["user"] = user
# return stock JSON with user details
return _json_response(user=user.to_json())
# Utility method for generating random questions around a
# given point. The point is currently Apple's headquarters
# so this works well with testing with the simulator.
def randomize(request):
import random
# location to generate questions around
near_lat, near_lon = 37.331693, -122.030457
# ~50 miles
dx = 50.0/69.0
# Number of questions to generate
num_questions = 10
# Possible users to assign questions to. These
# users will be looked up by the email addresses
# supply in this list and they must exist
email_accounts = ["[email protected]", "[email protected]"]
# no more editing
# look up the user objects associated with the
# given email addresses
users = []
for email in email_accounts:
user = User.all().filter("email =", email).get()
if user is not None:
users.append(user)
# return false if there were no user objects found
if not users:
return _json_response(success=False, msg="No users found")
# generate num_questions random questions around the given
# point (near_lat, near_lon) within some distance dx and
# assigning a random user to the question
for i in range(num_questions):
lat = random.uniform(near_lat-dx, near_lat+dx)
lon = random.uniform(near_lon-dx, near_lon+dx)
user = random.sample(users, 1)[0]
q = Question(user=user,
question="Question %d" % i,
location=db.GeoPt(lat, lon))
q.update_location()
q.put()
# return true
return _json_response()
| """
Helper method to build an HTTPResponse with a stock
JSON object.
@param success=True: indicates success or failure of the API method
@param msg: string with details on success or failure
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# build up the response data and convert it to a string using the
# simplejson module
response_data = dict(success=success, msg=msg)
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
# All views must return a valid HttpResponse object so build it and
# set the JSON string and mimetype indicating that the result is
# JSON
return HttpResponse(response_string, mimetype="application/json") | identifier_body |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used in conjunction with the geomodel library for doing
# proximity based searches
from google.appengine.ext.db import GeoPt
from geo import geotypes
# HttpResponse is what all Django-based views must return
# to render the output. In our web application the
# _json* methods build and return HttpResponse objects
# for rendering JSON dat
from django.http import HttpResponse
# For encoding Python objects into JSON strings
from django.utils import simplejson
# Our datastore models
from model import *
# For handling user sessions
from appengine_utilities.sessions import Session
# Provides the sha1 module we use for hashing passwords
import hashlib
# The Python loggin module. We use the basicConfig method
# to setup to log to the console (or GoogleAppEngineLauncher
# logs screen)
import logging
logging.basicConfig(level=logging.DEBUG)
##
# CONSTANTS
##
"""
The email address to send from. See the Notes section of the README
for more information on what to set this to.
"""
SENDER_EMAIL_ADDRESS = "VALID@APPENGINE_ADDRESS.COM"
##
# UTILITY METHODS
##
def _hash_password(password):
"""
Returns a sha1-hashed version of the given plaintext password.
"""
return hashlib.sha1(password).hexdigest()
def _json_response(success=True, msg="OK", **kwargs):
"""
Helper method to build an HTTPResponse with a stock
JSON object.
@param success=True: indicates success or failure of the API method
@param msg: string with details on success or failure
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# build up the response data and convert it to a string using the
# simplejson module
response_data = dict(success=success, msg=msg)
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
# All views must return a valid HttpResponse object so build it and
# set the JSON string and mimetype indicating that the result is
# JSON
return HttpResponse(response_string, mimetype="application/json")
def _json_unauthorized_response(**kwargs):
"""
Helper method to build an HTTPResponse with a stock JSON object
that represents unauthorized access to an API method.
NOTE: Always returns success=false and msg="Unauthorized"
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# Same process as _json_response method, accept always return false and
# an Unauthorized message with a status code of 401
response_data = dict(success=False, msg="Unauthorized")
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
return HttpResponse(response_string, status=401, mimetype="application/json")
##
# DECORATORS
#
# For more information about decorators in Python see:
#
# http://www.python.org/dev/peps/pep-0318/
# http://wiki.python.org/moin/PythonDecorators
# http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
# Google...
##
# Usage: @validate_request(method, p1, p2, ...)
def validate_request(method, *params):
"""
Decorator for validating the required request method for an API call as
well as enforcing any required parameters in the request. If either the
method or parameter checks fail a stock failure JSON object is returned
with the exact issue in the msg field. If all checks pass then the
API call proceeds.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# check the required method
if request.method == method:
# check that each parameter exists and has a value
for param in params:
value = request.REQUEST.get(param, "")
if not value:
# failed parameter check
return _json_response(success=False,
msg="'%s' is required." % param)
# return the original API call through
return view_func(request, *args, **kwargs)
else:
# failed method check
return _json_response(success=False,
msg="%s requests are not allowed." % request.method)
return _view
return _dec
# Usage: @validate_session()
def validate_session():
"""
Decorator for validating that a user is authenticated by checking the
session for a user object. If this fails the stock json_unauthorized_response
is returned or else the API call is allowed to proceed.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# get the session and check for a user, fail if it doesn't exist
if Session().get("user") is None:
# failed request
return _json_unauthorized_response()
# return the original API call through
return view_func(request, *args, **kwargs)
return _view
return _dec
##
# API METHODS
##
@validate_session()
@validate_request("POST", "question", "latitude", "longitude", "pay_key")
def ask(request):
"""
API Method - /ask
Creates a new Question and adds it to the datastore
@method POST
@param question: the text of the question
@param latitude: latitude of the location
@param longitude: longitude of the location
@param pay_key: the pay key from a successful PayPal purchase
@returns stock success or failure JSON response along with
the question and user objects.
"""
# authenticated user
user = Session().get("user")
# required parameters
question = request.REQUEST.get("question")
latitude = float(request.REQUEST.get("latitude"))
longitude = float(request.REQUEST.get("longitude"))
pay_key = request.REQUEST.get("pay_key")
# Using the PayKey you could validate it using PayPal APIs
# to confirm that a user paid and the transaction is complete.
# This is left up to the curious coder to implement :)
# Create the question with the required fields and tie it
# to the authenticated user
q = Question(question=question,
location=GeoPt(latitude, longitude),
user=user)
q.update_location()
q.put()
# return stock JSON with the Question object details
return _json_response(question=q.to_json(), user=user.to_json())
@validate_session()
@validate_request("POST", "question_id", "answer")
def answer(request):
"""
API Method - /answer
Creates a new Answer object and adds it to the datastore. Validates
that the question exists and does not have an accepted answer before
accepting the answer.
This method also takes care of sending the owner of the question
an email saying a new answer has been given with the answer in the
body of the message.
@method POST
@param question_id: id of an existing question
@param answer: the text for the answer to a question
@returns one answer object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
question_id = int(request.REQUEST.get("question_id"))
answer = request.REQUEST.get("answer")
# find the question associated with the question_id parameter
question = Question.get_by_id(question_id)
# no question with the given id
if question is None:
return _json_response(success=False, msg="Question does not exist.")
# question has already been answered
if question.closed:
return _json_response(success=False, msg="Question has an accepted answer and is now closed.")
# create a new answer and save it to the datastore
a = Answer(user=user,
question=question,
answer=answer)
a.put()
# send an email to the owner of the question
question_owner_email = question.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=question_owner_email,
subject="Your question has a new answer!",
body="""
This is to inform you that one of your questions has
received a new answer.
Your question:
%s
The answer:
%s
Regards,
Inquire Application
""" % (question.question, answer))
# return stock JSON with details of the answer object
return _json_response(answer=a.to_json())
@validate_session()
@validate_request("POST", "answer_id")
def accept(request):
"""
API Method - /accept
Accepts an answer for a question. The question must be owned by the
current authenticated user accepting the question and not already
have an accepted answer.
This method also takes care of sending the owner of the answer
an email saying their answer was accepted. The accepted answer
owner will also be given one karma point.
@method POST
@param answer_id: id of the answer being accepted
@returns stock JSON object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
answer_id = int(request.REQUEST.get("answer_id"))
# find the answer associated with the answer_id
answer = Answer.get_by_id(answer_id)
# no answer with the given id
if answer is None:
return _json_response(success=False, msg="Answer does not exist.")
# associated question
question = answer.question
# make sure the question for this answer is owned by this user
question = answer.question
if question.user.key().id() != user.key().id():
return _json_response(success=False, msg="You must be the owner of the question to accept an answer.")
# also make sure the question is not already answered
if question.closed:
return _json_response(success=False, msg="Question already has an accepted answer.")
# change the accepted flag of the answer and save it.
answer.accepted_answer = True
answer.put()
# close the question and save it
question.closed = True
question.put()
# update the answer owner's karma points
answer.user.karma += 1
answer.user.put()
# send an email to the address assigned to the answer
answer_owner_email = answer.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=answer_owner_email,
subject="Your answer was accepted!",
body="""
This is to inform you that one of your answers has
been accepted! You have been given one karma point.
The question you answered:
%s
Your answer:
%s
Regards,
Inquire Application
""" % (question.question, answer.answer))
# return stock success JSON
return _json_response()
@validate_session()
@validate_request("GET", "question_id")
def answers(request):
"""
API Method - /answers
Returns a list of answers for a given question id.
@method GET
@param question_id: The question id to retrieve answers for
@returns list of answer objects
"""
# required parameters
question_id = int(request.GET.get("question_id"))
# retrieve the matching question
question = Question.get_by_id(question_id)
if question is None:
return _json_response(success=False,
msg="Question does not exist!")
return _json_response(answers=[a.to_json() for a in question.answer_set])
@validate_session()
@validate_request("GET", "latitude", "longitude")
def questions(request):
"""
API Method - /questions
Returns a list of questions that are within geographical proximity
to the passed in latitude/longitude.
@method GET
@param latitude: latitude of the location
@param longitude longitude of the location
@optional max_results: max number of questions to return, default=25
@optional max_distance: max distance to search in miles
@returns list of question objects
"""
# required parameters
latitude = float(request.GET.get("latitude"))
longitude = float(request.GET.get("longitude"))
# defines the center of our proximity search
# geotypes.Point provided by geomodel project
center = geotypes.Point(latitude, longitude)
# default
max_results = int(request.GET.get("max_results", 25)) # 25 results default
max_distance = int(request.GET.get("max_distance", 50)) # 50 mile default
# convert miles to kilometers
max_distance = 1000*max_distance/0.621371192
# Get all unclosed questions within the proximity max_distance and
# limit to max_results
base_query = Question.all().filter("closed =", False)
questions = Question.proximity_fetch(base_query,
center,
max_results=max_results,
max_distance=max_distance)
return _json_response(questions=[q.to_json() for q in questions])
@validate_request("POST", "email", "password")
def register(request):
"""
API Method - /register
Creates a new user and adds it to the datastore. If a user already
exists with the given email address the request fails and an
appropriate JSON response is returned.
@method POST
@param email: email address for the user
@param password: password for the user
@returns newly created user object or failure JSON
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
#
users = User.all()
users.filter("email =", email)
if users.count() != 0:
return _json_response(success=False,
msg="Email address already exists.", users=users.count())
password = _hash_password(password)
new_user = User(email=email, password=password)
new_user.put()
return _json_response()
def logout(request):
"""
API Method - /logout
Destroys the active user's session object. Any further use of
protected API methods will require a new session via the auth
API.
@method GET
@returns stock JSON response
"""
# delete session and return stock JSON response with a msg
# indicating the user has logged out
session = Session()
session.delete()
return _json_response(msg="User has been logged out.")
@validate_request("POST", "email", "password")
def auth(request):
"""
API Method - /auth
If credentials are correct a new session is created for this
user which authorizes them to use protected API methods.
@method POST
@param email: user's email address
@param password: user's password
@returns stock JSON response
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
# hash the password
password = _hash_password(password)
# Look up a User object that matches the email/password
users = User.all()
users \
.filter("email =", email) \
.filter("password =", password)
# No user found, return a failure message
if users.count() == 0:
return _json_response(success=False,
msg="Email or password is invalid.")
# Somehow more than one client with the same user/password have
# been created, which should never happen. Error out here.
if users.count() > 1:
|
# Pull the User from the datastore
user = users.get()
# Build a new session object and store the user
session = Session()
session["user"] = user
# return stock JSON with user details
return _json_response(user=user.to_json())
# Utility method for generating random questions around a
# given point. The point is currently Apple's headquarters
# so this works well with testing with the simulator.
def randomize(request):
import random
# location to generate questions around
near_lat, near_lon = 37.331693, -122.030457
# ~50 miles
dx = 50.0/69.0
# Number of questions to generate
num_questions = 10
# Possible users to assign questions to. These
# users will be looked up by the email addresses
# supply in this list and they must exist
email_accounts = ["[email protected]", "[email protected]"]
# no more editing
# look up the user objects associated with the
# given email addresses
users = []
for email in email_accounts:
user = User.all().filter("email =", email).get()
if user is not None:
users.append(user)
# return false if there were no user objects found
if not users:
return _json_response(success=False, msg="No users found")
# generate num_questions random questions around the given
# point (near_lat, near_lon) within some distance dx and
# assigning a random user to the question
for i in range(num_questions):
lat = random.uniform(near_lat-dx, near_lat+dx)
lon = random.uniform(near_lon-dx, near_lon+dx)
user = random.sample(users, 1)[0]
q = Question(user=user,
question="Question %d" % i,
location=db.GeoPt(lat, lon))
q.update_location()
q.put()
# return true
return _json_response()
| return _json_response(details=None,
success=False,
msg="Internal security error. Contact an administrator") | conditional_block |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used in conjunction with the geomodel library for doing
# proximity based searches
from google.appengine.ext.db import GeoPt
from geo import geotypes
# HttpResponse is what all Django-based views must return
# to render the output. In our web application the
# _json* methods build and return HttpResponse objects
# for rendering JSON dat
from django.http import HttpResponse
# For encoding Python objects into JSON strings
from django.utils import simplejson
# Our datastore models
from model import *
# For handling user sessions
from appengine_utilities.sessions import Session
# Provides the sha1 module we use for hashing passwords
import hashlib
# The Python loggin module. We use the basicConfig method
# to setup to log to the console (or GoogleAppEngineLauncher
# logs screen)
import logging
logging.basicConfig(level=logging.DEBUG)
##
# CONSTANTS
##
"""
The email address to send from. See the Notes section of the README
for more information on what to set this to.
"""
SENDER_EMAIL_ADDRESS = "VALID@APPENGINE_ADDRESS.COM"
##
# UTILITY METHODS
##
def _hash_password(password):
"""
Returns a sha1-hashed version of the given plaintext password.
"""
return hashlib.sha1(password).hexdigest()
def _json_response(success=True, msg="OK", **kwargs):
"""
Helper method to build an HTTPResponse with a stock
JSON object.
@param success=True: indicates success or failure of the API method
@param msg: string with details on success or failure
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# build up the response data and convert it to a string using the
# simplejson module
response_data = dict(success=success, msg=msg)
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
# All views must return a valid HttpResponse object so build it and
# set the JSON string and mimetype indicating that the result is
# JSON
return HttpResponse(response_string, mimetype="application/json")
def _json_unauthorized_response(**kwargs):
"""
Helper method to build an HTTPResponse with a stock JSON object
that represents unauthorized access to an API method.
NOTE: Always returns success=false and msg="Unauthorized"
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# Same process as _json_response method, accept always return false and
# an Unauthorized message with a status code of 401
response_data = dict(success=False, msg="Unauthorized")
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
return HttpResponse(response_string, status=401, mimetype="application/json")
##
# DECORATORS
#
# For more information about decorators in Python see:
#
# http://www.python.org/dev/peps/pep-0318/
# http://wiki.python.org/moin/PythonDecorators
# http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
# Google...
##
# Usage: @validate_request(method, p1, p2, ...)
def | (method, *params):
"""
Decorator for validating the required request method for an API call as
well as enforcing any required parameters in the request. If either the
method or parameter checks fail a stock failure JSON object is returned
with the exact issue in the msg field. If all checks pass then the
API call proceeds.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# check the required method
if request.method == method:
# check that each parameter exists and has a value
for param in params:
value = request.REQUEST.get(param, "")
if not value:
# failed parameter check
return _json_response(success=False,
msg="'%s' is required." % param)
# return the original API call through
return view_func(request, *args, **kwargs)
else:
# failed method check
return _json_response(success=False,
msg="%s requests are not allowed." % request.method)
return _view
return _dec
# Usage: @validate_session()
def validate_session():
"""
Decorator for validating that a user is authenticated by checking the
session for a user object. If this fails the stock json_unauthorized_response
is returned or else the API call is allowed to proceed.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# get the session and check for a user, fail if it doesn't exist
if Session().get("user") is None:
# failed request
return _json_unauthorized_response()
# return the original API call through
return view_func(request, *args, **kwargs)
return _view
return _dec
##
# API METHODS
##
@validate_session()
@validate_request("POST", "question", "latitude", "longitude", "pay_key")
def ask(request):
"""
API Method - /ask
Creates a new Question and adds it to the datastore
@method POST
@param question: the text of the question
@param latitude: latitude of the location
@param longitude: longitude of the location
@param pay_key: the pay key from a successful PayPal purchase
@returns stock success or failure JSON response along with
the question and user objects.
"""
# authenticated user
user = Session().get("user")
# required parameters
question = request.REQUEST.get("question")
latitude = float(request.REQUEST.get("latitude"))
longitude = float(request.REQUEST.get("longitude"))
pay_key = request.REQUEST.get("pay_key")
# Using the PayKey you could validate it using PayPal APIs
# to confirm that a user paid and the transaction is complete.
# This is left up to the curious coder to implement :)
# Create the question with the required fields and tie it
# to the authenticated user
q = Question(question=question,
location=GeoPt(latitude, longitude),
user=user)
q.update_location()
q.put()
# return stock JSON with the Question object details
return _json_response(question=q.to_json(), user=user.to_json())
@validate_session()
@validate_request("POST", "question_id", "answer")
def answer(request):
"""
API Method - /answer
Creates a new Answer object and adds it to the datastore. Validates
that the question exists and does not have an accepted answer before
accepting the answer.
This method also takes care of sending the owner of the question
an email saying a new answer has been given with the answer in the
body of the message.
@method POST
@param question_id: id of an existing question
@param answer: the text for the answer to a question
@returns one answer object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
question_id = int(request.REQUEST.get("question_id"))
answer = request.REQUEST.get("answer")
# find the question associated with the question_id parameter
question = Question.get_by_id(question_id)
# no question with the given id
if question is None:
return _json_response(success=False, msg="Question does not exist.")
# question has already been answered
if question.closed:
return _json_response(success=False, msg="Question has an accepted answer and is now closed.")
# create a new answer and save it to the datastore
a = Answer(user=user,
question=question,
answer=answer)
a.put()
# send an email to the owner of the question
question_owner_email = question.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=question_owner_email,
subject="Your question has a new answer!",
body="""
This is to inform you that one of your questions has
received a new answer.
Your question:
%s
The answer:
%s
Regards,
Inquire Application
""" % (question.question, answer))
# return stock JSON with details of the answer object
return _json_response(answer=a.to_json())
@validate_session()
@validate_request("POST", "answer_id")
def accept(request):
"""
API Method - /accept
Accepts an answer for a question. The question must be owned by the
current authenticated user accepting the question and not already
have an accepted answer.
This method also takes care of sending the owner of the answer
an email saying their answer was accepted. The accepted answer
owner will also be given one karma point.
@method POST
@param answer_id: id of the answer being accepted
@returns stock JSON object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
answer_id = int(request.REQUEST.get("answer_id"))
# find the answer associated with the answer_id
answer = Answer.get_by_id(answer_id)
# no answer with the given id
if answer is None:
return _json_response(success=False, msg="Answer does not exist.")
# associated question
question = answer.question
# make sure the question for this answer is owned by this user
question = answer.question
if question.user.key().id() != user.key().id():
return _json_response(success=False, msg="You must be the owner of the question to accept an answer.")
# also make sure the question is not already answered
if question.closed:
return _json_response(success=False, msg="Question already has an accepted answer.")
# change the accepted flag of the answer and save it.
answer.accepted_answer = True
answer.put()
# close the question and save it
question.closed = True
question.put()
# update the answer owner's karma points
answer.user.karma += 1
answer.user.put()
# send an email to the address assigned to the answer
answer_owner_email = answer.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=answer_owner_email,
subject="Your answer was accepted!",
body="""
This is to inform you that one of your answers has
been accepted! You have been given one karma point.
The question you answered:
%s
Your answer:
%s
Regards,
Inquire Application
""" % (question.question, answer.answer))
# return stock success JSON
return _json_response()
@validate_session()
@validate_request("GET", "question_id")
def answers(request):
"""
API Method - /answers
Returns a list of answers for a given question id.
@method GET
@param question_id: The question id to retrieve answers for
@returns list of answer objects
"""
# required parameters
question_id = int(request.GET.get("question_id"))
# retrieve the matching question
question = Question.get_by_id(question_id)
if question is None:
return _json_response(success=False,
msg="Question does not exist!")
return _json_response(answers=[a.to_json() for a in question.answer_set])
@validate_session()
@validate_request("GET", "latitude", "longitude")
def questions(request):
"""
API Method - /questions
Returns a list of questions that are within geographical proximity
to the passed in latitude/longitude.
@method GET
@param latitude: latitude of the location
@param longitude longitude of the location
@optional max_results: max number of questions to return, default=25
@optional max_distance: max distance to search in miles
@returns list of question objects
"""
# required parameters
latitude = float(request.GET.get("latitude"))
longitude = float(request.GET.get("longitude"))
# defines the center of our proximity search
# geotypes.Point provided by geomodel project
center = geotypes.Point(latitude, longitude)
# default
max_results = int(request.GET.get("max_results", 25)) # 25 results default
max_distance = int(request.GET.get("max_distance", 50)) # 50 mile default
# convert miles to kilometers
max_distance = 1000*max_distance/0.621371192
# Get all unclosed questions within the proximity max_distance and
# limit to max_results
base_query = Question.all().filter("closed =", False)
questions = Question.proximity_fetch(base_query,
center,
max_results=max_results,
max_distance=max_distance)
return _json_response(questions=[q.to_json() for q in questions])
@validate_request("POST", "email", "password")
def register(request):
"""
API Method - /register
Creates a new user and adds it to the datastore. If a user already
exists with the given email address the request fails and an
appropriate JSON response is returned.
@method POST
@param email: email address for the user
@param password: password for the user
@returns newly created user object or failure JSON
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
#
users = User.all()
users.filter("email =", email)
if users.count() != 0:
return _json_response(success=False,
msg="Email address already exists.", users=users.count())
password = _hash_password(password)
new_user = User(email=email, password=password)
new_user.put()
return _json_response()
def logout(request):
"""
API Method - /logout
Destroys the active user's session object. Any further use of
protected API methods will require a new session via the auth
API.
@method GET
@returns stock JSON response
"""
# delete session and return stock JSON response with a msg
# indicating the user has logged out
session = Session()
session.delete()
return _json_response(msg="User has been logged out.")
@validate_request("POST", "email", "password")
def auth(request):
"""
API Method - /auth
If credentials are correct a new session is created for this
user which authorizes them to use protected API methods.
@method POST
@param email: user's email address
@param password: user's password
@returns stock JSON response
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
# hash the password
password = _hash_password(password)
# Look up a User object that matches the email/password
users = User.all()
users \
.filter("email =", email) \
.filter("password =", password)
# No user found, return a failure message
if users.count() == 0:
return _json_response(success=False,
msg="Email or password is invalid.")
# Somehow more than one client with the same user/password have
# been created, which should never happen. Error out here.
if users.count() > 1:
return _json_response(details=None,
success=False,
msg="Internal security error. Contact an administrator")
# Pull the User from the datastore
user = users.get()
# Build a new session object and store the user
session = Session()
session["user"] = user
# return stock JSON with user details
return _json_response(user=user.to_json())
# Utility method for generating random questions around a
# given point. The point is currently Apple's headquarters
# so this works well with testing with the simulator.
def randomize(request):
import random
# location to generate questions around
near_lat, near_lon = 37.331693, -122.030457
# ~50 miles
dx = 50.0/69.0
# Number of questions to generate
num_questions = 10
# Possible users to assign questions to. These
# users will be looked up by the email addresses
# supply in this list and they must exist
email_accounts = ["[email protected]", "[email protected]"]
# no more editing
# look up the user objects associated with the
# given email addresses
users = []
for email in email_accounts:
user = User.all().filter("email =", email).get()
if user is not None:
users.append(user)
# return false if there were no user objects found
if not users:
return _json_response(success=False, msg="No users found")
# generate num_questions random questions around the given
# point (near_lat, near_lon) within some distance dx and
# assigning a random user to the question
for i in range(num_questions):
lat = random.uniform(near_lat-dx, near_lat+dx)
lon = random.uniform(near_lon-dx, near_lon+dx)
user = random.sample(users, 1)[0]
q = Question(user=user,
question="Question %d" % i,
location=db.GeoPt(lat, lon))
q.update_location()
q.put()
# return true
return _json_response()
| validate_request | identifier_name |
testText.ts | import {delay} from './delay'
import { Laya } from 'Laya';
import { Text } from 'laya/display/Text';
import { TextRender } from 'laya/webgl/text/TextRender';
export class Main {
constructor() |
/**
* 某张文字贴图的一部分被释放后,应该能正确恢复。
* 有cacheas normal的情况
*/
async test1(){
// 先创建两个文字贴图,由于字体较大,4个字就占一张图。
var t1 = new Text();
t1.fontSize = 120;
t1.text = 'abcd'; // 1是 abcd
t1.color='red';
t1.cacheAs='normal';
Laya.stage.addChild(t1);
var t2 = new Text();
t2.pos(0,120);
t2.fontSize = 120;
t2.text = 'efgh'; // 2是efgh
t2.color='red';
Laya.stage.addChild(t2);
await delay(10);
// 上面两个隐藏掉,里面的文字不再使用。
t1.visible=false;
t2.visible=false;
await delay(10);
//t3 使用第一张的3个字,第二张的1个字,如果GC的话,会导致第二张被回收,第一张的d被释放
var t3 = new Text();
t3.pos(0,240);
t3.text='abce';
t3.fontSize=120;
t3.color='red';
Laya.stage.addChild(t3);
await delay(10); //等待画出来
//t3.visible=false;
TextRender.textRenderInst.GC();
await delay(10);
t1.visible=true; // 这时候d由于被释放了,应该触发重新创建
await delay(10); // 等待渲染结果
(window as any).testEnd=true; // 告诉测试程序可以停止了
}
}
//激活启动类
new Main();
| {
Laya.init(800,600);
//Laya.stage.scaleMode = 'fixedwidth';
Laya.stage.screenMode = 'none';
//Laya.Stat.show();
this.test1();
} | identifier_body |
testText.ts | import {delay} from './delay'
import { Laya } from 'Laya';
import { Text } from 'laya/display/Text';
import { TextRender } from 'laya/webgl/text/TextRender';
export class Main {
| () {
Laya.init(800,600);
//Laya.stage.scaleMode = 'fixedwidth';
Laya.stage.screenMode = 'none';
//Laya.Stat.show();
this.test1();
}
/**
* 某张文字贴图的一部分被释放后,应该能正确恢复。
* 有cacheas normal的情况
*/
async test1(){
// 先创建两个文字贴图,由于字体较大,4个字就占一张图。
var t1 = new Text();
t1.fontSize = 120;
t1.text = 'abcd'; // 1是 abcd
t1.color='red';
t1.cacheAs='normal';
Laya.stage.addChild(t1);
var t2 = new Text();
t2.pos(0,120);
t2.fontSize = 120;
t2.text = 'efgh'; // 2是efgh
t2.color='red';
Laya.stage.addChild(t2);
await delay(10);
// 上面两个隐藏掉,里面的文字不再使用。
t1.visible=false;
t2.visible=false;
await delay(10);
//t3 使用第一张的3个字,第二张的1个字,如果GC的话,会导致第二张被回收,第一张的d被释放
var t3 = new Text();
t3.pos(0,240);
t3.text='abce';
t3.fontSize=120;
t3.color='red';
Laya.stage.addChild(t3);
await delay(10); //等待画出来
//t3.visible=false;
TextRender.textRenderInst.GC();
await delay(10);
t1.visible=true; // 这时候d由于被释放了,应该触发重新创建
await delay(10); // 等待渲染结果
(window as any).testEnd=true; // 告诉测试程序可以停止了
}
}
//激活启动类
new Main();
| constructor | identifier_name |
testText.ts | import {delay} from './delay'
import { Laya } from 'Laya';
import { Text } from 'laya/display/Text';
import { TextRender } from 'laya/webgl/text/TextRender';
export class Main { | //Laya.stage.scaleMode = 'fixedwidth';
Laya.stage.screenMode = 'none';
//Laya.Stat.show();
this.test1();
}
/**
* 某张文字贴图的一部分被释放后,应该能正确恢复。
* 有cacheas normal的情况
*/
async test1(){
// 先创建两个文字贴图,由于字体较大,4个字就占一张图。
var t1 = new Text();
t1.fontSize = 120;
t1.text = 'abcd'; // 1是 abcd
t1.color='red';
t1.cacheAs='normal';
Laya.stage.addChild(t1);
var t2 = new Text();
t2.pos(0,120);
t2.fontSize = 120;
t2.text = 'efgh'; // 2是efgh
t2.color='red';
Laya.stage.addChild(t2);
await delay(10);
// 上面两个隐藏掉,里面的文字不再使用。
t1.visible=false;
t2.visible=false;
await delay(10);
//t3 使用第一张的3个字,第二张的1个字,如果GC的话,会导致第二张被回收,第一张的d被释放
var t3 = new Text();
t3.pos(0,240);
t3.text='abce';
t3.fontSize=120;
t3.color='red';
Laya.stage.addChild(t3);
await delay(10); //等待画出来
//t3.visible=false;
TextRender.textRenderInst.GC();
await delay(10);
t1.visible=true; // 这时候d由于被释放了,应该触发重新创建
await delay(10); // 等待渲染结果
(window as any).testEnd=true; // 告诉测试程序可以停止了
}
}
//激活启动类
new Main(); | constructor() {
Laya.init(800,600); | random_line_split |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.readline().strip()
password= fi.readline().strip()
except:
print 'read user file failed, use default username, password'
user = 'atupal'
password = ''
proxy_password = ''
http_proxy = {
'http': 'http://atupal:%[email protected]:3000' % proxy_password
}
#def login():
# data = {
# 'user_id1': user,
# 'password1': password,
# 'B1': 'login',
# 'url': '/',
# }
#
# r = s.post('http://poj.org/login', data=data, allow_redirects=0)
# print r
def submit_code():
with open(sys.argv[1]) as fi:
data = {
'Action': 'submit',
'SpaceID': '1',
'JudgeID': password,
'Language': '28',
'ProblemNum': sys.argv[1].split('_')[0],
'Source': fi.read(),
}
r = s.post('http://acm.timus.ru/submit.aspx?space=1', proxies=http_proxy, data=data)
print r
def | (text, color='red'):
color_dict = {
'red': '\033[31m',
}
print color_dict[color]+text+'\033[0m',
def fetch_result():
while 1:
try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')[7:13]:
flag = 0
for td in tr('td'):
if user in td.text:
flag = 1
break
elif 'BoardHome' in td.text:
flag = 2
break
if flag == 2:
continue
for td in tr('td'):
if flag:
colorful_print(td.text)
else:
print td.text,
print
print '-' * 100
time.sleep(1)
except KeyboardInterrupt:
exit(0)
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() != 'status':
#login()
submit_code()
fetch_result()
if __name__ == '__main__':
main()
| colorful_print | identifier_name |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.readline().strip()
password= fi.readline().strip()
except:
print 'read user file failed, use default username, password'
user = 'atupal'
password = ''
proxy_password = ''
http_proxy = {
'http': 'http://atupal:%[email protected]:3000' % proxy_password
}
#def login():
# data = {
# 'user_id1': user,
# 'password1': password,
# 'B1': 'login',
# 'url': '/',
# }
#
# r = s.post('http://poj.org/login', data=data, allow_redirects=0)
# print r
def submit_code():
with open(sys.argv[1]) as fi:
data = {
'Action': 'submit',
'SpaceID': '1',
'JudgeID': password,
'Language': '28',
'ProblemNum': sys.argv[1].split('_')[0],
'Source': fi.read(),
}
r = s.post('http://acm.timus.ru/submit.aspx?space=1', proxies=http_proxy, data=data)
print r
def colorful_print(text, color='red'):
color_dict = {
'red': '\033[31m',
}
print color_dict[color]+text+'\033[0m',
def fetch_result():
|
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() != 'status':
#login()
submit_code()
fetch_result()
if __name__ == '__main__':
main()
| while 1:
try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')[7:13]:
flag = 0
for td in tr('td'):
if user in td.text:
flag = 1
break
elif 'BoardHome' in td.text:
flag = 2
break
if flag == 2:
continue
for td in tr('td'):
if flag:
colorful_print(td.text)
else:
print td.text,
print
print '-' * 100
time.sleep(1)
except KeyboardInterrupt:
exit(0) | identifier_body |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.readline().strip()
password= fi.readline().strip()
except:
print 'read user file failed, use default username, password'
user = 'atupal'
password = ''
proxy_password = ''
http_proxy = {
'http': 'http://atupal:%[email protected]:3000' % proxy_password
}
#def login():
# data = {
# 'user_id1': user,
# 'password1': password,
# 'B1': 'login',
# 'url': '/',
# }
#
# r = s.post('http://poj.org/login', data=data, allow_redirects=0)
# print r
def submit_code():
with open(sys.argv[1]) as fi:
data = {
'Action': 'submit',
'SpaceID': '1',
'JudgeID': password,
'Language': '28',
'ProblemNum': sys.argv[1].split('_')[0],
'Source': fi.read(),
}
r = s.post('http://acm.timus.ru/submit.aspx?space=1', proxies=http_proxy, data=data)
print r
def colorful_print(text, color='red'):
color_dict = {
'red': '\033[31m',
}
print color_dict[color]+text+'\033[0m',
def fetch_result():
while 1:
|
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() != 'status':
#login()
submit_code()
fetch_result()
if __name__ == '__main__':
main()
| try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')[7:13]:
flag = 0
for td in tr('td'):
if user in td.text:
flag = 1
break
elif 'BoardHome' in td.text:
flag = 2
break
if flag == 2:
continue
for td in tr('td'):
if flag:
colorful_print(td.text)
else:
print td.text,
print
print '-' * 100
time.sleep(1)
except KeyboardInterrupt:
exit(0) | conditional_block |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.readline().strip()
password= fi.readline().strip()
except:
print 'read user file failed, use default username, password'
user = 'atupal'
password = ''
proxy_password = ''
http_proxy = {
'http': 'http://atupal:%[email protected]:3000' % proxy_password
}
#def login():
# data = {
# 'user_id1': user,
# 'password1': password,
# 'B1': 'login',
# 'url': '/',
# }
#
# r = s.post('http://poj.org/login', data=data, allow_redirects=0)
# print r
def submit_code():
with open(sys.argv[1]) as fi:
data = {
'Action': 'submit',
'SpaceID': '1',
'JudgeID': password,
'Language': '28',
'ProblemNum': sys.argv[1].split('_')[0],
'Source': fi.read(),
}
r = s.post('http://acm.timus.ru/submit.aspx?space=1', proxies=http_proxy, data=data)
print r
def colorful_print(text, color='red'):
color_dict = {
'red': '\033[31m',
}
print color_dict[color]+text+'\033[0m',
def fetch_result():
while 1:
try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')[7:13]:
flag = 0
for td in tr('td'):
if user in td.text:
flag = 1
break
elif 'BoardHome' in td.text:
flag = 2
break | if flag == 2:
continue
for td in tr('td'):
if flag:
colorful_print(td.text)
else:
print td.text,
print
print '-' * 100
time.sleep(1)
except KeyboardInterrupt:
exit(0)
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() != 'status':
#login()
submit_code()
fetch_result()
if __name__ == '__main__':
main() | random_line_split |
|
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn | (input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len != len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 {
input.push('A' as u8);
} else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
}
| encryption_oracle | identifier_name |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() | {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len != len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 {
input.push('A' as u8);
} else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
} | identifier_body |
|
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len != len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 | else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
}
| {
input.push('A' as u8);
} | conditional_block |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len != len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 {
input.push('A' as u8);
} else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
} | let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
} |
let out = encryption_oracle(&input, &unknown, &key);
| random_line_split |
general_tests.rs |
#[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Team(u8);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SomeFeature;
components! {
TestComponents {
#[hot] blank_data: (),
#[hot] position: Position,
#[cold] team: Team,
#[hot] feature: SomeFeature
}
}
systems! {
TestSystems<TestComponents, ()> {
hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
)
)
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn process(&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut DataHelper<TestComponents, ()>)
{
for e in en
{
println!("{:?}", co.position.borrow(&e));
}
}
}
impl System for PrintPosition {
type Components = TestComponents;
type Services = ();
fn is_active(&self) -> bool { false }
}
#[test]
fn test_general_1()
| {
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.6, y: 0.8 });
c.team.add(&e, Team(3));
c.feature.add(&e, SomeFeature);
});
// Test passive systems
world.systems.print_position.process(&mut world.data);
// Test entity modifiers
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Some(Position { x: 0.5, y: 0.7 }), c.position.insert(&e, Position { x: -2.5, y: 7.6 }));
assert_eq!(Some(Team(4)), c.team.remove(&e));
assert!(!c.feature.has(&e));
assert!(c.feature.insert(&e, SomeFeature).is_none());
});
process!(world, print_position);
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Position { x: -2.5, y: 7.6 }, c.position[e]);
assert_eq!(None, c.team.remove(&e));
assert!(c.feature.insert(&e, SomeFeature).is_some());
});
// Test external entity iterator
for e in world.entities()
{
assert!(world.position.has(&e));
}
// Test external entity iterator with aspect filtering
for e in world.entities().filter(aspect!(<TestComponents> all: [team]), &world)
{
assert!(world.team.has(&e));
}
// Test active systems
world.update();
// Test system modification
world.systems.hello_world.0 = "Goodbye, World!";
world.update();
} | identifier_body |
|
general_tests.rs | #[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Team(u8);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SomeFeature;
components! {
TestComponents {
#[hot] blank_data: (),
#[hot] position: Position,
#[cold] team: Team,
#[hot] feature: SomeFeature
}
}
systems! {
TestSystems<TestComponents, ()> { | )
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn process(&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut DataHelper<TestComponents, ()>)
{
for e in en
{
println!("{:?}", co.position.borrow(&e));
}
}
}
impl System for PrintPosition {
type Components = TestComponents;
type Services = ();
fn is_active(&self) -> bool { false }
}
#[test]
fn test_general_1()
{
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.6, y: 0.8 });
c.team.add(&e, Team(3));
c.feature.add(&e, SomeFeature);
});
// Test passive systems
world.systems.print_position.process(&mut world.data);
// Test entity modifiers
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Some(Position { x: 0.5, y: 0.7 }), c.position.insert(&e, Position { x: -2.5, y: 7.6 }));
assert_eq!(Some(Team(4)), c.team.remove(&e));
assert!(!c.feature.has(&e));
assert!(c.feature.insert(&e, SomeFeature).is_none());
});
process!(world, print_position);
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Position { x: -2.5, y: 7.6 }, c.position[e]);
assert_eq!(None, c.team.remove(&e));
assert!(c.feature.insert(&e, SomeFeature).is_some());
});
// Test external entity iterator
for e in world.entities()
{
assert!(world.position.has(&e));
}
// Test external entity iterator with aspect filtering
for e in world.entities().filter(aspect!(<TestComponents> all: [team]), &world)
{
assert!(world.team.has(&e));
}
// Test active systems
world.update();
// Test system modification
world.systems.hello_world.0 = "Goodbye, World!";
world.update();
} | hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
) | random_line_split |
general_tests.rs |
#[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Team(u8);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SomeFeature;
components! {
TestComponents {
#[hot] blank_data: (),
#[hot] position: Position,
#[cold] team: Team,
#[hot] feature: SomeFeature
}
}
systems! {
TestSystems<TestComponents, ()> {
hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
)
)
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn | (&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut DataHelper<TestComponents, ()>)
{
for e in en
{
println!("{:?}", co.position.borrow(&e));
}
}
}
impl System for PrintPosition {
type Components = TestComponents;
type Services = ();
fn is_active(&self) -> bool { false }
}
#[test]
fn test_general_1()
{
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.6, y: 0.8 });
c.team.add(&e, Team(3));
c.feature.add(&e, SomeFeature);
});
// Test passive systems
world.systems.print_position.process(&mut world.data);
// Test entity modifiers
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Some(Position { x: 0.5, y: 0.7 }), c.position.insert(&e, Position { x: -2.5, y: 7.6 }));
assert_eq!(Some(Team(4)), c.team.remove(&e));
assert!(!c.feature.has(&e));
assert!(c.feature.insert(&e, SomeFeature).is_none());
});
process!(world, print_position);
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Position { x: -2.5, y: 7.6 }, c.position[e]);
assert_eq!(None, c.team.remove(&e));
assert!(c.feature.insert(&e, SomeFeature).is_some());
});
// Test external entity iterator
for e in world.entities()
{
assert!(world.position.has(&e));
}
// Test external entity iterator with aspect filtering
for e in world.entities().filter(aspect!(<TestComponents> all: [team]), &world)
{
assert!(world.team.has(&e));
}
// Test active systems
world.update();
// Test system modification
world.systems.hello_world.0 = "Goodbye, World!";
world.update();
}
| process | identifier_name |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive shadowcasting algorithm
* Currently only supports 4/8 topologies, not hexagonal.
* Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting
* @augments ROT.FOV
*/
export default class RecursiveShadowcasting extends FOV {
/**
* Compute visibility for a 360-degree circle
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
compute(x: number, y: number, R: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
for(let i = 0; i < OCTANTS.length; i++) {
this._renderOctant(x, y, OCTANTS[i], R, callback);
}
}
/**
* Compute visibility for a 180-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute180(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees
let nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees
let nextOctant = (dir+ 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees
this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[nextOctant], R, callback);
};
/**
* Compute visibility for a 90-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute90(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
}
/**
* Render one octant (45-degree arc) of the viewshed
* @param {int} x
* @param {int} y
* @param {int} octant Octant to be rendered
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
_renderOctant(x: number, y: number, octant: number[], R: number, callback: VisibilityCallback) {
//Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses
this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback);
}
/**
* Actually calculates the visibility
* @param {int} startX The starting X coordinate
* @param {int} startY The starting Y coordinate
* @param {int} row The row to render
* @param {float} visSlopeStart The slope to start at
* @param {float} visSlopeEnd The slope to end at
* @param {int} radius The radius to reach out to
* @param {int} xx
* @param {int} xy
* @param {int} yx
* @param {int} yy
* @param {function} callback The callback to use when we hit a block that is visible
*/
_castVisibility(startX: number, startY: number, row: number, visSlopeStart: number, visSlopeEnd: number, radius: number, xx: number, xy: number, yx: number, yy: number, callback: VisibilityCallback) {
| if (visSlopeStart < visSlopeEnd) { return; }
for (let i = row; i <= radius; i++) {
let dx = -i - 1;
let dy = -i;
let blocked = false;
let newStart = 0;
//'Row' could be column, names here assume octant 0 and would be flipped for half the octants
while (dx <= 0) {
dx += 1;
//Translate from relative coordinates to map coordinates
let mapX = startX + dx * xx + dy * xy;
let mapY = startY + dx * yx + dy * yy;
//Range of the row
let slopeStart = (dx - 0.5) / (dy + 0.5);
let slopeEnd = (dx + 0.5) / (dy - 0.5);
//Ignore if not yet at left edge of Octant
if (slopeEnd > visSlopeStart) { continue; }
//Done if past right edge
if (slopeStart < visSlopeEnd) { break; }
//If it's in range, it's visible
if ((dx * dx + dy * dy) < (radius * radius)) {
callback(mapX, mapY, i, 1);
}
if (!blocked) {
//If tile is a blocking tile, cast around it
if (!this._lightPasses(mapX, mapY) && i < radius) {
blocked = true;
this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback);
newStart = slopeEnd;
}
} else {
//Keep narrowing if scanning across a block
if (!this._lightPasses(mapX, mapY)) {
newStart = slopeEnd;
continue;
}
//Block has ended
blocked = false;
visSlopeStart = newStart;
}
}
if (blocked) { break; }
}
}
} | identifier_body |
|
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive shadowcasting algorithm
* Currently only supports 4/8 topologies, not hexagonal.
* Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting
* @augments ROT.FOV
*/
export default class RecursiveShadowcasting extends FOV {
/**
* Compute visibility for a 360-degree circle
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
compute(x: number, y: number, R: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
for(let i = 0; i < OCTANTS.length; i++) {
this._renderOctant(x, y, OCTANTS[i], R, callback);
}
}
/**
* Compute visibility for a 180-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute180(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees
let nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees
let nextOctant = (dir+ 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees
this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[nextOctant], R, callback);
};
/**
* Compute visibility for a 90-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute90(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
}
/**
* Render one octant (45-degree arc) of the viewshed
* @param {int} x
* @param {int} y
* @param {int} octant Octant to be rendered
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
_renderOctant(x: number, y: number, octant: number[], R: number, callback: VisibilityCallback) {
//Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses
this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback);
}
/**
* Actually calculates the visibility
* @param {int} startX The starting X coordinate
* @param {int} startY The starting Y coordinate
* @param {int} row The row to render
* @param {float} visSlopeStart The slope to start at
* @param {float} visSlopeEnd The slope to end at
* @param {int} radius The radius to reach out to
* @param {int} xx
* @param {int} xy
* @param {int} yx
* @param {int} yy
* @param {function} callback The callback to use when we hit a block that is visible
*/
_castVisibility(startX: number, startY: number, row: number, visSlopeStart: number, visSlopeEnd: number, radius: number, xx: number, xy: number, yx: number, yy: number, callback: VisibilityCallback) {
if (visSlopeStart < visSlopeEnd) { return; }
for (let i = row; i <= radius; i++) {
let dx = -i - 1;
let dy = -i;
let blocked = false;
let newStart = 0;
//'Row' could be column, names here assume octant 0 and would be flipped for half the octants
while (dx <= 0) {
dx += 1;
//Translate from relative coordinates to map coordinates
let mapX = startX + dx * xx + dy * xy;
let mapY = startY + dx * yx + dy * yy;
//Range of the row
let slopeStart = (dx - 0.5) / (dy + 0.5);
let slopeEnd = (dx + 0.5) / (dy - 0.5);
//Ignore if not yet at left edge of Octant
if (slopeEnd > visSlopeStart) { continue; }
//Done if past right edge
if (slopeStart < visSlopeEnd) { break; }
//If it's in range, it's visible
if ((dx * dx + dy * dy) < (radius * radius)) {
callback(mapX, mapY, i, 1);
}
if (!blocked) {
//If tile is a blocking tile, cast around it
if (!this._lightPasses(mapX, mapY) && i < radius) {
blocked = true;
this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback);
newStart = slopeEnd;
}
} else {
//Keep narrowing if scanning across a block
if (!this._lightPasses(mapX, mapY)) {
|
//Block has ended
blocked = false;
visSlopeStart = newStart;
}
}
if (blocked) { break; }
}
}
}
| newStart = slopeEnd;
continue;
}
| conditional_block |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive shadowcasting algorithm
* Currently only supports 4/8 topologies, not hexagonal.
* Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting
* @augments ROT.FOV
*/
export default class RecursiveShadowcasting extends FOV {
/**
* Compute visibility for a 360-degree circle
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
compute(x: number, y: number, R: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
for(let i = 0; i < OCTANTS.length; i++) {
this._renderOctant(x, y, OCTANTS[i], R, callback);
}
}
/**
* Compute visibility for a 180-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute180(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees
let nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees
let nextOctant = (dir+ 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees
this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[nextOctant], R, callback);
};
/**
* Compute visibility for a 90-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
co | : number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
}
/**
* Render one octant (45-degree arc) of the viewshed
* @param {int} x
* @param {int} y
* @param {int} octant Octant to be rendered
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
_renderOctant(x: number, y: number, octant: number[], R: number, callback: VisibilityCallback) {
//Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses
this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback);
}
/**
* Actually calculates the visibility
* @param {int} startX The starting X coordinate
* @param {int} startY The starting Y coordinate
* @param {int} row The row to render
* @param {float} visSlopeStart The slope to start at
* @param {float} visSlopeEnd The slope to end at
* @param {int} radius The radius to reach out to
* @param {int} xx
* @param {int} xy
* @param {int} yx
* @param {int} yy
* @param {function} callback The callback to use when we hit a block that is visible
*/
_castVisibility(startX: number, startY: number, row: number, visSlopeStart: number, visSlopeEnd: number, radius: number, xx: number, xy: number, yx: number, yy: number, callback: VisibilityCallback) {
if (visSlopeStart < visSlopeEnd) { return; }
for (let i = row; i <= radius; i++) {
let dx = -i - 1;
let dy = -i;
let blocked = false;
let newStart = 0;
//'Row' could be column, names here assume octant 0 and would be flipped for half the octants
while (dx <= 0) {
dx += 1;
//Translate from relative coordinates to map coordinates
let mapX = startX + dx * xx + dy * xy;
let mapY = startY + dx * yx + dy * yy;
//Range of the row
let slopeStart = (dx - 0.5) / (dy + 0.5);
let slopeEnd = (dx + 0.5) / (dy - 0.5);
//Ignore if not yet at left edge of Octant
if (slopeEnd > visSlopeStart) { continue; }
//Done if past right edge
if (slopeStart < visSlopeEnd) { break; }
//If it's in range, it's visible
if ((dx * dx + dy * dy) < (radius * radius)) {
callback(mapX, mapY, i, 1);
}
if (!blocked) {
//If tile is a blocking tile, cast around it
if (!this._lightPasses(mapX, mapY) && i < radius) {
blocked = true;
this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback);
newStart = slopeEnd;
}
} else {
//Keep narrowing if scanning across a block
if (!this._lightPasses(mapX, mapY)) {
newStart = slopeEnd;
continue;
}
//Block has ended
blocked = false;
visSlopeStart = newStart;
}
}
if (blocked) { break; }
}
}
}
| mpute90(x | identifier_name |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive shadowcasting algorithm
* Currently only supports 4/8 topologies, not hexagonal.
* Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting
* @augments ROT.FOV
*/
export default class RecursiveShadowcasting extends FOV {
/**
* Compute visibility for a 360-degree circle
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
compute(x: number, y: number, R: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
for(let i = 0; i < OCTANTS.length; i++) {
this._renderOctant(x, y, OCTANTS[i], R, callback);
}
}
/**
* Compute visibility for a 180-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute180(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees
let nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees
let nextOctant = (dir+ 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees
this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback);
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[nextOctant], R, callback);
};
/**
* Compute visibility for a 90-degree arc
* @param {int} x
* @param {int} y
* @param {int} R Maximum visibility radius
* @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
* @param {function} callback
*/
compute90(x: number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); | * Render one octant (45-degree arc) of the viewshed
* @param {int} x
* @param {int} y
* @param {int} octant Octant to be rendered
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
_renderOctant(x: number, y: number, octant: number[], R: number, callback: VisibilityCallback) {
//Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses
this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback);
}
/**
* Actually calculates the visibility
* @param {int} startX The starting X coordinate
* @param {int} startY The starting Y coordinate
* @param {int} row The row to render
* @param {float} visSlopeStart The slope to start at
* @param {float} visSlopeEnd The slope to end at
* @param {int} radius The radius to reach out to
* @param {int} xx
* @param {int} xy
* @param {int} yx
* @param {int} yy
* @param {function} callback The callback to use when we hit a block that is visible
*/
_castVisibility(startX: number, startY: number, row: number, visSlopeStart: number, visSlopeEnd: number, radius: number, xx: number, xy: number, yx: number, yy: number, callback: VisibilityCallback) {
if (visSlopeStart < visSlopeEnd) { return; }
for (let i = row; i <= radius; i++) {
let dx = -i - 1;
let dy = -i;
let blocked = false;
let newStart = 0;
//'Row' could be column, names here assume octant 0 and would be flipped for half the octants
while (dx <= 0) {
dx += 1;
//Translate from relative coordinates to map coordinates
let mapX = startX + dx * xx + dy * xy;
let mapY = startY + dx * yx + dy * yy;
//Range of the row
let slopeStart = (dx - 0.5) / (dy + 0.5);
let slopeEnd = (dx + 0.5) / (dy - 0.5);
//Ignore if not yet at left edge of Octant
if (slopeEnd > visSlopeStart) { continue; }
//Done if past right edge
if (slopeStart < visSlopeEnd) { break; }
//If it's in range, it's visible
if ((dx * dx + dy * dy) < (radius * radius)) {
callback(mapX, mapY, i, 1);
}
if (!blocked) {
//If tile is a blocking tile, cast around it
if (!this._lightPasses(mapX, mapY) && i < radius) {
blocked = true;
this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback);
newStart = slopeEnd;
}
} else {
//Keep narrowing if scanning across a block
if (!this._lightPasses(mapX, mapY)) {
newStart = slopeEnd;
continue;
}
//Block has ended
blocked = false;
visSlopeStart = newStart;
}
}
if (blocked) { break; }
}
}
} | }
/** | random_line_split |
htmltabledatacellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableDataCellElementDerived for EventTarget {
fn is_htmltabledatacellelement(&self) -> bool |
}
impl HTMLTableDataCellElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
document),
document,
HTMLTableDataCellElementBinding::Wrap)
}
}
| {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementTypeId::HTMLTableDataCellElement))))
} | identifier_body |
htmltabledatacellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableDataCellElementDerived for EventTarget {
fn is_htmltabledatacellelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementTypeId::HTMLTableDataCellElement))))
}
}
impl HTMLTableDataCellElement { | }
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
document),
document,
HTMLTableDataCellElementBinding::Wrap)
}
} | fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
localName, prefix, document)
} | random_line_split |
htmltabledatacellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableDataCellElementDerived for EventTarget {
fn is_htmltabledatacellelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementTypeId::HTMLTableDataCellElement))))
}
}
impl HTMLTableDataCellElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
document),
document,
HTMLTableDataCellElementBinding::Wrap)
}
}
| new | identifier_name |
constants.py | SEFARIA_API_NODE = "https://www.sefaria.org/api/texts/"
CACHE_MONITOR_LOOP_DELAY_IN_SECONDS = 86400
CACHE_LIFETIME_SECONDS = 604800
category_colors = {
"Commentary": "#4871bf",
"Tanakh": "#004e5f",
"Midrash": "#5d956f",
"Mishnah": "#5a99b7",
"Talmud": "#ccb479",
"Halakhah": "#802f3e",
"Kabbalah": "#594176",
"Philosophy": "#7f85a9",
"Liturgy": "#ab4e66",
"Tanaitic": "#00827f",
"Parshanut": "#9ab8cb", | "Responsa": "#cb6158",
"Apocrypha": "#c7a7b4",
"Other": "#073570",
"Quoting Commentary": "#cb6158",
"Sheets": "#7c406f",
"Community": "#7c406f",
"Targum": "#7f85a9",
"Modern Works": "#7c406f",
"Modern Commentary": "#7c406f",
}
platform_settings = {
"twitter": {
"font_size": 29,
"additional_line_spacing_he": 5,
"additional_line_spacing_en": -10,
"image_width": 506,
"image_height": 253,
"margin": 20,
"category_color_line_width": 7,
"sefaria_branding": False,
"branding_height": 0
},
"facebook": {
"font_size": 70,
"additional_line_spacing_he": 12,
"additional_line_spacing_en": -20,
"image_width": 1200,
"image_height": 630,
"margin": 40,
"category_color_line_width": 15,
"sefaria_branding": False,
"branding_height": 0
},
"instagram": {
"font_size": 70,
"additional_line_spacing_he": 12,
"additional_line_spacing_en": 0,
"image_width": 1040,
"image_height": 1040,
"margin": 40,
"category_color_line_width": 13,
"sefaria_branding": True,
"branding_height": 100
}
} | "Chasidut": "#97b386",
"Musar": "#7c406f", | random_line_split |
main.ts | import { ComponentDoc, Documentation } from './Documentation'
import { DocGenOptions, parseFile, ParseOptions, parseSource as parseSourceLocal } from './parse'
export { ScriptHandler, TemplateHandler } from './parse'
export { ComponentDoc, DocGenOptions, ParseOptions, Documentation }
export function parse(
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
return parsePrimitive((doc, options) => parseFile(doc, options), filePath, opts)
}
export function parseSource(
source: string,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
return parsePrimitive((doc, options) => parseSourceLocal(doc, source, options), filePath, opts)
}
function isOptionsObject(opts: any): opts is DocGenOptions {
return !!opts && !!opts.alias
}
function parsePrimitive(
createDoc: (doc: Documentation, opts: ParseOptions) => void,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc | {
const doc = new Documentation()
const options: ParseOptions = isOptionsObject(opts)
? { ...opts, filePath }
: { filePath, alias: opts }
createDoc(doc, options)
return doc.toObject()
} | identifier_body |
|
main.ts | import { ComponentDoc, Documentation } from './Documentation'
import { DocGenOptions, parseFile, ParseOptions, parseSource as parseSourceLocal } from './parse'
export { ScriptHandler, TemplateHandler } from './parse'
export { ComponentDoc, DocGenOptions, ParseOptions, Documentation }
export function parse(
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
return parsePrimitive((doc, options) => parseFile(doc, options), filePath, opts)
}
export function parseSource(
source: string,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
return parsePrimitive((doc, options) => parseSourceLocal(doc, source, options), filePath, opts)
}
function | (opts: any): opts is DocGenOptions {
return !!opts && !!opts.alias
}
function parsePrimitive(
createDoc: (doc: Documentation, opts: ParseOptions) => void,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
const doc = new Documentation()
const options: ParseOptions = isOptionsObject(opts)
? { ...opts, filePath }
: { filePath, alias: opts }
createDoc(doc, options)
return doc.toObject()
}
| isOptionsObject | identifier_name |
main.ts | import { ComponentDoc, Documentation } from './Documentation'
import { DocGenOptions, parseFile, ParseOptions, parseSource as parseSourceLocal } from './parse'
export { ScriptHandler, TemplateHandler } from './parse'
export { ComponentDoc, DocGenOptions, ParseOptions, Documentation }
export function parse(
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
return parsePrimitive((doc, options) => parseFile(doc, options), filePath, opts)
}
export function parseSource(
source: string,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
return parsePrimitive((doc, options) => parseSourceLocal(doc, source, options), filePath, opts)
}
| function isOptionsObject(opts: any): opts is DocGenOptions {
return !!opts && !!opts.alias
}
function parsePrimitive(
createDoc: (doc: Documentation, opts: ParseOptions) => void,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
const doc = new Documentation()
const options: ParseOptions = isOptionsObject(opts)
? { ...opts, filePath }
: { filePath, alias: opts }
createDoc(doc, options)
return doc.toObject()
} | random_line_split |
|
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn execute() -> String { | let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
} | random_line_split |
|
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn | () -> String {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
}
| execute | identifier_name |
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn execute() -> String | {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
} | identifier_body |
|
import.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | //~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn bar() { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() {
zed::foo(); //~ ERROR `foo` is private
bar();
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432] | random_line_split |
import.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432]
//~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn bar() { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() | {
zed::foo(); //~ ERROR `foo` is private
bar();
} | identifier_body |
|
import.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432]
//~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn | () { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() {
zed::foo(); //~ ERROR `foo` is private
bar();
}
| bar | identifier_name |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
} | use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status != gl::FRAMEBUFFER_COMPLETE {
panic!("Error while creating the framebuffer");
}
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
} | random_line_split |
|
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn | () {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status != gl::FRAMEBUFFER_COMPLETE {
panic!("Error while creating the framebuffer");
}
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
}
| test_headless | identifier_name |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() | {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status != gl::FRAMEBUFFER_COMPLETE {
panic!("Error while creating the framebuffer");
}
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
} | identifier_body |
|
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status != gl::FRAMEBUFFER_COMPLETE |
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
}
| {
panic!("Error while creating the framebuffer");
} | conditional_block |
ConfigVariable-extensions.py |
def __str__(self):
return self.getStringValue()
def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self):
|
def __int__(self):
return int(self.getValue())
def __long__(self):
return long(self.getValue())
def __float__(self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValue())
def __oct__(self):
return oct(self.getValue())
def __hex__(self):
return hex(self.getValue())
def __cmp__(self, other):
return self.getValue().__cmp__(other)
def __neg__(self):
return -self.getValue()
def __coerce__(self, other):
return (self.getValue(), other)
def __len__(self):
return self.getNumWords()
def __getitem__(self, n):
if n < 0 or n >= self.getNumWords():
raise IndexError
return self.getWord(n)
def __setitem__(self, n, value):
if n < 0 or n > self.getNumWords():
raise IndexError
self.setWord(n, value)
| from pandac.Notify import Notify
self.write(Notify.out()) | identifier_body |
ConfigVariable-extensions.py |
def __str__(self):
return self.getStringValue()
def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self):
from pandac.Notify import Notify
self.write(Notify.out())
def __int__(self):
return int(self.getValue())
def __long__(self):
return long(self.getValue())
def __float__(self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValue())
def __oct__(self):
return oct(self.getValue())
def __hex__(self):
return hex(self.getValue())
def __cmp__(self, other):
return self.getValue().__cmp__(other)
def __neg__(self):
return -self.getValue()
def __coerce__(self, other):
return (self.getValue(), other)
def __len__(self):
return self.getNumWords()
def __getitem__(self, n):
if n < 0 or n >= self.getNumWords():
|
return self.getWord(n)
def __setitem__(self, n, value):
if n < 0 or n > self.getNumWords():
raise IndexError
self.setWord(n, value)
| raise IndexError | conditional_block |
ConfigVariable-extensions.py | def __str__(self):
return self.getStringValue()
| from pandac.Notify import Notify
self.write(Notify.out())
def __int__(self):
return int(self.getValue())
def __long__(self):
return long(self.getValue())
def __float__(self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValue())
def __oct__(self):
return oct(self.getValue())
def __hex__(self):
return hex(self.getValue())
def __cmp__(self, other):
return self.getValue().__cmp__(other)
def __neg__(self):
return -self.getValue()
def __coerce__(self, other):
return (self.getValue(), other)
def __len__(self):
return self.getNumWords()
def __getitem__(self, n):
if n < 0 or n >= self.getNumWords():
raise IndexError
return self.getWord(n)
def __setitem__(self, n, value):
if n < 0 or n > self.getNumWords():
raise IndexError
self.setWord(n, value) | def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self): | random_line_split |
ConfigVariable-extensions.py |
def __str__(self):
return self.getStringValue()
def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self):
from pandac.Notify import Notify
self.write(Notify.out())
def __int__(self):
return int(self.getValue())
def __long__(self):
return long(self.getValue())
def | (self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValue())
def __oct__(self):
return oct(self.getValue())
def __hex__(self):
return hex(self.getValue())
def __cmp__(self, other):
return self.getValue().__cmp__(other)
def __neg__(self):
return -self.getValue()
def __coerce__(self, other):
return (self.getValue(), other)
def __len__(self):
return self.getNumWords()
def __getitem__(self, n):
if n < 0 or n >= self.getNumWords():
raise IndexError
return self.getWord(n)
def __setitem__(self, n, value):
if n < 0 or n > self.getNumWords():
raise IndexError
self.setWord(n, value)
| __float__ | identifier_name |
forms.py | #
# Copyright (C) 2014 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details. You should have received a copy of the GNU General Public
# License along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Forms for PortAdmin"""
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, Submit
class | (forms.Form):
"""Form for searching for ip-devices and interfaces"""
query = forms.CharField(
label='',
widget=forms.TextInput(
attrs={'placeholder': 'Search for ip device or interface'}))
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = 'portadmin-index'
self.helper.form_method = 'GET'
self.helper.layout = Layout(
Row(
Column('query', css_class='medium-9'),
Column(Submit('submit', 'Search', css_class='postfix'),
css_class='medium-3'),
css_class='collapse'
)
)
| SearchForm | identifier_name |
forms.py | #
# Copyright (C) 2014 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details. You should have received a copy of the GNU General Public
# License along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Forms for PortAdmin"""
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, Submit
class SearchForm(forms.Form):
| """Form for searching for ip-devices and interfaces"""
query = forms.CharField(
label='',
widget=forms.TextInput(
attrs={'placeholder': 'Search for ip device or interface'}))
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = 'portadmin-index'
self.helper.form_method = 'GET'
self.helper.layout = Layout(
Row(
Column('query', css_class='medium-9'),
Column(Submit('submit', 'Search', css_class='postfix'),
css_class='medium-3'),
css_class='collapse'
)
) | identifier_body |
|
forms.py | #
# Copyright (C) 2014 Uninett AS
# | # NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details. You should have received a copy of the GNU General Public
# License along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Forms for PortAdmin"""
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, Submit
class SearchForm(forms.Form):
"""Form for searching for ip-devices and interfaces"""
query = forms.CharField(
label='',
widget=forms.TextInput(
attrs={'placeholder': 'Search for ip device or interface'}))
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = 'portadmin-index'
self.helper.form_method = 'GET'
self.helper.layout = Layout(
Row(
Column('query', css_class='medium-9'),
Column(Submit('submit', 'Search', css_class='postfix'),
css_class='medium-3'),
css_class='collapse'
)
) | # This file is part of Network Administration Visualized (NAV).
# | random_line_split |
test_mnistplus.py | """
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_if_no_data
import numpy as np
def test_MNISTPlus():
| """
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, test sets.
Tests that a topological batch has 4 dimensions.
Tests that it work well with selected type of augmentation.
"""
skip_if_no_data()
for subset in ['train', 'valid', 'test']:
ids = MNISTPlus(which_set=subset)
assert 0.01 >= ids.X.min() >= 0.0
assert 0.99 <= ids.X.max() <= 1.0
topo = ids.get_batch_topo(1)
assert topo.ndim == 4
del ids
train_y = MNISTPlus(which_set='train', label_type='label')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='azimuth')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert 0.0 <= train_y.y.max() <= 1.0
assert 0.0 <= train_y.y.min() <= 1.0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='rotation')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='texture_id')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1) | identifier_body |
|
test_mnistplus.py | """
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_if_no_data
import numpy as np
def test_MNISTPlus():
"""
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, test sets.
Tests that a topological batch has 4 dimensions.
Tests that it work well with selected type of augmentation.
"""
skip_if_no_data()
for subset in ['train', 'valid', 'test']:
|
train_y = MNISTPlus(which_set='train', label_type='label')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='azimuth')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert 0.0 <= train_y.y.max() <= 1.0
assert 0.0 <= train_y.y.min() <= 1.0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='rotation')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='texture_id')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
| ids = MNISTPlus(which_set=subset)
assert 0.01 >= ids.X.min() >= 0.0
assert 0.99 <= ids.X.max() <= 1.0
topo = ids.get_batch_topo(1)
assert topo.ndim == 4
del ids | conditional_block |
test_mnistplus.py | """ | views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_if_no_data
import numpy as np
def test_MNISTPlus():
"""
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, test sets.
Tests that a topological batch has 4 dimensions.
Tests that it work well with selected type of augmentation.
"""
skip_if_no_data()
for subset in ['train', 'valid', 'test']:
ids = MNISTPlus(which_set=subset)
assert 0.01 >= ids.X.min() >= 0.0
assert 0.99 <= ids.X.max() <= 1.0
topo = ids.get_batch_topo(1)
assert topo.ndim == 4
del ids
train_y = MNISTPlus(which_set='train', label_type='label')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='azimuth')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert 0.0 <= train_y.y.max() <= 1.0
assert 0.0 <= train_y.y.min() <= 1.0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='rotation')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='texture_id')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1) | This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological | random_line_split |
test_mnistplus.py | """
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_if_no_data
import numpy as np
def | ():
"""
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, test sets.
Tests that a topological batch has 4 dimensions.
Tests that it work well with selected type of augmentation.
"""
skip_if_no_data()
for subset in ['train', 'valid', 'test']:
ids = MNISTPlus(which_set=subset)
assert 0.01 >= ids.X.min() >= 0.0
assert 0.99 <= ids.X.max() <= 1.0
topo = ids.get_batch_topo(1)
assert topo.ndim == 4
del ids
train_y = MNISTPlus(which_set='train', label_type='label')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='azimuth')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert 0.0 <= train_y.y.max() <= 1.0
assert 0.0 <= train_y.y.min() <= 1.0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='rotation')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_type='texture_id')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
| test_MNISTPlus | identifier_name |
when.ts | import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { ArrayObserver, splice } from 'observe-js';
import { ChangeNotification, Model, TypedChangeNotification } from './model';
import * as isFunction from 'lodash.isfunction';
import * as isObject from 'lodash.isobject';
import * as isEqual from 'lodash.isequal';
import * as LRU from 'lru-cache';
import { Updatable } from './updatable';
const proxyCache = LRU(64);
import './standard-operators';
const identifier = /^[$A-Z_][0-9A-Z_$]*$/i;
export function whenPropertyInternal(target: any, valueOnly: boolean, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
if (propsAndSelector.length < 1) {
throw new Error('Must specify at least one property!');
}
if (propsAndSelector.length === 1) {
let ret = observableForPropertyChain(target, propsAndSelector[0] as string);
return valueOnly ? ret.map(x => x.value) : ret;
}
let [selector] = propsAndSelector.splice(-1, 1);
if (!(selector instanceof Function)) {
throw new Error('In multi-item properties, the last function must be a selector');
}
let propsOnly = propsAndSelector as Array<string|string[]>;
let propWatchers = propsOnly.map((p) =>
valueOnly ?
observableForPropertyChain(target, p).map(x => x.value) :
observableForPropertyChain(target, p));
return Observable.combineLatest(...propWatchers, selector).distinctUntilChanged((x, y) => isEqual(x, y));
}
export type ArrayChange<T> = { value: T[], splices: splice[] };
export function whenArray<TSource, TProp>(
target: TSource,
prop: (t: TSource) => TProp[]): Observable<ArrayChange<TProp>> {
return when(target, prop).switchMap(x => observeArray(x).startWith({ value: x ? Array.from(x) : x, splices: []}));
}
export function observeArray<T>(arr: T[]): Observable<ArrayChange<T>> {
if (!arr || !Array.isArray(arr)) return Observable.empty();
return Observable.create((subj) => {
let ao: ArrayObserver;
try {
ao = new ArrayObserver(arr);
ao.open((s) => {
subj.next({value: Array.from(arr), splices: s});
});
} catch (e) {
subj.error(e);
}
return new Subscription(() => ao.close());
});
}
export function observableForPropertyChain(target: any, chain: (Array<string> | string | Function), before = false): Observable<ChangeNotification> {
let props: Array<string>;
if (Array.isArray(chain)) {
props = chain;
} else if (isFunction(chain)) {
props = functionToPropertyChain(chain as Function);
} else {
props = (chain as string).split('.');
if (props.find((x) => x.match(identifier) === null)) {
throw new Error("property name must be of the form 'foo.bar.baz'");
}
}
let firstProp = props[0];
let start = notificationForProperty(target, firstProp, before);
if (isObject(target) && firstProp in target) {
let val = target[firstProp];
if (isObject(val) && (val instanceof Updatable)) {
val = val.value;
}
start = start.startWith({ sender: target, property: firstProp, value: val });
}
if (props.length === 1) {
return start.distinctUntilChanged((x, y) => isEqual(x.value, y.value));
}
return start // target.foo
.map((x) => {
return observableForPropertyChain(x.value, props.slice(1), before)
.map((y) => {
// This is for target.foo.bar.baz, its sender will be
// target.foo, and its property will be bar.baz
return { sender: target, property: `${firstProp}.${y.property}`, value: y.value };
});
})
.switch()
.distinctUntilChanged((x, y) => isEqual(x.value, y.value));
}
export function notificationForProperty(target: any, prop: string, before = false): Observable<ChangeNotification> {
if (!(target instanceof Model)) {
return Observable.never();
}
if (!(prop in target)) {
return Observable.never();
}
if (target[prop] instanceof Updatable) {
return (before ? target.changing : target.changed)
.startWith({sender: target, property: prop, value: target[prop]})
.filter(({property}) => prop === property)
.switchMap(cn => {
let obs: Observable<any> = cn.value;
return obs.skip(1)
.map((value) => ({ sender: cn.sender, property: cn.property, value }));
});
}
return (before ? target.changing : target.changed)
.filter(({property}) => prop === property);
}
// tslint:disable-next-line:no-empty
const EMPTY_FN = () => {};
export class SelfDescribingProxyHandler {
constructor(public name: string) {}
get(_target: any, name: string) {
return SelfDescribingProxyHandler.create(`${this.name}.${name}`);
}
apply() {
return this.name;
}
static create(name = '') {
let ret = proxyCache.get(name);
if (ret) return ret;
ret = new Proxy(EMPTY_FN, new SelfDescribingProxyHandler(name));
proxyCache.set(name, ret);
return ret;
}
}
export function functionToPropertyChain(chain: Function): Array<string> {
let input = SelfDescribingProxyHandler.create();
let result: Function = chain(input);
let ret: string = result();
return ret.substring(1).split('.');
}
const didntWork = { failed: true };
export function fetchValueForPropertyChain(target: any, chain: Array<string>): { result?: any, failed: boolean } {
let current = target;
if (current instanceof Updatable && chain[0] !== 'value') {
try {
current = current.value;
} catch (_e) {
return didntWork;
}
}
for (let i = 0; i < chain.length; i++) {
try {
current = current[chain[i]];
} catch (_e) {
return didntWork;
}
if (current === undefined) return didntWork;
// NB: Current is a non-object; if we're at the end of the chain, we
// should return it, if we're not, we're in an error state and should
// bail
if (!isObject(current)) {
return (i === chain.length - 1) ? { result: current, failed: false} : didntWork;
}
if (current instanceof Updatable && chain[i + 1] !== 'value') {
try {
current = current.value;
} catch (_e) {
return didntWork;
}
}
}
return { result: current, failed: false };
}
export function getValue<T, TRet>(target: T, accessor: ((x: T) => TRet)): { result?: TRet, failed: boolean } |
const defaultResultPredicate = (v: any) => Array.isArray(v) ? !!v.length : !!v;
export function getResultAfterChange<T extends Model, TProp>(
target: T,
selector: (value: T) => TProp,
predicate: (value: TProp, index: number) => boolean = defaultResultPredicate,
numberOfChanges: number = 1)
: Promise<TProp> {
return whenPropertyInternal(target, true, selector)
.filter(predicate)
.take(numberOfChanges)
.toPromise();
}
/*
* Extremely boring and ugly type descriptions ahead
*/
export type PropSelector<TIn, TOut> = (t: TIn) => TOut;
export function when<TSource, TRet>(
target: TSource,
prop: PropSelector<TSource, TRet>): Observable<TRet>;
export function when<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TProp1, p2: TProp2) => TRet)):
Observable<TRet>;
export function when<TSource, TProp1, TProp2, TProp3, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
sel: ((p1: TProp1, p2: TProp2, p3: TProp3) => TRet)):
Observable<TRet>;
export function when<TSource, TProp1, TProp2, TProp3, TProp4, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
prop4: PropSelector<TSource, TProp4>,
sel: ((p1: TProp1, p2: TProp2, p3: TProp3, p4: TProp4) => TRet)):
Observable<TRet>;
export function when<TSource, TRet>(
target: TSource,
prop: string): Observable<TRet>;
export function when<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: string,
prop2: string,
sel: ((p1: TProp1, p2: TProp2) => TRet)):
Observable<TRet>;
export function when(target: any, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
return whenPropertyInternal(target, true, ...propsAndSelector);
}
export function whenProperty<TSource, TRet>(
target: TSource,
prop: PropSelector<TSource, TRet>):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TypedChangeNotification<TSource, TProp1>, p2: TypedChangeNotification<TSource, TProp2>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TProp3, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
sel: ((
p1: TypedChangeNotification<TSource, TProp1>,
p2: TypedChangeNotification<TSource, TProp2>,
p3: TypedChangeNotification<TSource, TProp3>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TProp3, TProp4, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
prop4: PropSelector<TSource, TProp4>,
sel: ((
p1: TypedChangeNotification<TSource, TProp1>,
p2: TypedChangeNotification<TSource, TProp2>,
p3: TypedChangeNotification<TSource, TProp3>,
p4: TypedChangeNotification<TSource, TProp4>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty(target: any, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
return whenPropertyInternal(target, false, ...propsAndSelector);
} | {
const propChain = functionToPropertyChain(accessor);
return fetchValueForPropertyChain(target, propChain);
} | identifier_body |
when.ts | import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { ArrayObserver, splice } from 'observe-js';
import { ChangeNotification, Model, TypedChangeNotification } from './model';
import * as isFunction from 'lodash.isfunction';
import * as isObject from 'lodash.isobject';
import * as isEqual from 'lodash.isequal';
import * as LRU from 'lru-cache';
import { Updatable } from './updatable';
const proxyCache = LRU(64);
import './standard-operators';
const identifier = /^[$A-Z_][0-9A-Z_$]*$/i;
export function whenPropertyInternal(target: any, valueOnly: boolean, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
if (propsAndSelector.length < 1) {
throw new Error('Must specify at least one property!');
}
if (propsAndSelector.length === 1) {
let ret = observableForPropertyChain(target, propsAndSelector[0] as string);
return valueOnly ? ret.map(x => x.value) : ret;
}
let [selector] = propsAndSelector.splice(-1, 1);
if (!(selector instanceof Function)) {
throw new Error('In multi-item properties, the last function must be a selector');
}
let propsOnly = propsAndSelector as Array<string|string[]>;
let propWatchers = propsOnly.map((p) =>
valueOnly ?
observableForPropertyChain(target, p).map(x => x.value) :
observableForPropertyChain(target, p));
return Observable.combineLatest(...propWatchers, selector).distinctUntilChanged((x, y) => isEqual(x, y));
}
export type ArrayChange<T> = { value: T[], splices: splice[] };
export function whenArray<TSource, TProp>(
target: TSource,
prop: (t: TSource) => TProp[]): Observable<ArrayChange<TProp>> {
return when(target, prop).switchMap(x => observeArray(x).startWith({ value: x ? Array.from(x) : x, splices: []}));
}
export function observeArray<T>(arr: T[]): Observable<ArrayChange<T>> {
if (!arr || !Array.isArray(arr)) return Observable.empty();
return Observable.create((subj) => {
let ao: ArrayObserver;
try {
ao = new ArrayObserver(arr);
ao.open((s) => {
subj.next({value: Array.from(arr), splices: s});
});
} catch (e) {
subj.error(e);
}
return new Subscription(() => ao.close());
});
}
export function observableForPropertyChain(target: any, chain: (Array<string> | string | Function), before = false): Observable<ChangeNotification> {
let props: Array<string>;
if (Array.isArray(chain)) {
props = chain;
} else if (isFunction(chain)) {
props = functionToPropertyChain(chain as Function);
} else {
props = (chain as string).split('.');
if (props.find((x) => x.match(identifier) === null)) {
throw new Error("property name must be of the form 'foo.bar.baz'");
}
}
let firstProp = props[0];
let start = notificationForProperty(target, firstProp, before);
if (isObject(target) && firstProp in target) {
let val = target[firstProp];
if (isObject(val) && (val instanceof Updatable)) {
val = val.value;
}
start = start.startWith({ sender: target, property: firstProp, value: val });
}
if (props.length === 1) {
return start.distinctUntilChanged((x, y) => isEqual(x.value, y.value));
}
return start // target.foo
.map((x) => {
return observableForPropertyChain(x.value, props.slice(1), before)
.map((y) => {
// This is for target.foo.bar.baz, its sender will be
// target.foo, and its property will be bar.baz
return { sender: target, property: `${firstProp}.${y.property}`, value: y.value };
});
})
.switch()
.distinctUntilChanged((x, y) => isEqual(x.value, y.value));
}
export function notificationForProperty(target: any, prop: string, before = false): Observable<ChangeNotification> {
if (!(target instanceof Model)) {
return Observable.never();
}
if (!(prop in target)) {
return Observable.never();
}
if (target[prop] instanceof Updatable) {
return (before ? target.changing : target.changed)
.startWith({sender: target, property: prop, value: target[prop]})
.filter(({property}) => prop === property)
.switchMap(cn => {
let obs: Observable<any> = cn.value;
return obs.skip(1)
.map((value) => ({ sender: cn.sender, property: cn.property, value }));
});
}
return (before ? target.changing : target.changed)
.filter(({property}) => prop === property);
}
// tslint:disable-next-line:no-empty
const EMPTY_FN = () => {};
export class SelfDescribingProxyHandler {
constructor(public name: string) {}
get(_target: any, name: string) {
return SelfDescribingProxyHandler.create(`${this.name}.${name}`);
}
apply() {
return this.name;
}
static | (name = '') {
let ret = proxyCache.get(name);
if (ret) return ret;
ret = new Proxy(EMPTY_FN, new SelfDescribingProxyHandler(name));
proxyCache.set(name, ret);
return ret;
}
}
export function functionToPropertyChain(chain: Function): Array<string> {
let input = SelfDescribingProxyHandler.create();
let result: Function = chain(input);
let ret: string = result();
return ret.substring(1).split('.');
}
const didntWork = { failed: true };
export function fetchValueForPropertyChain(target: any, chain: Array<string>): { result?: any, failed: boolean } {
let current = target;
if (current instanceof Updatable && chain[0] !== 'value') {
try {
current = current.value;
} catch (_e) {
return didntWork;
}
}
for (let i = 0; i < chain.length; i++) {
try {
current = current[chain[i]];
} catch (_e) {
return didntWork;
}
if (current === undefined) return didntWork;
// NB: Current is a non-object; if we're at the end of the chain, we
// should return it, if we're not, we're in an error state and should
// bail
if (!isObject(current)) {
return (i === chain.length - 1) ? { result: current, failed: false} : didntWork;
}
if (current instanceof Updatable && chain[i + 1] !== 'value') {
try {
current = current.value;
} catch (_e) {
return didntWork;
}
}
}
return { result: current, failed: false };
}
export function getValue<T, TRet>(target: T, accessor: ((x: T) => TRet)): { result?: TRet, failed: boolean } {
const propChain = functionToPropertyChain(accessor);
return fetchValueForPropertyChain(target, propChain);
}
const defaultResultPredicate = (v: any) => Array.isArray(v) ? !!v.length : !!v;
export function getResultAfterChange<T extends Model, TProp>(
target: T,
selector: (value: T) => TProp,
predicate: (value: TProp, index: number) => boolean = defaultResultPredicate,
numberOfChanges: number = 1)
: Promise<TProp> {
return whenPropertyInternal(target, true, selector)
.filter(predicate)
.take(numberOfChanges)
.toPromise();
}
/*
* Extremely boring and ugly type descriptions ahead
*/
export type PropSelector<TIn, TOut> = (t: TIn) => TOut;
export function when<TSource, TRet>(
target: TSource,
prop: PropSelector<TSource, TRet>): Observable<TRet>;
export function when<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TProp1, p2: TProp2) => TRet)):
Observable<TRet>;
export function when<TSource, TProp1, TProp2, TProp3, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
sel: ((p1: TProp1, p2: TProp2, p3: TProp3) => TRet)):
Observable<TRet>;
export function when<TSource, TProp1, TProp2, TProp3, TProp4, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
prop4: PropSelector<TSource, TProp4>,
sel: ((p1: TProp1, p2: TProp2, p3: TProp3, p4: TProp4) => TRet)):
Observable<TRet>;
export function when<TSource, TRet>(
target: TSource,
prop: string): Observable<TRet>;
export function when<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: string,
prop2: string,
sel: ((p1: TProp1, p2: TProp2) => TRet)):
Observable<TRet>;
export function when(target: any, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
return whenPropertyInternal(target, true, ...propsAndSelector);
}
export function whenProperty<TSource, TRet>(
target: TSource,
prop: PropSelector<TSource, TRet>):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TypedChangeNotification<TSource, TProp1>, p2: TypedChangeNotification<TSource, TProp2>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TProp3, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
sel: ((
p1: TypedChangeNotification<TSource, TProp1>,
p2: TypedChangeNotification<TSource, TProp2>,
p3: TypedChangeNotification<TSource, TProp3>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TProp3, TProp4, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
prop4: PropSelector<TSource, TProp4>,
sel: ((
p1: TypedChangeNotification<TSource, TProp1>,
p2: TypedChangeNotification<TSource, TProp2>,
p3: TypedChangeNotification<TSource, TProp3>,
p4: TypedChangeNotification<TSource, TProp4>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty(target: any, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
return whenPropertyInternal(target, false, ...propsAndSelector);
} | create | identifier_name |
when.ts | import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { ArrayObserver, splice } from 'observe-js';
import { ChangeNotification, Model, TypedChangeNotification } from './model';
import * as isFunction from 'lodash.isfunction';
import * as isObject from 'lodash.isobject';
import * as isEqual from 'lodash.isequal';
import * as LRU from 'lru-cache';
import { Updatable } from './updatable';
const proxyCache = LRU(64);
import './standard-operators';
const identifier = /^[$A-Z_][0-9A-Z_$]*$/i;
export function whenPropertyInternal(target: any, valueOnly: boolean, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
if (propsAndSelector.length < 1) {
throw new Error('Must specify at least one property!');
}
if (propsAndSelector.length === 1) {
let ret = observableForPropertyChain(target, propsAndSelector[0] as string);
return valueOnly ? ret.map(x => x.value) : ret;
}
let [selector] = propsAndSelector.splice(-1, 1);
if (!(selector instanceof Function)) {
throw new Error('In multi-item properties, the last function must be a selector');
}
let propsOnly = propsAndSelector as Array<string|string[]>;
let propWatchers = propsOnly.map((p) =>
valueOnly ?
observableForPropertyChain(target, p).map(x => x.value) :
observableForPropertyChain(target, p));
return Observable.combineLatest(...propWatchers, selector).distinctUntilChanged((x, y) => isEqual(x, y));
}
export type ArrayChange<T> = { value: T[], splices: splice[] };
export function whenArray<TSource, TProp>(
target: TSource,
prop: (t: TSource) => TProp[]): Observable<ArrayChange<TProp>> {
return when(target, prop).switchMap(x => observeArray(x).startWith({ value: x ? Array.from(x) : x, splices: []}));
}
export function observeArray<T>(arr: T[]): Observable<ArrayChange<T>> {
if (!arr || !Array.isArray(arr)) return Observable.empty();
return Observable.create((subj) => {
let ao: ArrayObserver;
try {
ao = new ArrayObserver(arr);
ao.open((s) => {
subj.next({value: Array.from(arr), splices: s});
});
} catch (e) {
subj.error(e);
}
return new Subscription(() => ao.close());
});
}
export function observableForPropertyChain(target: any, chain: (Array<string> | string | Function), before = false): Observable<ChangeNotification> {
let props: Array<string>;
if (Array.isArray(chain)) {
props = chain;
} else if (isFunction(chain)) {
props = functionToPropertyChain(chain as Function);
} else {
props = (chain as string).split('.');
if (props.find((x) => x.match(identifier) === null)) {
throw new Error("property name must be of the form 'foo.bar.baz'");
}
}
let firstProp = props[0];
let start = notificationForProperty(target, firstProp, before);
if (isObject(target) && firstProp in target) {
let val = target[firstProp];
if (isObject(val) && (val instanceof Updatable)) {
val = val.value;
}
start = start.startWith({ sender: target, property: firstProp, value: val });
}
if (props.length === 1) {
return start.distinctUntilChanged((x, y) => isEqual(x.value, y.value));
}
return start // target.foo
.map((x) => {
return observableForPropertyChain(x.value, props.slice(1), before)
.map((y) => {
// This is for target.foo.bar.baz, its sender will be
// target.foo, and its property will be bar.baz
return { sender: target, property: `${firstProp}.${y.property}`, value: y.value };
});
})
.switch()
.distinctUntilChanged((x, y) => isEqual(x.value, y.value));
}
export function notificationForProperty(target: any, prop: string, before = false): Observable<ChangeNotification> {
if (!(target instanceof Model)) {
return Observable.never();
}
if (!(prop in target)) {
return Observable.never();
}
if (target[prop] instanceof Updatable) {
return (before ? target.changing : target.changed)
.startWith({sender: target, property: prop, value: target[prop]})
.filter(({property}) => prop === property)
.switchMap(cn => {
let obs: Observable<any> = cn.value;
return obs.skip(1)
.map((value) => ({ sender: cn.sender, property: cn.property, value }));
});
}
return (before ? target.changing : target.changed)
.filter(({property}) => prop === property);
}
// tslint:disable-next-line:no-empty
const EMPTY_FN = () => {};
export class SelfDescribingProxyHandler {
constructor(public name: string) {}
get(_target: any, name: string) {
return SelfDescribingProxyHandler.create(`${this.name}.${name}`);
}
apply() {
return this.name;
}
static create(name = '') {
let ret = proxyCache.get(name);
if (ret) return ret;
ret = new Proxy(EMPTY_FN, new SelfDescribingProxyHandler(name));
proxyCache.set(name, ret);
return ret;
}
}
export function functionToPropertyChain(chain: Function): Array<string> {
let input = SelfDescribingProxyHandler.create();
let result: Function = chain(input);
let ret: string = result();
return ret.substring(1).split('.');
}
const didntWork = { failed: true };
export function fetchValueForPropertyChain(target: any, chain: Array<string>): { result?: any, failed: boolean } {
let current = target;
if (current instanceof Updatable && chain[0] !== 'value') {
try {
current = current.value;
} catch (_e) {
return didntWork;
}
}
for (let i = 0; i < chain.length; i++) {
try {
current = current[chain[i]];
} catch (_e) {
return didntWork;
}
if (current === undefined) return didntWork;
// NB: Current is a non-object; if we're at the end of the chain, we
// should return it, if we're not, we're in an error state and should
// bail
if (!isObject(current)) {
return (i === chain.length - 1) ? { result: current, failed: false} : didntWork;
}
if (current instanceof Updatable && chain[i + 1] !== 'value') {
try {
current = current.value;
} catch (_e) {
return didntWork;
}
}
}
return { result: current, failed: false };
}
export function getValue<T, TRet>(target: T, accessor: ((x: T) => TRet)): { result?: TRet, failed: boolean } {
const propChain = functionToPropertyChain(accessor);
return fetchValueForPropertyChain(target, propChain);
}
const defaultResultPredicate = (v: any) => Array.isArray(v) ? !!v.length : !!v;
export function getResultAfterChange<T extends Model, TProp>(
target: T,
selector: (value: T) => TProp,
predicate: (value: TProp, index: number) => boolean = defaultResultPredicate,
numberOfChanges: number = 1)
: Promise<TProp> {
return whenPropertyInternal(target, true, selector)
.filter(predicate)
.take(numberOfChanges)
.toPromise();
}
/*
* Extremely boring and ugly type descriptions ahead
*/
export type PropSelector<TIn, TOut> = (t: TIn) => TOut;
export function when<TSource, TRet>(
target: TSource,
prop: PropSelector<TSource, TRet>): Observable<TRet>;
export function when<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TProp1, p2: TProp2) => TRet)):
Observable<TRet>;
export function when<TSource, TProp1, TProp2, TProp3, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
sel: ((p1: TProp1, p2: TProp2, p3: TProp3) => TRet)):
Observable<TRet>;
export function when<TSource, TProp1, TProp2, TProp3, TProp4, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
prop4: PropSelector<TSource, TProp4>,
sel: ((p1: TProp1, p2: TProp2, p3: TProp3, p4: TProp4) => TRet)):
Observable<TRet>;
export function when<TSource, TRet>(
target: TSource,
prop: string): Observable<TRet>;
export function when<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: string,
prop2: string,
sel: ((p1: TProp1, p2: TProp2) => TRet)):
Observable<TRet>;
export function when(target: any, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
return whenPropertyInternal(target, true, ...propsAndSelector);
}
export function whenProperty<TSource, TRet>(
target: TSource, | export function whenProperty<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TypedChangeNotification<TSource, TProp1>, p2: TypedChangeNotification<TSource, TProp2>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TProp3, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
sel: ((
p1: TypedChangeNotification<TSource, TProp1>,
p2: TypedChangeNotification<TSource, TProp2>,
p3: TypedChangeNotification<TSource, TProp3>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty<TSource, TProp1, TProp2, TProp3, TProp4, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
prop3: PropSelector<TSource, TProp3>,
prop4: PropSelector<TSource, TProp4>,
sel: ((
p1: TypedChangeNotification<TSource, TProp1>,
p2: TypedChangeNotification<TSource, TProp2>,
p3: TypedChangeNotification<TSource, TProp3>,
p4: TypedChangeNotification<TSource, TProp4>) => TRet)):
Observable<TypedChangeNotification<TSource, TRet>>;
export function whenProperty(target: any, ...propsAndSelector: Array<string|Function|string[]>): Observable<any> {
return whenPropertyInternal(target, false, ...propsAndSelector);
} | prop: PropSelector<TSource, TRet>):
Observable<TypedChangeNotification<TSource, TRet>>;
| random_line_split |
settestpath.py | # yum-rhn-plugin - RHN support for yum
#
# Copyright (C) 2006 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import sys
# Adjust path so we can see the src modules running from branch as well
# as test dir:
sys.path.insert(0, './')
sys.path.insert(0, '../')
sys.path.insert(0, '../../') | # (at your option) any later version.
# | random_line_split |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct | {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
}
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
}
fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => ()
}
}
fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => ()
}
}
fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>,
in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => (),
_ = in4.recv() => (),
_ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => ()
}
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]),
_ => ()
}
}
fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) {
let mut results = Vec::new();
let mut start = time::precise_time_ns();
let mut i = 0;
for count in 0..total {
if count % 65536 == 0 {
let total = (time::precise_time_ns() - start) / 65536;
results.push(total);
println!("{}", i);
println!("{} ns", total);
start = time::precise_time_ns();
i += 1;
}
do_select(N, &input);
}
save_results(input.len(), results);
}
fn experiment(iterations : i32, threads : i32) {
let mut chans = Vec::new();
for i in 0..threads {
let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0);
chans.push(rx);
thread::spawn(move || { writer(tx, i, iterations / threads); } );
}
reader(threads, chans, iterations);
}
fn main() {
let x : i32 = 2;
experiment(x.pow(24), 1);
experiment(x.pow(24), 2);
experiment(x.pow(24), 4);
experiment(x.pow(24), 8);
}
| StressedPacket | identifier_name |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct StressedPacket {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) |
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
}
fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => ()
}
}
fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => ()
}
}
fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>,
in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => (),
_ = in4.recv() => (),
_ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => ()
}
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]),
_ => ()
}
}
fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) {
let mut results = Vec::new();
let mut start = time::precise_time_ns();
let mut i = 0;
for count in 0..total {
if count % 65536 == 0 {
let total = (time::precise_time_ns() - start) / 65536;
results.push(total);
println!("{}", i);
println!("{} ns", total);
start = time::precise_time_ns();
i += 1;
}
do_select(N, &input);
}
save_results(input.len(), results);
}
fn experiment(iterations : i32, threads : i32) {
let mut chans = Vec::new();
for i in 0..threads {
let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0);
chans.push(rx);
thread::spawn(move || { writer(tx, i, iterations / threads); } );
}
reader(threads, chans, iterations);
}
fn main() {
let x : i32 = 2;
experiment(x.pow(24), 1);
experiment(x.pow(24), 2);
experiment(x.pow(24), 4);
experiment(x.pow(24), 8);
}
| {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
} | identifier_body |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct StressedPacket {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
}
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
}
fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => ()
}
}
fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => ()
}
}
fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>,
in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => (),
_ = in4.recv() => (), | }
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]),
_ => ()
}
}
fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) {
let mut results = Vec::new();
let mut start = time::precise_time_ns();
let mut i = 0;
for count in 0..total {
if count % 65536 == 0 {
let total = (time::precise_time_ns() - start) / 65536;
results.push(total);
println!("{}", i);
println!("{} ns", total);
start = time::precise_time_ns();
i += 1;
}
do_select(N, &input);
}
save_results(input.len(), results);
}
fn experiment(iterations : i32, threads : i32) {
let mut chans = Vec::new();
for i in 0..threads {
let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0);
chans.push(rx);
thread::spawn(move || { writer(tx, i, iterations / threads); } );
}
reader(threads, chans, iterations);
}
fn main() {
let x : i32 = 2;
experiment(x.pow(24), 1);
experiment(x.pow(24), 2);
experiment(x.pow(24), 4);
experiment(x.pow(24), 8);
} | _ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => () | random_line_split |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
};
var brickSet = {};
Crafty.e('Line, 2D, Canvas, Color')
.color('#AAAAAA')
.attr({ x:0, y:8*_height/10, w:_width, h:2});
Crafty.e('Line, 2D, Canvas, Color')
.color('#000000')
.attr({ x:0, y:8*_height/10, w:_width, h:1});
var BrickCreator = Crafty.e('BrickCreator, 2D, Canvas, Color, BrickC, Mouse');
// Adds brick to level by its ID
// It will overwrite any info already saved with this ID
var addBrickToSet = function addBrickToSet (brick) {
brickSet[brick._brickID] = {
w: brick.w,
h: brick.h,
x: brick.x,
y: brick.y
};
console.log('Added brick', brickSet[brick._brickID]);
};
var onBrickDropped = function onBrickDropped (mouseEvent) {
console.log('brick %d dropped', this._brickID);
addBrickToSet(this);
};
var createBrick = function createBrick () {
console.log('Cloning');
bricksCreated++;
var newBrick = Crafty.e('DynamicBrick'+bricksCreated+', 2D, Canvas, Color, BrickC, Draggable')
.attr({_brickID: bricksCreated})
.startDrag()
.bind('StopDrag', onBrickDropped);
};
BrickCreator.bind('MouseUp', createBrick);
// SAVE BUTTON
var saveText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 5*_width / 6 + 20 - 8,
y : 9*_height / 10 + 3
})
.text('Save')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var saveButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 5*_width / 6 - 8,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
lvl.name = getLevelName();
var lvlWithBricks = withBricks(lvl);
if (lvlWithBricks.bricks.length <= 0) {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
}
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blob([lvlData], {type: "text/plain;charset=utf-8"});
window.saveAs(blob, lvl.name+".json");
} else {
console.warn('Blob is not supported.');
window.prompt("Copy it go! (Ctrl/Cmd + C and Enter)", lvlData);
}
})
.attach(saveText);
// CANCEL BUTTON
var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 4*_width / 6 - 10,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
if (window.confirm('You will lose any unsaved data if you continue, are you sure?')) {
clearLevelName();
hideEditorForm();
Crafty.scene('menu');
}
})
.attach(cancelText);
function withBricks(lvl) {
lvl.bricks = [];
for (var brick in brickSet) {
if (Object.prototype.hasOwnProperty.call(brickSet, brick)) {
lvl.bricks.push(brickSet[brick]);
}
}
return lvl;
}
});
function showEditorForm () |
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, 10000000);
}
}
function clearLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
$input.val('');
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})(jQuery);
| {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
} | identifier_body |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
};
var brickSet = {};
Crafty.e('Line, 2D, Canvas, Color')
.color('#AAAAAA')
.attr({ x:0, y:8*_height/10, w:_width, h:2});
Crafty.e('Line, 2D, Canvas, Color')
.color('#000000')
.attr({ x:0, y:8*_height/10, w:_width, h:1});
var BrickCreator = Crafty.e('BrickCreator, 2D, Canvas, Color, BrickC, Mouse');
// Adds brick to level by its ID
// It will overwrite any info already saved with this ID
var addBrickToSet = function addBrickToSet (brick) {
brickSet[brick._brickID] = {
w: brick.w,
h: brick.h,
x: brick.x,
y: brick.y
};
console.log('Added brick', brickSet[brick._brickID]);
};
var onBrickDropped = function onBrickDropped (mouseEvent) {
console.log('brick %d dropped', this._brickID);
addBrickToSet(this);
};
var createBrick = function createBrick () {
console.log('Cloning');
bricksCreated++;
var newBrick = Crafty.e('DynamicBrick'+bricksCreated+', 2D, Canvas, Color, BrickC, Draggable')
.attr({_brickID: bricksCreated})
.startDrag()
.bind('StopDrag', onBrickDropped);
};
BrickCreator.bind('MouseUp', createBrick);
// SAVE BUTTON
var saveText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 5*_width / 6 + 20 - 8,
y : 9*_height / 10 + 3
})
.text('Save')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var saveButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 5*_width / 6 - 8,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
lvl.name = getLevelName();
var lvlWithBricks = withBricks(lvl);
if (lvlWithBricks.bricks.length <= 0) {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
}
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blob([lvlData], {type: "text/plain;charset=utf-8"});
window.saveAs(blob, lvl.name+".json");
} else {
console.warn('Blob is not supported.');
window.prompt("Copy it go! (Ctrl/Cmd + C and Enter)", lvlData);
}
})
.attach(saveText); | var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 4*_width / 6 - 10,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
if (window.confirm('You will lose any unsaved data if you continue, are you sure?')) {
clearLevelName();
hideEditorForm();
Crafty.scene('menu');
}
})
.attach(cancelText);
function withBricks(lvl) {
lvl.bricks = [];
for (var brick in brickSet) {
if (Object.prototype.hasOwnProperty.call(brickSet, brick)) {
lvl.bricks.push(brickSet[brick]);
}
}
return lvl;
}
});
function showEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
}
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, 10000000);
}
}
function clearLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
$input.val('');
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})(jQuery); |
// CANCEL BUTTON | random_line_split |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
};
var brickSet = {};
Crafty.e('Line, 2D, Canvas, Color')
.color('#AAAAAA')
.attr({ x:0, y:8*_height/10, w:_width, h:2});
Crafty.e('Line, 2D, Canvas, Color')
.color('#000000')
.attr({ x:0, y:8*_height/10, w:_width, h:1});
var BrickCreator = Crafty.e('BrickCreator, 2D, Canvas, Color, BrickC, Mouse');
// Adds brick to level by its ID
// It will overwrite any info already saved with this ID
var addBrickToSet = function addBrickToSet (brick) {
brickSet[brick._brickID] = {
w: brick.w,
h: brick.h,
x: brick.x,
y: brick.y
};
console.log('Added brick', brickSet[brick._brickID]);
};
var onBrickDropped = function onBrickDropped (mouseEvent) {
console.log('brick %d dropped', this._brickID);
addBrickToSet(this);
};
var createBrick = function createBrick () {
console.log('Cloning');
bricksCreated++;
var newBrick = Crafty.e('DynamicBrick'+bricksCreated+', 2D, Canvas, Color, BrickC, Draggable')
.attr({_brickID: bricksCreated})
.startDrag()
.bind('StopDrag', onBrickDropped);
};
BrickCreator.bind('MouseUp', createBrick);
// SAVE BUTTON
var saveText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 5*_width / 6 + 20 - 8,
y : 9*_height / 10 + 3
})
.text('Save')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var saveButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 5*_width / 6 - 8,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
lvl.name = getLevelName();
var lvlWithBricks = withBricks(lvl);
if (lvlWithBricks.bricks.length <= 0) {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
}
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blob([lvlData], {type: "text/plain;charset=utf-8"});
window.saveAs(blob, lvl.name+".json");
} else {
console.warn('Blob is not supported.');
window.prompt("Copy it go! (Ctrl/Cmd + C and Enter)", lvlData);
}
})
.attach(saveText);
// CANCEL BUTTON
var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 4*_width / 6 - 10,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
if (window.confirm('You will lose any unsaved data if you continue, are you sure?')) {
clearLevelName();
hideEditorForm();
Crafty.scene('menu');
}
})
.attach(cancelText);
function withBricks(lvl) {
lvl.bricks = [];
for (var brick in brickSet) {
if (Object.prototype.hasOwnProperty.call(brickSet, brick)) {
lvl.bricks.push(brickSet[brick]);
}
}
return lvl;
}
});
function | () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
}
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, 10000000);
}
}
function clearLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
$input.val('');
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})(jQuery);
| showEditorForm | identifier_name |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
};
var brickSet = {};
Crafty.e('Line, 2D, Canvas, Color')
.color('#AAAAAA')
.attr({ x:0, y:8*_height/10, w:_width, h:2});
Crafty.e('Line, 2D, Canvas, Color')
.color('#000000')
.attr({ x:0, y:8*_height/10, w:_width, h:1});
var BrickCreator = Crafty.e('BrickCreator, 2D, Canvas, Color, BrickC, Mouse');
// Adds brick to level by its ID
// It will overwrite any info already saved with this ID
var addBrickToSet = function addBrickToSet (brick) {
brickSet[brick._brickID] = {
w: brick.w,
h: brick.h,
x: brick.x,
y: brick.y
};
console.log('Added brick', brickSet[brick._brickID]);
};
var onBrickDropped = function onBrickDropped (mouseEvent) {
console.log('brick %d dropped', this._brickID);
addBrickToSet(this);
};
var createBrick = function createBrick () {
console.log('Cloning');
bricksCreated++;
var newBrick = Crafty.e('DynamicBrick'+bricksCreated+', 2D, Canvas, Color, BrickC, Draggable')
.attr({_brickID: bricksCreated})
.startDrag()
.bind('StopDrag', onBrickDropped);
};
BrickCreator.bind('MouseUp', createBrick);
// SAVE BUTTON
var saveText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 5*_width / 6 + 20 - 8,
y : 9*_height / 10 + 3
})
.text('Save')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var saveButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 5*_width / 6 - 8,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
lvl.name = getLevelName();
var lvlWithBricks = withBricks(lvl);
if (lvlWithBricks.bricks.length <= 0) |
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blob([lvlData], {type: "text/plain;charset=utf-8"});
window.saveAs(blob, lvl.name+".json");
} else {
console.warn('Blob is not supported.');
window.prompt("Copy it go! (Ctrl/Cmd + C and Enter)", lvlData);
}
})
.attach(saveText);
// CANCEL BUTTON
var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 4*_width / 6 - 10,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
if (window.confirm('You will lose any unsaved data if you continue, are you sure?')) {
clearLevelName();
hideEditorForm();
Crafty.scene('menu');
}
})
.attach(cancelText);
function withBricks(lvl) {
lvl.bricks = [];
for (var brick in brickSet) {
if (Object.prototype.hasOwnProperty.call(brickSet, brick)) {
lvl.bricks.push(brickSet[brick]);
}
}
return lvl;
}
});
function showEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
}
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, 10000000);
}
}
function clearLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
$input.val('');
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})(jQuery);
| {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
} | conditional_block |
Users.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) {
classNames.push(className); | if (user.image) {
avatar = <img className="avatar" alt="avatar" src={user.image.data} />;
} else {
avatar = <UserIcon className="avatar" />;
}
return (
<Link className={classNames.join(' ')} to={`/users/${user._id}`}>
<div className="item">
<span className="box--row box--static">
{avatar}
<span className="item__name">{user.name}</span>
</span>
<span>{user.email}</span>
</div>
</Link>
);
};
Item.propTypes = {
className: PropTypes.string,
item: PropTypes.shape({
administrator: PropTypes.bool,
domainIds: PropTypes.arrayOf(PropTypes.string),
email: PropTypes.string,
}).isRequired,
};
Item.defaultProps = {
className: undefined,
};
export default class Users extends List {}
Users.defaultProps = {
...List.defaultProps,
category: 'users',
adminable: false,
Item,
path: '/users',
sort: '-modified name email',
title: 'People',
}; | }
let avatar; | random_line_split |
Users.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) {
classNames.push(className);
}
let avatar;
if (user.image) {
avatar = <img className="avatar" alt="avatar" src={user.image.data} />;
} else {
avatar = <UserIcon className="avatar" />;
}
return (
<Link className={classNames.join(' ')} to={`/users/${user._id}`}>
<div className="item">
<span className="box--row box--static">
{avatar}
<span className="item__name">{user.name}</span>
</span>
<span>{user.email}</span>
</div>
</Link>
);
};
Item.propTypes = {
className: PropTypes.string,
item: PropTypes.shape({
administrator: PropTypes.bool,
domainIds: PropTypes.arrayOf(PropTypes.string),
email: PropTypes.string,
}).isRequired,
};
Item.defaultProps = {
className: undefined,
};
export default class | extends List {}
Users.defaultProps = {
...List.defaultProps,
category: 'users',
adminable: false,
Item,
path: '/users',
sort: '-modified name email',
title: 'People',
};
| Users | identifier_name |
Users.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) |
let avatar;
if (user.image) {
avatar = <img className="avatar" alt="avatar" src={user.image.data} />;
} else {
avatar = <UserIcon className="avatar" />;
}
return (
<Link className={classNames.join(' ')} to={`/users/${user._id}`}>
<div className="item">
<span className="box--row box--static">
{avatar}
<span className="item__name">{user.name}</span>
</span>
<span>{user.email}</span>
</div>
</Link>
);
};
Item.propTypes = {
className: PropTypes.string,
item: PropTypes.shape({
administrator: PropTypes.bool,
domainIds: PropTypes.arrayOf(PropTypes.string),
email: PropTypes.string,
}).isRequired,
};
Item.defaultProps = {
className: undefined,
};
export default class Users extends List {}
Users.defaultProps = {
...List.defaultProps,
category: 'users',
adminable: false,
Item,
path: '/users',
sort: '-modified name email',
title: 'People',
};
| {
classNames.push(className);
} | conditional_block |
methodelement.ts | import {defineClass} from './decorator.js'
import {Method, method} from './mixin.js'
@defineClass('method-ts')
export default class MethodElement extends method(HTMLElement) {
state:object = {}
constructor() {
super()
} | selector(select:HTMLSelectElement, json:any){
const data:Method[] = json.data
data.forEach((v)=>{
const option = document.createElement('option')
option.value = v.id
option.innerText = v.description
select.appendChild(option)
})
}
connectedCallback() {
const root = this.attachShadow({mode: 'open'});
root.innerHTML = `<slot name="input"></slot>`
const select = this.querySelector('select')
this.method()
.then(json => this.selector(select!, json))
.catch(err => console.log(err))
}
disconnectedCallback() { }
attributeChangedCallback(name: string, oldValue: string, newValue: string) { }
adoptedCallback() { }
} | random_line_split |
|
methodelement.ts | import {defineClass} from './decorator.js'
import {Method, method} from './mixin.js'
@defineClass('method-ts')
export default class MethodElement extends method(HTMLElement) {
state:object = {}
constructor() {
super()
}
selector(select:HTMLSelectElement, json:any){
const data:Method[] = json.data
data.forEach((v)=>{
const option = document.createElement('option')
option.value = v.id
option.innerText = v.description
select.appendChild(option)
})
}
connectedCallback() {
const root = this.attachShadow({mode: 'open'});
root.innerHTML = `<slot name="input"></slot>`
const select = this.querySelector('select')
this.method()
.then(json => this.selector(select!, json))
.catch(err => console.log(err))
}
disconnectedCallback() { }
attributeChangedCallback(name: string, oldValue: string, newValue: string) { }
adoptedCallback() |
}
| { } | identifier_body |
methodelement.ts | import {defineClass} from './decorator.js'
import {Method, method} from './mixin.js'
@defineClass('method-ts')
export default class MethodElement extends method(HTMLElement) {
state:object = {}
constructor() {
super()
}
selector(select:HTMLSelectElement, json:any){
const data:Method[] = json.data
data.forEach((v)=>{
const option = document.createElement('option')
option.value = v.id
option.innerText = v.description
select.appendChild(option)
})
}
| () {
const root = this.attachShadow({mode: 'open'});
root.innerHTML = `<slot name="input"></slot>`
const select = this.querySelector('select')
this.method()
.then(json => this.selector(select!, json))
.catch(err => console.log(err))
}
disconnectedCallback() { }
attributeChangedCallback(name: string, oldValue: string, newValue: string) { }
adoptedCallback() { }
}
| connectedCallback | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext); |
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while !window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
} | window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext); | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while !window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) |
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
} | identifier_body |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while !window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn | (&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| call | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while !window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else |
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| { println("Cursor left window."); } | conditional_block |
definition_spec.ts | import "../spec_helper";
describe("Definition#buildModel", function () {
class LocalType extends Factory.Model {
public id: number;
}
const getDef = (cb: Function): Factory.Definition => Factory.define("test", cb);
it("must build model without given attributes", function () {
const definition: Factory.Definition = getDef(function () { });
expect(definition.buildModel<LocalType>()).not.toBeNull();
});
it("must build model with given attributes", function () {
const definition: Factory.Definition = getDef(function () {
field("id", 1);
});
const model = definition.buildModel<LocalType>({id: 1});
expect(model).not.toBeNull();
});
it("must throw error if attribute wasn't defined", function () { | });
it("must define field using this notation", function () {
const definition = getDef(function () {
this.id = 234;
});
expect(function () {
definition.buildModel({id: 1})
}).not.toThrowError("Unexpected data: [\"id\"]");
});
it("must define field using passed library", function () {
const definition = getDef(function (lib) {
lib.id = 234;
});
expect(function () {
definition.buildModel({id: 1})
}).not.toThrowError("Unexpected data: [\"id\"]");
});
}); | const definition: Factory.Definition = getDef(() => {});
expect(function () {
definition.buildModel({id: 1})
}).toThrowError("Unexpected data: [\"id\"]"); | random_line_split |
definition_spec.ts | import "../spec_helper";
describe("Definition#buildModel", function () {
class | extends Factory.Model {
public id: number;
}
const getDef = (cb: Function): Factory.Definition => Factory.define("test", cb);
it("must build model without given attributes", function () {
const definition: Factory.Definition = getDef(function () { });
expect(definition.buildModel<LocalType>()).not.toBeNull();
});
it("must build model with given attributes", function () {
const definition: Factory.Definition = getDef(function () {
field("id", 1);
});
const model = definition.buildModel<LocalType>({id: 1});
expect(model).not.toBeNull();
});
it("must throw error if attribute wasn't defined", function () {
const definition: Factory.Definition = getDef(() => {});
expect(function () {
definition.buildModel({id: 1})
}).toThrowError("Unexpected data: [\"id\"]");
});
it("must define field using this notation", function () {
const definition = getDef(function () {
this.id = 234;
});
expect(function () {
definition.buildModel({id: 1})
}).not.toThrowError("Unexpected data: [\"id\"]");
});
it("must define field using passed library", function () {
const definition = getDef(function (lib) {
lib.id = 234;
});
expect(function () {
definition.buildModel({id: 1})
}).not.toThrowError("Unexpected data: [\"id\"]");
});
});
| LocalType | identifier_name |
TestMNITagPoints.py | #!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Test label reading from an MNI tag file
#
# The current directory must be writeable.
#
try:
fname = "mni-tagtest.tag"
channel = open(fname, "wb")
channel.close()
# create some random points in a sphere
#
sphere1 = vtk.vtkPointSource()
sphere1.SetNumberOfPoints(13)
| xform.RotateWXYZ(20, 1, 0, 0)
xformFilter = vtk.vtkTransformFilter()
xformFilter.SetTransform(xform)
xformFilter.SetInputConnection(sphere1.GetOutputPort())
labels = vtk.vtkStringArray()
labels.InsertNextValue("0")
labels.InsertNextValue("1")
labels.InsertNextValue("2")
labels.InsertNextValue("3")
labels.InsertNextValue("Halifax")
labels.InsertNextValue("Toronto")
labels.InsertNextValue("Vancouver")
labels.InsertNextValue("Larry")
labels.InsertNextValue("Bob")
labels.InsertNextValue("Jackie")
labels.InsertNextValue("10")
labels.InsertNextValue("11")
labels.InsertNextValue("12")
weights = vtk.vtkDoubleArray()
weights.InsertNextValue(1.0)
weights.InsertNextValue(1.1)
weights.InsertNextValue(1.2)
weights.InsertNextValue(1.3)
weights.InsertNextValue(1.4)
weights.InsertNextValue(1.5)
weights.InsertNextValue(1.6)
weights.InsertNextValue(1.7)
weights.InsertNextValue(1.8)
weights.InsertNextValue(1.9)
weights.InsertNextValue(0.9)
weights.InsertNextValue(0.8)
weights.InsertNextValue(0.7)
writer = vtk.vtkMNITagPointWriter()
writer.SetFileName(fname)
writer.SetInputConnection(sphere1.GetOutputPort())
writer.SetInputConnection(1, xformFilter.GetOutputPort())
writer.SetLabelText(labels)
writer.SetWeights(weights)
writer.SetComments("Volume 1: sphere points\nVolume 2: transformed points")
writer.Write()
reader = vtk.vtkMNITagPointReader()
reader.CanReadFile(fname)
reader.SetFileName(fname)
textProp = vtk.vtkTextProperty()
textProp.SetFontSize(12)
textProp.SetColor(1.0, 1.0, 0.5)
labelHier = vtk.vtkPointSetToLabelHierarchy()
labelHier.SetInputConnection(reader.GetOutputPort())
labelHier.SetTextProperty(textProp)
labelHier.SetLabelArrayName("LabelText")
labelHier.SetMaximumDepth(15)
labelHier.SetTargetLabelCount(12)
labelMapper = vtk.vtkLabelPlacementMapper()
labelMapper.SetInputConnection(labelHier.GetOutputPort())
labelMapper.UseDepthBufferOff()
labelMapper.SetShapeToRect()
labelMapper.SetStyleToOutline()
labelActor = vtk.vtkActor2D()
labelActor.SetMapper(labelMapper)
glyphSource = vtk.vtkSphereSource()
glyphSource.SetRadius(0.01)
glyph = vtk.vtkGlyph3D()
glyph.SetSourceConnection(glyphSource.GetOutputPort())
glyph.SetInputConnection(reader.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(glyph.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
# Create rendering stuff
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size
#
ren1.AddViewProp(actor)
ren1.AddViewProp(labelActor)
ren1.SetBackground(0, 0, 0)
renWin.SetSize(300, 300)
renWin.Render()
try:
os.remove(fname)
except OSError:
pass
# render the image
#
# iren.Start()
except IOError:
print "Unable to test the writer/reader." |
xform = vtk.vtkTransform()
| random_line_split |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
"""
def __init__(self, path, directory_digest=None):
self._path = path
self._directory_digest = directory_digest
@property
def path(self):
"""Returns the pants internal path of this classpath entry.
Suitable for use in constructing classpaths for pants executions and pants generated artifacts.
:API: public
:rtype: string
"""
return self._path
@property
def directory_digest(self):
"""Returns the directory digest which contains this file. May be None.
This API is experimental, and subject to change.
:rtype: pants.engine.fs.Digest
"""
return self._directory_digest
def is_excluded_by(self, excludes):
"""Returns `True` if this classpath entry should be excluded given the `excludes` in play.
:param excludes: The excludes to check this classpath entry against.
:type excludes: list of :class:`pants.backend.jvm.targets.exclude.Exclude`
:rtype: bool
"""
return False
def __hash__(self):
return hash((self.path, self.directory_digest))
def __eq__(self, other):
return (
isinstance(other, ClasspathEntry) and
self.path == other.path and
self.directory_digest == other.directory_digest
)
def __ne__(self, other):
return not self == other
def __repr__(self):
return 'ClasspathEntry(path={!r}, directory_digest={!r})'.format(
self.path,
self.directory_digest,
)
@classmethod
def is_artifact_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return isinstance(classpath_entry, ArtifactClasspathEntry)
@classmethod
def is_internal_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return not cls.is_artifact_classpath_entry(classpath_entry)
class ArtifactClasspathEntry(ClasspathEntry):
"""Represents a resolved third party classpath entry.
:API: public
"""
def __init__(self, path, coordinate, cache_path, directory_digest=None):
super(ArtifactClasspathEntry, self).__init__(path, directory_digest)
self._coordinate = coordinate
self._cache_path = cache_path
@property
def coordinate(self):
"""Returns the maven coordinate that used to resolve this classpath entry's artifact.
:rtype: :class:`pants.java.jar.M2Coordinate`
"""
return self._coordinate
@property
def cache_path(self):
"""Returns the external cache path of this classpath entry.
For example, the `~/.m2/repository` or `~/.ivy2/cache` location of the resolved artifact for
maven and ivy resolvers respectively.
Suitable for use in constructing classpaths for external tools that should not be subject to
potential volatility in pants own internal caches.
:API: public
:rtype: string
"""
return self._cache_path
def is_excluded_by(self, excludes):
return any(_matches_exclude(self.coordinate, exclude) for exclude in excludes)
def __hash__(self):
return hash((self.path, self.coordinate, self.cache_path))
def __eq__(self, other):
return (isinstance(other, ArtifactClasspathEntry) and
self.path == other.path and
self.coordinate == other.coordinate and
self.cache_path == other.cache_path and
self.directory_digest == other.directory_digest)
def __ne__(self, other):
return not self == other
def __repr__(self):
return (
'ArtifactClasspathEntry(path={!r}, coordinate={!r}, cache_path={!r}, directory_digest={!r})'
.format(self.path, self.coordinate, self.cache_path, self.directory_digest)
)
def _matches_exclude(coordinate, exclude):
if not coordinate.org == exclude.org:
return False
if not exclude.name:
|
if coordinate.name == exclude.name:
return True
return False
| return True | conditional_block |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
"""
def __init__(self, path, directory_digest=None):
self._path = path
self._directory_digest = directory_digest
@property
def path(self):
"""Returns the pants internal path of this classpath entry.
Suitable for use in constructing classpaths for pants executions and pants generated artifacts.
:API: public
:rtype: string
"""
return self._path
@property
def directory_digest(self):
"""Returns the directory digest which contains this file. May be None.
This API is experimental, and subject to change.
:rtype: pants.engine.fs.Digest
"""
return self._directory_digest
def is_excluded_by(self, excludes):
"""Returns `True` if this classpath entry should be excluded given the `excludes` in play.
:param excludes: The excludes to check this classpath entry against.
:type excludes: list of :class:`pants.backend.jvm.targets.exclude.Exclude`
:rtype: bool
"""
return False
def __hash__(self):
return hash((self.path, self.directory_digest))
def __eq__(self, other):
return (
isinstance(other, ClasspathEntry) and
self.path == other.path and
self.directory_digest == other.directory_digest
)
def | (self, other):
return not self == other
def __repr__(self):
return 'ClasspathEntry(path={!r}, directory_digest={!r})'.format(
self.path,
self.directory_digest,
)
@classmethod
def is_artifact_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return isinstance(classpath_entry, ArtifactClasspathEntry)
@classmethod
def is_internal_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return not cls.is_artifact_classpath_entry(classpath_entry)
class ArtifactClasspathEntry(ClasspathEntry):
"""Represents a resolved third party classpath entry.
:API: public
"""
def __init__(self, path, coordinate, cache_path, directory_digest=None):
super(ArtifactClasspathEntry, self).__init__(path, directory_digest)
self._coordinate = coordinate
self._cache_path = cache_path
@property
def coordinate(self):
"""Returns the maven coordinate that used to resolve this classpath entry's artifact.
:rtype: :class:`pants.java.jar.M2Coordinate`
"""
return self._coordinate
@property
def cache_path(self):
"""Returns the external cache path of this classpath entry.
For example, the `~/.m2/repository` or `~/.ivy2/cache` location of the resolved artifact for
maven and ivy resolvers respectively.
Suitable for use in constructing classpaths for external tools that should not be subject to
potential volatility in pants own internal caches.
:API: public
:rtype: string
"""
return self._cache_path
def is_excluded_by(self, excludes):
return any(_matches_exclude(self.coordinate, exclude) for exclude in excludes)
def __hash__(self):
return hash((self.path, self.coordinate, self.cache_path))
def __eq__(self, other):
return (isinstance(other, ArtifactClasspathEntry) and
self.path == other.path and
self.coordinate == other.coordinate and
self.cache_path == other.cache_path and
self.directory_digest == other.directory_digest)
def __ne__(self, other):
return not self == other
def __repr__(self):
return (
'ArtifactClasspathEntry(path={!r}, coordinate={!r}, cache_path={!r}, directory_digest={!r})'
.format(self.path, self.coordinate, self.cache_path, self.directory_digest)
)
def _matches_exclude(coordinate, exclude):
if not coordinate.org == exclude.org:
return False
if not exclude.name:
return True
if coordinate.name == exclude.name:
return True
return False
| __ne__ | identifier_name |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
"""
def __init__(self, path, directory_digest=None):
self._path = path
self._directory_digest = directory_digest
@property
def path(self):
"""Returns the pants internal path of this classpath entry.
Suitable for use in constructing classpaths for pants executions and pants generated artifacts.
:API: public
:rtype: string
"""
return self._path
@property
def directory_digest(self):
"""Returns the directory digest which contains this file. May be None.
This API is experimental, and subject to change.
:rtype: pants.engine.fs.Digest
"""
return self._directory_digest
def is_excluded_by(self, excludes):
"""Returns `True` if this classpath entry should be excluded given the `excludes` in play.
:param excludes: The excludes to check this classpath entry against.
:type excludes: list of :class:`pants.backend.jvm.targets.exclude.Exclude`
:rtype: bool
"""
return False
def __hash__(self):
return hash((self.path, self.directory_digest))
def __eq__(self, other):
return (
isinstance(other, ClasspathEntry) and
self.path == other.path and
self.directory_digest == other.directory_digest
)
def __ne__(self, other):
return not self == other
def __repr__(self):
return 'ClasspathEntry(path={!r}, directory_digest={!r})'.format(
self.path,
self.directory_digest,
)
@classmethod
def is_artifact_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return isinstance(classpath_entry, ArtifactClasspathEntry)
@classmethod
def is_internal_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return not cls.is_artifact_classpath_entry(classpath_entry)
class ArtifactClasspathEntry(ClasspathEntry):
"""Represents a resolved third party classpath entry.
:API: public
"""
def __init__(self, path, coordinate, cache_path, directory_digest=None):
super(ArtifactClasspathEntry, self).__init__(path, directory_digest)
self._coordinate = coordinate
self._cache_path = cache_path
@property
def coordinate(self):
"""Returns the maven coordinate that used to resolve this classpath entry's artifact.
:rtype: :class:`pants.java.jar.M2Coordinate`
"""
return self._coordinate
@property
def cache_path(self):
"""Returns the external cache path of this classpath entry.
For example, the `~/.m2/repository` or `~/.ivy2/cache` location of the resolved artifact for
maven and ivy resolvers respectively.
Suitable for use in constructing classpaths for external tools that should not be subject to
potential volatility in pants own internal caches.
:API: public
:rtype: string
"""
return self._cache_path
def is_excluded_by(self, excludes):
return any(_matches_exclude(self.coordinate, exclude) for exclude in excludes)
def __hash__(self):
return hash((self.path, self.coordinate, self.cache_path))
def __eq__(self, other):
return (isinstance(other, ArtifactClasspathEntry) and
self.path == other.path and
self.coordinate == other.coordinate and
self.cache_path == other.cache_path and
self.directory_digest == other.directory_digest)
def __ne__(self, other):
return not self == other
def __repr__(self):
|
def _matches_exclude(coordinate, exclude):
if not coordinate.org == exclude.org:
return False
if not exclude.name:
return True
if coordinate.name == exclude.name:
return True
return False
| return (
'ArtifactClasspathEntry(path={!r}, coordinate={!r}, cache_path={!r}, directory_digest={!r})'
.format(self.path, self.coordinate, self.cache_path, self.directory_digest)
) | identifier_body |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
"""
| self._directory_digest = directory_digest
@property
def path(self):
"""Returns the pants internal path of this classpath entry.
Suitable for use in constructing classpaths for pants executions and pants generated artifacts.
:API: public
:rtype: string
"""
return self._path
@property
def directory_digest(self):
"""Returns the directory digest which contains this file. May be None.
This API is experimental, and subject to change.
:rtype: pants.engine.fs.Digest
"""
return self._directory_digest
def is_excluded_by(self, excludes):
"""Returns `True` if this classpath entry should be excluded given the `excludes` in play.
:param excludes: The excludes to check this classpath entry against.
:type excludes: list of :class:`pants.backend.jvm.targets.exclude.Exclude`
:rtype: bool
"""
return False
def __hash__(self):
return hash((self.path, self.directory_digest))
def __eq__(self, other):
return (
isinstance(other, ClasspathEntry) and
self.path == other.path and
self.directory_digest == other.directory_digest
)
def __ne__(self, other):
return not self == other
def __repr__(self):
return 'ClasspathEntry(path={!r}, directory_digest={!r})'.format(
self.path,
self.directory_digest,
)
@classmethod
def is_artifact_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return isinstance(classpath_entry, ArtifactClasspathEntry)
@classmethod
def is_internal_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return not cls.is_artifact_classpath_entry(classpath_entry)
class ArtifactClasspathEntry(ClasspathEntry):
"""Represents a resolved third party classpath entry.
:API: public
"""
def __init__(self, path, coordinate, cache_path, directory_digest=None):
super(ArtifactClasspathEntry, self).__init__(path, directory_digest)
self._coordinate = coordinate
self._cache_path = cache_path
@property
def coordinate(self):
"""Returns the maven coordinate that used to resolve this classpath entry's artifact.
:rtype: :class:`pants.java.jar.M2Coordinate`
"""
return self._coordinate
@property
def cache_path(self):
"""Returns the external cache path of this classpath entry.
For example, the `~/.m2/repository` or `~/.ivy2/cache` location of the resolved artifact for
maven and ivy resolvers respectively.
Suitable for use in constructing classpaths for external tools that should not be subject to
potential volatility in pants own internal caches.
:API: public
:rtype: string
"""
return self._cache_path
def is_excluded_by(self, excludes):
return any(_matches_exclude(self.coordinate, exclude) for exclude in excludes)
def __hash__(self):
return hash((self.path, self.coordinate, self.cache_path))
def __eq__(self, other):
return (isinstance(other, ArtifactClasspathEntry) and
self.path == other.path and
self.coordinate == other.coordinate and
self.cache_path == other.cache_path and
self.directory_digest == other.directory_digest)
def __ne__(self, other):
return not self == other
def __repr__(self):
return (
'ArtifactClasspathEntry(path={!r}, coordinate={!r}, cache_path={!r}, directory_digest={!r})'
.format(self.path, self.coordinate, self.cache_path, self.directory_digest)
)
def _matches_exclude(coordinate, exclude):
if not coordinate.org == exclude.org:
return False
if not exclude.name:
return True
if coordinate.name == exclude.name:
return True
return False | def __init__(self, path, directory_digest=None):
self._path = path | random_line_split |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db_args
from common import add_plot_limit_args
from common import set_db_connection
from common import set_plot_limits
def parse_args(*argument_list):
parser = argparse.ArgumentParser()
source_group = parser.add_mutually_exclusive_group(required=True)
source_group.add_argument('--csv')
source_group.add_argument('--table')
source_group.add_argument('--query')
plot_type_group = parser.add_mutually_exclusive_group(required=True)
plot_type_group.add_argument('--scatter', nargs=2)
plot_type_group.add_argument('--histogram')
plot_type_group.add_argument('--hist2d', nargs=2)
plot_type_group.add_argument('--scatter3d', nargs=3)
parser.add_argument('--histogram-bins', type=int, default=100)
parser.add_argument('--filter-num-rtus', type=int)
parser.add_argument('--filter-controller', type=int)
parser.add_argument('--labels',
help='Labels for labeled data (different colors on the '
'plot)')
parser.add_argument('--miscellaneous-cutoff', type=float, default=0.001,
help='Part of the data, that should a label have in '
'order to be show in the plot')
parser.add_argument('--do-not-scale-down', action='store_false',
dest='scale_down')
parser.add_argument('--scale-down', action='store_true')
parser.add_argument('--savefig')
add_plot_limit_args(parser)
add_db_args(parser)
args = parser.parse_args(*argument_list)
if args.csv is None:
set_db_connection(args)
return args
def plot_scatter3d(data, args):
data = data[data[args.scatter3d[0]].notnull()][data[args.scatter3d[1]].notnull()][data[args.scatter3d[2]].notnull()]
data = data[:100000]
print len(data)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[args.scatter3d[0]],
data[args.scatter3d[1]],
data[args.scatter3d[2]])
def _plot_hist2d(data, args):
data = data[data[args.hist2d[0]].notnull()][data[args.hist2d[1]].notnull()]
if data.shape[0] < 1000:
sys.exit(1)
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=args.hist2d)
plt.hist2d(df[args.hist2d[0]].astype(float),
df[args.hist2d[1]].astype(float),
bins=args.histogram_bins,
norm=LogNorm())
plt.colorbar()
set_plot_limits(plt, args)
plt.xlabel(args.hist2d[0])
plt.ylabel(args.hist2d[1])
set_plot_limits(plt, args)
plt.title("N = {}".format(data.shape[0]))
def plot_distribution(args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtus]
print 'after filtering size =', data.shape[0]
if args.filter_controller:
print 'before filtering size =', data.shape[0]
data = data[data['controller_id'] == args.filter_controller]
print 'after filtering size =', data.shape[0]
if 'controller_id' in data:
print 'total controller_ids included =', len(set(data['controller_id']))
if 'num_rtus' in data:
print 'distinct num_rtus =', len(set(data['num_rtus'])), set(data['num_rtus'])
else:
cursor = args.db_connection.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") # noqa
if args.query:
|
else:
sql = """
SELECT {select} FROM {table};
""".format(select='*', table=args.table)
print sql
cursor.execute(sql)
colnames = [desc[0] for desc in cursor.description]
data = pd.DataFrame(cursor.fetchall(), columns=colnames)
# Set args.data, so we can pass only args to functions
args.data = data
data_size = data.shape[0]
if args.scatter is not None:
if args.labels:
interesting_data = data[[args.scatter[0], args.scatter[1], args.labels]]
different_labels = set(data[args.labels])
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
plt.scatter(df[args.scatter[0]], df[args.scatter[1]],
c=color, label=label)
else:
plt.scatter(data[args.scatter[0]], data[args.scatter[1]],
c=color)
plt.xlabel(args.scatter[0])
plt.ylabel(args.scatter[1])
elif args.histogram is not None:
if args.labels:
interesting_data = data[[args.histogram, args.labels]]
different_labels = set(data[args.labels])
data_to_plot, colors_to_use, labels_to_show = [], [], []
miscellaneous_labels = set()
misc_frame, misc_color = pd.DataFrame(), None
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
if df.shape[0] < args.miscellaneous_cutoff * data_size:
miscellaneous_labels.add(label)
misc_frame = pd.concat([misc_frame, df[args.histogram]])
misc_color = color
continue
labels_to_show.append('{label} ({count})'.format(label=label,
count=df.shape[0]))
data_to_plot.append(df[args.histogram])
colors_to_use.append(color)
if misc_color is not None:
labels_to_show.append('miscellaneous ({count})'.format(
count=misc_frame.shape[0]))
data_to_plot.append(misc_frame)
# colors_to_use.append(misc_color)
colors_to_use.append('cyan')
plt.hist(data_to_plot, args.histogram_bins, histtype='bar',
color=colors_to_use, label=labels_to_show)
else:
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=[args.histogram])
plt.hist(df[args.histogram].astype(float),
bins=args.histogram_bins,
label=args.histogram)
plt.yscale('log')
plt.xlabel(args.histogram)
if args.scale_down:
plt.ylim(ymax=int(data_size * args.miscellaneous_cutoff))
elif args.hist2d is not None:
_plot_hist2d(data, args)
elif args.scatter3d is not None:
plot_scatter3d(data, args)
plt.legend()
if not args.scatter3d and not args.histogram:
set_plot_limits(plt, args)
if args.savefig is not None:
plt.savefig(args.savefig, dpi=320)
plt.clf()
else:
plt.show()
if __name__ == '__main__':
args = parse_args()
plot_distribution(args)
| with open(args.query, 'r') as infile:
sql = ''.join(list(infile)) | conditional_block |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db_args
from common import add_plot_limit_args
from common import set_db_connection
from common import set_plot_limits
def parse_args(*argument_list):
parser = argparse.ArgumentParser()
source_group = parser.add_mutually_exclusive_group(required=True)
source_group.add_argument('--csv')
source_group.add_argument('--table')
source_group.add_argument('--query')
plot_type_group = parser.add_mutually_exclusive_group(required=True)
plot_type_group.add_argument('--scatter', nargs=2)
plot_type_group.add_argument('--histogram')
plot_type_group.add_argument('--hist2d', nargs=2)
plot_type_group.add_argument('--scatter3d', nargs=3)
parser.add_argument('--histogram-bins', type=int, default=100)
parser.add_argument('--filter-num-rtus', type=int)
parser.add_argument('--filter-controller', type=int)
parser.add_argument('--labels',
help='Labels for labeled data (different colors on the '
'plot)')
parser.add_argument('--miscellaneous-cutoff', type=float, default=0.001,
help='Part of the data, that should a label have in '
'order to be show in the plot')
parser.add_argument('--do-not-scale-down', action='store_false',
dest='scale_down')
parser.add_argument('--scale-down', action='store_true')
parser.add_argument('--savefig')
add_plot_limit_args(parser)
add_db_args(parser)
args = parser.parse_args(*argument_list)
if args.csv is None:
set_db_connection(args)
return args
def plot_scatter3d(data, args):
data = data[data[args.scatter3d[0]].notnull()][data[args.scatter3d[1]].notnull()][data[args.scatter3d[2]].notnull()]
data = data[:100000]
print len(data)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[args.scatter3d[0]],
data[args.scatter3d[1]],
data[args.scatter3d[2]])
def _plot_hist2d(data, args):
data = data[data[args.hist2d[0]].notnull()][data[args.hist2d[1]].notnull()]
if data.shape[0] < 1000:
sys.exit(1)
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=args.hist2d)
plt.hist2d(df[args.hist2d[0]].astype(float),
df[args.hist2d[1]].astype(float),
bins=args.histogram_bins,
norm=LogNorm())
plt.colorbar()
set_plot_limits(plt, args) | plt.title("N = {}".format(data.shape[0]))
def plot_distribution(args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtus]
print 'after filtering size =', data.shape[0]
if args.filter_controller:
print 'before filtering size =', data.shape[0]
data = data[data['controller_id'] == args.filter_controller]
print 'after filtering size =', data.shape[0]
if 'controller_id' in data:
print 'total controller_ids included =', len(set(data['controller_id']))
if 'num_rtus' in data:
print 'distinct num_rtus =', len(set(data['num_rtus'])), set(data['num_rtus'])
else:
cursor = args.db_connection.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") # noqa
if args.query:
with open(args.query, 'r') as infile:
sql = ''.join(list(infile))
else:
sql = """
SELECT {select} FROM {table};
""".format(select='*', table=args.table)
print sql
cursor.execute(sql)
colnames = [desc[0] for desc in cursor.description]
data = pd.DataFrame(cursor.fetchall(), columns=colnames)
# Set args.data, so we can pass only args to functions
args.data = data
data_size = data.shape[0]
if args.scatter is not None:
if args.labels:
interesting_data = data[[args.scatter[0], args.scatter[1], args.labels]]
different_labels = set(data[args.labels])
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
plt.scatter(df[args.scatter[0]], df[args.scatter[1]],
c=color, label=label)
else:
plt.scatter(data[args.scatter[0]], data[args.scatter[1]],
c=color)
plt.xlabel(args.scatter[0])
plt.ylabel(args.scatter[1])
elif args.histogram is not None:
if args.labels:
interesting_data = data[[args.histogram, args.labels]]
different_labels = set(data[args.labels])
data_to_plot, colors_to_use, labels_to_show = [], [], []
miscellaneous_labels = set()
misc_frame, misc_color = pd.DataFrame(), None
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
if df.shape[0] < args.miscellaneous_cutoff * data_size:
miscellaneous_labels.add(label)
misc_frame = pd.concat([misc_frame, df[args.histogram]])
misc_color = color
continue
labels_to_show.append('{label} ({count})'.format(label=label,
count=df.shape[0]))
data_to_plot.append(df[args.histogram])
colors_to_use.append(color)
if misc_color is not None:
labels_to_show.append('miscellaneous ({count})'.format(
count=misc_frame.shape[0]))
data_to_plot.append(misc_frame)
# colors_to_use.append(misc_color)
colors_to_use.append('cyan')
plt.hist(data_to_plot, args.histogram_bins, histtype='bar',
color=colors_to_use, label=labels_to_show)
else:
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=[args.histogram])
plt.hist(df[args.histogram].astype(float),
bins=args.histogram_bins,
label=args.histogram)
plt.yscale('log')
plt.xlabel(args.histogram)
if args.scale_down:
plt.ylim(ymax=int(data_size * args.miscellaneous_cutoff))
elif args.hist2d is not None:
_plot_hist2d(data, args)
elif args.scatter3d is not None:
plot_scatter3d(data, args)
plt.legend()
if not args.scatter3d and not args.histogram:
set_plot_limits(plt, args)
if args.savefig is not None:
plt.savefig(args.savefig, dpi=320)
plt.clf()
else:
plt.show()
if __name__ == '__main__':
args = parse_args()
plot_distribution(args) | plt.xlabel(args.hist2d[0])
plt.ylabel(args.hist2d[1])
set_plot_limits(plt, args) | random_line_split |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db_args
from common import add_plot_limit_args
from common import set_db_connection
from common import set_plot_limits
def parse_args(*argument_list):
parser = argparse.ArgumentParser()
source_group = parser.add_mutually_exclusive_group(required=True)
source_group.add_argument('--csv')
source_group.add_argument('--table')
source_group.add_argument('--query')
plot_type_group = parser.add_mutually_exclusive_group(required=True)
plot_type_group.add_argument('--scatter', nargs=2)
plot_type_group.add_argument('--histogram')
plot_type_group.add_argument('--hist2d', nargs=2)
plot_type_group.add_argument('--scatter3d', nargs=3)
parser.add_argument('--histogram-bins', type=int, default=100)
parser.add_argument('--filter-num-rtus', type=int)
parser.add_argument('--filter-controller', type=int)
parser.add_argument('--labels',
help='Labels for labeled data (different colors on the '
'plot)')
parser.add_argument('--miscellaneous-cutoff', type=float, default=0.001,
help='Part of the data, that should a label have in '
'order to be show in the plot')
parser.add_argument('--do-not-scale-down', action='store_false',
dest='scale_down')
parser.add_argument('--scale-down', action='store_true')
parser.add_argument('--savefig')
add_plot_limit_args(parser)
add_db_args(parser)
args = parser.parse_args(*argument_list)
if args.csv is None:
set_db_connection(args)
return args
def plot_scatter3d(data, args):
data = data[data[args.scatter3d[0]].notnull()][data[args.scatter3d[1]].notnull()][data[args.scatter3d[2]].notnull()]
data = data[:100000]
print len(data)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[args.scatter3d[0]],
data[args.scatter3d[1]],
data[args.scatter3d[2]])
def _plot_hist2d(data, args):
data = data[data[args.hist2d[0]].notnull()][data[args.hist2d[1]].notnull()]
if data.shape[0] < 1000:
sys.exit(1)
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=args.hist2d)
plt.hist2d(df[args.hist2d[0]].astype(float),
df[args.hist2d[1]].astype(float),
bins=args.histogram_bins,
norm=LogNorm())
plt.colorbar()
set_plot_limits(plt, args)
plt.xlabel(args.hist2d[0])
plt.ylabel(args.hist2d[1])
set_plot_limits(plt, args)
plt.title("N = {}".format(data.shape[0]))
def | (args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtus]
print 'after filtering size =', data.shape[0]
if args.filter_controller:
print 'before filtering size =', data.shape[0]
data = data[data['controller_id'] == args.filter_controller]
print 'after filtering size =', data.shape[0]
if 'controller_id' in data:
print 'total controller_ids included =', len(set(data['controller_id']))
if 'num_rtus' in data:
print 'distinct num_rtus =', len(set(data['num_rtus'])), set(data['num_rtus'])
else:
cursor = args.db_connection.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") # noqa
if args.query:
with open(args.query, 'r') as infile:
sql = ''.join(list(infile))
else:
sql = """
SELECT {select} FROM {table};
""".format(select='*', table=args.table)
print sql
cursor.execute(sql)
colnames = [desc[0] for desc in cursor.description]
data = pd.DataFrame(cursor.fetchall(), columns=colnames)
# Set args.data, so we can pass only args to functions
args.data = data
data_size = data.shape[0]
if args.scatter is not None:
if args.labels:
interesting_data = data[[args.scatter[0], args.scatter[1], args.labels]]
different_labels = set(data[args.labels])
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
plt.scatter(df[args.scatter[0]], df[args.scatter[1]],
c=color, label=label)
else:
plt.scatter(data[args.scatter[0]], data[args.scatter[1]],
c=color)
plt.xlabel(args.scatter[0])
plt.ylabel(args.scatter[1])
elif args.histogram is not None:
if args.labels:
interesting_data = data[[args.histogram, args.labels]]
different_labels = set(data[args.labels])
data_to_plot, colors_to_use, labels_to_show = [], [], []
miscellaneous_labels = set()
misc_frame, misc_color = pd.DataFrame(), None
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
if df.shape[0] < args.miscellaneous_cutoff * data_size:
miscellaneous_labels.add(label)
misc_frame = pd.concat([misc_frame, df[args.histogram]])
misc_color = color
continue
labels_to_show.append('{label} ({count})'.format(label=label,
count=df.shape[0]))
data_to_plot.append(df[args.histogram])
colors_to_use.append(color)
if misc_color is not None:
labels_to_show.append('miscellaneous ({count})'.format(
count=misc_frame.shape[0]))
data_to_plot.append(misc_frame)
# colors_to_use.append(misc_color)
colors_to_use.append('cyan')
plt.hist(data_to_plot, args.histogram_bins, histtype='bar',
color=colors_to_use, label=labels_to_show)
else:
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=[args.histogram])
plt.hist(df[args.histogram].astype(float),
bins=args.histogram_bins,
label=args.histogram)
plt.yscale('log')
plt.xlabel(args.histogram)
if args.scale_down:
plt.ylim(ymax=int(data_size * args.miscellaneous_cutoff))
elif args.hist2d is not None:
_plot_hist2d(data, args)
elif args.scatter3d is not None:
plot_scatter3d(data, args)
plt.legend()
if not args.scatter3d and not args.histogram:
set_plot_limits(plt, args)
if args.savefig is not None:
plt.savefig(args.savefig, dpi=320)
plt.clf()
else:
plt.show()
if __name__ == '__main__':
args = parse_args()
plot_distribution(args)
| plot_distribution | identifier_name |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db_args
from common import add_plot_limit_args
from common import set_db_connection
from common import set_plot_limits
def parse_args(*argument_list):
parser = argparse.ArgumentParser()
source_group = parser.add_mutually_exclusive_group(required=True)
source_group.add_argument('--csv')
source_group.add_argument('--table')
source_group.add_argument('--query')
plot_type_group = parser.add_mutually_exclusive_group(required=True)
plot_type_group.add_argument('--scatter', nargs=2)
plot_type_group.add_argument('--histogram')
plot_type_group.add_argument('--hist2d', nargs=2)
plot_type_group.add_argument('--scatter3d', nargs=3)
parser.add_argument('--histogram-bins', type=int, default=100)
parser.add_argument('--filter-num-rtus', type=int)
parser.add_argument('--filter-controller', type=int)
parser.add_argument('--labels',
help='Labels for labeled data (different colors on the '
'plot)')
parser.add_argument('--miscellaneous-cutoff', type=float, default=0.001,
help='Part of the data, that should a label have in '
'order to be show in the plot')
parser.add_argument('--do-not-scale-down', action='store_false',
dest='scale_down')
parser.add_argument('--scale-down', action='store_true')
parser.add_argument('--savefig')
add_plot_limit_args(parser)
add_db_args(parser)
args = parser.parse_args(*argument_list)
if args.csv is None:
set_db_connection(args)
return args
def plot_scatter3d(data, args):
data = data[data[args.scatter3d[0]].notnull()][data[args.scatter3d[1]].notnull()][data[args.scatter3d[2]].notnull()]
data = data[:100000]
print len(data)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[args.scatter3d[0]],
data[args.scatter3d[1]],
data[args.scatter3d[2]])
def _plot_hist2d(data, args):
|
def plot_distribution(args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtus]
print 'after filtering size =', data.shape[0]
if args.filter_controller:
print 'before filtering size =', data.shape[0]
data = data[data['controller_id'] == args.filter_controller]
print 'after filtering size =', data.shape[0]
if 'controller_id' in data:
print 'total controller_ids included =', len(set(data['controller_id']))
if 'num_rtus' in data:
print 'distinct num_rtus =', len(set(data['num_rtus'])), set(data['num_rtus'])
else:
cursor = args.db_connection.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") # noqa
if args.query:
with open(args.query, 'r') as infile:
sql = ''.join(list(infile))
else:
sql = """
SELECT {select} FROM {table};
""".format(select='*', table=args.table)
print sql
cursor.execute(sql)
colnames = [desc[0] for desc in cursor.description]
data = pd.DataFrame(cursor.fetchall(), columns=colnames)
# Set args.data, so we can pass only args to functions
args.data = data
data_size = data.shape[0]
if args.scatter is not None:
if args.labels:
interesting_data = data[[args.scatter[0], args.scatter[1], args.labels]]
different_labels = set(data[args.labels])
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
plt.scatter(df[args.scatter[0]], df[args.scatter[1]],
c=color, label=label)
else:
plt.scatter(data[args.scatter[0]], data[args.scatter[1]],
c=color)
plt.xlabel(args.scatter[0])
plt.ylabel(args.scatter[1])
elif args.histogram is not None:
if args.labels:
interesting_data = data[[args.histogram, args.labels]]
different_labels = set(data[args.labels])
data_to_plot, colors_to_use, labels_to_show = [], [], []
miscellaneous_labels = set()
misc_frame, misc_color = pd.DataFrame(), None
for label, color in zip(different_labels,
matplotlib.colors.cnames.keys()):
df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label))
if df.shape[0] < args.miscellaneous_cutoff * data_size:
miscellaneous_labels.add(label)
misc_frame = pd.concat([misc_frame, df[args.histogram]])
misc_color = color
continue
labels_to_show.append('{label} ({count})'.format(label=label,
count=df.shape[0]))
data_to_plot.append(df[args.histogram])
colors_to_use.append(color)
if misc_color is not None:
labels_to_show.append('miscellaneous ({count})'.format(
count=misc_frame.shape[0]))
data_to_plot.append(misc_frame)
# colors_to_use.append(misc_color)
colors_to_use.append('cyan')
plt.hist(data_to_plot, args.histogram_bins, histtype='bar',
color=colors_to_use, label=labels_to_show)
else:
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=[args.histogram])
plt.hist(df[args.histogram].astype(float),
bins=args.histogram_bins,
label=args.histogram)
plt.yscale('log')
plt.xlabel(args.histogram)
if args.scale_down:
plt.ylim(ymax=int(data_size * args.miscellaneous_cutoff))
elif args.hist2d is not None:
_plot_hist2d(data, args)
elif args.scatter3d is not None:
plot_scatter3d(data, args)
plt.legend()
if not args.scatter3d and not args.histogram:
set_plot_limits(plt, args)
if args.savefig is not None:
plt.savefig(args.savefig, dpi=320)
plt.clf()
else:
plt.show()
if __name__ == '__main__':
args = parse_args()
plot_distribution(args)
| data = data[data[args.hist2d[0]].notnull()][data[args.hist2d[1]].notnull()]
if data.shape[0] < 1000:
sys.exit(1)
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=args.hist2d)
plt.hist2d(df[args.hist2d[0]].astype(float),
df[args.hist2d[1]].astype(float),
bins=args.histogram_bins,
norm=LogNorm())
plt.colorbar()
set_plot_limits(plt, args)
plt.xlabel(args.hist2d[0])
plt.ylabel(args.hist2d[1])
set_plot_limits(plt, args)
plt.title("N = {}".format(data.shape[0])) | identifier_body |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieParser = require('cookie-parser'),
bodyParser = require("body-parser");
// Create a prototypical class for our own chatbot.
var AsyncBot = function(onReady) {
var self = this; | rs.loadDirectory("./eg/brain", function() {
rs.sortReplies();
onReady();
});
// This is a function for delivering the message to a user. Its actual
// implementation could vary; for example if you were writing an IRC chatbot
// this message could deliver a private message to a target username.
self.sendMessage = function(username, message) {
// This just logs it to the console like "[Bot] @username: message"
console.log(
["[Brick Tamland]", message].join(": ").underline.green
);
};
// This is a function for a user requesting a reply. It just proxies through
// to RiveScript.
self.getReply = function(username, message, callback) {
return rs.replyAsync(username, message, self).then(function(reply){
callback.call(this, null, reply);
}).catch(function(error) {
callback.call(this, error);
});
}
};
var guest = 0;
// Create and run the example bot.
var bot = new AsyncBot(function() {
// Set up the Express app.
var app = express();
app.use(cookieParser());
app.use('/BOTeo/public', express.static('public'))
// Parse application/json inputs.
app.use(bodyParser.json());
app.set("json spaces", 4);
// Set up routes.
app.post("/BOTeo/reply", getReply);
app.get("/", showUsage);
//app.get("*", showUsage);
// Start listening.
app.listen(2001, function() {
console.log("Listening on http://localhost:2001");
});
});
// POST to /reply to get a RiveScript reply.
function getReply(req, res) {
// Get data from the JSON post.
var message = req.body.message;
var vars = req.body.vars;
var username = req.body.username;
if (req.cookies.username) {
username = req.cookies.username;
} else {
username = "guest" + guest++;
console.log(username);
res.cookie('username', username, { maxAge: 100000 * 60 });
}
/*
if (username == undefined) {
username = "guest" + guest++;
};
*/
console.log(username);
// Make sure username and message are included.
if (typeof(message) === "undefined") {
return error(res, "message is a required key");
}
// Copy any user vars from the post into RiveScript.
if (typeof(vars) !== "undefined") {
for (var key in vars) {
if (vars.hasOwnProperty(key)) {
rs.setUservar(username, key, vars[key]);
}
}
rs.setUservar(username, "username", username);
}
var reply = bot.getReply(username, message, function(error, reply){
if (error) {
res.json({
"status": "ko",
"reply": error,
"vars": vars
});
} else {
// Get all the user's vars back out of the bot to include in the response.
vars = rs.getUservars(username);
// Send the JSON response.
res.json({
"status": "ok",
"reply": reply,
"vars": vars
});
}
});
};
// All other routes shows the usage to test the /reply route.
function showUsage(req, res) {
var egPayload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso"
}
};
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Usage: curl -i \\\n");
res.write(" -H \"Content-Type: application/json\" \\\n");
res.write(" -X POST -d '" + JSON.stringify(egPayload) + "' \\\n");
res.write(" http://localhost:2001/BOTeo/reply");
res.end();
}
// Send a JSON error to the browser.
function error(res, message) {
res.json({
"status": "error",
"message": message
});
} |
// Load the replies and process them. | random_line_split |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieParser = require('cookie-parser'),
bodyParser = require("body-parser");
// Create a prototypical class for our own chatbot.
var AsyncBot = function(onReady) {
var self = this;
// Load the replies and process them.
rs.loadDirectory("./eg/brain", function() {
rs.sortReplies();
onReady();
});
// This is a function for delivering the message to a user. Its actual
// implementation could vary; for example if you were writing an IRC chatbot
// this message could deliver a private message to a target username.
self.sendMessage = function(username, message) {
// This just logs it to the console like "[Bot] @username: message"
console.log(
["[Brick Tamland]", message].join(": ").underline.green
);
};
// This is a function for a user requesting a reply. It just proxies through
// to RiveScript.
self.getReply = function(username, message, callback) {
return rs.replyAsync(username, message, self).then(function(reply){
callback.call(this, null, reply);
}).catch(function(error) {
callback.call(this, error);
});
}
};
var guest = 0;
// Create and run the example bot.
var bot = new AsyncBot(function() {
// Set up the Express app.
var app = express();
app.use(cookieParser());
app.use('/BOTeo/public', express.static('public'))
// Parse application/json inputs.
app.use(bodyParser.json());
app.set("json spaces", 4);
// Set up routes.
app.post("/BOTeo/reply", getReply);
app.get("/", showUsage);
//app.get("*", showUsage);
// Start listening.
app.listen(2001, function() {
console.log("Listening on http://localhost:2001");
});
});
// POST to /reply to get a RiveScript reply.
function getReply(req, res) {
// Get data from the JSON post.
var message = req.body.message;
var vars = req.body.vars;
var username = req.body.username;
if (req.cookies.username) | else {
username = "guest" + guest++;
console.log(username);
res.cookie('username', username, { maxAge: 100000 * 60 });
}
/*
if (username == undefined) {
username = "guest" + guest++;
};
*/
console.log(username);
// Make sure username and message are included.
if (typeof(message) === "undefined") {
return error(res, "message is a required key");
}
// Copy any user vars from the post into RiveScript.
if (typeof(vars) !== "undefined") {
for (var key in vars) {
if (vars.hasOwnProperty(key)) {
rs.setUservar(username, key, vars[key]);
}
}
rs.setUservar(username, "username", username);
}
var reply = bot.getReply(username, message, function(error, reply){
if (error) {
res.json({
"status": "ko",
"reply": error,
"vars": vars
});
} else {
// Get all the user's vars back out of the bot to include in the response.
vars = rs.getUservars(username);
// Send the JSON response.
res.json({
"status": "ok",
"reply": reply,
"vars": vars
});
}
});
};
// All other routes shows the usage to test the /reply route.
function showUsage(req, res) {
var egPayload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso"
}
};
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Usage: curl -i \\\n");
res.write(" -H \"Content-Type: application/json\" \\\n");
res.write(" -X POST -d '" + JSON.stringify(egPayload) + "' \\\n");
res.write(" http://localhost:2001/BOTeo/reply");
res.end();
}
// Send a JSON error to the browser.
function error(res, message) {
res.json({
"status": "error",
"message": message
});
}
| {
username = req.cookies.username;
} | conditional_block |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieParser = require('cookie-parser'),
bodyParser = require("body-parser");
// Create a prototypical class for our own chatbot.
var AsyncBot = function(onReady) {
var self = this;
// Load the replies and process them.
rs.loadDirectory("./eg/brain", function() {
rs.sortReplies();
onReady();
});
// This is a function for delivering the message to a user. Its actual
// implementation could vary; for example if you were writing an IRC chatbot
// this message could deliver a private message to a target username.
self.sendMessage = function(username, message) {
// This just logs it to the console like "[Bot] @username: message"
console.log(
["[Brick Tamland]", message].join(": ").underline.green
);
};
// This is a function for a user requesting a reply. It just proxies through
// to RiveScript.
self.getReply = function(username, message, callback) {
return rs.replyAsync(username, message, self).then(function(reply){
callback.call(this, null, reply);
}).catch(function(error) {
callback.call(this, error);
});
}
};
var guest = 0;
// Create and run the example bot.
var bot = new AsyncBot(function() {
// Set up the Express app.
var app = express();
app.use(cookieParser());
app.use('/BOTeo/public', express.static('public'))
// Parse application/json inputs.
app.use(bodyParser.json());
app.set("json spaces", 4);
// Set up routes.
app.post("/BOTeo/reply", getReply);
app.get("/", showUsage);
//app.get("*", showUsage);
// Start listening.
app.listen(2001, function() {
console.log("Listening on http://localhost:2001");
});
});
// POST to /reply to get a RiveScript reply.
function getReply(req, res) | ;
// All other routes shows the usage to test the /reply route.
function showUsage(req, res) {
var egPayload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso"
}
};
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Usage: curl -i \\\n");
res.write(" -H \"Content-Type: application/json\" \\\n");
res.write(" -X POST -d '" + JSON.stringify(egPayload) + "' \\\n");
res.write(" http://localhost:2001/BOTeo/reply");
res.end();
}
// Send a JSON error to the browser.
function error(res, message) {
res.json({
"status": "error",
"message": message
});
}
| {
// Get data from the JSON post.
var message = req.body.message;
var vars = req.body.vars;
var username = req.body.username;
if (req.cookies.username) {
username = req.cookies.username;
} else {
username = "guest" + guest++;
console.log(username);
res.cookie('username', username, { maxAge: 100000 * 60 });
}
/*
if (username == undefined) {
username = "guest" + guest++;
};
*/
console.log(username);
// Make sure username and message are included.
if (typeof(message) === "undefined") {
return error(res, "message is a required key");
}
// Copy any user vars from the post into RiveScript.
if (typeof(vars) !== "undefined") {
for (var key in vars) {
if (vars.hasOwnProperty(key)) {
rs.setUservar(username, key, vars[key]);
}
}
rs.setUservar(username, "username", username);
}
var reply = bot.getReply(username, message, function(error, reply){
if (error) {
res.json({
"status": "ko",
"reply": error,
"vars": vars
});
} else {
// Get all the user's vars back out of the bot to include in the response.
vars = rs.getUservars(username);
// Send the JSON response.
res.json({
"status": "ok",
"reply": reply,
"vars": vars
});
}
});
} | identifier_body |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieParser = require('cookie-parser'),
bodyParser = require("body-parser");
// Create a prototypical class for our own chatbot.
var AsyncBot = function(onReady) {
var self = this;
// Load the replies and process them.
rs.loadDirectory("./eg/brain", function() {
rs.sortReplies();
onReady();
});
// This is a function for delivering the message to a user. Its actual
// implementation could vary; for example if you were writing an IRC chatbot
// this message could deliver a private message to a target username.
self.sendMessage = function(username, message) {
// This just logs it to the console like "[Bot] @username: message"
console.log(
["[Brick Tamland]", message].join(": ").underline.green
);
};
// This is a function for a user requesting a reply. It just proxies through
// to RiveScript.
self.getReply = function(username, message, callback) {
return rs.replyAsync(username, message, self).then(function(reply){
callback.call(this, null, reply);
}).catch(function(error) {
callback.call(this, error);
});
}
};
var guest = 0;
// Create and run the example bot.
var bot = new AsyncBot(function() {
// Set up the Express app.
var app = express();
app.use(cookieParser());
app.use('/BOTeo/public', express.static('public'))
// Parse application/json inputs.
app.use(bodyParser.json());
app.set("json spaces", 4);
// Set up routes.
app.post("/BOTeo/reply", getReply);
app.get("/", showUsage);
//app.get("*", showUsage);
// Start listening.
app.listen(2001, function() {
console.log("Listening on http://localhost:2001");
});
});
// POST to /reply to get a RiveScript reply.
function getReply(req, res) {
// Get data from the JSON post.
var message = req.body.message;
var vars = req.body.vars;
var username = req.body.username;
if (req.cookies.username) {
username = req.cookies.username;
} else {
username = "guest" + guest++;
console.log(username);
res.cookie('username', username, { maxAge: 100000 * 60 });
}
/*
if (username == undefined) {
username = "guest" + guest++;
};
*/
console.log(username);
// Make sure username and message are included.
if (typeof(message) === "undefined") {
return error(res, "message is a required key");
}
// Copy any user vars from the post into RiveScript.
if (typeof(vars) !== "undefined") {
for (var key in vars) {
if (vars.hasOwnProperty(key)) {
rs.setUservar(username, key, vars[key]);
}
}
rs.setUservar(username, "username", username);
}
var reply = bot.getReply(username, message, function(error, reply){
if (error) {
res.json({
"status": "ko",
"reply": error,
"vars": vars
});
} else {
// Get all the user's vars back out of the bot to include in the response.
vars = rs.getUservars(username);
// Send the JSON response.
res.json({
"status": "ok",
"reply": reply,
"vars": vars
});
}
});
};
// All other routes shows the usage to test the /reply route.
function showUsage(req, res) {
var egPayload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso"
}
};
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Usage: curl -i \\\n");
res.write(" -H \"Content-Type: application/json\" \\\n");
res.write(" -X POST -d '" + JSON.stringify(egPayload) + "' \\\n");
res.write(" http://localhost:2001/BOTeo/reply");
res.end();
}
// Send a JSON error to the browser.
function | (res, message) {
res.json({
"status": "error",
"message": message
});
}
| error | identifier_name |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function gameObj(eventId, name, image, rules, scoreType) {
this.eventId = eventId;
this.name = name; // str
this.image = image; // url
this.rules = rules; // str
this.scoreType = scoreType; // str
}
self.games = ko.observableArray([]);
function getGames() {
// http.get(app.url+'event/78f9075c-f81c-42fe-9d50-63e666b5450d/games').then(function(response) {
// for(var i = 0; i < response.items.length; i++) {
// self.games.push(new gameObj("NAME", response.items[i].media.m, "HDLSFHSD", "sdfhjksdhfdjs"));
// }
// });
http.get('https://public.opencpu.org/ocpu/library/').then(function(response) {
console.dir(response);
for(var i = 0; i < response.items.length; i++) {
self.games.unshift(new gameObj(app.event.id, "game name", response.items[i].media.m, "rules", "timed"));
}
});
}
| this.showHeader = true;
this.title = 'Games';
this.addingGame = ko.observable(false);
this.imgSrc = function() {
var randomNum1 = Math.round((Math.random()*100+300)/10)*10;
var randomNum2 = Math.round((Math.random()*100+200)/10)*10;
return "http://placesheen.com/"+randomNum1+"/"+randomNum2;
};
this.newItem = function(game) {
var gaaame = new NewGame();
gaaame.game = game || new gameObj(app.event.id, "", "", "", "timed");
app.showDialog(gaaame).then(function(result) {
if(result) {
console.dir(result);
//http.post(app.url+'event/'+app.event.id+'/games/', JSON.stringify(result)).then(function(response) {
self.games.unshift(new gameObj(result.eventId, result.name, "", result.rules, result.scoreType));
//});
}
});
};
getGames();
};
return ctor;
}); | random_line_split |
|
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function gameObj(eventId, name, image, rules, scoreType) |
self.games = ko.observableArray([]);
function getGames() {
// http.get(app.url+'event/78f9075c-f81c-42fe-9d50-63e666b5450d/games').then(function(response) {
// for(var i = 0; i < response.items.length; i++) {
// self.games.push(new gameObj("NAME", response.items[i].media.m, "HDLSFHSD", "sdfhjksdhfdjs"));
// }
// });
http.get('https://public.opencpu.org/ocpu/library/').then(function(response) {
console.dir(response);
for(var i = 0; i < response.items.length; i++) {
self.games.unshift(new gameObj(app.event.id, "game name", response.items[i].media.m, "rules", "timed"));
}
});
}
this.showHeader = true;
this.title = 'Games';
this.addingGame = ko.observable(false);
this.imgSrc = function() {
var randomNum1 = Math.round((Math.random()*100+300)/10)*10;
var randomNum2 = Math.round((Math.random()*100+200)/10)*10;
return "http://placesheen.com/"+randomNum1+"/"+randomNum2;
};
this.newItem = function(game) {
var gaaame = new NewGame();
gaaame.game = game || new gameObj(app.event.id, "", "", "", "timed");
app.showDialog(gaaame).then(function(result) {
if(result) {
console.dir(result);
//http.post(app.url+'event/'+app.event.id+'/games/', JSON.stringify(result)).then(function(response) {
self.games.unshift(new gameObj(result.eventId, result.name, "", result.rules, result.scoreType));
//});
}
});
};
getGames();
};
return ctor;
}); | {
this.eventId = eventId;
this.name = name; // str
this.image = image; // url
this.rules = rules; // str
this.scoreType = scoreType; // str
} | identifier_body |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function | (eventId, name, image, rules, scoreType) {
this.eventId = eventId;
this.name = name; // str
this.image = image; // url
this.rules = rules; // str
this.scoreType = scoreType; // str
}
self.games = ko.observableArray([]);
function getGames() {
// http.get(app.url+'event/78f9075c-f81c-42fe-9d50-63e666b5450d/games').then(function(response) {
// for(var i = 0; i < response.items.length; i++) {
// self.games.push(new gameObj("NAME", response.items[i].media.m, "HDLSFHSD", "sdfhjksdhfdjs"));
// }
// });
http.get('https://public.opencpu.org/ocpu/library/').then(function(response) {
console.dir(response);
for(var i = 0; i < response.items.length; i++) {
self.games.unshift(new gameObj(app.event.id, "game name", response.items[i].media.m, "rules", "timed"));
}
});
}
this.showHeader = true;
this.title = 'Games';
this.addingGame = ko.observable(false);
this.imgSrc = function() {
var randomNum1 = Math.round((Math.random()*100+300)/10)*10;
var randomNum2 = Math.round((Math.random()*100+200)/10)*10;
return "http://placesheen.com/"+randomNum1+"/"+randomNum2;
};
this.newItem = function(game) {
var gaaame = new NewGame();
gaaame.game = game || new gameObj(app.event.id, "", "", "", "timed");
app.showDialog(gaaame).then(function(result) {
if(result) {
console.dir(result);
//http.post(app.url+'event/'+app.event.id+'/games/', JSON.stringify(result)).then(function(response) {
self.games.unshift(new gameObj(result.eventId, result.name, "", result.rules, result.scoreType));
//});
}
});
};
getGames();
};
return ctor;
}); | gameObj | identifier_name |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function gameObj(eventId, name, image, rules, scoreType) {
this.eventId = eventId;
this.name = name; // str
this.image = image; // url
this.rules = rules; // str
this.scoreType = scoreType; // str
}
self.games = ko.observableArray([]);
function getGames() {
// http.get(app.url+'event/78f9075c-f81c-42fe-9d50-63e666b5450d/games').then(function(response) {
// for(var i = 0; i < response.items.length; i++) {
// self.games.push(new gameObj("NAME", response.items[i].media.m, "HDLSFHSD", "sdfhjksdhfdjs"));
// }
// });
http.get('https://public.opencpu.org/ocpu/library/').then(function(response) {
console.dir(response);
for(var i = 0; i < response.items.length; i++) {
self.games.unshift(new gameObj(app.event.id, "game name", response.items[i].media.m, "rules", "timed"));
}
});
}
this.showHeader = true;
this.title = 'Games';
this.addingGame = ko.observable(false);
this.imgSrc = function() {
var randomNum1 = Math.round((Math.random()*100+300)/10)*10;
var randomNum2 = Math.round((Math.random()*100+200)/10)*10;
return "http://placesheen.com/"+randomNum1+"/"+randomNum2;
};
this.newItem = function(game) {
var gaaame = new NewGame();
gaaame.game = game || new gameObj(app.event.id, "", "", "", "timed");
app.showDialog(gaaame).then(function(result) {
if(result) |
});
};
getGames();
};
return ctor;
}); | {
console.dir(result);
//http.post(app.url+'event/'+app.event.id+'/games/', JSON.stringify(result)).then(function(response) {
self.games.unshift(new gameObj(result.eventId, result.name, "", result.rules, result.scoreType));
//});
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.