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 |
|---|---|---|---|---|
MCEImageBrowserDialog.js | class InsertImageDialog extends ConfirmMessageDialog {
constructor() {
super();
this.contents = "";
/**
*
* @type {MessageDialog}
*/
this.parent = null;
this.icon_enabled = false;
this.itemClass = "MCEImagesBean";
}
setImageID(imageID) {
this.imageID = imageID;
}
setParent(dialog) {
this.parent = dialog;
}
setContents(contents) {
this.contents = contents;
this.setText(this.contents);
}
buttonAction(action) {
if (action == "confirm") {
this.confirm();
} else if (action == "cancel") {
this.remove();
}
}
confirm() {
let image_url = new URL(STORAGE_LOCAL, location.href);
image_url.searchParams.set("cmd", "image");
image_url.searchParams.set("class", this.itemClass);
image_url.searchParams.set("id", this.imageID);
let form = this.modal_pane.popup.find("FORM");
let render_mode = form.find("[name='render_mode']").val();
let caption = form.find("[name='caption']").val();
let enable_popup = form.find("[name='enable_popup']");
let width = parseInt(form.find("[name='width']").val());
let height = parseInt(form.find("[name='height']").val());
if (isNaN(width) || width < 1) {
width = -1;
}
if (isNaN(height) || height < 1) {
height = -1;
}
if (width < 1 && height < 1) {
showAlert("One of width or height should be positive number");
return;
}
let image_tag = $("<img>");
if (render_mode == "fit_prc") {
if (width>0) {
image_tag.attr("width", "" + width + "%");
}
if (height>0) {
image_tag.attr("height", "" + height + "%");
}
}
else if (render_mode == "fit_px") {
image_url.searchParams.set("width", width);
image_url.searchParams.set("height", height);
}
image_tag.attr("src", image_url.href);
image_tag.attr("alt", caption);
let final_tag = image_tag;
if (enable_popup.is(":checked")) {
console.log("Enabling popup");
final_tag = $("<a href='#'></a>");
final_tag.attr("class", "ImagePopup");
final_tag.attr("itemID", this.imageID);
final_tag.attr("itemClass", this.itemClass);
final_tag.attr("title", caption);
final_tag.html(image_tag);
}
console.log("Inserting into MCE: " + final_tag.get(0).outerHTML);
this.parent.mce_textarea.editor.execCommand("mceInsertContent", false, final_tag.get(0).outerHTML);
this.remove();
this.parent.remove();
}
show() {
super.show();
this.modal_pane.popup.find(".preview IMG").on("load", function (event) {
this.modal_pane.centerContents();
}.bind(this));
}
}
class MCEImageBrowserDialog extends JSONDialog {
constructor() {
super();
this.setID("mceImage_browser");
this.mce_textarea = null;
this.field_name = null;
this.req.setResponder("mceImage");
this.insert_image = new InsertImageDialog();
this.insert_image.setCaption("Insert Image");
this.insert_image.setParent(this);
}
setMCETextArea(textarea) {
this.mce_textarea = textarea;
}
buttonAction(action, dialog) {
this.remove();
}
processResult(responder, funct, result) {
let jsonResult = result.json_result;
let message = jsonResult.message;
let imageID = this.req.getParameter("imageID");
if (funct == "renderDimensionDialog") {
this.insert_image.setContents(jsonResult.contents);
this.insert_image.setImageID(this.req.getParameter("imageID"));
this.insert_image.show();
} else if (funct == "remove") {
let element = this.modal_pane.popup.find(".ImageStorage .Collection .Element[imageID='" + imageID + "']");
element.remove();
this.modal_pane.centerContents();
} else if (funct == "find") {
const dialog = this;
for (var a = 0; a < jsonResult.result_count; a++) {
var image = jsonResult.objects[a];
this.modal_pane.popup.find(".ImageStorage .Collection").first().append(image.html);
}
this.modal_pane.popup.find(".ImageStorage .Collection .Element").each(function (index) {
let imageID = $(this).attr("imageID");
$(this).on("click", function (event) {
dialog.onClickImage(imageID, event);
return false;
});
let remove_button = $(this).children(".remove_button").first();
remove_button.on("click", function (event) {
dialog.removeImage(imageID, event);
return false;
});
}); //each image
} //find
}
show() {
super.show();
//subsequent shows need clear parameters
this.req.clearParameters();
var field = this.modal_pane.popup.find(".SessionUpload").first();
this.field_name = field.attr("field");
this.req.setParameter("field_name", this.field_name);
var upload_control = field.data("upload_control");
upload_control.processResult = this.processUploadResult.bind(this);
this.loadImages();
//setTimeout(this.loadImages.bind(this), 100);
}
/**
* Handle new image upload to collection
* @param result
*/
processUploadResult(result) {
for (var a = 0; a < result.result_count; a++) {
var image = result.objects[a];
var imageID = image.imageID;
//load the image into the view
this.loadImages(imageID);
}
}
loadImages(imageID) {
this.req.setFunction("find");
this.req.removeParameter("imageID");
if (imageID > 0) {
this.req.setParameter("imageID", imageID);
} else {
this.modal_pane.popup.find(".ImageStorage .Collection").first().empty();
}
this.req.start();
}
onClickImage(imageID, event) {
this.req.setFunction("renderDimensionDialog");
this.req.setParameter("imageID", imageID);
this.req.start();
}
| (imageID, event) {
this.req.setFunction("remove");
this.req.setParameter("imageID", imageID);
this.req.start();
}
}
| removeImage | identifier_name |
server.js | const fs = require('fs')
const http = require('http')
const mst = require('mustache')
const config = require('config')
const util = require('./util')
// Begin module
module.exports = function() {
// Create a server
http.createServer(function(req, res) {
const response = (res, output, content_type, status) => {
// Write the headers
res.writeHead(status = status || 200, {
'Content-Type': content_type || 'text/html',
'Access-Control-Allow-Origin': '*'
})
// Send the result with output
res.end(output)
console.log(status + ' ' + req.method + ' ' + req.url)
}
let output
if(req.url == '/') {
// Read the JSON log file
let log = util.readLog()
// Read the template
let template = fs.readFileSync(util.appPath('template'))
// Render the template with colours from log
output = mst.render(template.toString(), {
colours: log,
google_analytics: config.google_analytics,
formatDate: function() {
return function(date, render) { | })
return response(res, output)
}
else if(req.url == '/style.css') {
// Read the css file
output = fs.readFileSync(util.appPath('style'))
return response(res, output, 'text/css')
}
else if(req.url == '/json') {
// Read the JSON log file
output = fs.readFileSync(util.appPath('log'))
return response(res, output, 'text/json')
}
else {
return response(res, '404 Page Not Found', 'text/html', 404)
}
}).listen(config.server_port, config.server_address)
console.log('Server running at http://%s:%s/', config.server_address, config.server_port)
console.log('Close with CTRL + C')
} | return util.formatDate(render(date))
}
} | random_line_split |
server.js | const fs = require('fs')
const http = require('http')
const mst = require('mustache')
const config = require('config')
const util = require('./util')
// Begin module
module.exports = function() {
// Create a server
http.createServer(function(req, res) {
const response = (res, output, content_type, status) => {
// Write the headers
res.writeHead(status = status || 200, {
'Content-Type': content_type || 'text/html',
'Access-Control-Allow-Origin': '*'
})
// Send the result with output
res.end(output)
console.log(status + ' ' + req.method + ' ' + req.url)
}
let output
if(req.url == '/') {
// Read the JSON log file
let log = util.readLog()
// Read the template
let template = fs.readFileSync(util.appPath('template'))
// Render the template with colours from log
output = mst.render(template.toString(), {
colours: log,
google_analytics: config.google_analytics,
formatDate: function() {
return function(date, render) {
return util.formatDate(render(date))
}
}
})
return response(res, output)
}
else if(req.url == '/style.css') |
else if(req.url == '/json') {
// Read the JSON log file
output = fs.readFileSync(util.appPath('log'))
return response(res, output, 'text/json')
}
else {
return response(res, '404 Page Not Found', 'text/html', 404)
}
}).listen(config.server_port, config.server_address)
console.log('Server running at http://%s:%s/', config.server_address, config.server_port)
console.log('Close with CTRL + C')
}
| {
// Read the css file
output = fs.readFileSync(util.appPath('style'))
return response(res, output, 'text/css')
} | conditional_block |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneField(User, null=True, on_delete=models.SET_NULL)
data = jsonfield.JSONField(default=dict, blank=True)
@classmethod
def for_user(cls, user):
assert user.is_authenticated(), "user must be authenticated"
user_state, _ = cls.objects.get_or_create(user=user)
return user_state
def get(self, key):
return self.data.get(key)
def set(self, key, value):
self.data[key] = value
self.save()
class ActivityState(models.Model):
"""
this stores the overall state of a particular user doing a particular
activity across all sessions of that activity.
"""
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
activity_key = models.CharField(max_length=300)
activity_class_path = models.CharField(max_length=300)
# how many sessions have been completed by this user
completed_count = models.IntegerField(default=0)
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("user", "activity_key")]
@property
def activity_class(self): | return next(iter(self.sessions.filter(completed=None)), None)
@property
def latest(self):
session, _ = self.sessions.get_or_create(completed=None)
return session
@property
def last_completed(self):
return self.sessions.filter(completed__isnull=False).order_by("-started").first()
@property
def all_sessions(self):
return self.sessions.order_by("started")
@classmethod
def state_for_user(cls, user, activity_key):
assert user.is_authenticated(), "user must be authenticated"
return cls.objects.filter(user=user, activity_key=activity_key).first()
@property
def progression(self):
if self.in_progress:
return "continue"
elif self.activity_class.repeatable:
return "repeat"
else:
return "completed"
class ActivitySessionState(models.Model):
"""
this stores the state of a particular session of a particular user
doing a particular activity.
"""
activity_state = models.ForeignKey(ActivityState, related_name="sessions", on_delete=models.CASCADE)
started = models.DateTimeField(default=timezone.now)
completed = models.DateTimeField(null=True) # NULL means in progress
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("activity_state", "started")]
def mark_completed(self):
self.completed = timezone.now()
self.save()
self.activity_state.completed_count = models.F("completed_count") + 1
self.activity_state.save()
def activities_for_user(user):
activities = {
"available": [],
"inprogress": [],
"completed": [],
"repeatable": []
}
for key, activity_class_path in hookset.all_activities():
activity = load_path_attr(activity_class_path)
state = ActivityState.state_for_user(user, key)
user_num_completions = ActivitySessionState.objects.filter(
user=user,
activity_key=key,
completed__isnull=False
).count()
activity_entry = {
"activity_key": key,
"title": activity.title,
"description": activity.description,
"state": state,
"user_num_completions": user_num_completions,
"repeatable": activity.repeatable,
}
if state:
if state.in_progress:
activities["inprogress"].append(activity_entry)
elif activity.repeatable:
activities["repeatable"].append(activity_entry)
else:
activities["completed"].append(activity_entry)
else:
activities["available"].append(activity_entry)
return activities | return load_path_attr(self.activity_class_path)
@property
def in_progress(self): | random_line_split |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneField(User, null=True, on_delete=models.SET_NULL)
data = jsonfield.JSONField(default=dict, blank=True)
@classmethod
def for_user(cls, user):
assert user.is_authenticated(), "user must be authenticated"
user_state, _ = cls.objects.get_or_create(user=user)
return user_state
def get(self, key):
return self.data.get(key)
def set(self, key, value):
self.data[key] = value
self.save()
class ActivityState(models.Model):
"""
this stores the overall state of a particular user doing a particular
activity across all sessions of that activity.
"""
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
activity_key = models.CharField(max_length=300)
activity_class_path = models.CharField(max_length=300)
# how many sessions have been completed by this user
completed_count = models.IntegerField(default=0)
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("user", "activity_key")]
@property
def activity_class(self):
return load_path_attr(self.activity_class_path)
@property
def in_progress(self):
return next(iter(self.sessions.filter(completed=None)), None)
@property
def latest(self):
session, _ = self.sessions.get_or_create(completed=None)
return session
@property
def last_completed(self):
return self.sessions.filter(completed__isnull=False).order_by("-started").first()
@property
def all_sessions(self):
return self.sessions.order_by("started")
@classmethod
def state_for_user(cls, user, activity_key):
assert user.is_authenticated(), "user must be authenticated"
return cls.objects.filter(user=user, activity_key=activity_key).first()
@property
def progression(self):
if self.in_progress:
return "continue"
elif self.activity_class.repeatable:
return "repeat"
else:
return "completed"
class ActivitySessionState(models.Model):
"""
this stores the state of a particular session of a particular user
doing a particular activity.
"""
activity_state = models.ForeignKey(ActivityState, related_name="sessions", on_delete=models.CASCADE)
started = models.DateTimeField(default=timezone.now)
completed = models.DateTimeField(null=True) # NULL means in progress
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("activity_state", "started")]
def mark_completed(self):
self.completed = timezone.now()
self.save()
self.activity_state.completed_count = models.F("completed_count") + 1
self.activity_state.save()
def activities_for_user(user):
| activities = {
"available": [],
"inprogress": [],
"completed": [],
"repeatable": []
}
for key, activity_class_path in hookset.all_activities():
activity = load_path_attr(activity_class_path)
state = ActivityState.state_for_user(user, key)
user_num_completions = ActivitySessionState.objects.filter(
user=user,
activity_key=key,
completed__isnull=False
).count()
activity_entry = {
"activity_key": key,
"title": activity.title,
"description": activity.description,
"state": state,
"user_num_completions": user_num_completions,
"repeatable": activity.repeatable,
}
if state:
if state.in_progress:
activities["inprogress"].append(activity_entry)
elif activity.repeatable:
activities["repeatable"].append(activity_entry)
else:
activities["completed"].append(activity_entry)
else:
activities["available"].append(activity_entry)
return activities | identifier_body | |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneField(User, null=True, on_delete=models.SET_NULL)
data = jsonfield.JSONField(default=dict, blank=True)
@classmethod
def for_user(cls, user):
assert user.is_authenticated(), "user must be authenticated"
user_state, _ = cls.objects.get_or_create(user=user)
return user_state
def get(self, key):
return self.data.get(key)
def set(self, key, value):
self.data[key] = value
self.save()
class ActivityState(models.Model):
"""
this stores the overall state of a particular user doing a particular
activity across all sessions of that activity.
"""
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
activity_key = models.CharField(max_length=300)
activity_class_path = models.CharField(max_length=300)
# how many sessions have been completed by this user
completed_count = models.IntegerField(default=0)
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("user", "activity_key")]
@property
def activity_class(self):
return load_path_attr(self.activity_class_path)
@property
def in_progress(self):
return next(iter(self.sessions.filter(completed=None)), None)
@property
def latest(self):
session, _ = self.sessions.get_or_create(completed=None)
return session
@property
def last_completed(self):
return self.sessions.filter(completed__isnull=False).order_by("-started").first()
@property
def all_sessions(self):
return self.sessions.order_by("started")
@classmethod
def state_for_user(cls, user, activity_key):
assert user.is_authenticated(), "user must be authenticated"
return cls.objects.filter(user=user, activity_key=activity_key).first()
@property
def progression(self):
if self.in_progress:
return "continue"
elif self.activity_class.repeatable:
return "repeat"
else:
return "completed"
class | (models.Model):
"""
this stores the state of a particular session of a particular user
doing a particular activity.
"""
activity_state = models.ForeignKey(ActivityState, related_name="sessions", on_delete=models.CASCADE)
started = models.DateTimeField(default=timezone.now)
completed = models.DateTimeField(null=True) # NULL means in progress
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("activity_state", "started")]
def mark_completed(self):
self.completed = timezone.now()
self.save()
self.activity_state.completed_count = models.F("completed_count") + 1
self.activity_state.save()
def activities_for_user(user):
activities = {
"available": [],
"inprogress": [],
"completed": [],
"repeatable": []
}
for key, activity_class_path in hookset.all_activities():
activity = load_path_attr(activity_class_path)
state = ActivityState.state_for_user(user, key)
user_num_completions = ActivitySessionState.objects.filter(
user=user,
activity_key=key,
completed__isnull=False
).count()
activity_entry = {
"activity_key": key,
"title": activity.title,
"description": activity.description,
"state": state,
"user_num_completions": user_num_completions,
"repeatable": activity.repeatable,
}
if state:
if state.in_progress:
activities["inprogress"].append(activity_entry)
elif activity.repeatable:
activities["repeatable"].append(activity_entry)
else:
activities["completed"].append(activity_entry)
else:
activities["available"].append(activity_entry)
return activities
| ActivitySessionState | identifier_name |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneField(User, null=True, on_delete=models.SET_NULL)
data = jsonfield.JSONField(default=dict, blank=True)
@classmethod
def for_user(cls, user):
assert user.is_authenticated(), "user must be authenticated"
user_state, _ = cls.objects.get_or_create(user=user)
return user_state
def get(self, key):
return self.data.get(key)
def set(self, key, value):
self.data[key] = value
self.save()
class ActivityState(models.Model):
"""
this stores the overall state of a particular user doing a particular
activity across all sessions of that activity.
"""
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
activity_key = models.CharField(max_length=300)
activity_class_path = models.CharField(max_length=300)
# how many sessions have been completed by this user
completed_count = models.IntegerField(default=0)
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("user", "activity_key")]
@property
def activity_class(self):
return load_path_attr(self.activity_class_path)
@property
def in_progress(self):
return next(iter(self.sessions.filter(completed=None)), None)
@property
def latest(self):
session, _ = self.sessions.get_or_create(completed=None)
return session
@property
def last_completed(self):
return self.sessions.filter(completed__isnull=False).order_by("-started").first()
@property
def all_sessions(self):
return self.sessions.order_by("started")
@classmethod
def state_for_user(cls, user, activity_key):
assert user.is_authenticated(), "user must be authenticated"
return cls.objects.filter(user=user, activity_key=activity_key).first()
@property
def progression(self):
if self.in_progress:
return "continue"
elif self.activity_class.repeatable:
return "repeat"
else:
return "completed"
class ActivitySessionState(models.Model):
"""
this stores the state of a particular session of a particular user
doing a particular activity.
"""
activity_state = models.ForeignKey(ActivityState, related_name="sessions", on_delete=models.CASCADE)
started = models.DateTimeField(default=timezone.now)
completed = models.DateTimeField(null=True) # NULL means in progress
data = jsonfield.JSONField(default=dict, blank=True)
class Meta:
unique_together = [("activity_state", "started")]
def mark_completed(self):
self.completed = timezone.now()
self.save()
self.activity_state.completed_count = models.F("completed_count") + 1
self.activity_state.save()
def activities_for_user(user):
activities = {
"available": [],
"inprogress": [],
"completed": [],
"repeatable": []
}
for key, activity_class_path in hookset.all_activities():
activity = load_path_attr(activity_class_path)
state = ActivityState.state_for_user(user, key)
user_num_completions = ActivitySessionState.objects.filter(
user=user,
activity_key=key,
completed__isnull=False
).count()
activity_entry = {
"activity_key": key,
"title": activity.title,
"description": activity.description,
"state": state,
"user_num_completions": user_num_completions,
"repeatable": activity.repeatable,
}
if state:
|
else:
activities["available"].append(activity_entry)
return activities
| if state.in_progress:
activities["inprogress"].append(activity_entry)
elif activity.repeatable:
activities["repeatable"].append(activity_entry)
else:
activities["completed"].append(activity_entry) | conditional_block |
server.js | var io = require('socket.io').listen(4242);
io.set('log level', 1);
var Cube = require('./Cube');
var cubes = {};
io.sockets.on('connection', function (socket) {
// Envía la lista de cubos actual al nuevo jugador
for (var playerId in cubes) {
socket.emit('cubeUpdate', cubes[playerId]);
}
| socket.on('cubeUpdate', function (cubeData) {
var cube = cubes[socket.id];
if (cube !== undefined) cube.updateWithCubeData(cubeData);
socket.broadcast.emit('cubeUpdate', cube);
});
socket.on('disconnect', function () {
console.log(socket.id + " has disconnected from the server!");
delete cubes[socket.id];
io.sockets.emit('cubeDisconnect', socket.id);
});
}); | // Crea el nuevo cubo y lo envía a todos
var cube = new Cube (socket.id);
cubes[socket.id] = cube;
io.sockets.emit('cubeUpdate', cube);
| random_line_split |
fs.rs | // Copyright 2015 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.
//! Unix-specific extensions to primitives in the `std::fs` module.
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::v1::*;
use fs::{self, Permissions, OpenOptions};
use io;
use mem;
use os::raw::c_long;
use os::unix::raw;
use path::Path;
use sys::platform;
use sys;
use sys_common::{FromInner, AsInner, AsInnerMut};
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_READ: raw::mode_t = 0o400;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_WRITE: raw::mode_t = 0o200;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_EXECUTE: raw::mode_t = 0o100;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_RWX: raw::mode_t = 0o700;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_READ: raw::mode_t = 0o040;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_WRITE: raw::mode_t = 0o020;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_EXECUTE: raw::mode_t = 0o010;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_RWX: raw::mode_t = 0o070;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_READ: raw::mode_t = 0o004;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_WRITE: raw::mode_t = 0o002;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_EXECUTE: raw::mode_t = 0o001;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_RWX: raw::mode_t = 0o007;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_READ: raw::mode_t = 0o444;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_WRITE: raw::mode_t = 0o222;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_EXECUTE: raw::mode_t = 0o111;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_RWX: raw::mode_t = 0o777;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETUID: raw::mode_t = 0o4000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETGID: raw::mode_t = 0o2000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const STICKY_BIT: raw::mode_t = 0o1000;
/// Unix-specific extensions to `Permissions`
#[unstable(feature = "fs_ext",
reason = "may want a more useful mode abstraction")]
pub trait PermissionsExt {
fn mode(&self) -> raw::mode_t;
fn set_mode(&mut self, mode: raw::mode_t);
fn from_mode(mode: raw::mode_t) -> Self;
}
impl PermissionsExt for Permissions {
fn mode(&self) -> raw::mode_t { self.as_inner().mode() }
fn set_mode(&mut self, mode: raw::mode_t) {
*self = FromInner::from_inner(FromInner::from_inner(mode));
}
fn from_mode(mode: raw::mode_t) -> Permissions {
FromInner::from_inner(FromInner::from_inner(mode))
}
}
/// Unix-specific extensions to `OpenOptions`
#[unstable(feature = "fs_ext",
reason = "may want a more useful mode abstraction")]
pub trait OpenOptionsExt {
/// Sets the mode bits that a new file will be created with.
///
/// If a new file is created as part of a `File::open_opts` call then this
/// specified `mode` will be used as the permission bits for the new file.
fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}
impl OpenOptionsExt for OpenOptions {
fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions {
self.as_inner_mut().mode(mode); self
}
}
#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub struct Metadata(sys::fs::FileAttr);
#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub trait MetadataExt {
fn as_raw(&self) -> &Metadata;
}
impl MetadataExt for fs::Metadata {
fn as_raw(&self) -> &Metadata {
let inner: &sys::fs::FileAttr = self.as_inner();
unsafe { mem::transmute(inner) }
}
}
impl AsInner<platform::raw::stat> for Metadata {
fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() }
}
// Hm, why are there casts here to the returned type, shouldn't the types always
// be the same? Right you are! Turns out, however, on android at least the types
// in the raw `stat` structure are not the same as the types being returned. Who
// knew!
//
// As a result to make sure this compiles for all platforms we do the manual
// casts and rely on manual lowering to `stat` if the raw type is desired.
#[unstable(feature = "metadata_ext", reason = "recently added API")]
impl Metadata {
pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t }
pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t }
pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t }
pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t }
pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t }
pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t }
pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t }
pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t }
pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime }
pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long }
pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime }
pub fn | (&self) -> c_long { self.0.raw().st_mtime_nsec as c_long }
pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime }
pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long }
pub fn blksize(&self) -> raw::blksize_t {
self.0.raw().st_blksize as raw::blksize_t
}
pub fn blocks(&self) -> raw::blkcnt_t {
self.0.raw().st_blocks as raw::blkcnt_t
}
}
#[unstable(feature = "dir_entry_ext", reason = "recently added API")]
pub trait DirEntryExt {
fn ino(&self) -> raw::ino_t;
}
impl DirEntryExt for fs::DirEntry {
fn ino(&self) -> raw::ino_t { self.as_inner().ino() }
}
/// Creates a new symbolic link on the filesystem.
///
/// The `dst` path will be a symbolic link pointing to the `src` path.
///
/// # Note
///
/// On Windows, you must specify whether a symbolic link points to a file
/// or directory. Use `os::windows::fs::symlink_file` to create a
/// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a
/// symbolic link to a directory. Additionally, the process must have
/// `SeCreateSymbolicLinkPrivilege` in order to be able to create a
/// symbolic link.
///
/// # Examples
///
/// ```
/// use std::os::unix::fs;
///
/// # fn foo() -> std::io::Result<()> {
/// try!(fs::symlink("a.txt", "b.txt"));
/// # Ok(())
/// # }
/// ```
#[stable(feature = "symlink", since = "1.1.0")]
pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
{
sys::fs::symlink(src.as_ref(), dst.as_ref())
}
#[unstable(feature = "dir_builder", reason = "recently added API")]
/// An extension trait for `fs::DirBuilder` for unix-specific options.
pub trait DirBuilderExt {
/// Sets the mode to create new directories with. This option defaults to
/// 0o777.
fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}
impl DirBuilderExt for fs::DirBuilder {
fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder {
self.as_inner_mut().set_mode(mode);
self
}
}
| mtime_nsec | identifier_name |
fs.rs | // Copyright 2015 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.
//! Unix-specific extensions to primitives in the `std::fs` module.
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::v1::*;
use fs::{self, Permissions, OpenOptions};
use io;
use mem;
use os::raw::c_long;
use os::unix::raw;
use path::Path;
use sys::platform;
use sys;
use sys_common::{FromInner, AsInner, AsInnerMut};
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_READ: raw::mode_t = 0o400;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_WRITE: raw::mode_t = 0o200;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_EXECUTE: raw::mode_t = 0o100;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_RWX: raw::mode_t = 0o700;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_READ: raw::mode_t = 0o040;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_WRITE: raw::mode_t = 0o020;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_EXECUTE: raw::mode_t = 0o010;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_RWX: raw::mode_t = 0o070;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_READ: raw::mode_t = 0o004;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_WRITE: raw::mode_t = 0o002;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_EXECUTE: raw::mode_t = 0o001;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_RWX: raw::mode_t = 0o007;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_READ: raw::mode_t = 0o444;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_WRITE: raw::mode_t = 0o222;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_EXECUTE: raw::mode_t = 0o111;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_RWX: raw::mode_t = 0o777;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETUID: raw::mode_t = 0o4000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETGID: raw::mode_t = 0o2000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const STICKY_BIT: raw::mode_t = 0o1000;
/// Unix-specific extensions to `Permissions`
#[unstable(feature = "fs_ext",
reason = "may want a more useful mode abstraction")]
pub trait PermissionsExt {
fn mode(&self) -> raw::mode_t;
fn set_mode(&mut self, mode: raw::mode_t);
fn from_mode(mode: raw::mode_t) -> Self;
}
impl PermissionsExt for Permissions {
fn mode(&self) -> raw::mode_t { self.as_inner().mode() }
fn set_mode(&mut self, mode: raw::mode_t) {
*self = FromInner::from_inner(FromInner::from_inner(mode));
}
fn from_mode(mode: raw::mode_t) -> Permissions {
FromInner::from_inner(FromInner::from_inner(mode))
}
}
/// Unix-specific extensions to `OpenOptions`
#[unstable(feature = "fs_ext",
reason = "may want a more useful mode abstraction")]
pub trait OpenOptionsExt {
/// Sets the mode bits that a new file will be created with.
///
/// If a new file is created as part of a `File::open_opts` call then this
/// specified `mode` will be used as the permission bits for the new file.
fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}
impl OpenOptionsExt for OpenOptions {
fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions {
self.as_inner_mut().mode(mode); self
}
}
#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub struct Metadata(sys::fs::FileAttr);
#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub trait MetadataExt {
fn as_raw(&self) -> &Metadata;
}
impl MetadataExt for fs::Metadata {
fn as_raw(&self) -> &Metadata {
let inner: &sys::fs::FileAttr = self.as_inner();
unsafe { mem::transmute(inner) }
}
}
impl AsInner<platform::raw::stat> for Metadata {
fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() }
}
// Hm, why are there casts here to the returned type, shouldn't the types always
// be the same? Right you are! Turns out, however, on android at least the types
// in the raw `stat` structure are not the same as the types being returned. Who
// knew!
//
// As a result to make sure this compiles for all platforms we do the manual
// casts and rely on manual lowering to `stat` if the raw type is desired.
#[unstable(feature = "metadata_ext", reason = "recently added API")]
impl Metadata {
pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t }
pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t }
pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t }
pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t }
pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t }
pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t }
pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t }
pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t }
pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime }
pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long }
pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime }
pub fn mtime_nsec(&self) -> c_long { self.0.raw().st_mtime_nsec as c_long }
pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime }
pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long }
pub fn blksize(&self) -> raw::blksize_t {
self.0.raw().st_blksize as raw::blksize_t
}
pub fn blocks(&self) -> raw::blkcnt_t {
self.0.raw().st_blocks as raw::blkcnt_t
}
}
#[unstable(feature = "dir_entry_ext", reason = "recently added API")]
pub trait DirEntryExt {
fn ino(&self) -> raw::ino_t;
}
impl DirEntryExt for fs::DirEntry {
fn ino(&self) -> raw::ino_t { self.as_inner().ino() }
}
/// Creates a new symbolic link on the filesystem.
///
/// The `dst` path will be a symbolic link pointing to the `src` path.
///
/// # Note
///
/// On Windows, you must specify whether a symbolic link points to a file
/// or directory. Use `os::windows::fs::symlink_file` to create a
/// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a
/// symbolic link to a directory. Additionally, the process must have
/// `SeCreateSymbolicLinkPrivilege` in order to be able to create a
/// symbolic link.
///
/// # Examples
///
/// ```
/// use std::os::unix::fs;
///
/// # fn foo() -> std::io::Result<()> {
/// try!(fs::symlink("a.txt", "b.txt"));
/// # Ok(())
/// # }
/// ```
#[stable(feature = "symlink", since = "1.1.0")]
pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
|
#[unstable(feature = "dir_builder", reason = "recently added API")]
/// An extension trait for `fs::DirBuilder` for unix-specific options.
pub trait DirBuilderExt {
/// Sets the mode to create new directories with. This option defaults to
/// 0o777.
fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}
impl DirBuilderExt for fs::DirBuilder {
fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder {
self.as_inner_mut().set_mode(mode);
self
}
}
| {
sys::fs::symlink(src.as_ref(), dst.as_ref())
} | identifier_body |
fs.rs | // Copyright 2015 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.
//! Unix-specific extensions to primitives in the `std::fs` module.
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::v1::*;
use fs::{self, Permissions, OpenOptions};
use io;
use mem;
use os::raw::c_long;
use os::unix::raw;
use path::Path;
use sys::platform;
use sys;
use sys_common::{FromInner, AsInner, AsInnerMut};
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_READ: raw::mode_t = 0o400;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_WRITE: raw::mode_t = 0o200;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_EXECUTE: raw::mode_t = 0o100;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_RWX: raw::mode_t = 0o700;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_READ: raw::mode_t = 0o040;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_WRITE: raw::mode_t = 0o020;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_EXECUTE: raw::mode_t = 0o010;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const GROUP_RWX: raw::mode_t = 0o070;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_READ: raw::mode_t = 0o004;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_WRITE: raw::mode_t = 0o002;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_EXECUTE: raw::mode_t = 0o001;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const OTHER_RWX: raw::mode_t = 0o007;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_READ: raw::mode_t = 0o444;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_WRITE: raw::mode_t = 0o222;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_EXECUTE: raw::mode_t = 0o111;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const ALL_RWX: raw::mode_t = 0o777;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETUID: raw::mode_t = 0o4000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const SETGID: raw::mode_t = 0o2000;
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const STICKY_BIT: raw::mode_t = 0o1000;
/// Unix-specific extensions to `Permissions`
#[unstable(feature = "fs_ext",
reason = "may want a more useful mode abstraction")]
pub trait PermissionsExt {
fn mode(&self) -> raw::mode_t;
fn set_mode(&mut self, mode: raw::mode_t);
fn from_mode(mode: raw::mode_t) -> Self;
}
impl PermissionsExt for Permissions {
fn mode(&self) -> raw::mode_t { self.as_inner().mode() }
fn set_mode(&mut self, mode: raw::mode_t) {
*self = FromInner::from_inner(FromInner::from_inner(mode));
}
fn from_mode(mode: raw::mode_t) -> Permissions {
FromInner::from_inner(FromInner::from_inner(mode))
}
}
/// Unix-specific extensions to `OpenOptions`
#[unstable(feature = "fs_ext",
reason = "may want a more useful mode abstraction")]
pub trait OpenOptionsExt {
/// Sets the mode bits that a new file will be created with.
///
/// If a new file is created as part of a `File::open_opts` call then this
/// specified `mode` will be used as the permission bits for the new file.
fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}
impl OpenOptionsExt for OpenOptions {
fn mode(&mut self, mode: raw::mode_t) -> &mut OpenOptions {
self.as_inner_mut().mode(mode); self
}
}
#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub struct Metadata(sys::fs::FileAttr);
#[unstable(feature = "metadata_ext", reason = "recently added API")]
pub trait MetadataExt {
fn as_raw(&self) -> &Metadata;
}
impl MetadataExt for fs::Metadata {
fn as_raw(&self) -> &Metadata {
let inner: &sys::fs::FileAttr = self.as_inner();
unsafe { mem::transmute(inner) }
}
}
impl AsInner<platform::raw::stat> for Metadata {
fn as_inner(&self) -> &platform::raw::stat { self.0.as_inner() }
}
// Hm, why are there casts here to the returned type, shouldn't the types always
// be the same? Right you are! Turns out, however, on android at least the types
// in the raw `stat` structure are not the same as the types being returned. Who
// knew!
//
// As a result to make sure this compiles for all platforms we do the manual
// casts and rely on manual lowering to `stat` if the raw type is desired.
#[unstable(feature = "metadata_ext", reason = "recently added API")] | impl Metadata {
pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t }
pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t }
pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t }
pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_t }
pub fn uid(&self) -> raw::uid_t { self.0.raw().st_uid as raw::uid_t }
pub fn gid(&self) -> raw::gid_t { self.0.raw().st_gid as raw::gid_t }
pub fn rdev(&self) -> raw::dev_t { self.0.raw().st_rdev as raw::dev_t }
pub fn size(&self) -> raw::off_t { self.0.raw().st_size as raw::off_t }
pub fn atime(&self) -> raw::time_t { self.0.raw().st_atime }
pub fn atime_nsec(&self) -> c_long { self.0.raw().st_atime_nsec as c_long }
pub fn mtime(&self) -> raw::time_t { self.0.raw().st_mtime }
pub fn mtime_nsec(&self) -> c_long { self.0.raw().st_mtime_nsec as c_long }
pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime }
pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long }
pub fn blksize(&self) -> raw::blksize_t {
self.0.raw().st_blksize as raw::blksize_t
}
pub fn blocks(&self) -> raw::blkcnt_t {
self.0.raw().st_blocks as raw::blkcnt_t
}
}
#[unstable(feature = "dir_entry_ext", reason = "recently added API")]
pub trait DirEntryExt {
fn ino(&self) -> raw::ino_t;
}
impl DirEntryExt for fs::DirEntry {
fn ino(&self) -> raw::ino_t { self.as_inner().ino() }
}
/// Creates a new symbolic link on the filesystem.
///
/// The `dst` path will be a symbolic link pointing to the `src` path.
///
/// # Note
///
/// On Windows, you must specify whether a symbolic link points to a file
/// or directory. Use `os::windows::fs::symlink_file` to create a
/// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a
/// symbolic link to a directory. Additionally, the process must have
/// `SeCreateSymbolicLinkPrivilege` in order to be able to create a
/// symbolic link.
///
/// # Examples
///
/// ```
/// use std::os::unix::fs;
///
/// # fn foo() -> std::io::Result<()> {
/// try!(fs::symlink("a.txt", "b.txt"));
/// # Ok(())
/// # }
/// ```
#[stable(feature = "symlink", since = "1.1.0")]
pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
{
sys::fs::symlink(src.as_ref(), dst.as_ref())
}
#[unstable(feature = "dir_builder", reason = "recently added API")]
/// An extension trait for `fs::DirBuilder` for unix-specific options.
pub trait DirBuilderExt {
/// Sets the mode to create new directories with. This option defaults to
/// 0o777.
fn mode(&mut self, mode: raw::mode_t) -> &mut Self;
}
impl DirBuilderExt for fs::DirBuilder {
fn mode(&mut self, mode: raw::mode_t) -> &mut fs::DirBuilder {
self.as_inner_mut().set_mode(mode);
self
}
} | random_line_split | |
ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var mapBy = require( '@stdlib/strided/base/map-by' ).ndarray;
var abs = require( '@stdlib/math/base/special/abs' );
// MAIN //
/**
* Computes the absolute value of each element retrieved from a strided input array `x` via a callback function and assigns each result to an element in a strided output array `y`.
*
* @param {NonNegativeInteger} N - number of indexed elements
* @param {Collection} x - input array/collection
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {Collection} y - destination array/collection
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @param {Callback} clbk - callback
* @param {*} [thisArg] - callback execution context
* @returns {Collection} `y`
*
* @example
* function accessor( v ) {
* return v * 2.0;
* }
*
* var x = [ 1.0, -2.0, 3.0, -4.0, 5.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* absBy( x.length, x, 1, 0, y, 1, 0, accessor );
*
* console.log( y );
* // => [ 2.0, 4.0, 6.0, 8.0, 10.0 ]
*/
function absBy( N, x, strideX, offsetX, y, strideY, offsetY, clbk, thisArg ) |
// EXPORTS //
module.exports = absBy;
| {
return mapBy( N, x, strideX, offsetX, y, strideY, offsetY, abs, clbk, thisArg ); // eslint-disable-line max-len
} | identifier_body |
ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var mapBy = require( '@stdlib/strided/base/map-by' ).ndarray;
var abs = require( '@stdlib/math/base/special/abs' );
// MAIN //
/**
* Computes the absolute value of each element retrieved from a strided input array `x` via a callback function and assigns each result to an element in a strided output array `y`.
*
* @param {NonNegativeInteger} N - number of indexed elements
* @param {Collection} x - input array/collection
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {Collection} y - destination array/collection
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @param {Callback} clbk - callback
* @param {*} [thisArg] - callback execution context | * return v * 2.0;
* }
*
* var x = [ 1.0, -2.0, 3.0, -4.0, 5.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* absBy( x.length, x, 1, 0, y, 1, 0, accessor );
*
* console.log( y );
* // => [ 2.0, 4.0, 6.0, 8.0, 10.0 ]
*/
function absBy( N, x, strideX, offsetX, y, strideY, offsetY, clbk, thisArg ) {
return mapBy( N, x, strideX, offsetX, y, strideY, offsetY, abs, clbk, thisArg ); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = absBy; | * @returns {Collection} `y`
*
* @example
* function accessor( v ) { | random_line_split |
ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var mapBy = require( '@stdlib/strided/base/map-by' ).ndarray;
var abs = require( '@stdlib/math/base/special/abs' );
// MAIN //
/**
* Computes the absolute value of each element retrieved from a strided input array `x` via a callback function and assigns each result to an element in a strided output array `y`.
*
* @param {NonNegativeInteger} N - number of indexed elements
* @param {Collection} x - input array/collection
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {Collection} y - destination array/collection
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @param {Callback} clbk - callback
* @param {*} [thisArg] - callback execution context
* @returns {Collection} `y`
*
* @example
* function accessor( v ) {
* return v * 2.0;
* }
*
* var x = [ 1.0, -2.0, 3.0, -4.0, 5.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* absBy( x.length, x, 1, 0, y, 1, 0, accessor );
*
* console.log( y );
* // => [ 2.0, 4.0, 6.0, 8.0, 10.0 ]
*/
function | ( N, x, strideX, offsetX, y, strideY, offsetY, clbk, thisArg ) {
return mapBy( N, x, strideX, offsetX, y, strideY, offsetY, abs, clbk, thisArg ); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = absBy;
| absBy | identifier_name |
configuration.py | #!/usr/bin/python2.5 | #
# Copyright 2008 Google Inc.
#
# 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.
#
"""System-wide configuration variables."""
import datetime
# This HTML block will be printed in the footer of every page.
FOOTER_HTML = (
'cocos Live v0.3.6 - © 2009 <a href="http://www.sapusmedia.com">Sapus Media</a>'
)
# File caching controls
FILE_CACHE_CONTROL = 'private, max-age=86400'
FILE_CACHE_TIME = datetime.timedelta(days=1)
# Title for the website
SYSTEM_TITLE = 'cocos Live'
# Unique identifier from Google Analytics
ANALYTICS_ID = 'UA-871936-6' | random_line_split | |
greatfet.rs | #![allow(missing_docs)] | use hal::lpc17xx::pin;
use hal::pin::Gpio;
use hal::pin::GpioDirection;
pub struct Led {
pin: pin::Pin,
}
impl Led {
pub fn new(idx: u8) -> Led {
Led {
pin: match idx {
0 => get_led(pin::Port::Port3, 14),
1 => get_led(pin::Port::Port2, 1),
2 => get_led(pin::Port::Port3, 13),
3 => get_led(pin::Port::Port3, 12),
_ => unsafe { abort() },
}
}
}
pub fn on(&self) {
self.pin.set_low();
}
pub fn off(&self) {
self.pin.set_high();
}
}
fn get_led(port: pin::Port, pin: u8) -> pin::Pin {
pin::Pin::new(
port, pin,
pin::Function::Gpio,
Some(GpioDirection::Out))
} |
use core::intrinsics::abort; | random_line_split |
greatfet.rs | #![allow(missing_docs)]
use core::intrinsics::abort;
use hal::lpc17xx::pin;
use hal::pin::Gpio;
use hal::pin::GpioDirection;
pub struct Led {
pin: pin::Pin,
}
impl Led {
pub fn | (idx: u8) -> Led {
Led {
pin: match idx {
0 => get_led(pin::Port::Port3, 14),
1 => get_led(pin::Port::Port2, 1),
2 => get_led(pin::Port::Port3, 13),
3 => get_led(pin::Port::Port3, 12),
_ => unsafe { abort() },
}
}
}
pub fn on(&self) {
self.pin.set_low();
}
pub fn off(&self) {
self.pin.set_high();
}
}
fn get_led(port: pin::Port, pin: u8) -> pin::Pin {
pin::Pin::new(
port, pin,
pin::Function::Gpio,
Some(GpioDirection::Out))
}
| new | identifier_name |
greatfet.rs | #![allow(missing_docs)]
use core::intrinsics::abort;
use hal::lpc17xx::pin;
use hal::pin::Gpio;
use hal::pin::GpioDirection;
pub struct Led {
pin: pin::Pin,
}
impl Led {
pub fn new(idx: u8) -> Led {
Led {
pin: match idx {
0 => get_led(pin::Port::Port3, 14),
1 => get_led(pin::Port::Port2, 1),
2 => get_led(pin::Port::Port3, 13),
3 => get_led(pin::Port::Port3, 12),
_ => unsafe { abort() },
}
}
}
pub fn on(&self) {
self.pin.set_low();
}
pub fn off(&self) |
}
fn get_led(port: pin::Port, pin: u8) -> pin::Pin {
pin::Pin::new(
port, pin,
pin::Function::Gpio,
Some(GpioDirection::Out))
}
| {
self.pin.set_high();
} | identifier_body |
customer_form.js | import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtrekk",
selector: "customerForm",
restrict: "E",
replace: true,
controller: "CustomersFormCtrl",
template: CustomersFormTpl
})
@Controller({
module: "webtrekk",
name: "CustomersFormCtrl",
deps: ["$location", "$rootScope", "CustomerService"],
scope: {
model: "@"
}
})
@Logging({
loggerName: "CustomersFormLogger",
...Config
})
export class CustomersFormCtrl extends EventedController {
constructor(...args) {
super(...args);
this.$scope.$on("change", this.handleEvent.bind(this));
}
handleEvent (ev, { scope, triggerTokens }) {
if (scope._name.fn === "CustomersFormCtrl" &&
triggerTokens.type === "mouseup") {
this.log({
level: "warn",
msg: "Button Clicked, Handle Behaviour Propagation?"
});
}
}
@Evented({
selector: "label#save",
type: "mouseup",
})
async saveAndReturn () {
let valid = Object.getOwnPropertyNames(this.$scope.model)
.map((tupel) => {
let valid = this.$scope.model[tupel].validate();
if (!valid) {
this.log({
level: "error",
msg: `${this.$scope.model[tupel].label} cannot be ${this.$scope.model[tupel].content} -- invalid`,
});
}
this.$scope.model[tupel].valid = valid;
return valid;
}).reduce((acc, tupel) => acc && tupel);
if (valid) {
await this.CustomerService.upsertCustomer({
customer_id: this.$scope.model.id.content,
first_name: this.$scope.model.first_name.content,
last_name: this.$scope.model.last_name.content, | this.$location.url("/");
this.$rootScope.$apply();
}
this._digest();
}
@Evented({
selector: "label#cancel",
type: "mouseup",
})
cancelByReturn () {
this.$location.path("/");
this.$rootScope.$apply();
}
} | birthday: this.$scope.model.age.content.toString(),
gender: this.$scope.model.gender.content,
last_contact: this.$scope.model.last_contact.content.toString(),
customer_lifetime_value: this.$scope.model.customer_lifetime_value.content,
}); | random_line_split |
customer_form.js | import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtrekk",
selector: "customerForm",
restrict: "E",
replace: true,
controller: "CustomersFormCtrl",
template: CustomersFormTpl
})
@Controller({
module: "webtrekk",
name: "CustomersFormCtrl",
deps: ["$location", "$rootScope", "CustomerService"],
scope: {
model: "@"
}
})
@Logging({
loggerName: "CustomersFormLogger",
...Config
})
export class CustomersFormCtrl extends EventedController {
constructor(...args) {
super(...args);
this.$scope.$on("change", this.handleEvent.bind(this));
}
handleEvent (ev, { scope, triggerTokens }) {
if (scope._name.fn === "CustomersFormCtrl" &&
triggerTokens.type === "mouseup") |
}
@Evented({
selector: "label#save",
type: "mouseup",
})
async saveAndReturn () {
let valid = Object.getOwnPropertyNames(this.$scope.model)
.map((tupel) => {
let valid = this.$scope.model[tupel].validate();
if (!valid) {
this.log({
level: "error",
msg: `${this.$scope.model[tupel].label} cannot be ${this.$scope.model[tupel].content} -- invalid`,
});
}
this.$scope.model[tupel].valid = valid;
return valid;
}).reduce((acc, tupel) => acc && tupel);
if (valid) {
await this.CustomerService.upsertCustomer({
customer_id: this.$scope.model.id.content,
first_name: this.$scope.model.first_name.content,
last_name: this.$scope.model.last_name.content,
birthday: this.$scope.model.age.content.toString(),
gender: this.$scope.model.gender.content,
last_contact: this.$scope.model.last_contact.content.toString(),
customer_lifetime_value: this.$scope.model.customer_lifetime_value.content,
});
this.$location.url("/");
this.$rootScope.$apply();
}
this._digest();
}
@Evented({
selector: "label#cancel",
type: "mouseup",
})
cancelByReturn () {
this.$location.path("/");
this.$rootScope.$apply();
}
}
| {
this.log({
level: "warn",
msg: "Button Clicked, Handle Behaviour Propagation?"
});
} | conditional_block |
customer_form.js | import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtrekk",
selector: "customerForm",
restrict: "E",
replace: true,
controller: "CustomersFormCtrl",
template: CustomersFormTpl
})
@Controller({
module: "webtrekk",
name: "CustomersFormCtrl",
deps: ["$location", "$rootScope", "CustomerService"],
scope: {
model: "@"
}
})
@Logging({
loggerName: "CustomersFormLogger",
...Config
})
export class CustomersFormCtrl extends EventedController {
constructor(...args) {
super(...args);
this.$scope.$on("change", this.handleEvent.bind(this));
}
| (ev, { scope, triggerTokens }) {
if (scope._name.fn === "CustomersFormCtrl" &&
triggerTokens.type === "mouseup") {
this.log({
level: "warn",
msg: "Button Clicked, Handle Behaviour Propagation?"
});
}
}
@Evented({
selector: "label#save",
type: "mouseup",
})
async saveAndReturn () {
let valid = Object.getOwnPropertyNames(this.$scope.model)
.map((tupel) => {
let valid = this.$scope.model[tupel].validate();
if (!valid) {
this.log({
level: "error",
msg: `${this.$scope.model[tupel].label} cannot be ${this.$scope.model[tupel].content} -- invalid`,
});
}
this.$scope.model[tupel].valid = valid;
return valid;
}).reduce((acc, tupel) => acc && tupel);
if (valid) {
await this.CustomerService.upsertCustomer({
customer_id: this.$scope.model.id.content,
first_name: this.$scope.model.first_name.content,
last_name: this.$scope.model.last_name.content,
birthday: this.$scope.model.age.content.toString(),
gender: this.$scope.model.gender.content,
last_contact: this.$scope.model.last_contact.content.toString(),
customer_lifetime_value: this.$scope.model.customer_lifetime_value.content,
});
this.$location.url("/");
this.$rootScope.$apply();
}
this._digest();
}
@Evented({
selector: "label#cancel",
type: "mouseup",
})
cancelByReturn () {
this.$location.path("/");
this.$rootScope.$apply();
}
}
| handleEvent | identifier_name |
svg_attach.js | /*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo.require("dojox.gfx.svg");
dojo.experimental("dojox.gfx.svg_attach");
(function(){
dojox.gfx.attachNode=function(_1){
if(!_1) |
var s=null;
switch(_1.tagName.toLowerCase()){
case dojox.gfx.Rect.nodeType:
s=new dojox.gfx.Rect(_1);
_2(s);
break;
case dojox.gfx.Ellipse.nodeType:
s=new dojox.gfx.Ellipse(_1);
_3(s,dojox.gfx.defaultEllipse);
break;
case dojox.gfx.Polyline.nodeType:
s=new dojox.gfx.Polyline(_1);
_3(s,dojox.gfx.defaultPolyline);
break;
case dojox.gfx.Path.nodeType:
s=new dojox.gfx.Path(_1);
_3(s,dojox.gfx.defaultPath);
break;
case dojox.gfx.Circle.nodeType:
s=new dojox.gfx.Circle(_1);
_3(s,dojox.gfx.defaultCircle);
break;
case dojox.gfx.Line.nodeType:
s=new dojox.gfx.Line(_1);
_3(s,dojox.gfx.defaultLine);
break;
case dojox.gfx.Image.nodeType:
s=new dojox.gfx.Image(_1);
_3(s,dojox.gfx.defaultImage);
break;
case dojox.gfx.Text.nodeType:
var t=_1.getElementsByTagName("textPath");
if(t&&t.length){
s=new dojox.gfx.TextPath(_1);
_3(s,dojox.gfx.defaultPath);
_4(s);
}else{
s=new dojox.gfx.Text(_1);
_5(s);
}
_6(s);
break;
default:
return null;
}
if(!(s instanceof dojox.gfx.Image)){
_7(s);
_8(s);
}
_9(s);
return s;
};
dojox.gfx.attachSurface=function(_a){
var s=new dojox.gfx.Surface();
s.rawNode=_a;
var _b=_a.getElementsByTagName("defs");
if(_b.length==0){
return null;
}
s.defNode=_b[0];
return s;
};
var _7=function(_c){
var _d=_c.rawNode.getAttribute("fill");
if(_d=="none"){
_c.fillStyle=null;
return;
}
var _e=null,_f=dojox.gfx.svg.getRef(_d);
if(_f){
switch(_f.tagName.toLowerCase()){
case "lineargradient":
_e=_10(dojox.gfx.defaultLinearGradient,_f);
dojo.forEach(["x1","y1","x2","y2"],function(x){
_e[x]=_f.getAttribute(x);
});
break;
case "radialgradient":
_e=_10(dojox.gfx.defaultRadialGradient,_f);
dojo.forEach(["cx","cy","r"],function(x){
_e[x]=_f.getAttribute(x);
});
_e.cx=_f.getAttribute("cx");
_e.cy=_f.getAttribute("cy");
_e.r=_f.getAttribute("r");
break;
case "pattern":
_e=dojo.lang.shallowCopy(dojox.gfx.defaultPattern,true);
dojo.forEach(["x","y","width","height"],function(x){
_e[x]=_f.getAttribute(x);
});
_e.src=_f.firstChild.getAttributeNS(dojox.gfx.svg.xmlns.xlink,"href");
break;
}
}else{
_e=new dojo.Color(_d);
var _11=_c.rawNode.getAttribute("fill-opacity");
if(_11!=null){
_e.a=_11;
}
}
_c.fillStyle=_e;
};
var _10=function(_12,_13){
var _14=dojo.clone(_12);
_14.colors=[];
for(var i=0;i<_13.childNodes.length;++i){
_14.colors.push({offset:_13.childNodes[i].getAttribute("offset"),color:new dojo.Color(_13.childNodes[i].getAttribute("stop-color"))});
}
return _14;
};
var _8=function(_15){
var _16=_15.rawNode,_17=_16.getAttribute("stroke");
if(_17==null||_17=="none"){
_15.strokeStyle=null;
return;
}
var _18=_15.strokeStyle=dojo.clone(dojox.gfx.defaultStroke);
var _19=new dojo.Color(_17);
if(_19){
_18.color=_19;
_18.color.a=_16.getAttribute("stroke-opacity");
_18.width=_16.getAttribute("stroke-width");
_18.cap=_16.getAttribute("stroke-linecap");
_18.join=_16.getAttribute("stroke-linejoin");
if(_18.join=="miter"){
_18.join=_16.getAttribute("stroke-miterlimit");
}
_18.style=_16.getAttribute("dojoGfxStrokeStyle");
}
};
var _9=function(_1a){
var _1b=_1a.rawNode.getAttribute("transform");
if(_1b.match(/^matrix\(.+\)$/)){
var t=_1b.slice(7,-1).split(",");
_1a.matrix=dojox.gfx.matrix.normalize({xx:parseFloat(t[0]),xy:parseFloat(t[2]),yx:parseFloat(t[1]),yy:parseFloat(t[3]),dx:parseFloat(t[4]),dy:parseFloat(t[5])});
}else{
_1a.matrix=null;
}
};
var _6=function(_1c){
var _1d=_1c.fontStyle=dojo.clone(dojox.gfx.defaultFont),r=_1c.rawNode;
_1d.style=r.getAttribute("font-style");
_1d.variant=r.getAttribute("font-variant");
_1d.weight=r.getAttribute("font-weight");
_1d.size=r.getAttribute("font-size");
_1d.family=r.getAttribute("font-family");
};
var _3=function(_1e,def){
var _1f=_1e.shape=dojo.clone(def),r=_1e.rawNode;
for(var i in _1f){
_1f[i]=r.getAttribute(i);
}
};
var _2=function(_20){
_3(_20,dojox.gfx.defaultRect);
_20.shape.r=Math.min(_20.rawNode.getAttribute("rx"),_20.rawNode.getAttribute("ry"));
};
var _5=function(_21){
var _22=_21.shape=dojo.clone(dojox.gfx.defaultText),r=_21.rawNode;
_22.x=r.getAttribute("x");
_22.y=r.getAttribute("y");
_22.align=r.getAttribute("text-anchor");
_22.decoration=r.getAttribute("text-decoration");
_22.rotated=parseFloat(r.getAttribute("rotate"))!=0;
_22.kerning=r.getAttribute("kerning")=="auto";
_22.text=r.firstChild.nodeValue;
};
var _4=function(_23){
var _24=_23.shape=dojo.clone(dojox.gfx.defaultTextPath),r=_23.rawNode;
_24.align=r.getAttribute("text-anchor");
_24.decoration=r.getAttribute("text-decoration");
_24.rotated=parseFloat(r.getAttribute("rotate"))!=0;
_24.kerning=r.getAttribute("kerning")=="auto";
_24.text=r.firstChild.nodeValue;
};
})();
| {
return null;
} | conditional_block |
svg_attach.js | /*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo.require("dojox.gfx.svg");
dojo.experimental("dojox.gfx.svg_attach");
(function(){
dojox.gfx.attachNode=function(_1){
if(!_1){
return null;
}
var s=null;
switch(_1.tagName.toLowerCase()){
case dojox.gfx.Rect.nodeType:
s=new dojox.gfx.Rect(_1);
_2(s);
break;
case dojox.gfx.Ellipse.nodeType:
s=new dojox.gfx.Ellipse(_1);
_3(s,dojox.gfx.defaultEllipse);
break;
case dojox.gfx.Polyline.nodeType:
s=new dojox.gfx.Polyline(_1);
_3(s,dojox.gfx.defaultPolyline);
break;
case dojox.gfx.Path.nodeType:
s=new dojox.gfx.Path(_1);
_3(s,dojox.gfx.defaultPath);
break;
case dojox.gfx.Circle.nodeType:
s=new dojox.gfx.Circle(_1);
_3(s,dojox.gfx.defaultCircle);
break;
case dojox.gfx.Line.nodeType:
s=new dojox.gfx.Line(_1);
_3(s,dojox.gfx.defaultLine);
break;
case dojox.gfx.Image.nodeType:
s=new dojox.gfx.Image(_1);
_3(s,dojox.gfx.defaultImage);
break;
case dojox.gfx.Text.nodeType:
var t=_1.getElementsByTagName("textPath");
if(t&&t.length){
s=new dojox.gfx.TextPath(_1);
_3(s,dojox.gfx.defaultPath);
_4(s);
}else{
s=new dojox.gfx.Text(_1);
_5(s);
}
_6(s);
break;
default:
return null;
}
if(!(s instanceof dojox.gfx.Image)){
_7(s);
_8(s);
}
_9(s);
return s;
};
dojox.gfx.attachSurface=function(_a){
var s=new dojox.gfx.Surface();
s.rawNode=_a;
var _b=_a.getElementsByTagName("defs");
if(_b.length==0){
return null;
}
s.defNode=_b[0];
return s;
};
var _7=function(_c){
var _d=_c.rawNode.getAttribute("fill");
if(_d=="none"){
_c.fillStyle=null;
return;
}
var _e=null,_f=dojox.gfx.svg.getRef(_d);
if(_f){
switch(_f.tagName.toLowerCase()){
case "lineargradient":
_e=_10(dojox.gfx.defaultLinearGradient,_f);
dojo.forEach(["x1","y1","x2","y2"],function(x){
_e[x]=_f.getAttribute(x);
});
break;
case "radialgradient":
_e=_10(dojox.gfx.defaultRadialGradient,_f);
dojo.forEach(["cx","cy","r"],function(x){
_e[x]=_f.getAttribute(x);
});
_e.cx=_f.getAttribute("cx");
_e.cy=_f.getAttribute("cy");
_e.r=_f.getAttribute("r");
break;
case "pattern":
_e=dojo.lang.shallowCopy(dojox.gfx.defaultPattern,true);
dojo.forEach(["x","y","width","height"],function(x){
_e[x]=_f.getAttribute(x);
});
_e.src=_f.firstChild.getAttributeNS(dojox.gfx.svg.xmlns.xlink,"href");
break;
}
}else{
_e=new dojo.Color(_d);
var _11=_c.rawNode.getAttribute("fill-opacity");
if(_11!=null){
_e.a=_11;
}
}
_c.fillStyle=_e;
};
var _10=function(_12,_13){
var _14=dojo.clone(_12);
_14.colors=[];
for(var i=0;i<_13.childNodes.length;++i){
_14.colors.push({offset:_13.childNodes[i].getAttribute("offset"),color:new dojo.Color(_13.childNodes[i].getAttribute("stop-color"))});
}
return _14;
};
var _8=function(_15){
var _16=_15.rawNode,_17=_16.getAttribute("stroke");
if(_17==null||_17=="none"){
_15.strokeStyle=null;
return;
}
var _18=_15.strokeStyle=dojo.clone(dojox.gfx.defaultStroke);
var _19=new dojo.Color(_17);
if(_19){
_18.color=_19;
_18.color.a=_16.getAttribute("stroke-opacity");
_18.width=_16.getAttribute("stroke-width");
_18.cap=_16.getAttribute("stroke-linecap");
_18.join=_16.getAttribute("stroke-linejoin");
if(_18.join=="miter"){
_18.join=_16.getAttribute("stroke-miterlimit");
}
_18.style=_16.getAttribute("dojoGfxStrokeStyle"); | }
};
var _9=function(_1a){
var _1b=_1a.rawNode.getAttribute("transform");
if(_1b.match(/^matrix\(.+\)$/)){
var t=_1b.slice(7,-1).split(",");
_1a.matrix=dojox.gfx.matrix.normalize({xx:parseFloat(t[0]),xy:parseFloat(t[2]),yx:parseFloat(t[1]),yy:parseFloat(t[3]),dx:parseFloat(t[4]),dy:parseFloat(t[5])});
}else{
_1a.matrix=null;
}
};
var _6=function(_1c){
var _1d=_1c.fontStyle=dojo.clone(dojox.gfx.defaultFont),r=_1c.rawNode;
_1d.style=r.getAttribute("font-style");
_1d.variant=r.getAttribute("font-variant");
_1d.weight=r.getAttribute("font-weight");
_1d.size=r.getAttribute("font-size");
_1d.family=r.getAttribute("font-family");
};
var _3=function(_1e,def){
var _1f=_1e.shape=dojo.clone(def),r=_1e.rawNode;
for(var i in _1f){
_1f[i]=r.getAttribute(i);
}
};
var _2=function(_20){
_3(_20,dojox.gfx.defaultRect);
_20.shape.r=Math.min(_20.rawNode.getAttribute("rx"),_20.rawNode.getAttribute("ry"));
};
var _5=function(_21){
var _22=_21.shape=dojo.clone(dojox.gfx.defaultText),r=_21.rawNode;
_22.x=r.getAttribute("x");
_22.y=r.getAttribute("y");
_22.align=r.getAttribute("text-anchor");
_22.decoration=r.getAttribute("text-decoration");
_22.rotated=parseFloat(r.getAttribute("rotate"))!=0;
_22.kerning=r.getAttribute("kerning")=="auto";
_22.text=r.firstChild.nodeValue;
};
var _4=function(_23){
var _24=_23.shape=dojo.clone(dojox.gfx.defaultTextPath),r=_23.rawNode;
_24.align=r.getAttribute("text-anchor");
_24.decoration=r.getAttribute("text-decoration");
_24.rotated=parseFloat(r.getAttribute("rotate"))!=0;
_24.kerning=r.getAttribute("kerning")=="auto";
_24.text=r.firstChild.nodeValue;
};
})(); | random_line_split | |
profiler.py | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$stat_type"
# eg: tendrl-node-agent : /var/lib/tendrl/profiling/node_agent/last_run_func_stat.pstat
import atexit
import GreenletProfiler
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start()
sys.stdout.write("\nStarted Tendrl profiling...")
@atexit.register
def finish():
GreenletProfiler.stop()
sys.stdout.write("\nStopped Tendrl profiling...")
stats = GreenletProfiler.get_func_stats()
_base_path = "/var/lib/tendrl/profiling/{0}/".format(NS.publisher_id)
if not os.path.exists(_base_path):
os.makedirs(_base_path)
for stat_type in ['pstat', 'callgrind', 'ystat']: | _stat_file = "last_run_func_stat.{0}".format(stat_type)
_stat_path = os.path.join(_base_path, _stat_file)
stats.save(_stat_path, type=stat_type)
sys.stdout.write("\nSaved Tendrl profiling stats at %s" % _base_path) | random_line_split | |
profiler.py | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$stat_type"
# eg: tendrl-node-agent : /var/lib/tendrl/profiling/node_agent/last_run_func_stat.pstat
import atexit
import GreenletProfiler
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start()
sys.stdout.write("\nStarted Tendrl profiling...")
@atexit.register
def finish():
| GreenletProfiler.stop()
sys.stdout.write("\nStopped Tendrl profiling...")
stats = GreenletProfiler.get_func_stats()
_base_path = "/var/lib/tendrl/profiling/{0}/".format(NS.publisher_id)
if not os.path.exists(_base_path):
os.makedirs(_base_path)
for stat_type in ['pstat', 'callgrind', 'ystat']:
_stat_file = "last_run_func_stat.{0}".format(stat_type)
_stat_path = os.path.join(_base_path, _stat_file)
stats.save(_stat_path, type=stat_type)
sys.stdout.write("\nSaved Tendrl profiling stats at %s" % _base_path) | identifier_body | |
profiler.py | import os
import sys
def | ():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$stat_type"
# eg: tendrl-node-agent : /var/lib/tendrl/profiling/node_agent/last_run_func_stat.pstat
import atexit
import GreenletProfiler
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start()
sys.stdout.write("\nStarted Tendrl profiling...")
@atexit.register
def finish():
GreenletProfiler.stop()
sys.stdout.write("\nStopped Tendrl profiling...")
stats = GreenletProfiler.get_func_stats()
_base_path = "/var/lib/tendrl/profiling/{0}/".format(NS.publisher_id)
if not os.path.exists(_base_path):
os.makedirs(_base_path)
for stat_type in ['pstat', 'callgrind', 'ystat']:
_stat_file = "last_run_func_stat.{0}".format(stat_type)
_stat_path = os.path.join(_base_path, _stat_file)
stats.save(_stat_path, type=stat_type)
sys.stdout.write("\nSaved Tendrl profiling stats at %s" % _base_path)
| start | identifier_name |
profiler.py | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$stat_type"
# eg: tendrl-node-agent : /var/lib/tendrl/profiling/node_agent/last_run_func_stat.pstat
import atexit
import GreenletProfiler
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start()
sys.stdout.write("\nStarted Tendrl profiling...")
@atexit.register
def finish():
GreenletProfiler.stop()
sys.stdout.write("\nStopped Tendrl profiling...")
stats = GreenletProfiler.get_func_stats()
_base_path = "/var/lib/tendrl/profiling/{0}/".format(NS.publisher_id)
if not os.path.exists(_base_path):
|
for stat_type in ['pstat', 'callgrind', 'ystat']:
_stat_file = "last_run_func_stat.{0}".format(stat_type)
_stat_path = os.path.join(_base_path, _stat_file)
stats.save(_stat_path, type=stat_type)
sys.stdout.write("\nSaved Tendrl profiling stats at %s" % _base_path)
| os.makedirs(_base_path) | conditional_block |
RamachandranFeature.py | import os
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Bio.PDB as PDB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class RamachandranFeature(Feature):
'''Analyze the phi/psi torsion distributions of proteins.'''
def __init__(self):
super().__init__()
self.clf = None
self.de = None
def extract(self, input_path, total_num_threads=1, my_id=0):
'''Extract phi, psi angles from structures in the input path.'''
for f in self.list_my_jobs(input_path, total_num_threads, my_id):
if f.endswith('.pdb'):
self.extract_from_one_file(os.path.join(input_path, f))
def extract_from_one_file(self, pdb_file):
'''Extract phi, psi angles from a pdb_file.'''
structure = data_loading.structure_from_pdb_file(pdb_file)
for model in structure:
for chain in model:
for residue in chain:
try:
feature_dict = {'phi' : geometry.get_phi(chain, residue),
'psi' : geometry.get_psi(chain, residue)}
self.feature_list.append(feature_dict)
except:
pass
def visualize(self, transform_features=True):
'''Visualize the feature statistics.'''
phis = [ d['phi'] for d in self.feature_list ]
psis = [ d['psi'] for d in self.feature_list ]
# Prepare grid points
xx, yy = np.meshgrid(np.linspace(-np.pi, np.pi, 200), np.linspace(-np.pi, np.pi, 200))
transformed_data = np.c_[xx.ravel(), yy.ravel()]
if transform_features:
transformed_data = self.transform_features(transformed_data)
# Draw the decision boundary from the machine learning classifier
if self.clf:
Z = self.clf.decision_function(transformed_data)
Z = Z.reshape(xx.shape)
Z_pred = self.clf.predict(transformed_data)
Z_pred = Z_pred.reshape(xx.shape)
#plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 20), cmap=plt.cm.Blues_r)
#plt.contourf(xx, yy, Z, levels=np.linspace(0, Z.max()), colors='orange')
plt.contourf(xx, yy, Z_pred, levels=[0.9, 1.1], colors='orange')
# Draw the density estimation
if self.de:
Z = self.de.score_samples(transformed_data)
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 7), cmap=plt.cm.Blues_r)
# Draw the data
plt.scatter(phis, psis, c='green', s=5)
# Plot the support vectors if the classifier is SVM
if isinstance(self.clf, svm.OneClassSVM):
if transform_features:
s_phis = [ machine_learning.cos_sin_to_angle(v[0], v[1]) for v in self.clf.support_vectors_ ]
s_psis = [ machine_learning.cos_sin_to_angle(v[2], v[3]) for v in self.clf.support_vectors_ ]
plt.scatter(s_phis, s_psis, c='red') |
plt.axis([- np.pi, np.pi, - np.pi, np.pi])
plt.show()
def save(self, data_path):
'''Save the data into a csv file.'''
data = [ (d['phi'], d['psi']) for d in self.feature_list ]
df = pd.DataFrame(data=data, columns=['phi', 'psi'])
self.append_to_csv(df, os.path.join(data_path, 'rama_features.csv'))
def load(self, data_path):
'''Load data from a csv file.'''
df = pd.read_csv(os.path.join(data_path, 'rama_features.csv'), header=None)
for index, row in df.iterrows():
self.feature_list.append({'phi':row[0], 'psi':row[1]})
def transform_features(self, feature_list):
'''Transform feature representations. The arguement feature_list
could be a list of dictionary or a list of list.
'''
if isinstance(feature_list[0], dict):
return [machine_learning.angle_to_cos_sin(d['phi']) + machine_learning.angle_to_cos_sin(d['psi'])
for d in feature_list]
else:
return [machine_learning.angle_to_cos_sin(d[0]) + machine_learning.angle_to_cos_sin(d[1])
for d in feature_list]
def learn(self, clf_type="OneClassSVM", transform_features=True):
'''Learn the distribution with a machine learning classifier'''
# Prepare the training data
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.6 * n_data)]
test_data = all_data[int(0.6 * n_data):int(0.8 * n_data)]
cv_data = all_data[int(0.8 * n_data):n_data]
# Train the classifier
if clf_type == "OneClassSVM":
nus = [0.05, 0.02, 0.01, 0.005, 0.002, 0.001]
least_error = len(test_data)
for i in range(len(nus)):
print("nu = {0}".format(nus[i]))
clf = svm.OneClassSVM(nu=nus[i], kernel="rbf", gamma='auto')
clf.fit(training_data)
predictions = clf.predict(training_data)
print("{0}/{1} training error.".format(len(predictions[-1 == predictions]), len(training_data)))
predictions = clf.predict(test_data)
print("{0}/{1} test error.\n".format(len(predictions[-1 == predictions]), len(test_data)))
if len(predictions[-1 == predictions]) < least_error:
least_error = len(predictions[-1 == predictions])
self.clf = clf
elif clf_type == "IsolationForest":
self.clf = IsolationForest(max_samples=20000,
contamination=0.01, random_state=np.random.RandomState(42))
self.clf.fit(training_data)
# Print Training results
predictions = self.clf.predict(cv_data)
print("{0}/{1} cross validation error.".format(len(predictions[-1 == predictions]), len(cv_data)))
if clf_type == "OneClassSVM":
print("{0} support vectors found.".format(len(self.clf.support_)))
def predict(self, input_data, transform_features=True):
'''Make a prediction for the input data with the machine learning classifier.
input_data is a list of phi, psi angles.
'''
transformed_data = input_data
if transform_features:
transformed_data = self.transform_features(transformed_data)
return self.clf.predict(transformed_data)
def calculate_space_reduction(self, transform_features=True):
'''Calculate the space reduction power of the machine learning model.'''
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
predictions = self.predict(list(zip(phis, psis)), transform_features=transform_features)
print("The space is reduced by {0}.".format(len(predictions[1 == predictions]) / len(predictions)))
def density_estimate(self, de_type="GaussianMixture", transform_features=True):
'''Get a density estimation of the data.'''
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.7 * n_data)]
test_data = all_data[int(0.7 * n_data):n_data]
# Make some random data
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
random_data = list(zip(phis, psis))
if transform_features:
random_data = self.transform_features(random_data)
if de_type == "GaussianMixture":
self.de = mixture.BayesianGaussianMixture(n_components=100, covariance_type='full').fit(training_data)
# Evalute the cumulative distribution functions of scores of test data
test_scores = self.de.score_samples(test_data)
values, base = np.histogram(test_scores, bins=40)
cumulative = np.cumsum(values)
for i in range(40):
# Evaluate the space compression
random_scores = self.de.score_samples(random_data)
compress_coe = len(random_scores[random_scores > base[i]]) / len(random_scores)
print('{0:.3f}\t{1}\t{2:.5f}\t{3:.5f}'.format(base[i], cumulative[i], cumulative[i] / len(test_data), compress_coe))
elif de_type == "KernelDensity":
params = {'bandwidth': np.logspace(-1, 1, 5)}
grid = GridSearchCV(KernelDensity(), params)
grid.fit(training_data)
self.de = grid.best_estimator_ | else:
plt.scatter(self.clf.support_vectors_[:][0], self.clf.support_vectors_[:][1], c='red') | random_line_split |
RamachandranFeature.py | import os
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Bio.PDB as PDB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class | (Feature):
'''Analyze the phi/psi torsion distributions of proteins.'''
def __init__(self):
super().__init__()
self.clf = None
self.de = None
def extract(self, input_path, total_num_threads=1, my_id=0):
'''Extract phi, psi angles from structures in the input path.'''
for f in self.list_my_jobs(input_path, total_num_threads, my_id):
if f.endswith('.pdb'):
self.extract_from_one_file(os.path.join(input_path, f))
def extract_from_one_file(self, pdb_file):
'''Extract phi, psi angles from a pdb_file.'''
structure = data_loading.structure_from_pdb_file(pdb_file)
for model in structure:
for chain in model:
for residue in chain:
try:
feature_dict = {'phi' : geometry.get_phi(chain, residue),
'psi' : geometry.get_psi(chain, residue)}
self.feature_list.append(feature_dict)
except:
pass
def visualize(self, transform_features=True):
'''Visualize the feature statistics.'''
phis = [ d['phi'] for d in self.feature_list ]
psis = [ d['psi'] for d in self.feature_list ]
# Prepare grid points
xx, yy = np.meshgrid(np.linspace(-np.pi, np.pi, 200), np.linspace(-np.pi, np.pi, 200))
transformed_data = np.c_[xx.ravel(), yy.ravel()]
if transform_features:
transformed_data = self.transform_features(transformed_data)
# Draw the decision boundary from the machine learning classifier
if self.clf:
Z = self.clf.decision_function(transformed_data)
Z = Z.reshape(xx.shape)
Z_pred = self.clf.predict(transformed_data)
Z_pred = Z_pred.reshape(xx.shape)
#plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 20), cmap=plt.cm.Blues_r)
#plt.contourf(xx, yy, Z, levels=np.linspace(0, Z.max()), colors='orange')
plt.contourf(xx, yy, Z_pred, levels=[0.9, 1.1], colors='orange')
# Draw the density estimation
if self.de:
Z = self.de.score_samples(transformed_data)
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 7), cmap=plt.cm.Blues_r)
# Draw the data
plt.scatter(phis, psis, c='green', s=5)
# Plot the support vectors if the classifier is SVM
if isinstance(self.clf, svm.OneClassSVM):
if transform_features:
s_phis = [ machine_learning.cos_sin_to_angle(v[0], v[1]) for v in self.clf.support_vectors_ ]
s_psis = [ machine_learning.cos_sin_to_angle(v[2], v[3]) for v in self.clf.support_vectors_ ]
plt.scatter(s_phis, s_psis, c='red')
else:
plt.scatter(self.clf.support_vectors_[:][0], self.clf.support_vectors_[:][1], c='red')
plt.axis([- np.pi, np.pi, - np.pi, np.pi])
plt.show()
def save(self, data_path):
'''Save the data into a csv file.'''
data = [ (d['phi'], d['psi']) for d in self.feature_list ]
df = pd.DataFrame(data=data, columns=['phi', 'psi'])
self.append_to_csv(df, os.path.join(data_path, 'rama_features.csv'))
def load(self, data_path):
'''Load data from a csv file.'''
df = pd.read_csv(os.path.join(data_path, 'rama_features.csv'), header=None)
for index, row in df.iterrows():
self.feature_list.append({'phi':row[0], 'psi':row[1]})
def transform_features(self, feature_list):
'''Transform feature representations. The arguement feature_list
could be a list of dictionary or a list of list.
'''
if isinstance(feature_list[0], dict):
return [machine_learning.angle_to_cos_sin(d['phi']) + machine_learning.angle_to_cos_sin(d['psi'])
for d in feature_list]
else:
return [machine_learning.angle_to_cos_sin(d[0]) + machine_learning.angle_to_cos_sin(d[1])
for d in feature_list]
def learn(self, clf_type="OneClassSVM", transform_features=True):
'''Learn the distribution with a machine learning classifier'''
# Prepare the training data
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.6 * n_data)]
test_data = all_data[int(0.6 * n_data):int(0.8 * n_data)]
cv_data = all_data[int(0.8 * n_data):n_data]
# Train the classifier
if clf_type == "OneClassSVM":
nus = [0.05, 0.02, 0.01, 0.005, 0.002, 0.001]
least_error = len(test_data)
for i in range(len(nus)):
print("nu = {0}".format(nus[i]))
clf = svm.OneClassSVM(nu=nus[i], kernel="rbf", gamma='auto')
clf.fit(training_data)
predictions = clf.predict(training_data)
print("{0}/{1} training error.".format(len(predictions[-1 == predictions]), len(training_data)))
predictions = clf.predict(test_data)
print("{0}/{1} test error.\n".format(len(predictions[-1 == predictions]), len(test_data)))
if len(predictions[-1 == predictions]) < least_error:
least_error = len(predictions[-1 == predictions])
self.clf = clf
elif clf_type == "IsolationForest":
self.clf = IsolationForest(max_samples=20000,
contamination=0.01, random_state=np.random.RandomState(42))
self.clf.fit(training_data)
# Print Training results
predictions = self.clf.predict(cv_data)
print("{0}/{1} cross validation error.".format(len(predictions[-1 == predictions]), len(cv_data)))
if clf_type == "OneClassSVM":
print("{0} support vectors found.".format(len(self.clf.support_)))
def predict(self, input_data, transform_features=True):
'''Make a prediction for the input data with the machine learning classifier.
input_data is a list of phi, psi angles.
'''
transformed_data = input_data
if transform_features:
transformed_data = self.transform_features(transformed_data)
return self.clf.predict(transformed_data)
def calculate_space_reduction(self, transform_features=True):
'''Calculate the space reduction power of the machine learning model.'''
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
predictions = self.predict(list(zip(phis, psis)), transform_features=transform_features)
print("The space is reduced by {0}.".format(len(predictions[1 == predictions]) / len(predictions)))
def density_estimate(self, de_type="GaussianMixture", transform_features=True):
'''Get a density estimation of the data.'''
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.7 * n_data)]
test_data = all_data[int(0.7 * n_data):n_data]
# Make some random data
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
random_data = list(zip(phis, psis))
if transform_features:
random_data = self.transform_features(random_data)
if de_type == "GaussianMixture":
self.de = mixture.BayesianGaussianMixture(n_components=100, covariance_type='full').fit(training_data)
# Evalute the cumulative distribution functions of scores of test data
test_scores = self.de.score_samples(test_data)
values, base = np.histogram(test_scores, bins=40)
cumulative = np.cumsum(values)
for i in range(40):
# Evaluate the space compression
random_scores = self.de.score_samples(random_data)
compress_coe = len(random_scores[random_scores > base[i]]) / len(random_scores)
print('{0:.3f}\t{1}\t{2:.5f}\t{3:.5f}'.format(base[i], cumulative[i], cumulative[i] / len(test_data), compress_coe))
elif de_type == "KernelDensity":
params = {'bandwidth': np.logspace(-1, 1, 5)}
grid = GridSearchCV(KernelDensity(), params)
grid.fit(training_data)
self.de = grid.best_estimator_
| RamachandranFeature | identifier_name |
RamachandranFeature.py | import os
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Bio.PDB as PDB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class RamachandranFeature(Feature):
'''Analyze the phi/psi torsion distributions of proteins.'''
def __init__(self):
super().__init__()
self.clf = None
self.de = None
def extract(self, input_path, total_num_threads=1, my_id=0):
'''Extract phi, psi angles from structures in the input path.'''
for f in self.list_my_jobs(input_path, total_num_threads, my_id):
if f.endswith('.pdb'):
self.extract_from_one_file(os.path.join(input_path, f))
def extract_from_one_file(self, pdb_file):
'''Extract phi, psi angles from a pdb_file.'''
structure = data_loading.structure_from_pdb_file(pdb_file)
for model in structure:
for chain in model:
for residue in chain:
try:
feature_dict = {'phi' : geometry.get_phi(chain, residue),
'psi' : geometry.get_psi(chain, residue)}
self.feature_list.append(feature_dict)
except:
pass
def visualize(self, transform_features=True):
'''Visualize the feature statistics.'''
phis = [ d['phi'] for d in self.feature_list ]
psis = [ d['psi'] for d in self.feature_list ]
# Prepare grid points
xx, yy = np.meshgrid(np.linspace(-np.pi, np.pi, 200), np.linspace(-np.pi, np.pi, 200))
transformed_data = np.c_[xx.ravel(), yy.ravel()]
if transform_features:
transformed_data = self.transform_features(transformed_data)
# Draw the decision boundary from the machine learning classifier
if self.clf:
Z = self.clf.decision_function(transformed_data)
Z = Z.reshape(xx.shape)
Z_pred = self.clf.predict(transformed_data)
Z_pred = Z_pred.reshape(xx.shape)
#plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 20), cmap=plt.cm.Blues_r)
#plt.contourf(xx, yy, Z, levels=np.linspace(0, Z.max()), colors='orange')
plt.contourf(xx, yy, Z_pred, levels=[0.9, 1.1], colors='orange')
# Draw the density estimation
if self.de:
Z = self.de.score_samples(transformed_data)
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 7), cmap=plt.cm.Blues_r)
# Draw the data
plt.scatter(phis, psis, c='green', s=5)
# Plot the support vectors if the classifier is SVM
if isinstance(self.clf, svm.OneClassSVM):
if transform_features:
s_phis = [ machine_learning.cos_sin_to_angle(v[0], v[1]) for v in self.clf.support_vectors_ ]
s_psis = [ machine_learning.cos_sin_to_angle(v[2], v[3]) for v in self.clf.support_vectors_ ]
plt.scatter(s_phis, s_psis, c='red')
else:
plt.scatter(self.clf.support_vectors_[:][0], self.clf.support_vectors_[:][1], c='red')
plt.axis([- np.pi, np.pi, - np.pi, np.pi])
plt.show()
def save(self, data_path):
'''Save the data into a csv file.'''
data = [ (d['phi'], d['psi']) for d in self.feature_list ]
df = pd.DataFrame(data=data, columns=['phi', 'psi'])
self.append_to_csv(df, os.path.join(data_path, 'rama_features.csv'))
def load(self, data_path):
'''Load data from a csv file.'''
df = pd.read_csv(os.path.join(data_path, 'rama_features.csv'), header=None)
for index, row in df.iterrows():
self.feature_list.append({'phi':row[0], 'psi':row[1]})
def transform_features(self, feature_list):
'''Transform feature representations. The arguement feature_list
could be a list of dictionary or a list of list.
'''
if isinstance(feature_list[0], dict):
return [machine_learning.angle_to_cos_sin(d['phi']) + machine_learning.angle_to_cos_sin(d['psi'])
for d in feature_list]
else:
return [machine_learning.angle_to_cos_sin(d[0]) + machine_learning.angle_to_cos_sin(d[1])
for d in feature_list]
def learn(self, clf_type="OneClassSVM", transform_features=True):
'''Learn the distribution with a machine learning classifier'''
# Prepare the training data
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.6 * n_data)]
test_data = all_data[int(0.6 * n_data):int(0.8 * n_data)]
cv_data = all_data[int(0.8 * n_data):n_data]
# Train the classifier
if clf_type == "OneClassSVM":
nus = [0.05, 0.02, 0.01, 0.005, 0.002, 0.001]
least_error = len(test_data)
for i in range(len(nus)):
print("nu = {0}".format(nus[i]))
clf = svm.OneClassSVM(nu=nus[i], kernel="rbf", gamma='auto')
clf.fit(training_data)
predictions = clf.predict(training_data)
print("{0}/{1} training error.".format(len(predictions[-1 == predictions]), len(training_data)))
predictions = clf.predict(test_data)
print("{0}/{1} test error.\n".format(len(predictions[-1 == predictions]), len(test_data)))
if len(predictions[-1 == predictions]) < least_error:
least_error = len(predictions[-1 == predictions])
self.clf = clf
elif clf_type == "IsolationForest":
self.clf = IsolationForest(max_samples=20000,
contamination=0.01, random_state=np.random.RandomState(42))
self.clf.fit(training_data)
# Print Training results
predictions = self.clf.predict(cv_data)
print("{0}/{1} cross validation error.".format(len(predictions[-1 == predictions]), len(cv_data)))
if clf_type == "OneClassSVM":
print("{0} support vectors found.".format(len(self.clf.support_)))
def predict(self, input_data, transform_features=True):
'''Make a prediction for the input data with the machine learning classifier.
input_data is a list of phi, psi angles.
'''
transformed_data = input_data
if transform_features:
transformed_data = self.transform_features(transformed_data)
return self.clf.predict(transformed_data)
def calculate_space_reduction(self, transform_features=True):
'''Calculate the space reduction power of the machine learning model.'''
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
predictions = self.predict(list(zip(phis, psis)), transform_features=transform_features)
print("The space is reduced by {0}.".format(len(predictions[1 == predictions]) / len(predictions)))
def density_estimate(self, de_type="GaussianMixture", transform_features=True):
'''Get a density estimation of the data.'''
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
|
n_data = len(all_data)
training_data = all_data[0:int(0.7 * n_data)]
test_data = all_data[int(0.7 * n_data):n_data]
# Make some random data
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
random_data = list(zip(phis, psis))
if transform_features:
random_data = self.transform_features(random_data)
if de_type == "GaussianMixture":
self.de = mixture.BayesianGaussianMixture(n_components=100, covariance_type='full').fit(training_data)
# Evalute the cumulative distribution functions of scores of test data
test_scores = self.de.score_samples(test_data)
values, base = np.histogram(test_scores, bins=40)
cumulative = np.cumsum(values)
for i in range(40):
# Evaluate the space compression
random_scores = self.de.score_samples(random_data)
compress_coe = len(random_scores[random_scores > base[i]]) / len(random_scores)
print('{0:.3f}\t{1}\t{2:.5f}\t{3:.5f}'.format(base[i], cumulative[i], cumulative[i] / len(test_data), compress_coe))
elif de_type == "KernelDensity":
params = {'bandwidth': np.logspace(-1, 1, 5)}
grid = GridSearchCV(KernelDensity(), params)
grid.fit(training_data)
self.de = grid.best_estimator_
| all_data = self.transform_features(all_data) | conditional_block |
RamachandranFeature.py | import os
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Bio.PDB as PDB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class RamachandranFeature(Feature):
'''Analyze the phi/psi torsion distributions of proteins.'''
def __init__(self):
super().__init__()
self.clf = None
self.de = None
def extract(self, input_path, total_num_threads=1, my_id=0):
'''Extract phi, psi angles from structures in the input path.'''
for f in self.list_my_jobs(input_path, total_num_threads, my_id):
if f.endswith('.pdb'):
self.extract_from_one_file(os.path.join(input_path, f))
def extract_from_one_file(self, pdb_file):
'''Extract phi, psi angles from a pdb_file.'''
structure = data_loading.structure_from_pdb_file(pdb_file)
for model in structure:
for chain in model:
for residue in chain:
try:
feature_dict = {'phi' : geometry.get_phi(chain, residue),
'psi' : geometry.get_psi(chain, residue)}
self.feature_list.append(feature_dict)
except:
pass
def visualize(self, transform_features=True):
'''Visualize the feature statistics.'''
phis = [ d['phi'] for d in self.feature_list ]
psis = [ d['psi'] for d in self.feature_list ]
# Prepare grid points
xx, yy = np.meshgrid(np.linspace(-np.pi, np.pi, 200), np.linspace(-np.pi, np.pi, 200))
transformed_data = np.c_[xx.ravel(), yy.ravel()]
if transform_features:
transformed_data = self.transform_features(transformed_data)
# Draw the decision boundary from the machine learning classifier
if self.clf:
Z = self.clf.decision_function(transformed_data)
Z = Z.reshape(xx.shape)
Z_pred = self.clf.predict(transformed_data)
Z_pred = Z_pred.reshape(xx.shape)
#plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 20), cmap=plt.cm.Blues_r)
#plt.contourf(xx, yy, Z, levels=np.linspace(0, Z.max()), colors='orange')
plt.contourf(xx, yy, Z_pred, levels=[0.9, 1.1], colors='orange')
# Draw the density estimation
if self.de:
Z = self.de.score_samples(transformed_data)
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), Z.max(), 7), cmap=plt.cm.Blues_r)
# Draw the data
plt.scatter(phis, psis, c='green', s=5)
# Plot the support vectors if the classifier is SVM
if isinstance(self.clf, svm.OneClassSVM):
if transform_features:
s_phis = [ machine_learning.cos_sin_to_angle(v[0], v[1]) for v in self.clf.support_vectors_ ]
s_psis = [ machine_learning.cos_sin_to_angle(v[2], v[3]) for v in self.clf.support_vectors_ ]
plt.scatter(s_phis, s_psis, c='red')
else:
plt.scatter(self.clf.support_vectors_[:][0], self.clf.support_vectors_[:][1], c='red')
plt.axis([- np.pi, np.pi, - np.pi, np.pi])
plt.show()
def save(self, data_path):
'''Save the data into a csv file.'''
data = [ (d['phi'], d['psi']) for d in self.feature_list ]
df = pd.DataFrame(data=data, columns=['phi', 'psi'])
self.append_to_csv(df, os.path.join(data_path, 'rama_features.csv'))
def load(self, data_path):
'''Load data from a csv file.'''
df = pd.read_csv(os.path.join(data_path, 'rama_features.csv'), header=None)
for index, row in df.iterrows():
self.feature_list.append({'phi':row[0], 'psi':row[1]})
def transform_features(self, feature_list):
'''Transform feature representations. The arguement feature_list
could be a list of dictionary or a list of list.
'''
if isinstance(feature_list[0], dict):
return [machine_learning.angle_to_cos_sin(d['phi']) + machine_learning.angle_to_cos_sin(d['psi'])
for d in feature_list]
else:
return [machine_learning.angle_to_cos_sin(d[0]) + machine_learning.angle_to_cos_sin(d[1])
for d in feature_list]
def learn(self, clf_type="OneClassSVM", transform_features=True):
|
def predict(self, input_data, transform_features=True):
'''Make a prediction for the input data with the machine learning classifier.
input_data is a list of phi, psi angles.
'''
transformed_data = input_data
if transform_features:
transformed_data = self.transform_features(transformed_data)
return self.clf.predict(transformed_data)
def calculate_space_reduction(self, transform_features=True):
'''Calculate the space reduction power of the machine learning model.'''
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
predictions = self.predict(list(zip(phis, psis)), transform_features=transform_features)
print("The space is reduced by {0}.".format(len(predictions[1 == predictions]) / len(predictions)))
def density_estimate(self, de_type="GaussianMixture", transform_features=True):
'''Get a density estimation of the data.'''
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.7 * n_data)]
test_data = all_data[int(0.7 * n_data):n_data]
# Make some random data
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
random_data = list(zip(phis, psis))
if transform_features:
random_data = self.transform_features(random_data)
if de_type == "GaussianMixture":
self.de = mixture.BayesianGaussianMixture(n_components=100, covariance_type='full').fit(training_data)
# Evalute the cumulative distribution functions of scores of test data
test_scores = self.de.score_samples(test_data)
values, base = np.histogram(test_scores, bins=40)
cumulative = np.cumsum(values)
for i in range(40):
# Evaluate the space compression
random_scores = self.de.score_samples(random_data)
compress_coe = len(random_scores[random_scores > base[i]]) / len(random_scores)
print('{0:.3f}\t{1}\t{2:.5f}\t{3:.5f}'.format(base[i], cumulative[i], cumulative[i] / len(test_data), compress_coe))
elif de_type == "KernelDensity":
params = {'bandwidth': np.logspace(-1, 1, 5)}
grid = GridSearchCV(KernelDensity(), params)
grid.fit(training_data)
self.de = grid.best_estimator_
| '''Learn the distribution with a machine learning classifier'''
# Prepare the training data
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.6 * n_data)]
test_data = all_data[int(0.6 * n_data):int(0.8 * n_data)]
cv_data = all_data[int(0.8 * n_data):n_data]
# Train the classifier
if clf_type == "OneClassSVM":
nus = [0.05, 0.02, 0.01, 0.005, 0.002, 0.001]
least_error = len(test_data)
for i in range(len(nus)):
print("nu = {0}".format(nus[i]))
clf = svm.OneClassSVM(nu=nus[i], kernel="rbf", gamma='auto')
clf.fit(training_data)
predictions = clf.predict(training_data)
print("{0}/{1} training error.".format(len(predictions[-1 == predictions]), len(training_data)))
predictions = clf.predict(test_data)
print("{0}/{1} test error.\n".format(len(predictions[-1 == predictions]), len(test_data)))
if len(predictions[-1 == predictions]) < least_error:
least_error = len(predictions[-1 == predictions])
self.clf = clf
elif clf_type == "IsolationForest":
self.clf = IsolationForest(max_samples=20000,
contamination=0.01, random_state=np.random.RandomState(42))
self.clf.fit(training_data)
# Print Training results
predictions = self.clf.predict(cv_data)
print("{0}/{1} cross validation error.".format(len(predictions[-1 == predictions]), len(cv_data)))
if clf_type == "OneClassSVM":
print("{0} support vectors found.".format(len(self.clf.support_))) | identifier_body |
utils.ts | import { Model } from 'models/Model';
export function camelcaseToDashcase(camelcaseString: string) {
return camelcaseString.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
export function autoBind(object: { [index: string]: any }) |
export function toIdLookup<T extends Model = Model>(list: T[]) {
return list.reduce((lookup: {[index: number]: T}, item) => {
lookup[item.id] = item;
return lookup;
}, {});
}
export function nodeHeight(node: HTMLElement) {
return Array.from(node.children).reduce((acc, child) => {
return acc + parseInt(getComputedStyle(child).height.replace('px', ''), 10);
}, 0) + 'px';
}
// The array needs to have the $resolved property since it is used
// to determine when the data has returned from the server normally
export function emptyArrayResponse<T>() {
const res: T[] = [];
res.$resolved = true;
return res;
}
| {
return Object.getOwnPropertyNames(object).forEach((propName: string) => {
const prop = object[propName];
if (typeof prop === 'function') {
object[prop] = prop.bind(object);
}
});
} | identifier_body |
utils.ts | import { Model } from 'models/Model';
export function camelcaseToDashcase(camelcaseString: string) {
return camelcaseString.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
export function autoBind(object: { [index: string]: any }) {
return Object.getOwnPropertyNames(object).forEach((propName: string) => {
const prop = object[propName];
if (typeof prop === 'function') |
});
}
export function toIdLookup<T extends Model = Model>(list: T[]) {
return list.reduce((lookup: {[index: number]: T}, item) => {
lookup[item.id] = item;
return lookup;
}, {});
}
export function nodeHeight(node: HTMLElement) {
return Array.from(node.children).reduce((acc, child) => {
return acc + parseInt(getComputedStyle(child).height.replace('px', ''), 10);
}, 0) + 'px';
}
// The array needs to have the $resolved property since it is used
// to determine when the data has returned from the server normally
export function emptyArrayResponse<T>() {
const res: T[] = [];
res.$resolved = true;
return res;
}
| {
object[prop] = prop.bind(object);
} | conditional_block |
utils.ts | import { Model } from 'models/Model';
export function camelcaseToDashcase(camelcaseString: string) {
return camelcaseString.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
export function autoBind(object: { [index: string]: any }) {
return Object.getOwnPropertyNames(object).forEach((propName: string) => {
const prop = object[propName];
if (typeof prop === 'function') {
object[prop] = prop.bind(object);
}
});
}
export function | <T extends Model = Model>(list: T[]) {
return list.reduce((lookup: {[index: number]: T}, item) => {
lookup[item.id] = item;
return lookup;
}, {});
}
export function nodeHeight(node: HTMLElement) {
return Array.from(node.children).reduce((acc, child) => {
return acc + parseInt(getComputedStyle(child).height.replace('px', ''), 10);
}, 0) + 'px';
}
// The array needs to have the $resolved property since it is used
// to determine when the data has returned from the server normally
export function emptyArrayResponse<T>() {
const res: T[] = [];
res.$resolved = true;
return res;
}
| toIdLookup | identifier_name |
buffer.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { OperatorFunction } from '../types';
/**
* Buffers the source Observable values until `closingNotifier` emits.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when another Observable emits.</span>
*
* 
*
* Buffers the incoming Observable values until the given `closingNotifier`
* Observable emits a value, at which point it emits the buffer on the output
* Observable and starts a new buffer internally, awaiting the next time
* `closingNotifier` emits.
*
* ## Example
*
* On every click, emit array of most recent interval events
*
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { buffer } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const intervalEvents = interval(1000);
* const buffered = intervalEvents.pipe(buffer(clicks));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link window}
*
* @param {Observable<any>} closingNotifier An Observable that signals the
* buffer to be emitted on the output Observable.
* @return {Observable<T[]>} An Observable of buffers, which are arrays of
* values.
* @method buffer
* @owner Observable
*/
export function buffer<T>(closingNotifier: Observable<any>): OperatorFunction<T, T[]> {
return function bufferOperatorFunction(source: Observable<T>) {
return source.lift(new BufferOperator<T>(closingNotifier));
};
}
class | <T> implements Operator<T, T[]> {
constructor(private closingNotifier: Observable<any>) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferSubscriber<T> extends OuterSubscriber<T, any> {
private buffer: T[] = [];
constructor(destination: Subscriber<T[]>, closingNotifier: Observable<any>) {
super(destination);
this.add(subscribeToResult(this, closingNotifier));
}
protected _next(value: T) {
this.buffer.push(value);
}
notifyNext(outerValue: T, innerValue: any,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, any>): void {
const buffer = this.buffer;
this.buffer = [];
this.destination.next(buffer);
}
}
| BufferOperator | identifier_name |
buffer.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { OperatorFunction } from '../types';
/**
* Buffers the source Observable values until `closingNotifier` emits.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when another Observable emits.</span>
*
* 
*
* Buffers the incoming Observable values until the given `closingNotifier`
* Observable emits a value, at which point it emits the buffer on the output
* Observable and starts a new buffer internally, awaiting the next time
* `closingNotifier` emits.
*
* ## Example
*
* On every click, emit array of most recent interval events
*
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { buffer } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const intervalEvents = interval(1000);
* const buffered = intervalEvents.pipe(buffer(clicks));
* buffered.subscribe(x => console.log(x)); | * @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link window}
*
* @param {Observable<any>} closingNotifier An Observable that signals the
* buffer to be emitted on the output Observable.
* @return {Observable<T[]>} An Observable of buffers, which are arrays of
* values.
* @method buffer
* @owner Observable
*/
export function buffer<T>(closingNotifier: Observable<any>): OperatorFunction<T, T[]> {
return function bufferOperatorFunction(source: Observable<T>) {
return source.lift(new BufferOperator<T>(closingNotifier));
};
}
class BufferOperator<T> implements Operator<T, T[]> {
constructor(private closingNotifier: Observable<any>) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferSubscriber<T> extends OuterSubscriber<T, any> {
private buffer: T[] = [];
constructor(destination: Subscriber<T[]>, closingNotifier: Observable<any>) {
super(destination);
this.add(subscribeToResult(this, closingNotifier));
}
protected _next(value: T) {
this.buffer.push(value);
}
notifyNext(outerValue: T, innerValue: any,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, any>): void {
const buffer = this.buffer;
this.buffer = [];
this.destination.next(buffer);
}
} | * ```
* | random_line_split |
gain.rs | use super::super::api;
pub fn information_gain<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let e = target_entropy(data, view);
let fe = entropy(data, view, criterion);
e - fe
}
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 {
let mut total = 0;
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
if criterion(&record.0) == value {
classes[record.1 as usize] += 1;
total += 1;
}
}
let mut result = 0f64;
for class in classes.iter() {
if *class != 0 {
let p = (*class as f64) / (total as f64);
result += p * p.log2()
}
}
-result
}
fn entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let total = data.records.len();
let mut ccs = vec![0u8, 0u8];
let values = vec![false, true];
for index in view.iter() {
let record = &data.records[*index];
let i = match criterion(&record.0) {
false => 0,
true => 1,
};
ccs[i] += 1;
}
let mut result = 0f64;
for i in 0..2 {
let p = (ccs[i] as f64) / (total as f64);
result += p * entropy_helper(data, view, values[i], criterion);
}
result
}
fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView) -> f64 | {
let total = data.records.len();
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
classes[record.1 as usize] += 1;
}
for class in classes.iter() {
if *class == 0 {
return 0f64
}
}
let mut result = 0f64;
for class in classes.iter() {
let p = (*class as f64) / (total as f64);
result += p * p.log2()
}
-result
} | identifier_body | |
gain.rs | use super::super::api;
pub fn | <T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let e = target_entropy(data, view);
let fe = entropy(data, view, criterion);
e - fe
}
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 {
let mut total = 0;
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
if criterion(&record.0) == value {
classes[record.1 as usize] += 1;
total += 1;
}
}
let mut result = 0f64;
for class in classes.iter() {
if *class != 0 {
let p = (*class as f64) / (total as f64);
result += p * p.log2()
}
}
-result
}
fn entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let total = data.records.len();
let mut ccs = vec![0u8, 0u8];
let values = vec![false, true];
for index in view.iter() {
let record = &data.records[*index];
let i = match criterion(&record.0) {
false => 0,
true => 1,
};
ccs[i] += 1;
}
let mut result = 0f64;
for i in 0..2 {
let p = (ccs[i] as f64) / (total as f64);
result += p * entropy_helper(data, view, values[i], criterion);
}
result
}
fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView) -> f64 {
let total = data.records.len();
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
classes[record.1 as usize] += 1;
}
for class in classes.iter() {
if *class == 0 {
return 0f64
}
}
let mut result = 0f64;
for class in classes.iter() {
let p = (*class as f64) / (total as f64);
result += p * p.log2()
}
-result
}
| information_gain | identifier_name |
gain.rs | use super::super::api;
pub fn information_gain<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let e = target_entropy(data, view);
let fe = entropy(data, view, criterion);
e - fe
|
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 {
let mut total = 0;
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
if criterion(&record.0) == value {
classes[record.1 as usize] += 1;
total += 1;
}
}
let mut result = 0f64;
for class in classes.iter() {
if *class != 0 {
let p = (*class as f64) / (total as f64);
result += p * p.log2()
}
}
-result
}
fn entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let total = data.records.len();
let mut ccs = vec![0u8, 0u8];
let values = vec![false, true];
for index in view.iter() {
let record = &data.records[*index];
let i = match criterion(&record.0) {
false => 0,
true => 1,
};
ccs[i] += 1;
}
let mut result = 0f64;
for i in 0..2 {
let p = (ccs[i] as f64) / (total as f64);
result += p * entropy_helper(data, view, values[i], criterion);
}
result
}
fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView) -> f64 {
let total = data.records.len();
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
classes[record.1 as usize] += 1;
}
for class in classes.iter() {
if *class == 0 {
return 0f64
}
}
let mut result = 0f64;
for class in classes.iter() {
let p = (*class as f64) / (total as f64);
result += p * p.log2()
}
-result
} | }
| random_line_split |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Subject, ReplaySubject} from '@reactivex/rxjs/dist/cjs/Rx';
/**
*
* Mock Connection to represent a {@link Connection} for tests.
*
**/
export class MockConnection implements Connection {
// TODO Name `readyState` should change to be more generic, and states could be made to be more
// descriptive than XHR states.
/**
* Describes the state of the connection, based on `XMLHttpRequest.readyState`, but with
* additional states. For example, state 5 indicates an aborted connection.
*/
readyState: ReadyStates;
/**
* {@link Request} instance used to create the connection.
*/
request: Request;
/**
* {@link EventEmitter} of {@link Response}. Can be subscribed to in order to be notified when a
* response is available.
*/
response: any; // Subject<Response>
constructor(req: Request) {
this.response = new ReplaySubject(1).take(1);
this.readyState = ReadyStates.Open;
this.request = req;
}
/**
* Sends a mock response to the connection. This response is the value that is emitted to the
* {@link EventEmitter} returned by {@link Http}.
*
* ### Example
*
* ```
* var connection;
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe(res => console.log(res.text()));
* connection.mockRespond(new Response('fake response')); //logs 'fake response'
* ```
*
*/
mockRespond(res: Response) {
if (this.readyState === ReadyStates.Done || this.readyState === ReadyStates.Cancelled) {
throw new BaseException('Connection has already been resolved');
}
this.readyState = ReadyStates.Done;
this.response.next(res);
this.response.complete();
}
/**
* Not yet implemented!
*
* Sends the provided {@link Response} to the `downloadObserver` of the `Request`
* associated with this connection.
*/
mockDownload(res: Response) {
// this.request.downloadObserver.onNext(res);
// if (res.bytesLoaded === res.totalBytes) {
// this.request.downloadObserver.onCompleted();
// }
}
// TODO(jeffbcross): consider using Response type
/**
* Emits the provided error object as an error to the {@link Response} {@link EventEmitter}
* returned
* from {@link Http}.
*/
mockError(err?: Error) {
// Matches XHR semantics | }
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* ### Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some data', inject([AsyncTestCompleter], (async) => {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, defaultOptions) => {
* return new Http(backend, defaultOptions)
* }, deps: [MockBackend, DefaultOptions]})]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
* //Assign any newly-created connection to local variable
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe((res) => {
* expect(res.text()).toBe('awesome');
* async.done();
* });
* connection.mockRespond(new Response('awesome'));
* }));
* ```
*
* This method only exists in the mock implementation, not in real Backends.
**/
@Injectable()
export class MockBackend implements ConnectionBackend {
/**
* {@link EventEmitter}
* of {@link MockConnection} instances that have been created by this backend. Can be subscribed
* to in order to respond to connections.
*
* ### Example
*
* ```
* import {MockBackend, Http, BaseRequestOptions} from 'angular2/http';
* import {Injector} from 'angular2/core';
*
* it('should get a response', () => {
* var connection; //this will be set when a new connection is emitted from the backend.
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, options) {
* return new Http(backend, options);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);
* http.request('something.json').subscribe(res => {
* text = res.text();
* });
* connection.mockRespond(new Response({body: 'Something'}));
* expect(text).toBe('Something');
* });
* ```
*
* This property only exists in the mock implementation, not in real Backends.
*/
connections: any; //<MockConnection>
/**
* An array representation of `connections`. This array will be updated with each connection that
* is created by this backend.
*
* This property only exists in the mock implementation, not in real Backends.
*/
connectionsArray: MockConnection[];
/**
* {@link EventEmitter} of {@link MockConnection} instances that haven't yet been resolved (i.e.
* with a `readyState`
* less than 4). Used internally to verify that no connections are pending via the
* `verifyNoPendingRequests` method.
*
* This property only exists in the mock implementation, not in real Backends.
*/
pendingConnections: any; // Subject<MockConnection>
constructor() {
this.connectionsArray = [];
this.connections = new Subject();
this.connections.subscribe(connection => this.connectionsArray.push(connection));
this.pendingConnections = new Subject();
}
/**
* Checks all connections, and raises an exception if any connection has not received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
verifyNoPendingRequests() {
let pending = 0;
this.pendingConnections.subscribe(c => pending++);
if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`);
}
/**
* Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve
* connections, if it's expected that there are connections that have not yet received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections() { this.connections.subscribe(c => c.readyState = 4); }
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
* MockConnection()`, except that it also will emit the new `Connection` to the `connections`
* emitter of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users.
*/
createConnection(req: Request): Connection {
if (!isPresent(req) || !(req instanceof Request)) {
throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
}
let connection = new MockConnection(req);
this.connections.next(connection);
return connection;
}
} | this.readyState = ReadyStates.Done;
this.response.error(err);
} | random_line_split |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Subject, ReplaySubject} from '@reactivex/rxjs/dist/cjs/Rx';
/**
*
* Mock Connection to represent a {@link Connection} for tests.
*
**/
export class MockConnection implements Connection {
// TODO Name `readyState` should change to be more generic, and states could be made to be more
// descriptive than XHR states.
/**
* Describes the state of the connection, based on `XMLHttpRequest.readyState`, but with
* additional states. For example, state 5 indicates an aborted connection.
*/
readyState: ReadyStates;
/**
* {@link Request} instance used to create the connection.
*/
request: Request;
/**
* {@link EventEmitter} of {@link Response}. Can be subscribed to in order to be notified when a
* response is available.
*/
response: any; // Subject<Response>
constructor(req: Request) {
this.response = new ReplaySubject(1).take(1);
this.readyState = ReadyStates.Open;
this.request = req;
}
/**
* Sends a mock response to the connection. This response is the value that is emitted to the
* {@link EventEmitter} returned by {@link Http}.
*
* ### Example
*
* ```
* var connection;
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe(res => console.log(res.text()));
* connection.mockRespond(new Response('fake response')); //logs 'fake response'
* ```
*
*/
mockRespond(res: Response) {
if (this.readyState === ReadyStates.Done || this.readyState === ReadyStates.Cancelled) {
throw new BaseException('Connection has already been resolved');
}
this.readyState = ReadyStates.Done;
this.response.next(res);
this.response.complete();
}
/**
* Not yet implemented!
*
* Sends the provided {@link Response} to the `downloadObserver` of the `Request`
* associated with this connection.
*/
mockDownload(res: Response) {
// this.request.downloadObserver.onNext(res);
// if (res.bytesLoaded === res.totalBytes) {
// this.request.downloadObserver.onCompleted();
// }
}
// TODO(jeffbcross): consider using Response type
/**
* Emits the provided error object as an error to the {@link Response} {@link EventEmitter}
* returned
* from {@link Http}.
*/
mockError(err?: Error) |
}
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* ### Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some data', inject([AsyncTestCompleter], (async) => {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, defaultOptions) => {
* return new Http(backend, defaultOptions)
* }, deps: [MockBackend, DefaultOptions]})]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
* //Assign any newly-created connection to local variable
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe((res) => {
* expect(res.text()).toBe('awesome');
* async.done();
* });
* connection.mockRespond(new Response('awesome'));
* }));
* ```
*
* This method only exists in the mock implementation, not in real Backends.
**/
@Injectable()
export class MockBackend implements ConnectionBackend {
/**
* {@link EventEmitter}
* of {@link MockConnection} instances that have been created by this backend. Can be subscribed
* to in order to respond to connections.
*
* ### Example
*
* ```
* import {MockBackend, Http, BaseRequestOptions} from 'angular2/http';
* import {Injector} from 'angular2/core';
*
* it('should get a response', () => {
* var connection; //this will be set when a new connection is emitted from the backend.
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, options) {
* return new Http(backend, options);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);
* http.request('something.json').subscribe(res => {
* text = res.text();
* });
* connection.mockRespond(new Response({body: 'Something'}));
* expect(text).toBe('Something');
* });
* ```
*
* This property only exists in the mock implementation, not in real Backends.
*/
connections: any; //<MockConnection>
/**
* An array representation of `connections`. This array will be updated with each connection that
* is created by this backend.
*
* This property only exists in the mock implementation, not in real Backends.
*/
connectionsArray: MockConnection[];
/**
* {@link EventEmitter} of {@link MockConnection} instances that haven't yet been resolved (i.e.
* with a `readyState`
* less than 4). Used internally to verify that no connections are pending via the
* `verifyNoPendingRequests` method.
*
* This property only exists in the mock implementation, not in real Backends.
*/
pendingConnections: any; // Subject<MockConnection>
constructor() {
this.connectionsArray = [];
this.connections = new Subject();
this.connections.subscribe(connection => this.connectionsArray.push(connection));
this.pendingConnections = new Subject();
}
/**
* Checks all connections, and raises an exception if any connection has not received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
verifyNoPendingRequests() {
let pending = 0;
this.pendingConnections.subscribe(c => pending++);
if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`);
}
/**
* Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve
* connections, if it's expected that there are connections that have not yet received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections() { this.connections.subscribe(c => c.readyState = 4); }
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
* MockConnection()`, except that it also will emit the new `Connection` to the `connections`
* emitter of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users.
*/
createConnection(req: Request): Connection {
if (!isPresent(req) || !(req instanceof Request)) {
throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
}
let connection = new MockConnection(req);
this.connections.next(connection);
return connection;
}
}
| {
// Matches XHR semantics
this.readyState = ReadyStates.Done;
this.response.error(err);
} | identifier_body |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Subject, ReplaySubject} from '@reactivex/rxjs/dist/cjs/Rx';
/**
*
* Mock Connection to represent a {@link Connection} for tests.
*
**/
export class MockConnection implements Connection {
// TODO Name `readyState` should change to be more generic, and states could be made to be more
// descriptive than XHR states.
/**
* Describes the state of the connection, based on `XMLHttpRequest.readyState`, but with
* additional states. For example, state 5 indicates an aborted connection.
*/
readyState: ReadyStates;
/**
* {@link Request} instance used to create the connection.
*/
request: Request;
/**
* {@link EventEmitter} of {@link Response}. Can be subscribed to in order to be notified when a
* response is available.
*/
response: any; // Subject<Response>
constructor(req: Request) {
this.response = new ReplaySubject(1).take(1);
this.readyState = ReadyStates.Open;
this.request = req;
}
/**
* Sends a mock response to the connection. This response is the value that is emitted to the
* {@link EventEmitter} returned by {@link Http}.
*
* ### Example
*
* ```
* var connection;
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe(res => console.log(res.text()));
* connection.mockRespond(new Response('fake response')); //logs 'fake response'
* ```
*
*/
mockRespond(res: Response) {
if (this.readyState === ReadyStates.Done || this.readyState === ReadyStates.Cancelled) {
throw new BaseException('Connection has already been resolved');
}
this.readyState = ReadyStates.Done;
this.response.next(res);
this.response.complete();
}
/**
* Not yet implemented!
*
* Sends the provided {@link Response} to the `downloadObserver` of the `Request`
* associated with this connection.
*/
mockDownload(res: Response) {
// this.request.downloadObserver.onNext(res);
// if (res.bytesLoaded === res.totalBytes) {
// this.request.downloadObserver.onCompleted();
// }
}
// TODO(jeffbcross): consider using Response type
/**
* Emits the provided error object as an error to the {@link Response} {@link EventEmitter}
* returned
* from {@link Http}.
*/
mockError(err?: Error) {
// Matches XHR semantics
this.readyState = ReadyStates.Done;
this.response.error(err);
}
}
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* ### Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some data', inject([AsyncTestCompleter], (async) => {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, defaultOptions) => {
* return new Http(backend, defaultOptions)
* }, deps: [MockBackend, DefaultOptions]})]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
* //Assign any newly-created connection to local variable
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe((res) => {
* expect(res.text()).toBe('awesome');
* async.done();
* });
* connection.mockRespond(new Response('awesome'));
* }));
* ```
*
* This method only exists in the mock implementation, not in real Backends.
**/
@Injectable()
export class | implements ConnectionBackend {
/**
* {@link EventEmitter}
* of {@link MockConnection} instances that have been created by this backend. Can be subscribed
* to in order to respond to connections.
*
* ### Example
*
* ```
* import {MockBackend, Http, BaseRequestOptions} from 'angular2/http';
* import {Injector} from 'angular2/core';
*
* it('should get a response', () => {
* var connection; //this will be set when a new connection is emitted from the backend.
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, options) {
* return new Http(backend, options);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);
* http.request('something.json').subscribe(res => {
* text = res.text();
* });
* connection.mockRespond(new Response({body: 'Something'}));
* expect(text).toBe('Something');
* });
* ```
*
* This property only exists in the mock implementation, not in real Backends.
*/
connections: any; //<MockConnection>
/**
* An array representation of `connections`. This array will be updated with each connection that
* is created by this backend.
*
* This property only exists in the mock implementation, not in real Backends.
*/
connectionsArray: MockConnection[];
/**
* {@link EventEmitter} of {@link MockConnection} instances that haven't yet been resolved (i.e.
* with a `readyState`
* less than 4). Used internally to verify that no connections are pending via the
* `verifyNoPendingRequests` method.
*
* This property only exists in the mock implementation, not in real Backends.
*/
pendingConnections: any; // Subject<MockConnection>
constructor() {
this.connectionsArray = [];
this.connections = new Subject();
this.connections.subscribe(connection => this.connectionsArray.push(connection));
this.pendingConnections = new Subject();
}
/**
* Checks all connections, and raises an exception if any connection has not received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
verifyNoPendingRequests() {
let pending = 0;
this.pendingConnections.subscribe(c => pending++);
if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`);
}
/**
* Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve
* connections, if it's expected that there are connections that have not yet received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections() { this.connections.subscribe(c => c.readyState = 4); }
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
* MockConnection()`, except that it also will emit the new `Connection` to the `connections`
* emitter of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users.
*/
createConnection(req: Request): Connection {
if (!isPresent(req) || !(req instanceof Request)) {
throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
}
let connection = new MockConnection(req);
this.connections.next(connection);
return connection;
}
}
| MockBackend | identifier_name |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Subject, ReplaySubject} from '@reactivex/rxjs/dist/cjs/Rx';
/**
*
* Mock Connection to represent a {@link Connection} for tests.
*
**/
export class MockConnection implements Connection {
// TODO Name `readyState` should change to be more generic, and states could be made to be more
// descriptive than XHR states.
/**
* Describes the state of the connection, based on `XMLHttpRequest.readyState`, but with
* additional states. For example, state 5 indicates an aborted connection.
*/
readyState: ReadyStates;
/**
* {@link Request} instance used to create the connection.
*/
request: Request;
/**
* {@link EventEmitter} of {@link Response}. Can be subscribed to in order to be notified when a
* response is available.
*/
response: any; // Subject<Response>
constructor(req: Request) {
this.response = new ReplaySubject(1).take(1);
this.readyState = ReadyStates.Open;
this.request = req;
}
/**
* Sends a mock response to the connection. This response is the value that is emitted to the
* {@link EventEmitter} returned by {@link Http}.
*
* ### Example
*
* ```
* var connection;
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe(res => console.log(res.text()));
* connection.mockRespond(new Response('fake response')); //logs 'fake response'
* ```
*
*/
mockRespond(res: Response) {
if (this.readyState === ReadyStates.Done || this.readyState === ReadyStates.Cancelled) |
this.readyState = ReadyStates.Done;
this.response.next(res);
this.response.complete();
}
/**
* Not yet implemented!
*
* Sends the provided {@link Response} to the `downloadObserver` of the `Request`
* associated with this connection.
*/
mockDownload(res: Response) {
// this.request.downloadObserver.onNext(res);
// if (res.bytesLoaded === res.totalBytes) {
// this.request.downloadObserver.onCompleted();
// }
}
// TODO(jeffbcross): consider using Response type
/**
* Emits the provided error object as an error to the {@link Response} {@link EventEmitter}
* returned
* from {@link Http}.
*/
mockError(err?: Error) {
// Matches XHR semantics
this.readyState = ReadyStates.Done;
this.response.error(err);
}
}
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* ### Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some data', inject([AsyncTestCompleter], (async) => {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, defaultOptions) => {
* return new Http(backend, defaultOptions)
* }, deps: [MockBackend, DefaultOptions]})]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
* //Assign any newly-created connection to local variable
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe((res) => {
* expect(res.text()).toBe('awesome');
* async.done();
* });
* connection.mockRespond(new Response('awesome'));
* }));
* ```
*
* This method only exists in the mock implementation, not in real Backends.
**/
@Injectable()
export class MockBackend implements ConnectionBackend {
/**
* {@link EventEmitter}
* of {@link MockConnection} instances that have been created by this backend. Can be subscribed
* to in order to respond to connections.
*
* ### Example
*
* ```
* import {MockBackend, Http, BaseRequestOptions} from 'angular2/http';
* import {Injector} from 'angular2/core';
*
* it('should get a response', () => {
* var connection; //this will be set when a new connection is emitted from the backend.
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* provide(Http, {useFactory: (backend, options) {
* return new Http(backend, options);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);
* http.request('something.json').subscribe(res => {
* text = res.text();
* });
* connection.mockRespond(new Response({body: 'Something'}));
* expect(text).toBe('Something');
* });
* ```
*
* This property only exists in the mock implementation, not in real Backends.
*/
connections: any; //<MockConnection>
/**
* An array representation of `connections`. This array will be updated with each connection that
* is created by this backend.
*
* This property only exists in the mock implementation, not in real Backends.
*/
connectionsArray: MockConnection[];
/**
* {@link EventEmitter} of {@link MockConnection} instances that haven't yet been resolved (i.e.
* with a `readyState`
* less than 4). Used internally to verify that no connections are pending via the
* `verifyNoPendingRequests` method.
*
* This property only exists in the mock implementation, not in real Backends.
*/
pendingConnections: any; // Subject<MockConnection>
constructor() {
this.connectionsArray = [];
this.connections = new Subject();
this.connections.subscribe(connection => this.connectionsArray.push(connection));
this.pendingConnections = new Subject();
}
/**
* Checks all connections, and raises an exception if any connection has not received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
verifyNoPendingRequests() {
let pending = 0;
this.pendingConnections.subscribe(c => pending++);
if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`);
}
/**
* Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve
* connections, if it's expected that there are connections that have not yet received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections() { this.connections.subscribe(c => c.readyState = 4); }
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
* MockConnection()`, except that it also will emit the new `Connection` to the `connections`
* emitter of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users.
*/
createConnection(req: Request): Connection {
if (!isPresent(req) || !(req instanceof Request)) {
throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
}
let connection = new MockConnection(req);
this.connections.next(connection);
return connection;
}
}
| {
throw new BaseException('Connection has already been resolved');
} | conditional_block |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArguments: Function that normalizes arguments for consumption by a query engine
* * querierFactory: Factory function that provides a default querier implementation to use if a collection doesn't
* define its own querier factory method for this query type
* * type: The type of query; corresponds to the query log entry's type and the name of the query engine method
*/
export interface QueryMethodArgs<T> {
applyQuery?: (newCollection: dstore.Collection<T>, logEntry: dstore.QueryLogEntry<T>) => dstore.Collection<T>;
normalizeArguments?: (...args: any[]) => any[];
querierFactory?: dstore.QuerierFactory<T>;
type: string;
}
/**
* The constructor for a dstore collection query method. It encapsulates the following:
* * Creating a new subcollection for the query results
* * Logging the query in the collection's `queryLog`
* * Normalizing query arguments
* * Applying the query engine
*
* @param kwArgs The properties that define the query method
* @return A function that takes query arguments and returns a new collection with the query associated with it
*/
export default function QueryMethod<T>(kwArgs: QueryMethodArgs<T>): (...args: any[]) => dstore.Collection<T> {
const type = kwArgs.type;
const normalizeArguments = kwArgs.normalizeArguments;
const applyQuery = kwArgs.applyQuery;
const defaultQuerierFactory = kwArgs.querierFactory;
return function () {
const originalArguments = Array.prototype.slice.call(arguments);
const normalizedArguments = normalizeArguments ?
normalizeArguments.apply(this, originalArguments) :
originalArguments;
const logEntry = <dstore.QueryLogEntry<T>> {
type: type,
arguments: originalArguments,
normalizedArguments: normalizedArguments
};
// TODO: coerce to Store<T> once that's converted
// (though we'd need to expose _getQuerierFactory for this to work as-is... maybe there's a better way?)
const store = <any> this;
const querierFactory: dstore.QuerierFactory<T> = store._getQuerierFactory(type) || defaultQuerierFactory;
if (querierFactory) |
const newCollection = store._createSubCollection({
queryLog: store.queryLog.concat(logEntry)
});
return applyQuery ? applyQuery.call(store, newCollection, logEntry) : newCollection;
};
};
| {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
} | conditional_block |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArguments: Function that normalizes arguments for consumption by a query engine
* * querierFactory: Factory function that provides a default querier implementation to use if a collection doesn't
* define its own querier factory method for this query type
* * type: The type of query; corresponds to the query log entry's type and the name of the query engine method
*/
export interface QueryMethodArgs<T> {
applyQuery?: (newCollection: dstore.Collection<T>, logEntry: dstore.QueryLogEntry<T>) => dstore.Collection<T>;
normalizeArguments?: (...args: any[]) => any[];
querierFactory?: dstore.QuerierFactory<T>;
type: string;
}
/**
* The constructor for a dstore collection query method. It encapsulates the following:
* * Creating a new subcollection for the query results
* * Logging the query in the collection's `queryLog`
* * Normalizing query arguments
* * Applying the query engine
*
* @param kwArgs The properties that define the query method
* @return A function that takes query arguments and returns a new collection with the query associated with it
*/
export default function QueryMethod<T>(kwArgs: QueryMethodArgs<T>): (...args: any[]) => dstore.Collection<T> {
const type = kwArgs.type;
const normalizeArguments = kwArgs.normalizeArguments;
const applyQuery = kwArgs.applyQuery;
const defaultQuerierFactory = kwArgs.querierFactory;
return function () {
const originalArguments = Array.prototype.slice.call(arguments);
const normalizedArguments = normalizeArguments ?
normalizeArguments.apply(this, originalArguments) :
originalArguments;
const logEntry = <dstore.QueryLogEntry<T>> {
type: type,
arguments: originalArguments,
normalizedArguments: normalizedArguments
};
// TODO: coerce to Store<T> once that's converted
// (though we'd need to expose _getQuerierFactory for this to work as-is... maybe there's a better way?)
const store = <any> this;
const querierFactory: dstore.QuerierFactory<T> = store._getQuerierFactory(type) || defaultQuerierFactory; |
if (querierFactory) {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
}
const newCollection = store._createSubCollection({
queryLog: store.queryLog.concat(logEntry)
});
return applyQuery ? applyQuery.call(store, newCollection, logEntry) : newCollection;
};
}; | random_line_split | |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArguments: Function that normalizes arguments for consumption by a query engine
* * querierFactory: Factory function that provides a default querier implementation to use if a collection doesn't
* define its own querier factory method for this query type
* * type: The type of query; corresponds to the query log entry's type and the name of the query engine method
*/
export interface QueryMethodArgs<T> {
applyQuery?: (newCollection: dstore.Collection<T>, logEntry: dstore.QueryLogEntry<T>) => dstore.Collection<T>;
normalizeArguments?: (...args: any[]) => any[];
querierFactory?: dstore.QuerierFactory<T>;
type: string;
}
/**
* The constructor for a dstore collection query method. It encapsulates the following:
* * Creating a new subcollection for the query results
* * Logging the query in the collection's `queryLog`
* * Normalizing query arguments
* * Applying the query engine
*
* @param kwArgs The properties that define the query method
* @return A function that takes query arguments and returns a new collection with the query associated with it
*/
export default function | <T>(kwArgs: QueryMethodArgs<T>): (...args: any[]) => dstore.Collection<T> {
const type = kwArgs.type;
const normalizeArguments = kwArgs.normalizeArguments;
const applyQuery = kwArgs.applyQuery;
const defaultQuerierFactory = kwArgs.querierFactory;
return function () {
const originalArguments = Array.prototype.slice.call(arguments);
const normalizedArguments = normalizeArguments ?
normalizeArguments.apply(this, originalArguments) :
originalArguments;
const logEntry = <dstore.QueryLogEntry<T>> {
type: type,
arguments: originalArguments,
normalizedArguments: normalizedArguments
};
// TODO: coerce to Store<T> once that's converted
// (though we'd need to expose _getQuerierFactory for this to work as-is... maybe there's a better way?)
const store = <any> this;
const querierFactory: dstore.QuerierFactory<T> = store._getQuerierFactory(type) || defaultQuerierFactory;
if (querierFactory) {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
}
const newCollection = store._createSubCollection({
queryLog: store.queryLog.concat(logEntry)
});
return applyQuery ? applyQuery.call(store, newCollection, logEntry) : newCollection;
};
};
| QueryMethod | identifier_name |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArguments: Function that normalizes arguments for consumption by a query engine
* * querierFactory: Factory function that provides a default querier implementation to use if a collection doesn't
* define its own querier factory method for this query type
* * type: The type of query; corresponds to the query log entry's type and the name of the query engine method
*/
export interface QueryMethodArgs<T> {
applyQuery?: (newCollection: dstore.Collection<T>, logEntry: dstore.QueryLogEntry<T>) => dstore.Collection<T>;
normalizeArguments?: (...args: any[]) => any[];
querierFactory?: dstore.QuerierFactory<T>;
type: string;
}
/**
* The constructor for a dstore collection query method. It encapsulates the following:
* * Creating a new subcollection for the query results
* * Logging the query in the collection's `queryLog`
* * Normalizing query arguments
* * Applying the query engine
*
* @param kwArgs The properties that define the query method
* @return A function that takes query arguments and returns a new collection with the query associated with it
*/
export default function QueryMethod<T>(kwArgs: QueryMethodArgs<T>): (...args: any[]) => dstore.Collection<T> | ;
| {
const type = kwArgs.type;
const normalizeArguments = kwArgs.normalizeArguments;
const applyQuery = kwArgs.applyQuery;
const defaultQuerierFactory = kwArgs.querierFactory;
return function () {
const originalArguments = Array.prototype.slice.call(arguments);
const normalizedArguments = normalizeArguments ?
normalizeArguments.apply(this, originalArguments) :
originalArguments;
const logEntry = <dstore.QueryLogEntry<T>> {
type: type,
arguments: originalArguments,
normalizedArguments: normalizedArguments
};
// TODO: coerce to Store<T> once that's converted
// (though we'd need to expose _getQuerierFactory for this to work as-is... maybe there's a better way?)
const store = <any> this;
const querierFactory: dstore.QuerierFactory<T> = store._getQuerierFactory(type) || defaultQuerierFactory;
if (querierFactory) {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
}
const newCollection = store._createSubCollection({
queryLog: store.queryLog.concat(logEntry)
});
return applyQuery ? applyQuery.call(store, newCollection, logEntry) : newCollection;
};
} | identifier_body |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
|
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill() | deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list()) | identifier_body |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
| from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill() |
from threading import Thread
from time import sleep
import random
| random_line_split |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
|
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill() | nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False | conditional_block |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def | (self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill() | ping | identifier_name |
_connectors.py | """Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
class HttpBasicClerk(_std_http.HttpStandardClerk):
"""An authentication clerk for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _inputs(self, upstream_affordances, downstream_affordances):
return ((),)
def _append_response_auth_challenge(self, realm, input=None,
affordances=None):
self._append_response_auth_challenge_header('Basic realm="{}"'
.format(realm))
def _outputs(self, upstream_affordances, downstream_affordances):
|
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,)
class HttpBasicScanner(_std_http.HttpStandardScanner):
"""An authentication scanner for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_AUTHORIZATION_HEADER_RE = \
_re.compile(r'\s*Basic\s*(?P<creds_base64>[^\s]*)')
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _outputs(self, upstream_affordances, downstream_affordances):
return (self._BASIC_USER_TOKENS,)
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,)
| return (_BASIC_USER_TOKENS,) | identifier_body |
_connectors.py | """Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
class HttpBasicClerk(_std_http.HttpStandardClerk):
"""An authentication clerk for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _inputs(self, upstream_affordances, downstream_affordances):
return ((),)
def _append_response_auth_challenge(self, realm, input=None,
affordances=None):
self._append_response_auth_challenge_header('Basic realm="{}"'
.format(realm))
def _outputs(self, upstream_affordances, downstream_affordances):
return (_BASIC_USER_TOKENS,)
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,)
class | (_std_http.HttpStandardScanner):
"""An authentication scanner for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_AUTHORIZATION_HEADER_RE = \
_re.compile(r'\s*Basic\s*(?P<creds_base64>[^\s]*)')
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _outputs(self, upstream_affordances, downstream_affordances):
return (self._BASIC_USER_TOKENS,)
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,)
| HttpBasicScanner | identifier_name |
_connectors.py | """Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
|
"""An authentication clerk for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _inputs(self, upstream_affordances, downstream_affordances):
return ((),)
def _append_response_auth_challenge(self, realm, input=None,
affordances=None):
self._append_response_auth_challenge_header('Basic realm="{}"'
.format(realm))
def _outputs(self, upstream_affordances, downstream_affordances):
return (_BASIC_USER_TOKENS,)
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,)
class HttpBasicScanner(_std_http.HttpStandardScanner):
"""An authentication scanner for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_AUTHORIZATION_HEADER_RE = \
_re.compile(r'\s*Basic\s*(?P<creds_base64>[^\s]*)')
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _outputs(self, upstream_affordances, downstream_affordances):
return (self._BASIC_USER_TOKENS,)
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,) | class HttpBasicClerk(_std_http.HttpStandardClerk): | random_line_split |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./html")
template_name = 'index.html'
app_data = {
'val': '0'
}
def processor(response):
response = str(response)
response = json.loads(response)['message']
print(response)
command, data = response.split('#')
if '@' in command:
command, subcommand = command.split('@')
if command == 'put':
app_data[subcommand] = data
class App(htmlPy.Object):
def __init__(self):
|
@htmlPy.Slot(str)
def link(self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)
sock.send(cmd)
response = sock.recv(1024)
processor(response)
app.template = (template_name, app_data)
app.template = (template_name, app_data)
app.bind(App())
app.start()
| super(App, self).__init__() | identifier_body |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024) | app.static_path = os.path.abspath("./html")
template_name = 'index.html'
app_data = {
'val': '0'
}
def processor(response):
response = str(response)
response = json.loads(response)['message']
print(response)
command, data = response.split('#')
if '@' in command:
command, subcommand = command.split('@')
if command == 'put':
app_data[subcommand] = data
class App(htmlPy.Object):
def __init__(self):
super(App, self).__init__()
@htmlPy.Slot(str)
def link(self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)
sock.send(cmd)
response = sock.recv(1024)
processor(response)
app.template = (template_name, app_data)
app.template = (template_name, app_data)
app.bind(App())
app.start() | sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html") | random_line_split |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./html")
template_name = 'index.html'
app_data = {
'val': '0'
}
def processor(response):
response = str(response)
response = json.loads(response)['message']
print(response)
command, data = response.split('#')
if '@' in command:
command, subcommand = command.split('@')
if command == 'put':
app_data[subcommand] = data
class App(htmlPy.Object):
def __init__(self):
super(App, self).__init__()
@htmlPy.Slot(str)
def | (self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)
sock.send(cmd)
response = sock.recv(1024)
processor(response)
app.template = (template_name, app_data)
app.template = (template_name, app_data)
app.bind(App())
app.start()
| link | identifier_name |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./html")
template_name = 'index.html'
app_data = {
'val': '0'
}
def processor(response):
response = str(response)
response = json.loads(response)['message']
print(response)
command, data = response.split('#')
if '@' in command:
|
if command == 'put':
app_data[subcommand] = data
class App(htmlPy.Object):
def __init__(self):
super(App, self).__init__()
@htmlPy.Slot(str)
def link(self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)
sock.send(cmd)
response = sock.recv(1024)
processor(response)
app.template = (template_name, app_data)
app.template = (template_name, app_data)
app.bind(App())
app.start()
| command, subcommand = command.split('@') | conditional_block |
index.d.ts | // Type definitions for passport-kakao 0.1
// Project: https://github.com/rotoshine/passport-kakao
// Definitions by: Park9eon <https://github.com/Park9eon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import passport = require("passport");
import express = require("express");
export interface Profile extends passport.Profile {
id: string;
provider: string;
_raw: string;
_json: any;
}
export interface StrategyOption {
clientID: string;
clientSecret: string;
callbackURL: string;
scopeSeparator?: string;
customHeaders?: string;
}
export type VerifyFunction =
(accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void;
export class | implements passport.Strategy {
constructor(options: StrategyOption, verify: VerifyFunction);
authenticate: (req: express.Request, options?: any) => void;
userProfile: (accessToken: string, done: (error: any, user?: any) => void) => void;
}
| Strategy | identifier_name |
index.d.ts | // Type definitions for passport-kakao 0.1
// Project: https://github.com/rotoshine/passport-kakao
// Definitions by: Park9eon <https://github.com/Park9eon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import passport = require("passport");
import express = require("express");
export interface Profile extends passport.Profile {
id: string;
provider: string;
_raw: string;
_json: any;
}
export interface StrategyOption {
clientID: string;
clientSecret: string;
callbackURL: string;
| }
export type VerifyFunction =
(accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void;
export class Strategy implements passport.Strategy {
constructor(options: StrategyOption, verify: VerifyFunction);
authenticate: (req: express.Request, options?: any) => void;
userProfile: (accessToken: string, done: (error: any, user?: any) => void) => void;
} | scopeSeparator?: string;
customHeaders?: string; | random_line_split |
cci_impl_lib.rs | // Copyright 2012 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.
#![crate_name="cci_impl_lib"]
pub trait uint_helpers {
fn to<F>(&self, v: uint, f: F) where F: FnMut(uint);
}
impl uint_helpers for uint {
#[inline]
fn to<F>(&self, v: uint, mut f: F) where F: FnMut(uint) {
let mut i = *self; | i += 1;
}
}
} | while i < v {
f(i); | random_line_split |
cci_impl_lib.rs | // Copyright 2012 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.
#![crate_name="cci_impl_lib"]
pub trait uint_helpers {
fn to<F>(&self, v: uint, f: F) where F: FnMut(uint);
}
impl uint_helpers for uint {
#[inline]
fn | <F>(&self, v: uint, mut f: F) where F: FnMut(uint) {
let mut i = *self;
while i < v {
f(i);
i += 1;
}
}
}
| to | identifier_name |
cci_impl_lib.rs | // Copyright 2012 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.
#![crate_name="cci_impl_lib"]
pub trait uint_helpers {
fn to<F>(&self, v: uint, f: F) where F: FnMut(uint);
}
impl uint_helpers for uint {
#[inline]
fn to<F>(&self, v: uint, mut f: F) where F: FnMut(uint) |
}
| {
let mut i = *self;
while i < v {
f(i);
i += 1;
}
} | identifier_body |
test_educollections.py | from educollections import ArrayList
def | (lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10 - i)
arr.set(i, 10 - i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(10):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [9, 4, 1, 6, 3, 0, 0, 0, 1, 0]:
item = arr.remove(i);
print('Removed', item, 'from index', i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8]:
print('Insert', i + 10, 'at index', i)
arr.insert(i, i + 10)
print_list_state(arr)
| print_list_state | identifier_name |
test_educollections.py | from educollections import ArrayList
def print_list_state(lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
|
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10 - i)
arr.set(i, 10 - i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(10):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [9, 4, 1, 6, 3, 0, 0, 0, 1, 0]:
item = arr.remove(i);
print('Removed', item, 'from index', i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8]:
print('Insert', i + 10, 'at index', i)
arr.insert(i, i + 10)
print_list_state(arr)
| print('Prepend', i)
arr.prepend(i) | conditional_block |
test_educollections.py | from educollections import ArrayList
def print_list_state(lst):
|
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10 - i)
arr.set(i, 10 - i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(10):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [9, 4, 1, 6, 3, 0, 0, 0, 1, 0]:
item = arr.remove(i);
print('Removed', item, 'from index', i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8]:
print('Insert', i + 10, 'at index', i)
arr.insert(i, i + 10)
print_list_state(arr)
| print('Size is', lst.size())
print('Contents are', lst)
print() | identifier_body |
test_educollections.py | from educollections import ArrayList
def print_list_state(lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10 - i)
arr.set(i, 10 - i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
| arr.append(i)
print_list_state(arr)
for i in [9, 4, 1, 6, 3, 0, 0, 0, 1, 0]:
item = arr.remove(i);
print('Removed', item, 'from index', i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8]:
print('Insert', i + 10, 'at index', i)
arr.insert(i, i + 10)
print_list_state(arr) | for i in range(10):
print('Append', i) | random_line_split |
commit.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Helper library for rendering commit info
use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use anyhow::Error;
use chrono::{DateTime, FixedOffset, Local, TimeZone};
use serde_derive::Serialize;
use source_control::types as thrift;
use crate::args::commit_id::map_commit_ids;
use crate::lib::commit_id::render_commit_id;
#[derive(Serialize)]
pub(crate) struct CommitInfo {
pub r#type: String, // For JSON output, always "commit".
pub ids: BTreeMap<String, String>,
pub parents: Vec<BTreeMap<String, String>>,
pub message: String,
pub date: DateTime<FixedOffset>,
pub timestamp: i64,
pub timezone: i32,
pub author: String,
pub generation: i64,
pub extra: BTreeMap<String, String>,
pub extra_hex: BTreeMap<String, String>,
} |
impl TryFrom<&thrift::CommitInfo> for CommitInfo {
type Error = Error;
fn try_from(commit: &thrift::CommitInfo) -> Result<CommitInfo, Error> {
let ids = map_commit_ids(commit.ids.values());
let parents = commit
.parents
.iter()
.map(|ids| map_commit_ids(ids.values()))
.collect();
let message = commit.message.clone();
let author = commit.author.clone();
// The commit date is recorded as a timestamp plus timezone pair, where
// the timezone is seconds east of UTC.
let timestamp = commit.date;
let timezone = commit.tz;
let date = FixedOffset::east(timezone).timestamp(timestamp, 0);
// Extras are binary data, but usually we want to render them as
// strings. In the case that they are not UTF-8 strings, they're
// probably a commit hash, so we should hex-encode them. Record extras
// that are valid UTF-8 as strings, and hex encode the rest.
let mut extra = BTreeMap::new();
let mut extra_hex = BTreeMap::new();
for (name, value) in commit.extra.iter() {
match std::str::from_utf8(value) {
Ok(value) => extra.insert(name.clone(), value.to_string()),
Err(_) => extra_hex.insert(name.clone(), faster_hex::hex_string(value)),
};
}
Ok(CommitInfo {
r#type: "commit".to_string(),
ids,
parents,
message,
date,
timestamp,
timezone,
author,
generation: commit.generation,
extra,
extra_hex,
})
}
}
pub(crate) fn render_commit_summary(
commit: &CommitInfo,
requested: &str,
schemes: &HashSet<String>,
w: &mut dyn Write,
) -> Result<(), Error> {
render_commit_id(
Some(("Commit", " ")),
"\n",
&requested,
&commit.ids,
schemes,
w,
)?;
write!(w, "\n")?;
let date = commit.date.to_string();
let local_date = commit.date.with_timezone(&Local).to_string();
if date != local_date {
write!(w, "Date: {} ({})\n", date, local_date)?;
} else {
write!(w, "Date: {}\n", date)?;
}
write!(w, "Author: {}\n", commit.author)?;
write!(
w,
"Summary: {}\n",
commit.message.lines().next().unwrap_or("")
)?;
Ok(())
}
pub(crate) fn render_commit_info(
commit: &CommitInfo,
requested: &str,
schemes: &HashSet<String>,
w: &mut dyn Write,
) -> Result<(), Error> {
render_commit_id(
Some(("Commit", " ")),
"\n",
&requested,
&commit.ids,
schemes,
w,
)?;
write!(w, "\n")?;
for (i, parent) in commit.parents.iter().enumerate() {
let header = if commit.parents.len() == 1 {
"Parent".to_string()
} else {
format!("Parent-{}", i)
};
render_commit_id(
Some((&header, " ")),
"\n",
&format!("Parent {} of {}", i, requested),
parent,
&schemes,
w,
)?;
write!(w, "\n")?;
}
let date = commit.date.to_string();
let local_date = commit.date.with_timezone(&Local).to_string();
if date != local_date {
write!(w, "Date: {} ({})\n", date, local_date)?;
} else {
write!(w, "Date: {}\n", date)?;
}
write!(w, "Author: {}\n", commit.author)?;
write!(w, "Generation: {}\n", commit.generation)?;
if !commit.extra.is_empty() {
write!(w, "Extra:\n")?;
for (name, value) in commit.extra.iter() {
write!(w, " {}={}\n", name, value)?;
}
}
if !commit.extra_hex.is_empty() {
write!(w, "Extra-Binary:\n")?;
for (name, value) in commit.extra_hex.iter() {
write!(w, " {}={}\n", name, value)?;
}
}
write!(w, "\n{}\n", commit.message)?;
Ok(())
} | random_line_split | |
commit.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Helper library for rendering commit info
use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use anyhow::Error;
use chrono::{DateTime, FixedOffset, Local, TimeZone};
use serde_derive::Serialize;
use source_control::types as thrift;
use crate::args::commit_id::map_commit_ids;
use crate::lib::commit_id::render_commit_id;
#[derive(Serialize)]
pub(crate) struct CommitInfo {
pub r#type: String, // For JSON output, always "commit".
pub ids: BTreeMap<String, String>,
pub parents: Vec<BTreeMap<String, String>>,
pub message: String,
pub date: DateTime<FixedOffset>,
pub timestamp: i64,
pub timezone: i32,
pub author: String,
pub generation: i64,
pub extra: BTreeMap<String, String>,
pub extra_hex: BTreeMap<String, String>,
}
impl TryFrom<&thrift::CommitInfo> for CommitInfo {
type Error = Error;
fn | (commit: &thrift::CommitInfo) -> Result<CommitInfo, Error> {
let ids = map_commit_ids(commit.ids.values());
let parents = commit
.parents
.iter()
.map(|ids| map_commit_ids(ids.values()))
.collect();
let message = commit.message.clone();
let author = commit.author.clone();
// The commit date is recorded as a timestamp plus timezone pair, where
// the timezone is seconds east of UTC.
let timestamp = commit.date;
let timezone = commit.tz;
let date = FixedOffset::east(timezone).timestamp(timestamp, 0);
// Extras are binary data, but usually we want to render them as
// strings. In the case that they are not UTF-8 strings, they're
// probably a commit hash, so we should hex-encode them. Record extras
// that are valid UTF-8 as strings, and hex encode the rest.
let mut extra = BTreeMap::new();
let mut extra_hex = BTreeMap::new();
for (name, value) in commit.extra.iter() {
match std::str::from_utf8(value) {
Ok(value) => extra.insert(name.clone(), value.to_string()),
Err(_) => extra_hex.insert(name.clone(), faster_hex::hex_string(value)),
};
}
Ok(CommitInfo {
r#type: "commit".to_string(),
ids,
parents,
message,
date,
timestamp,
timezone,
author,
generation: commit.generation,
extra,
extra_hex,
})
}
}
pub(crate) fn render_commit_summary(
commit: &CommitInfo,
requested: &str,
schemes: &HashSet<String>,
w: &mut dyn Write,
) -> Result<(), Error> {
render_commit_id(
Some(("Commit", " ")),
"\n",
&requested,
&commit.ids,
schemes,
w,
)?;
write!(w, "\n")?;
let date = commit.date.to_string();
let local_date = commit.date.with_timezone(&Local).to_string();
if date != local_date {
write!(w, "Date: {} ({})\n", date, local_date)?;
} else {
write!(w, "Date: {}\n", date)?;
}
write!(w, "Author: {}\n", commit.author)?;
write!(
w,
"Summary: {}\n",
commit.message.lines().next().unwrap_or("")
)?;
Ok(())
}
pub(crate) fn render_commit_info(
commit: &CommitInfo,
requested: &str,
schemes: &HashSet<String>,
w: &mut dyn Write,
) -> Result<(), Error> {
render_commit_id(
Some(("Commit", " ")),
"\n",
&requested,
&commit.ids,
schemes,
w,
)?;
write!(w, "\n")?;
for (i, parent) in commit.parents.iter().enumerate() {
let header = if commit.parents.len() == 1 {
"Parent".to_string()
} else {
format!("Parent-{}", i)
};
render_commit_id(
Some((&header, " ")),
"\n",
&format!("Parent {} of {}", i, requested),
parent,
&schemes,
w,
)?;
write!(w, "\n")?;
}
let date = commit.date.to_string();
let local_date = commit.date.with_timezone(&Local).to_string();
if date != local_date {
write!(w, "Date: {} ({})\n", date, local_date)?;
} else {
write!(w, "Date: {}\n", date)?;
}
write!(w, "Author: {}\n", commit.author)?;
write!(w, "Generation: {}\n", commit.generation)?;
if !commit.extra.is_empty() {
write!(w, "Extra:\n")?;
for (name, value) in commit.extra.iter() {
write!(w, " {}={}\n", name, value)?;
}
}
if !commit.extra_hex.is_empty() {
write!(w, "Extra-Binary:\n")?;
for (name, value) in commit.extra_hex.iter() {
write!(w, " {}={}\n", name, value)?;
}
}
write!(w, "\n{}\n", commit.message)?;
Ok(())
}
| try_from | identifier_name |
broad_phase_filter2.rs | extern crate nalgebra as na;
use na::{Isometry2, Point2, RealField, Vector2};
use ncollide2d::broad_phase::BroadPhasePairFilter;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{FreeJoint, RevoluteJoint};
use nphysics2d::object::{
BodyPartHandle, BodySet, Collider, ColliderAnchor, ColliderDesc, ColliderSet,
DefaultBodyHandle, DefaultBodySet, DefaultColliderHandle, DefaultColliderSet, Ground,
MultibodyDesc,
};
use nphysics2d::world::{
BroadPhasePairFilterSets, DefaultGeometricalWorld, DefaultMechanicalWorld,
};
use nphysics_testbed2d::Testbed;
struct NoMultibodySelfContactFilter;
impl<N, Bodies, Colliders>
BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>>
for NoMultibodySelfContactFilter
where
N: RealField,
Bodies: BodySet<N>,
Colliders: ColliderSet<N, Bodies::Handle>,
{
fn is_pair_valid(
&self,
h1: Colliders::Handle,
h2: Colliders::Handle,
set: &BroadPhasePairFilterSets<'_, N, Bodies, Colliders>,
) -> bool {
let a1 = set.colliders().get(h1).map(|c| c.anchor());
let a2 = set.colliders().get(h2).map(|c| c.anchor());
match (a1, a2) {
(
Some(ColliderAnchor::OnBodyPart {
body_part: part1, ..
}),
Some(ColliderAnchor::OnBodyPart {
body_part: part2, ..
}),
) => part1.0 != part2.0, // Don't collide if the two parts belong to the same body.
_ => true,
}
}
}
/*
* NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type.
* This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.)
*/
pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) {
/*
* World
*/
let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81)));
let geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let joint_constraints = DefaultJointConstraintSet::new();
let force_generators = DefaultForceGeneratorSet::new();
/*
* Ground
*/
let ground_size = r!(25.0);
let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, r!(1.0))));
let ground_handle = bodies.insert(Ground::new());
let co = ColliderDesc::new(ground_shape)
.translation(-Vector2::y())
.build(BodyPartHandle(ground_handle, 0));
colliders.insert(co);
/*
* Create the ragdolls
*/
build_ragdolls(&mut bodies, &mut colliders);
/*
* Run the simulation.
*/
testbed.set_ground_handle(Some(ground_handle));
testbed.set_broad_phase_pair_filter(NoMultibodySelfContactFilter);
testbed.set_world(
mechanical_world,
geometrical_world,
bodies,
colliders,
joint_constraints,
force_generators,
);
testbed.look_at(Point2::new(0.0, 5.0), 25.0);
}
fn build_ragdolls<N: RealField>(
bodies: &mut DefaultBodySet<N>,
colliders: &mut DefaultColliderSet<N>,
) {
let body_rady = r!(1.2);
let body_radx = r!(0.2);
let head_rad = r!(0.4);
let member_rad = r!(0.1);
let arm_length = r!(0.9);
let leg_length = r!(1.4);
let space = r!(0.1);
let body_geom = ShapeHandle::new(Cuboid::new(Vector2::new(body_radx, body_rady)));
let head_geom = ShapeHandle::new(Ball::new(head_rad));
let arm_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, arm_length)));
let leg_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, leg_length)));
// The position of the free joint will be modified in the
// final loop of this function (before we actually build the
// ragdoll body into the World.
let free = FreeJoint::new(Isometry2::new(Vector2::zeros(), na::zero()));
let spherical = RevoluteJoint::new(na::zero());
/*
* Body.
*/
let body_collider = ColliderDesc::new(body_geom).density(r!(0.3));
let mut body = MultibodyDesc::new(free);
/*
* Head.
*/
let head_collider = ColliderDesc::new(head_geom).density(r!(0.3));
body.add_child(spherical).set_parent_shift(Vector2::new(
r!(0.0),
body_rady + head_rad + space * r!(2.0),
));
/*
* Arms.
*/
let arm_collider = ColliderDesc::new(arm_geom).density(r!(0.3));
body.add_child(spherical)
.set_parent_shift(Vector2::new(body_radx + r!(2.0) * space, body_rady))
.set_body_shift(Vector2::new(r!(0.0), arm_length + space));
body.add_child(spherical)
.set_parent_shift(Vector2::new(-body_radx - r!(2.0) * space, body_rady))
.set_body_shift(Vector2::new(r!(0.0), arm_length + space));
/*
* Legs.
*/
let leg_collider = ColliderDesc::new(leg_geom).density(r!(0.3));
body.add_child(spherical)
.set_parent_shift(Vector2::new(body_radx, -body_rady))
.set_body_shift(Vector2::new(r!(0.0), leg_length + space));
body.add_child(spherical)
.set_parent_shift(Vector2::new(-body_radx, -body_rady))
.set_body_shift(Vector2::new(r!(0.0), leg_length + space));
let n = 5;
let shiftx = r!(2.0);
let shifty = r!(6.5);
for i in 0usize..n {
for j in 0usize..n {
let x = r!(i as f64) * shiftx - r!(n as f64) * shiftx / r!(2.0);
let y = r!(j as f64) * shifty + r!(6.0);
let free = FreeJoint::new(Isometry2::translation(x, y));
let ragdoll = body.set_joint(free).build();
let ragdoll_handle = bodies.insert(ragdoll);
colliders.insert(body_collider.build(BodyPartHandle(ragdoll_handle, 0)));
colliders.insert(head_collider.build(BodyPartHandle(ragdoll_handle, 1)));
colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 2)));
colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 3)));
colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 4)));
colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 5)));
}
}
}
fn main() | {
let mut testbed = Testbed::<f32>::new_empty();
init_world(&mut testbed);
testbed.run();
} | identifier_body | |
broad_phase_filter2.rs | extern crate nalgebra as na;
use na::{Isometry2, Point2, RealField, Vector2};
use ncollide2d::broad_phase::BroadPhasePairFilter;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{FreeJoint, RevoluteJoint};
use nphysics2d::object::{
BodyPartHandle, BodySet, Collider, ColliderAnchor, ColliderDesc, ColliderSet,
DefaultBodyHandle, DefaultBodySet, DefaultColliderHandle, DefaultColliderSet, Ground,
MultibodyDesc,
};
use nphysics2d::world::{
BroadPhasePairFilterSets, DefaultGeometricalWorld, DefaultMechanicalWorld,
};
use nphysics_testbed2d::Testbed;
struct | ;
impl<N, Bodies, Colliders>
BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>>
for NoMultibodySelfContactFilter
where
N: RealField,
Bodies: BodySet<N>,
Colliders: ColliderSet<N, Bodies::Handle>,
{
fn is_pair_valid(
&self,
h1: Colliders::Handle,
h2: Colliders::Handle,
set: &BroadPhasePairFilterSets<'_, N, Bodies, Colliders>,
) -> bool {
let a1 = set.colliders().get(h1).map(|c| c.anchor());
let a2 = set.colliders().get(h2).map(|c| c.anchor());
match (a1, a2) {
(
Some(ColliderAnchor::OnBodyPart {
body_part: part1, ..
}),
Some(ColliderAnchor::OnBodyPart {
body_part: part2, ..
}),
) => part1.0 != part2.0, // Don't collide if the two parts belong to the same body.
_ => true,
}
}
}
/*
* NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type.
* This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.)
*/
pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) {
/*
* World
*/
let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81)));
let geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let joint_constraints = DefaultJointConstraintSet::new();
let force_generators = DefaultForceGeneratorSet::new();
/*
* Ground
*/
let ground_size = r!(25.0);
let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, r!(1.0))));
let ground_handle = bodies.insert(Ground::new());
let co = ColliderDesc::new(ground_shape)
.translation(-Vector2::y())
.build(BodyPartHandle(ground_handle, 0));
colliders.insert(co);
/*
* Create the ragdolls
*/
build_ragdolls(&mut bodies, &mut colliders);
/*
* Run the simulation.
*/
testbed.set_ground_handle(Some(ground_handle));
testbed.set_broad_phase_pair_filter(NoMultibodySelfContactFilter);
testbed.set_world(
mechanical_world,
geometrical_world,
bodies,
colliders,
joint_constraints,
force_generators,
);
testbed.look_at(Point2::new(0.0, 5.0), 25.0);
}
fn build_ragdolls<N: RealField>(
bodies: &mut DefaultBodySet<N>,
colliders: &mut DefaultColliderSet<N>,
) {
let body_rady = r!(1.2);
let body_radx = r!(0.2);
let head_rad = r!(0.4);
let member_rad = r!(0.1);
let arm_length = r!(0.9);
let leg_length = r!(1.4);
let space = r!(0.1);
let body_geom = ShapeHandle::new(Cuboid::new(Vector2::new(body_radx, body_rady)));
let head_geom = ShapeHandle::new(Ball::new(head_rad));
let arm_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, arm_length)));
let leg_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, leg_length)));
// The position of the free joint will be modified in the
// final loop of this function (before we actually build the
// ragdoll body into the World.
let free = FreeJoint::new(Isometry2::new(Vector2::zeros(), na::zero()));
let spherical = RevoluteJoint::new(na::zero());
/*
* Body.
*/
let body_collider = ColliderDesc::new(body_geom).density(r!(0.3));
let mut body = MultibodyDesc::new(free);
/*
* Head.
*/
let head_collider = ColliderDesc::new(head_geom).density(r!(0.3));
body.add_child(spherical).set_parent_shift(Vector2::new(
r!(0.0),
body_rady + head_rad + space * r!(2.0),
));
/*
* Arms.
*/
let arm_collider = ColliderDesc::new(arm_geom).density(r!(0.3));
body.add_child(spherical)
.set_parent_shift(Vector2::new(body_radx + r!(2.0) * space, body_rady))
.set_body_shift(Vector2::new(r!(0.0), arm_length + space));
body.add_child(spherical)
.set_parent_shift(Vector2::new(-body_radx - r!(2.0) * space, body_rady))
.set_body_shift(Vector2::new(r!(0.0), arm_length + space));
/*
* Legs.
*/
let leg_collider = ColliderDesc::new(leg_geom).density(r!(0.3));
body.add_child(spherical)
.set_parent_shift(Vector2::new(body_radx, -body_rady))
.set_body_shift(Vector2::new(r!(0.0), leg_length + space));
body.add_child(spherical)
.set_parent_shift(Vector2::new(-body_radx, -body_rady))
.set_body_shift(Vector2::new(r!(0.0), leg_length + space));
let n = 5;
let shiftx = r!(2.0);
let shifty = r!(6.5);
for i in 0usize..n {
for j in 0usize..n {
let x = r!(i as f64) * shiftx - r!(n as f64) * shiftx / r!(2.0);
let y = r!(j as f64) * shifty + r!(6.0);
let free = FreeJoint::new(Isometry2::translation(x, y));
let ragdoll = body.set_joint(free).build();
let ragdoll_handle = bodies.insert(ragdoll);
colliders.insert(body_collider.build(BodyPartHandle(ragdoll_handle, 0)));
colliders.insert(head_collider.build(BodyPartHandle(ragdoll_handle, 1)));
colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 2)));
colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 3)));
colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 4)));
colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 5)));
}
}
}
fn main() {
let mut testbed = Testbed::<f32>::new_empty();
init_world(&mut testbed);
testbed.run();
}
| NoMultibodySelfContactFilter | identifier_name |
broad_phase_filter2.rs | extern crate nalgebra as na;
use na::{Isometry2, Point2, RealField, Vector2};
use ncollide2d::broad_phase::BroadPhasePairFilter;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{FreeJoint, RevoluteJoint};
use nphysics2d::object::{
BodyPartHandle, BodySet, Collider, ColliderAnchor, ColliderDesc, ColliderSet,
DefaultBodyHandle, DefaultBodySet, DefaultColliderHandle, DefaultColliderSet, Ground,
MultibodyDesc,
};
use nphysics2d::world::{
BroadPhasePairFilterSets, DefaultGeometricalWorld, DefaultMechanicalWorld,
};
use nphysics_testbed2d::Testbed;
struct NoMultibodySelfContactFilter;
impl<N, Bodies, Colliders>
BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>>
for NoMultibodySelfContactFilter
where
N: RealField,
Bodies: BodySet<N>,
Colliders: ColliderSet<N, Bodies::Handle>,
{
fn is_pair_valid(
&self,
h1: Colliders::Handle,
h2: Colliders::Handle,
set: &BroadPhasePairFilterSets<'_, N, Bodies, Colliders>,
) -> bool {
let a1 = set.colliders().get(h1).map(|c| c.anchor());
let a2 = set.colliders().get(h2).map(|c| c.anchor());
match (a1, a2) {
(
Some(ColliderAnchor::OnBodyPart {
body_part: part1, ..
}),
Some(ColliderAnchor::OnBodyPart {
body_part: part2, ..
}),
) => part1.0 != part2.0, // Don't collide if the two parts belong to the same body.
_ => true,
}
}
} | * This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.)
*/
pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) {
/*
* World
*/
let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81)));
let geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let joint_constraints = DefaultJointConstraintSet::new();
let force_generators = DefaultForceGeneratorSet::new();
/*
* Ground
*/
let ground_size = r!(25.0);
let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, r!(1.0))));
let ground_handle = bodies.insert(Ground::new());
let co = ColliderDesc::new(ground_shape)
.translation(-Vector2::y())
.build(BodyPartHandle(ground_handle, 0));
colliders.insert(co);
/*
* Create the ragdolls
*/
build_ragdolls(&mut bodies, &mut colliders);
/*
* Run the simulation.
*/
testbed.set_ground_handle(Some(ground_handle));
testbed.set_broad_phase_pair_filter(NoMultibodySelfContactFilter);
testbed.set_world(
mechanical_world,
geometrical_world,
bodies,
colliders,
joint_constraints,
force_generators,
);
testbed.look_at(Point2::new(0.0, 5.0), 25.0);
}
fn build_ragdolls<N: RealField>(
bodies: &mut DefaultBodySet<N>,
colliders: &mut DefaultColliderSet<N>,
) {
let body_rady = r!(1.2);
let body_radx = r!(0.2);
let head_rad = r!(0.4);
let member_rad = r!(0.1);
let arm_length = r!(0.9);
let leg_length = r!(1.4);
let space = r!(0.1);
let body_geom = ShapeHandle::new(Cuboid::new(Vector2::new(body_radx, body_rady)));
let head_geom = ShapeHandle::new(Ball::new(head_rad));
let arm_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, arm_length)));
let leg_geom = ShapeHandle::new(Cuboid::new(Vector2::new(member_rad, leg_length)));
// The position of the free joint will be modified in the
// final loop of this function (before we actually build the
// ragdoll body into the World.
let free = FreeJoint::new(Isometry2::new(Vector2::zeros(), na::zero()));
let spherical = RevoluteJoint::new(na::zero());
/*
* Body.
*/
let body_collider = ColliderDesc::new(body_geom).density(r!(0.3));
let mut body = MultibodyDesc::new(free);
/*
* Head.
*/
let head_collider = ColliderDesc::new(head_geom).density(r!(0.3));
body.add_child(spherical).set_parent_shift(Vector2::new(
r!(0.0),
body_rady + head_rad + space * r!(2.0),
));
/*
* Arms.
*/
let arm_collider = ColliderDesc::new(arm_geom).density(r!(0.3));
body.add_child(spherical)
.set_parent_shift(Vector2::new(body_radx + r!(2.0) * space, body_rady))
.set_body_shift(Vector2::new(r!(0.0), arm_length + space));
body.add_child(spherical)
.set_parent_shift(Vector2::new(-body_radx - r!(2.0) * space, body_rady))
.set_body_shift(Vector2::new(r!(0.0), arm_length + space));
/*
* Legs.
*/
let leg_collider = ColliderDesc::new(leg_geom).density(r!(0.3));
body.add_child(spherical)
.set_parent_shift(Vector2::new(body_radx, -body_rady))
.set_body_shift(Vector2::new(r!(0.0), leg_length + space));
body.add_child(spherical)
.set_parent_shift(Vector2::new(-body_radx, -body_rady))
.set_body_shift(Vector2::new(r!(0.0), leg_length + space));
let n = 5;
let shiftx = r!(2.0);
let shifty = r!(6.5);
for i in 0usize..n {
for j in 0usize..n {
let x = r!(i as f64) * shiftx - r!(n as f64) * shiftx / r!(2.0);
let y = r!(j as f64) * shifty + r!(6.0);
let free = FreeJoint::new(Isometry2::translation(x, y));
let ragdoll = body.set_joint(free).build();
let ragdoll_handle = bodies.insert(ragdoll);
colliders.insert(body_collider.build(BodyPartHandle(ragdoll_handle, 0)));
colliders.insert(head_collider.build(BodyPartHandle(ragdoll_handle, 1)));
colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 2)));
colliders.insert(arm_collider.build(BodyPartHandle(ragdoll_handle, 3)));
colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 4)));
colliders.insert(leg_collider.build(BodyPartHandle(ragdoll_handle, 5)));
}
}
}
fn main() {
let mut testbed = Testbed::<f32>::new_empty();
init_world(&mut testbed);
testbed.run();
} |
/*
* NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type. | random_line_split |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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
# (at your option) any later version.
from tests import TestCase, mkstemp
import os
from quodlibet.qltk.cbes import ComboBoxEntrySave, StandaloneEditor
import quodlibet.config
class TComboBoxEntrySave(TestCase):
memory = "pattern 1\npattern 2\n"
saved = "pattern text\npattern name\n"
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname, "w") as f:
f.write(self.memory)
with open(self.fname + ".saved", "w") as f:
f.write(self.saved)
self.cbes = ComboBoxEntrySave(self.fname, count=2)
self.cbes2 = ComboBoxEntrySave(self.fname, count=2)
self.cbes3 = ComboBoxEntrySave(self.fname, count=2,
filter=lambda ls, it, *d: ls.get_value(it, 0) == "filter")
def test_equivalence(self):
model1 = self.cbes.model_store
model2 = self.cbes2.model_store
self.failUnlessEqual(model1, model2)
rows1 = list(model1)
rows2 = list(model2)
for row1, row2 in zip(rows1, rows2):
self.failUnlessEqual(row1[0], row2[0])
self.failUnlessEqual(row1[1], row2[1])
self.failUnlessEqual(row1[2], row2[2])
def test_text_changed_signal(self):
called = [0]
def cb(*args):
called[0] += 1
def get_count():
c = called[0]
called[0] = 0
return c
self.cbes.connect("text-changed", cb)
entry = self.cbes.get_child()
entry.set_text("foo")
self.failUnlessEqual(get_count(), 1)
self.cbes.prepend_text("bar")
# in case the model got changed but the entry is still the same
# the text-changed signal should not be triggered
self.failUnlessEqual(entry.get_text(), "foo")
self.failUnlessEqual(get_count(), 0)
def test_shared_model(self):
self.cbes.prepend_text("a test")
self.test_equivalence()
def test_initial_size(self):
# 1 saved, Edit, separator, 3 remembered
self.failUnlessEqual(len(self.cbes.get_model()), 5)
def test_prepend_text(self):
self.cbes.prepend_text("pattern 3")
self.memory = "pattern 3\npattern 1\n"
self.test_save()
def | (self):
self.cbes.write()
self.failUnlessEqual(self.memory, open(self.fname).read())
self.failUnlessEqual(self.saved, open(self.fname + ".saved").read())
def test_set_text_then_prepend(self):
self.cbes.get_child().set_text("foobar")
self.cbes.prepend_text("foobar")
self.memory = "foobar\npattern 1\n"
self.test_save()
def test_filter(self):
self.cbes3.prepend_text("filter")
self.failUnlessEqual(1, len(self.cbes3.get_model()))
def tearDown(self):
self.cbes.destroy()
self.cbes2.destroy()
self.cbes3.destroy()
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
quodlibet.config.quit()
class TStandaloneEditor(TestCase):
TEST_KV_DATA = [
("Search Foo", "https://foo.com/search?q=<artist>-<title>")]
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname + ".saved", "w") as f:
f.write(
"%s\n%s\n" % (self.TEST_KV_DATA[0][1],
self.TEST_KV_DATA[0][0]))
self.sae = StandaloneEditor(self.fname, "test", None, None)
def test_constructor(self):
self.failUnless(self.sae.model)
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(data, self.TEST_KV_DATA)
def test_load_values(self):
values = StandaloneEditor.load_values(self.fname + ".saved")
self.failUnlessEqual(self.TEST_KV_DATA, values)
def test_defaults(self):
defaults = [("Dot-com Dream", "http://<artist>.com")]
try:
os.unlink(self.fname)
except OSError:
pass
# Now create a new SAE without saved results and use defaults
self.fname = "foo"
self.sae.destroy()
self.sae = StandaloneEditor(self.fname, "test2", defaults, None)
self.sae.write()
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(defaults, data)
def tearDown(self):
self.sae.destroy()
try:
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
except OSError:
pass
quodlibet.config.quit()
| test_save | identifier_name |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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
# (at your option) any later version.
from tests import TestCase, mkstemp
import os
from quodlibet.qltk.cbes import ComboBoxEntrySave, StandaloneEditor
import quodlibet.config
class TComboBoxEntrySave(TestCase):
memory = "pattern 1\npattern 2\n"
saved = "pattern text\npattern name\n"
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname, "w") as f:
f.write(self.memory)
with open(self.fname + ".saved", "w") as f:
f.write(self.saved)
self.cbes = ComboBoxEntrySave(self.fname, count=2)
self.cbes2 = ComboBoxEntrySave(self.fname, count=2)
self.cbes3 = ComboBoxEntrySave(self.fname, count=2,
filter=lambda ls, it, *d: ls.get_value(it, 0) == "filter")
def test_equivalence(self):
model1 = self.cbes.model_store
model2 = self.cbes2.model_store
self.failUnlessEqual(model1, model2)
rows1 = list(model1)
rows2 = list(model2)
for row1, row2 in zip(rows1, rows2):
self.failUnlessEqual(row1[0], row2[0])
self.failUnlessEqual(row1[1], row2[1])
self.failUnlessEqual(row1[2], row2[2])
def test_text_changed_signal(self):
called = [0]
def cb(*args):
called[0] += 1
def get_count():
c = called[0]
called[0] = 0
return c
self.cbes.connect("text-changed", cb)
entry = self.cbes.get_child()
entry.set_text("foo")
self.failUnlessEqual(get_count(), 1)
self.cbes.prepend_text("bar")
# in case the model got changed but the entry is still the same
# the text-changed signal should not be triggered
self.failUnlessEqual(entry.get_text(), "foo")
self.failUnlessEqual(get_count(), 0)
def test_shared_model(self):
self.cbes.prepend_text("a test")
self.test_equivalence()
def test_initial_size(self):
# 1 saved, Edit, separator, 3 remembered
self.failUnlessEqual(len(self.cbes.get_model()), 5)
def test_prepend_text(self):
|
def test_save(self):
self.cbes.write()
self.failUnlessEqual(self.memory, open(self.fname).read())
self.failUnlessEqual(self.saved, open(self.fname + ".saved").read())
def test_set_text_then_prepend(self):
self.cbes.get_child().set_text("foobar")
self.cbes.prepend_text("foobar")
self.memory = "foobar\npattern 1\n"
self.test_save()
def test_filter(self):
self.cbes3.prepend_text("filter")
self.failUnlessEqual(1, len(self.cbes3.get_model()))
def tearDown(self):
self.cbes.destroy()
self.cbes2.destroy()
self.cbes3.destroy()
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
quodlibet.config.quit()
class TStandaloneEditor(TestCase):
TEST_KV_DATA = [
("Search Foo", "https://foo.com/search?q=<artist>-<title>")]
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname + ".saved", "w") as f:
f.write(
"%s\n%s\n" % (self.TEST_KV_DATA[0][1],
self.TEST_KV_DATA[0][0]))
self.sae = StandaloneEditor(self.fname, "test", None, None)
def test_constructor(self):
self.failUnless(self.sae.model)
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(data, self.TEST_KV_DATA)
def test_load_values(self):
values = StandaloneEditor.load_values(self.fname + ".saved")
self.failUnlessEqual(self.TEST_KV_DATA, values)
def test_defaults(self):
defaults = [("Dot-com Dream", "http://<artist>.com")]
try:
os.unlink(self.fname)
except OSError:
pass
# Now create a new SAE without saved results and use defaults
self.fname = "foo"
self.sae.destroy()
self.sae = StandaloneEditor(self.fname, "test2", defaults, None)
self.sae.write()
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(defaults, data)
def tearDown(self):
self.sae.destroy()
try:
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
except OSError:
pass
quodlibet.config.quit()
| self.cbes.prepend_text("pattern 3")
self.memory = "pattern 3\npattern 1\n"
self.test_save() | identifier_body |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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
# (at your option) any later version.
from tests import TestCase, mkstemp
import os
from quodlibet.qltk.cbes import ComboBoxEntrySave, StandaloneEditor
import quodlibet.config
class TComboBoxEntrySave(TestCase):
memory = "pattern 1\npattern 2\n"
saved = "pattern text\npattern name\n"
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname, "w") as f:
f.write(self.memory)
with open(self.fname + ".saved", "w") as f:
f.write(self.saved)
self.cbes = ComboBoxEntrySave(self.fname, count=2)
self.cbes2 = ComboBoxEntrySave(self.fname, count=2)
self.cbes3 = ComboBoxEntrySave(self.fname, count=2,
filter=lambda ls, it, *d: ls.get_value(it, 0) == "filter")
def test_equivalence(self):
model1 = self.cbes.model_store
model2 = self.cbes2.model_store
self.failUnlessEqual(model1, model2)
rows1 = list(model1)
rows2 = list(model2)
for row1, row2 in zip(rows1, rows2):
|
def test_text_changed_signal(self):
called = [0]
def cb(*args):
called[0] += 1
def get_count():
c = called[0]
called[0] = 0
return c
self.cbes.connect("text-changed", cb)
entry = self.cbes.get_child()
entry.set_text("foo")
self.failUnlessEqual(get_count(), 1)
self.cbes.prepend_text("bar")
# in case the model got changed but the entry is still the same
# the text-changed signal should not be triggered
self.failUnlessEqual(entry.get_text(), "foo")
self.failUnlessEqual(get_count(), 0)
def test_shared_model(self):
self.cbes.prepend_text("a test")
self.test_equivalence()
def test_initial_size(self):
# 1 saved, Edit, separator, 3 remembered
self.failUnlessEqual(len(self.cbes.get_model()), 5)
def test_prepend_text(self):
self.cbes.prepend_text("pattern 3")
self.memory = "pattern 3\npattern 1\n"
self.test_save()
def test_save(self):
self.cbes.write()
self.failUnlessEqual(self.memory, open(self.fname).read())
self.failUnlessEqual(self.saved, open(self.fname + ".saved").read())
def test_set_text_then_prepend(self):
self.cbes.get_child().set_text("foobar")
self.cbes.prepend_text("foobar")
self.memory = "foobar\npattern 1\n"
self.test_save()
def test_filter(self):
self.cbes3.prepend_text("filter")
self.failUnlessEqual(1, len(self.cbes3.get_model()))
def tearDown(self):
self.cbes.destroy()
self.cbes2.destroy()
self.cbes3.destroy()
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
quodlibet.config.quit()
class TStandaloneEditor(TestCase):
TEST_KV_DATA = [
("Search Foo", "https://foo.com/search?q=<artist>-<title>")]
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname + ".saved", "w") as f:
f.write(
"%s\n%s\n" % (self.TEST_KV_DATA[0][1],
self.TEST_KV_DATA[0][0]))
self.sae = StandaloneEditor(self.fname, "test", None, None)
def test_constructor(self):
self.failUnless(self.sae.model)
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(data, self.TEST_KV_DATA)
def test_load_values(self):
values = StandaloneEditor.load_values(self.fname + ".saved")
self.failUnlessEqual(self.TEST_KV_DATA, values)
def test_defaults(self):
defaults = [("Dot-com Dream", "http://<artist>.com")]
try:
os.unlink(self.fname)
except OSError:
pass
# Now create a new SAE without saved results and use defaults
self.fname = "foo"
self.sae.destroy()
self.sae = StandaloneEditor(self.fname, "test2", defaults, None)
self.sae.write()
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(defaults, data)
def tearDown(self):
self.sae.destroy()
try:
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
except OSError:
pass
quodlibet.config.quit()
| self.failUnlessEqual(row1[0], row2[0])
self.failUnlessEqual(row1[1], row2[1])
self.failUnlessEqual(row1[2], row2[2]) | conditional_block |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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
# (at your option) any later version.
from tests import TestCase, mkstemp
import os
from quodlibet.qltk.cbes import ComboBoxEntrySave, StandaloneEditor
import quodlibet.config
class TComboBoxEntrySave(TestCase):
memory = "pattern 1\npattern 2\n"
saved = "pattern text\npattern name\n"
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname, "w") as f:
f.write(self.memory)
with open(self.fname + ".saved", "w") as f:
f.write(self.saved)
self.cbes = ComboBoxEntrySave(self.fname, count=2)
self.cbes2 = ComboBoxEntrySave(self.fname, count=2)
self.cbes3 = ComboBoxEntrySave(self.fname, count=2,
filter=lambda ls, it, *d: ls.get_value(it, 0) == "filter")
def test_equivalence(self):
model1 = self.cbes.model_store
model2 = self.cbes2.model_store
self.failUnlessEqual(model1, model2)
rows1 = list(model1)
rows2 = list(model2)
for row1, row2 in zip(rows1, rows2):
self.failUnlessEqual(row1[0], row2[0])
self.failUnlessEqual(row1[1], row2[1])
self.failUnlessEqual(row1[2], row2[2])
def test_text_changed_signal(self):
called = [0]
def cb(*args):
called[0] += 1
def get_count():
c = called[0]
called[0] = 0
return c
self.cbes.connect("text-changed", cb)
entry = self.cbes.get_child()
entry.set_text("foo")
self.failUnlessEqual(get_count(), 1)
self.cbes.prepend_text("bar")
# in case the model got changed but the entry is still the same
# the text-changed signal should not be triggered
self.failUnlessEqual(entry.get_text(), "foo")
self.failUnlessEqual(get_count(), 0)
def test_shared_model(self):
self.cbes.prepend_text("a test")
self.test_equivalence()
def test_initial_size(self):
# 1 saved, Edit, separator, 3 remembered
self.failUnlessEqual(len(self.cbes.get_model()), 5)
def test_prepend_text(self):
self.cbes.prepend_text("pattern 3")
self.memory = "pattern 3\npattern 1\n"
self.test_save()
def test_save(self):
self.cbes.write()
self.failUnlessEqual(self.memory, open(self.fname).read())
self.failUnlessEqual(self.saved, open(self.fname + ".saved").read())
def test_set_text_then_prepend(self):
self.cbes.get_child().set_text("foobar")
self.cbes.prepend_text("foobar")
self.memory = "foobar\npattern 1\n"
self.test_save()
def test_filter(self):
self.cbes3.prepend_text("filter")
self.failUnlessEqual(1, len(self.cbes3.get_model()))
def tearDown(self):
self.cbes.destroy()
self.cbes2.destroy()
self.cbes3.destroy()
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
quodlibet.config.quit()
class TStandaloneEditor(TestCase):
TEST_KV_DATA = [
("Search Foo", "https://foo.com/search?q=<artist>-<title>")]
def setUp(self):
quodlibet.config.init()
h, self.fname = mkstemp()
os.close(h)
with open(self.fname + ".saved", "w") as f:
f.write(
"%s\n%s\n" % (self.TEST_KV_DATA[0][1],
self.TEST_KV_DATA[0][0]))
self.sae = StandaloneEditor(self.fname, "test", None, None)
def test_constructor(self):
self.failUnless(self.sae.model)
data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(data, self.TEST_KV_DATA)
def test_load_values(self):
values = StandaloneEditor.load_values(self.fname + ".saved")
self.failUnlessEqual(self.TEST_KV_DATA, values)
def test_defaults(self):
defaults = [("Dot-com Dream", "http://<artist>.com")]
try:
os.unlink(self.fname)
except OSError:
pass
# Now create a new SAE without saved results and use defaults
self.fname = "foo"
self.sae.destroy()
self.sae = StandaloneEditor(self.fname, "test2", defaults, None) | data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(defaults, data)
def tearDown(self):
self.sae.destroy()
try:
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
except OSError:
pass
quodlibet.config.quit() | self.sae.write() | random_line_split |
websocket.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::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, JSRef};
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId};
use servo_net::resource_task::{Load, LoadData, LoadResponse};
use servo_util::str::DOMString;
use std::ascii::IntoBytes;
use std::comm::channel;
use url::Url;
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: DOMString,
response: LoadResponse,
state: u16
}
impl WebSocket {
pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(WebSocketTypeId),
url: url,
response: resp,
state: state_value
}
}
pub fn | (global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> {
let resource_task = global.resource_task();
let ws_url = Url::parse(url.as_slice()).unwrap();
let(start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(ws_url), start_chan));
let resp = start_port.recv();
reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN),
global,
WebSocketBinding::Wrap)
}
pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> {
Ok(WebSocket::new(global, url))
}
}
impl Reflectable for WebSocket {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
impl<'a> WebSocketMethods for JSRef<'a, WebSocket> {
event_handler!(open, GetOnopen, SetOnopen)
event_handler!(error, GetOnerror, SetOnerror)
event_handler!(close, GetOnclose, SetOnclose)
event_handler!(message, GetOnmessage, SetOnmessage)
fn Send(self, message: DOMString) {
if self.state == WebSocketConstants::OPEN {
let message_u8: Vec<u8>=message.to_string().into_bytes();
assert!(message.len() <= 125);
let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len());
/*
We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7.
10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129
*/
const ENTRY1: u8 = 0x81;
payload.push(ENTRY1);
payload.push(message.len() as u8);
payload.push_all(message_u8.as_slice());
} else {
return;
}
}
fn Close(self) {
}
fn Url(self) -> DOMString {
self.url.clone()
}
}
| new | identifier_name |
websocket.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::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, JSRef};
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId};
use servo_net::resource_task::{Load, LoadData, LoadResponse};
use servo_util::str::DOMString;
use std::ascii::IntoBytes;
use std::comm::channel;
use url::Url;
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: DOMString,
response: LoadResponse,
state: u16
}
impl WebSocket {
pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(WebSocketTypeId),
url: url,
response: resp,
state: state_value
}
}
pub fn new(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> |
pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> {
Ok(WebSocket::new(global, url))
}
}
impl Reflectable for WebSocket {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
impl<'a> WebSocketMethods for JSRef<'a, WebSocket> {
event_handler!(open, GetOnopen, SetOnopen)
event_handler!(error, GetOnerror, SetOnerror)
event_handler!(close, GetOnclose, SetOnclose)
event_handler!(message, GetOnmessage, SetOnmessage)
fn Send(self, message: DOMString) {
if self.state == WebSocketConstants::OPEN {
let message_u8: Vec<u8>=message.to_string().into_bytes();
assert!(message.len() <= 125);
let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len());
/*
We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7.
10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129
*/
const ENTRY1: u8 = 0x81;
payload.push(ENTRY1);
payload.push(message.len() as u8);
payload.push_all(message_u8.as_slice());
} else {
return;
}
}
fn Close(self) {
}
fn Url(self) -> DOMString {
self.url.clone()
}
}
| {
let resource_task = global.resource_task();
let ws_url = Url::parse(url.as_slice()).unwrap();
let(start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(ws_url), start_chan));
let resp = start_port.recv();
reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN),
global,
WebSocketBinding::Wrap)
} | identifier_body |
websocket.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::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, JSRef};
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId};
use servo_net::resource_task::{Load, LoadData, LoadResponse};
use servo_util::str::DOMString;
use std::ascii::IntoBytes;
use std::comm::channel;
use url::Url;
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: DOMString,
response: LoadResponse,
state: u16
}
impl WebSocket {
pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(WebSocketTypeId),
url: url,
response: resp,
state: state_value
}
}
pub fn new(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> {
let resource_task = global.resource_task();
let ws_url = Url::parse(url.as_slice()).unwrap();
let(start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(ws_url), start_chan));
let resp = start_port.recv();
reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN),
global,
WebSocketBinding::Wrap)
}
pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> {
Ok(WebSocket::new(global, url))
}
}
impl Reflectable for WebSocket {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
impl<'a> WebSocketMethods for JSRef<'a, WebSocket> {
event_handler!(open, GetOnopen, SetOnopen)
event_handler!(error, GetOnerror, SetOnerror)
event_handler!(close, GetOnclose, SetOnclose)
event_handler!(message, GetOnmessage, SetOnmessage)
fn Send(self, message: DOMString) {
if self.state == WebSocketConstants::OPEN {
let message_u8: Vec<u8>=message.to_string().into_bytes();
assert!(message.len() <= 125);
let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len());
/*
We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7.
10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129
*/
const ENTRY1: u8 = 0x81;
payload.push(ENTRY1);
payload.push(message.len() as u8);
payload.push_all(message_u8.as_slice());
} else |
}
fn Close(self) {
}
fn Url(self) -> DOMString {
self.url.clone()
}
}
| {
return;
} | conditional_block |
websocket.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::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketMethods;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSocketConstants;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{Temporary, JSRef};
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::eventtarget::{EventTarget, EventTargetHelpers, WebSocketTypeId};
use servo_net::resource_task::{Load, LoadData, LoadResponse};
use servo_util::str::DOMString;
use std::ascii::IntoBytes;
use std::comm::channel;
use url::Url;
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: DOMString,
response: LoadResponse,
state: u16
}
impl WebSocket {
pub fn new_inherited(url: DOMString, resp: LoadResponse, state_value: u16) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(WebSocketTypeId),
url: url,
response: resp,
state: state_value
}
}
pub fn new(global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> {
let resource_task = global.resource_task();
let ws_url = Url::parse(url.as_slice()).unwrap();
let(start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(ws_url), start_chan));
let resp = start_port.recv();
reflect_dom_object(box WebSocket::new_inherited(url, resp, WebSocketConstants::OPEN),
global,
WebSocketBinding::Wrap)
}
pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> {
Ok(WebSocket::new(global, url))
}
}
impl Reflectable for WebSocket {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
impl<'a> WebSocketMethods for JSRef<'a, WebSocket> {
event_handler!(open, GetOnopen, SetOnopen)
event_handler!(error, GetOnerror, SetOnerror)
event_handler!(close, GetOnclose, SetOnclose)
event_handler!(message, GetOnmessage, SetOnmessage)
fn Send(self, message: DOMString) {
if self.state == WebSocketConstants::OPEN {
let message_u8: Vec<u8>=message.to_string().into_bytes();
assert!(message.len() <= 125);
let mut payload: Vec<u8> = Vec::with_capacity(2 + message_u8.len());
/*
We are sending a single framed unmasked text message. Referring to http://tools.ietf.org/html/rfc6455#section-5.7.
10000001 this indicates FIN bit=1 and the opcode is 0001 which means it is a text frame and the decimal equivalent is 129
*/
const ENTRY1: u8 = 0x81;
payload.push(ENTRY1);
payload.push(message.len() as u8);
payload.push_all(message_u8.as_slice());
} else {
return;
}
}
fn Close(self) {
}
fn Url(self) -> DOMString {
self.url.clone()
}
} | random_line_split | |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Galaxy Harvester 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
import pymysql
import dbInfo
import optparse
import smtplib
from email.message import EmailMessage
from smtplib import SMTPRecipientsRefused
import time
from datetime import timedelta, datetime
import mailInfo
emailIDs = ['spawns', 'activity']
def ghConn():
conn = pymysql.connect(host = dbInfo.DB_HOST,
db = dbInfo.DB_NAME,
user = dbInfo.DB_USER,
passwd = dbInfo.DB_PASS)
conn.autocommit(True)
return conn
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle, emailIndex):
# Don't try to send mail if we exceeded quota within last hour
lastFailureTime = datetime(2000, 1, 1, 12)
currentTime = datetime.fromtimestamp(time.time())
timeSinceFailure = currentTime - lastFailureTime
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt")
lastFailureTime = datetime.strptime(f.read().strip(), "%Y-%m-%d %H:%M:%S")
f.close()
timeSinceFailure = currentTime - lastFailureTime
except IOError as e:
sys.stdout.write("No last failure time\n")
if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660:
sys.stderr.write(str(timeSinceFailure.seconds) + " less than 3660 no mail.\n")
return 1
# look up the user email
cursor = conn.cursor()
cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID + "';")
row = cursor.fetchone()
if row == None:
result = "bad username"
else:
email = row[0]
if (email.find("@") > -1 and email.find(".") > -1):
# send message
message = EmailMessage()
message['From'] = "\"Galaxy Harvester Alerts\" <" + emailIDs[emailIndex] + "@galaxyharvester.net>"
message['To'] = email
message['Subject'] = "".join(("Galaxy Harvester ", alertTitle))
message.set_content("".join(("Hello ", userID, ",\n\n", msgText, "\n\n", link, "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n")))
message.add_alternative("".join(("<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ", userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"), "</p><p><a style='text-decoration:none;' href='", link, "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ", link, "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Administrator</p>")), subtype='html')
mailer = smtplib.SMTP(mailInfo.MAIL_HOST)
mailer.login(emailIDs[emailIndex] + "@galaxyharvester.net", mailInfo.MAIL_PASS)
try:
mailer.send_message(message)
result = 'email sent'
except SMTPRecipientsRefused as e: | mailer.quit()
# update alert status
if ( result == 'email sent' ):
cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';')
else:
result = 'Invalid email.'
cursor.close()
def main():
emailIndex = 0
# check for command line argument for email to use
if len(sys.argv) > 1:
emailIndex = int(sys.argv[1])
conn = ghConn()
# try sending any backed up alert mails
retryPendingMail(conn, emailIndex)
def trackEmailFailure(failureTime, emailIndex):
# Update tracking file
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt", "w")
f.write(failureTime)
f.close()
except IOError as e:
sys.stderr.write("Could not write email failure tracking file")
def retryPendingMail(conn, emailIndex):
# open email alerts that have not been sucessfully sent less than 48 hours old
minTime = datetime.fromtimestamp(time.time()) - timedelta(days=4)
cursor = conn.cursor()
cursor.execute("SELECT userID, alertTime, alertMessage, alertLink, alertID FROM tAlerts WHERE alertType=2 AND alertStatus=0 and alertTime > '" + minTime.strftime("%Y-%m-%d %H:%M:%S") + "' and alertMessage LIKE '% - %';")
row = cursor.fetchone()
# try to send as long as not exceeding quota
while row != None:
fullText = row[2]
splitPos = fullText.find(" - ")
alertTitle = fullText[:splitPos]
alertBody = fullText[splitPos+3:]
result = sendAlertMail(conn, row[0], alertBody, row[3], row[4], alertTitle, emailIndex)
if result == 1:
sys.stderr.write("Delayed retrying rest of mail since quota reached.\n")
break
row = cursor.fetchone()
cursor.close()
if __name__ == "__main__":
main() | result = 'email failed'
sys.stderr.write('Email failed - ' + str(e))
trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"), emailIndex) | random_line_split |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Galaxy Harvester 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
import pymysql
import dbInfo
import optparse
import smtplib
from email.message import EmailMessage
from smtplib import SMTPRecipientsRefused
import time
from datetime import timedelta, datetime
import mailInfo
emailIDs = ['spawns', 'activity']
def ghConn():
conn = pymysql.connect(host = dbInfo.DB_HOST,
db = dbInfo.DB_NAME,
user = dbInfo.DB_USER,
passwd = dbInfo.DB_PASS)
conn.autocommit(True)
return conn
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle, emailIndex):
# Don't try to send mail if we exceeded quota within last hour
lastFailureTime = datetime(2000, 1, 1, 12)
currentTime = datetime.fromtimestamp(time.time())
timeSinceFailure = currentTime - lastFailureTime
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt")
lastFailureTime = datetime.strptime(f.read().strip(), "%Y-%m-%d %H:%M:%S")
f.close()
timeSinceFailure = currentTime - lastFailureTime
except IOError as e:
sys.stdout.write("No last failure time\n")
if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660:
sys.stderr.write(str(timeSinceFailure.seconds) + " less than 3660 no mail.\n")
return 1
# look up the user email
cursor = conn.cursor()
cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID + "';")
row = cursor.fetchone()
if row == None:
result = "bad username"
else:
email = row[0]
if (email.find("@") > -1 and email.find(".") > -1):
# send message
message = EmailMessage()
message['From'] = "\"Galaxy Harvester Alerts\" <" + emailIDs[emailIndex] + "@galaxyharvester.net>"
message['To'] = email
message['Subject'] = "".join(("Galaxy Harvester ", alertTitle))
message.set_content("".join(("Hello ", userID, ",\n\n", msgText, "\n\n", link, "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n")))
message.add_alternative("".join(("<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ", userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"), "</p><p><a style='text-decoration:none;' href='", link, "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ", link, "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Administrator</p>")), subtype='html')
mailer = smtplib.SMTP(mailInfo.MAIL_HOST)
mailer.login(emailIDs[emailIndex] + "@galaxyharvester.net", mailInfo.MAIL_PASS)
try:
mailer.send_message(message)
result = 'email sent'
except SMTPRecipientsRefused as e:
result = 'email failed'
sys.stderr.write('Email failed - ' + str(e))
trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"), emailIndex)
mailer.quit()
# update alert status
if ( result == 'email sent' ):
cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';')
else:
result = 'Invalid email.'
cursor.close()
def | ():
emailIndex = 0
# check for command line argument for email to use
if len(sys.argv) > 1:
emailIndex = int(sys.argv[1])
conn = ghConn()
# try sending any backed up alert mails
retryPendingMail(conn, emailIndex)
def trackEmailFailure(failureTime, emailIndex):
# Update tracking file
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt", "w")
f.write(failureTime)
f.close()
except IOError as e:
sys.stderr.write("Could not write email failure tracking file")
def retryPendingMail(conn, emailIndex):
# open email alerts that have not been sucessfully sent less than 48 hours old
minTime = datetime.fromtimestamp(time.time()) - timedelta(days=4)
cursor = conn.cursor()
cursor.execute("SELECT userID, alertTime, alertMessage, alertLink, alertID FROM tAlerts WHERE alertType=2 AND alertStatus=0 and alertTime > '" + minTime.strftime("%Y-%m-%d %H:%M:%S") + "' and alertMessage LIKE '% - %';")
row = cursor.fetchone()
# try to send as long as not exceeding quota
while row != None:
fullText = row[2]
splitPos = fullText.find(" - ")
alertTitle = fullText[:splitPos]
alertBody = fullText[splitPos+3:]
result = sendAlertMail(conn, row[0], alertBody, row[3], row[4], alertTitle, emailIndex)
if result == 1:
sys.stderr.write("Delayed retrying rest of mail since quota reached.\n")
break
row = cursor.fetchone()
cursor.close()
if __name__ == "__main__":
main()
| main | identifier_name |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Galaxy Harvester 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
import pymysql
import dbInfo
import optparse
import smtplib
from email.message import EmailMessage
from smtplib import SMTPRecipientsRefused
import time
from datetime import timedelta, datetime
import mailInfo
emailIDs = ['spawns', 'activity']
def ghConn():
conn = pymysql.connect(host = dbInfo.DB_HOST,
db = dbInfo.DB_NAME,
user = dbInfo.DB_USER,
passwd = dbInfo.DB_PASS)
conn.autocommit(True)
return conn
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle, emailIndex):
# Don't try to send mail if we exceeded quota within last hour
lastFailureTime = datetime(2000, 1, 1, 12)
currentTime = datetime.fromtimestamp(time.time())
timeSinceFailure = currentTime - lastFailureTime
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt")
lastFailureTime = datetime.strptime(f.read().strip(), "%Y-%m-%d %H:%M:%S")
f.close()
timeSinceFailure = currentTime - lastFailureTime
except IOError as e:
sys.stdout.write("No last failure time\n")
if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660:
sys.stderr.write(str(timeSinceFailure.seconds) + " less than 3660 no mail.\n")
return 1
# look up the user email
cursor = conn.cursor()
cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID + "';")
row = cursor.fetchone()
if row == None:
result = "bad username"
else:
email = row[0]
if (email.find("@") > -1 and email.find(".") > -1):
# send message
message = EmailMessage()
message['From'] = "\"Galaxy Harvester Alerts\" <" + emailIDs[emailIndex] + "@galaxyharvester.net>"
message['To'] = email
message['Subject'] = "".join(("Galaxy Harvester ", alertTitle))
message.set_content("".join(("Hello ", userID, ",\n\n", msgText, "\n\n", link, "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n")))
message.add_alternative("".join(("<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ", userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"), "</p><p><a style='text-decoration:none;' href='", link, "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ", link, "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Administrator</p>")), subtype='html')
mailer = smtplib.SMTP(mailInfo.MAIL_HOST)
mailer.login(emailIDs[emailIndex] + "@galaxyharvester.net", mailInfo.MAIL_PASS)
try:
mailer.send_message(message)
result = 'email sent'
except SMTPRecipientsRefused as e:
result = 'email failed'
sys.stderr.write('Email failed - ' + str(e))
trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"), emailIndex)
mailer.quit()
# update alert status
if ( result == 'email sent' ):
cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';')
else:
result = 'Invalid email.'
cursor.close()
def main():
emailIndex = 0
# check for command line argument for email to use
if len(sys.argv) > 1:
emailIndex = int(sys.argv[1])
conn = ghConn()
# try sending any backed up alert mails
retryPendingMail(conn, emailIndex)
def trackEmailFailure(failureTime, emailIndex):
# Update tracking file
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt", "w")
f.write(failureTime)
f.close()
except IOError as e:
sys.stderr.write("Could not write email failure tracking file")
def retryPendingMail(conn, emailIndex):
# open email alerts that have not been sucessfully sent less than 48 hours old
minTime = datetime.fromtimestamp(time.time()) - timedelta(days=4)
cursor = conn.cursor()
cursor.execute("SELECT userID, alertTime, alertMessage, alertLink, alertID FROM tAlerts WHERE alertType=2 AND alertStatus=0 and alertTime > '" + minTime.strftime("%Y-%m-%d %H:%M:%S") + "' and alertMessage LIKE '% - %';")
row = cursor.fetchone()
# try to send as long as not exceeding quota
while row != None:
|
cursor.close()
if __name__ == "__main__":
main()
| fullText = row[2]
splitPos = fullText.find(" - ")
alertTitle = fullText[:splitPos]
alertBody = fullText[splitPos+3:]
result = sendAlertMail(conn, row[0], alertBody, row[3], row[4], alertTitle, emailIndex)
if result == 1:
sys.stderr.write("Delayed retrying rest of mail since quota reached.\n")
break
row = cursor.fetchone() | conditional_block |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Galaxy Harvester 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
import pymysql
import dbInfo
import optparse
import smtplib
from email.message import EmailMessage
from smtplib import SMTPRecipientsRefused
import time
from datetime import timedelta, datetime
import mailInfo
emailIDs = ['spawns', 'activity']
def ghConn():
conn = pymysql.connect(host = dbInfo.DB_HOST,
db = dbInfo.DB_NAME,
user = dbInfo.DB_USER,
passwd = dbInfo.DB_PASS)
conn.autocommit(True)
return conn
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle, emailIndex):
# Don't try to send mail if we exceeded quota within last hour
lastFailureTime = datetime(2000, 1, 1, 12)
currentTime = datetime.fromtimestamp(time.time())
timeSinceFailure = currentTime - lastFailureTime
try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt")
lastFailureTime = datetime.strptime(f.read().strip(), "%Y-%m-%d %H:%M:%S")
f.close()
timeSinceFailure = currentTime - lastFailureTime
except IOError as e:
sys.stdout.write("No last failure time\n")
if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660:
sys.stderr.write(str(timeSinceFailure.seconds) + " less than 3660 no mail.\n")
return 1
# look up the user email
cursor = conn.cursor()
cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID + "';")
row = cursor.fetchone()
if row == None:
result = "bad username"
else:
email = row[0]
if (email.find("@") > -1 and email.find(".") > -1):
# send message
message = EmailMessage()
message['From'] = "\"Galaxy Harvester Alerts\" <" + emailIDs[emailIndex] + "@galaxyharvester.net>"
message['To'] = email
message['Subject'] = "".join(("Galaxy Harvester ", alertTitle))
message.set_content("".join(("Hello ", userID, ",\n\n", msgText, "\n\n", link, "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n")))
message.add_alternative("".join(("<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ", userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"), "</p><p><a style='text-decoration:none;' href='", link, "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ", link, "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Administrator</p>")), subtype='html')
mailer = smtplib.SMTP(mailInfo.MAIL_HOST)
mailer.login(emailIDs[emailIndex] + "@galaxyharvester.net", mailInfo.MAIL_PASS)
try:
mailer.send_message(message)
result = 'email sent'
except SMTPRecipientsRefused as e:
result = 'email failed'
sys.stderr.write('Email failed - ' + str(e))
trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"), emailIndex)
mailer.quit()
# update alert status
if ( result == 'email sent' ):
cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';')
else:
result = 'Invalid email.'
cursor.close()
def main():
emailIndex = 0
# check for command line argument for email to use
if len(sys.argv) > 1:
emailIndex = int(sys.argv[1])
conn = ghConn()
# try sending any backed up alert mails
retryPendingMail(conn, emailIndex)
def trackEmailFailure(failureTime, emailIndex):
# Update tracking file
|
def retryPendingMail(conn, emailIndex):
# open email alerts that have not been sucessfully sent less than 48 hours old
minTime = datetime.fromtimestamp(time.time()) - timedelta(days=4)
cursor = conn.cursor()
cursor.execute("SELECT userID, alertTime, alertMessage, alertLink, alertID FROM tAlerts WHERE alertType=2 AND alertStatus=0 and alertTime > '" + minTime.strftime("%Y-%m-%d %H:%M:%S") + "' and alertMessage LIKE '% - %';")
row = cursor.fetchone()
# try to send as long as not exceeding quota
while row != None:
fullText = row[2]
splitPos = fullText.find(" - ")
alertTitle = fullText[:splitPos]
alertBody = fullText[splitPos+3:]
result = sendAlertMail(conn, row[0], alertBody, row[3], row[4], alertTitle, emailIndex)
if result == 1:
sys.stderr.write("Delayed retrying rest of mail since quota reached.\n")
break
row = cursor.fetchone()
cursor.close()
if __name__ == "__main__":
main()
| try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt", "w")
f.write(failureTime)
f.close()
except IOError as e:
sys.stderr.write("Could not write email failure tracking file") | identifier_body |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Parrot Company nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL PARROT COMPANY BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#===============================================================================
import os
import obus
import ast
#===============================================================================
#===============================================================================
class BusInfo(object):
def __init__(self, xmlFile, addr, enabled, autoReload, primaryFields):
self.xmlFile = xmlFile
self.addr = addr
self.enabled = enabled
self.autoReload = autoReload
if primaryFields:
self.primaryFields = ast.literal_eval(primaryFields)
else:
self.primaryFields = {}
#===============================================================================
#===============================================================================
class BusItf(obus.BusEventCb, obus.ObjectCb):
def __init__(self, mainFrame, busInfo):
obus.BusEventCb.__init__(self)
obus.ObjectCb.__init__(self)
# Save parameters
self._mainFrame = mainFrame
self.busInfo = busInfo
# Load bus data
try:
self._status = "disconnected"
self._bus = obus.loadBus(busInfo.xmlFile)
except obus.DecodeError as ex:
self._bus = None
self._client = None
self._status = str(ex)
else:
# Create obus client
self._client = obus.Client(mainFrame.GetTitle(), self.getBusDesc(), self)
for objDesc in self.getObjectsDesc():
self._client.registerObjectCb(objDesc, self)
# To store Ids in TreeCtrl
self.treeIdBus = None
self.treeIdObj = {}
def getName(self):
if self._bus is not None:
return self._bus.BUS_DESC.name
else:
return os.path.basename(self.busInfo.xmlFile)
def getStatusStr(self):
return self._status
def start(self):
if self._client is not None:
self._status = "connecting"
self._client.start(self.busInfo.addr)
def stop(self):
if self._client is not None:
self._client.stop()
self._status = "disconnected"
def canStart(self):
return (self._client is not None) and (not self._client.isStarted())
def canStop(self):
return (self._client is not None) and (self._client.isStarted())
def isStarted(self):
return (self._client is not None) and (self._client.isStarted())
def dispatchBusEvent(self, busEvt):
self._client.dispatchBusEvent(busEvt)
def commitObjectEvent(self, objEvt):
self._client.commitObjectEvent(objEvt)
def sendMethodCall(self, call):
self._client.sendMethodCall(call)
def findObject(self, handle):
return self._client.findObject(handle)
def | (self):
return self._client.getAllObjects()
def getObjects(self, objDesc):
return self._client.getObjects(objDesc)
def getBusDesc(self):
return None if self._bus is None else self._bus.BUS_DESC
def getObjectsDesc(self):
return [] if self._bus is None else self._bus.BUS_DESC.objectsDesc.values()
def onBusEvent(self, busEvt):
if busEvt.isBaseEvent():
if busEvt.getType() == obus.BusEventBase.Type.CONNECTED:
self._status = "connected"
elif busEvt.getType() == obus.BusEventBase.Type.DISCONNECTED:
self._status = "connecting"
elif busEvt.getType() == obus.BusEventBase.Type.CONNECTION_REFUSED:
self._status = "refused"
self._mainFrame.onBusEvent(self, busEvt)
def onObjectAdd(self, obj, busEvt):
self._mainFrame.onObjectAdd(self, obj, busEvt)
def onObjectRemove(self, obj, busEvt):
self._mainFrame.onObjectRemove(self, obj, busEvt)
def onObjectEvent(self, objEvt, busEvt):
self._mainFrame.onObjectEvent(self, objEvt, busEvt)
def onObjectCallAck(self, call):
self._mainFrame.onObjectCallAck(self, call)
| getAllObjects | identifier_name |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Parrot Company nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL PARROT COMPANY BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#===============================================================================
import os
import obus
import ast
#===============================================================================
#===============================================================================
class BusInfo(object):
def __init__(self, xmlFile, addr, enabled, autoReload, primaryFields):
self.xmlFile = xmlFile
self.addr = addr
self.enabled = enabled
self.autoReload = autoReload
if primaryFields:
self.primaryFields = ast.literal_eval(primaryFields)
else:
self.primaryFields = {}
#===============================================================================
#===============================================================================
class BusItf(obus.BusEventCb, obus.ObjectCb):
def __init__(self, mainFrame, busInfo):
obus.BusEventCb.__init__(self)
obus.ObjectCb.__init__(self)
# Save parameters
self._mainFrame = mainFrame
self.busInfo = busInfo
# Load bus data
try:
self._status = "disconnected"
self._bus = obus.loadBus(busInfo.xmlFile)
except obus.DecodeError as ex:
self._bus = None
self._client = None
self._status = str(ex)
else:
# Create obus client
|
# To store Ids in TreeCtrl
self.treeIdBus = None
self.treeIdObj = {}
def getName(self):
if self._bus is not None:
return self._bus.BUS_DESC.name
else:
return os.path.basename(self.busInfo.xmlFile)
def getStatusStr(self):
return self._status
def start(self):
if self._client is not None:
self._status = "connecting"
self._client.start(self.busInfo.addr)
def stop(self):
if self._client is not None:
self._client.stop()
self._status = "disconnected"
def canStart(self):
return (self._client is not None) and (not self._client.isStarted())
def canStop(self):
return (self._client is not None) and (self._client.isStarted())
def isStarted(self):
return (self._client is not None) and (self._client.isStarted())
def dispatchBusEvent(self, busEvt):
self._client.dispatchBusEvent(busEvt)
def commitObjectEvent(self, objEvt):
self._client.commitObjectEvent(objEvt)
def sendMethodCall(self, call):
self._client.sendMethodCall(call)
def findObject(self, handle):
return self._client.findObject(handle)
def getAllObjects(self):
return self._client.getAllObjects()
def getObjects(self, objDesc):
return self._client.getObjects(objDesc)
def getBusDesc(self):
return None if self._bus is None else self._bus.BUS_DESC
def getObjectsDesc(self):
return [] if self._bus is None else self._bus.BUS_DESC.objectsDesc.values()
def onBusEvent(self, busEvt):
if busEvt.isBaseEvent():
if busEvt.getType() == obus.BusEventBase.Type.CONNECTED:
self._status = "connected"
elif busEvt.getType() == obus.BusEventBase.Type.DISCONNECTED:
self._status = "connecting"
elif busEvt.getType() == obus.BusEventBase.Type.CONNECTION_REFUSED:
self._status = "refused"
self._mainFrame.onBusEvent(self, busEvt)
def onObjectAdd(self, obj, busEvt):
self._mainFrame.onObjectAdd(self, obj, busEvt)
def onObjectRemove(self, obj, busEvt):
self._mainFrame.onObjectRemove(self, obj, busEvt)
def onObjectEvent(self, objEvt, busEvt):
self._mainFrame.onObjectEvent(self, objEvt, busEvt)
def onObjectCallAck(self, call):
self._mainFrame.onObjectCallAck(self, call)
| self._client = obus.Client(mainFrame.GetTitle(), self.getBusDesc(), self)
for objDesc in self.getObjectsDesc():
self._client.registerObjectCb(objDesc, self) | conditional_block |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Parrot Company nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL PARROT COMPANY BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#===============================================================================
import os
import obus
import ast
#===============================================================================
#===============================================================================
class BusInfo(object):
def __init__(self, xmlFile, addr, enabled, autoReload, primaryFields):
self.xmlFile = xmlFile
self.addr = addr
self.enabled = enabled
self.autoReload = autoReload
if primaryFields:
self.primaryFields = ast.literal_eval(primaryFields)
else:
self.primaryFields = {}
#===============================================================================
#===============================================================================
class BusItf(obus.BusEventCb, obus.ObjectCb):
def __init__(self, mainFrame, busInfo):
|
def getName(self):
if self._bus is not None:
return self._bus.BUS_DESC.name
else:
return os.path.basename(self.busInfo.xmlFile)
def getStatusStr(self):
return self._status
def start(self):
if self._client is not None:
self._status = "connecting"
self._client.start(self.busInfo.addr)
def stop(self):
if self._client is not None:
self._client.stop()
self._status = "disconnected"
def canStart(self):
return (self._client is not None) and (not self._client.isStarted())
def canStop(self):
return (self._client is not None) and (self._client.isStarted())
def isStarted(self):
return (self._client is not None) and (self._client.isStarted())
def dispatchBusEvent(self, busEvt):
self._client.dispatchBusEvent(busEvt)
def commitObjectEvent(self, objEvt):
self._client.commitObjectEvent(objEvt)
def sendMethodCall(self, call):
self._client.sendMethodCall(call)
def findObject(self, handle):
return self._client.findObject(handle)
def getAllObjects(self):
return self._client.getAllObjects()
def getObjects(self, objDesc):
return self._client.getObjects(objDesc)
def getBusDesc(self):
return None if self._bus is None else self._bus.BUS_DESC
def getObjectsDesc(self):
return [] if self._bus is None else self._bus.BUS_DESC.objectsDesc.values()
def onBusEvent(self, busEvt):
if busEvt.isBaseEvent():
if busEvt.getType() == obus.BusEventBase.Type.CONNECTED:
self._status = "connected"
elif busEvt.getType() == obus.BusEventBase.Type.DISCONNECTED:
self._status = "connecting"
elif busEvt.getType() == obus.BusEventBase.Type.CONNECTION_REFUSED:
self._status = "refused"
self._mainFrame.onBusEvent(self, busEvt)
def onObjectAdd(self, obj, busEvt):
self._mainFrame.onObjectAdd(self, obj, busEvt)
def onObjectRemove(self, obj, busEvt):
self._mainFrame.onObjectRemove(self, obj, busEvt)
def onObjectEvent(self, objEvt, busEvt):
self._mainFrame.onObjectEvent(self, objEvt, busEvt)
def onObjectCallAck(self, call):
self._mainFrame.onObjectCallAck(self, call)
| obus.BusEventCb.__init__(self)
obus.ObjectCb.__init__(self)
# Save parameters
self._mainFrame = mainFrame
self.busInfo = busInfo
# Load bus data
try:
self._status = "disconnected"
self._bus = obus.loadBus(busInfo.xmlFile)
except obus.DecodeError as ex:
self._bus = None
self._client = None
self._status = str(ex)
else:
# Create obus client
self._client = obus.Client(mainFrame.GetTitle(), self.getBusDesc(), self)
for objDesc in self.getObjectsDesc():
self._client.registerObjectCb(objDesc, self)
# To store Ids in TreeCtrl
self.treeIdBus = None
self.treeIdObj = {} | identifier_body |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Parrot Company nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL PARROT COMPANY BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#===============================================================================
import os
import obus
import ast
#===============================================================================
#===============================================================================
class BusInfo(object):
def __init__(self, xmlFile, addr, enabled, autoReload, primaryFields):
self.xmlFile = xmlFile
self.addr = addr
self.enabled = enabled
self.autoReload = autoReload
if primaryFields:
self.primaryFields = ast.literal_eval(primaryFields)
else:
self.primaryFields = {}
#===============================================================================
#===============================================================================
class BusItf(obus.BusEventCb, obus.ObjectCb):
def __init__(self, mainFrame, busInfo):
obus.BusEventCb.__init__(self)
obus.ObjectCb.__init__(self)
# Save parameters
self._mainFrame = mainFrame
self.busInfo = busInfo
# Load bus data
try:
self._status = "disconnected"
self._bus = obus.loadBus(busInfo.xmlFile)
except obus.DecodeError as ex: | self._client = None
self._status = str(ex)
else:
# Create obus client
self._client = obus.Client(mainFrame.GetTitle(), self.getBusDesc(), self)
for objDesc in self.getObjectsDesc():
self._client.registerObjectCb(objDesc, self)
# To store Ids in TreeCtrl
self.treeIdBus = None
self.treeIdObj = {}
def getName(self):
if self._bus is not None:
return self._bus.BUS_DESC.name
else:
return os.path.basename(self.busInfo.xmlFile)
def getStatusStr(self):
return self._status
def start(self):
if self._client is not None:
self._status = "connecting"
self._client.start(self.busInfo.addr)
def stop(self):
if self._client is not None:
self._client.stop()
self._status = "disconnected"
def canStart(self):
return (self._client is not None) and (not self._client.isStarted())
def canStop(self):
return (self._client is not None) and (self._client.isStarted())
def isStarted(self):
return (self._client is not None) and (self._client.isStarted())
def dispatchBusEvent(self, busEvt):
self._client.dispatchBusEvent(busEvt)
def commitObjectEvent(self, objEvt):
self._client.commitObjectEvent(objEvt)
def sendMethodCall(self, call):
self._client.sendMethodCall(call)
def findObject(self, handle):
return self._client.findObject(handle)
def getAllObjects(self):
return self._client.getAllObjects()
def getObjects(self, objDesc):
return self._client.getObjects(objDesc)
def getBusDesc(self):
return None if self._bus is None else self._bus.BUS_DESC
def getObjectsDesc(self):
return [] if self._bus is None else self._bus.BUS_DESC.objectsDesc.values()
def onBusEvent(self, busEvt):
if busEvt.isBaseEvent():
if busEvt.getType() == obus.BusEventBase.Type.CONNECTED:
self._status = "connected"
elif busEvt.getType() == obus.BusEventBase.Type.DISCONNECTED:
self._status = "connecting"
elif busEvt.getType() == obus.BusEventBase.Type.CONNECTION_REFUSED:
self._status = "refused"
self._mainFrame.onBusEvent(self, busEvt)
def onObjectAdd(self, obj, busEvt):
self._mainFrame.onObjectAdd(self, obj, busEvt)
def onObjectRemove(self, obj, busEvt):
self._mainFrame.onObjectRemove(self, obj, busEvt)
def onObjectEvent(self, objEvt, busEvt):
self._mainFrame.onObjectEvent(self, objEvt, busEvt)
def onObjectCallAck(self, call):
self._mainFrame.onObjectCallAck(self, call) | self._bus = None | random_line_split |
exterior.rs | // Copyright 2012 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.
#![feature(managed_boxes)]
use std::cell::Cell;
use std::gc::{Gc, GC};
struct Point {x: int, y: int, z: int}
fn f(p: Gc<Cell<Point>>) |
pub fn main() {
let a: Point = Point {x: 10, y: 11, z: 12};
let b: Gc<Cell<Point>> = box(GC) Cell::new(a);
assert_eq!(b.get().z, 12);
f(b);
assert_eq!(a.z, 12);
assert_eq!(b.get().z, 13);
}
| {
assert!((p.get().z == 12));
p.set(Point {x: 10, y: 11, z: 13});
assert!((p.get().z == 13));
} | identifier_body |
exterior.rs | // Copyright 2012 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.
#![feature(managed_boxes)]
use std::cell::Cell;
use std::gc::{Gc, GC}; |
fn f(p: Gc<Cell<Point>>) {
assert!((p.get().z == 12));
p.set(Point {x: 10, y: 11, z: 13});
assert!((p.get().z == 13));
}
pub fn main() {
let a: Point = Point {x: 10, y: 11, z: 12};
let b: Gc<Cell<Point>> = box(GC) Cell::new(a);
assert_eq!(b.get().z, 12);
f(b);
assert_eq!(a.z, 12);
assert_eq!(b.get().z, 13);
} |
struct Point {x: int, y: int, z: int} | random_line_split |
exterior.rs | // Copyright 2012 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.
#![feature(managed_boxes)]
use std::cell::Cell;
use std::gc::{Gc, GC};
struct Point {x: int, y: int, z: int}
fn f(p: Gc<Cell<Point>>) {
assert!((p.get().z == 12));
p.set(Point {x: 10, y: 11, z: 13});
assert!((p.get().z == 13));
}
pub fn | () {
let a: Point = Point {x: 10, y: 11, z: 12};
let b: Gc<Cell<Point>> = box(GC) Cell::new(a);
assert_eq!(b.get().z, 12);
f(b);
assert_eq!(a.z, 12);
assert_eq!(b.get().z, 13);
}
| main | identifier_name |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notification: ToastParams, id: string) => {
// Get notification DOM element and stick an id to it.
const refs = { refs: {} };
const containerElement = notificationSystem.refs[`container-${notification.position}`] || refs;
const notificationElement = containerElement.refs[`notification-${notification.id}`] || refs;
const notificationNode = ReactDOM.findDOMNode(notificationElement);
if (notificationNode) {
const toastId = ['toast', notification.level, id];
notificationNode.setAttribute('id', toastId.join('-'));
}
};
class Toast implements IToastFactory {
private | (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if (!notificationSystem) {
const element = document.createElement('div');
const wrapper = document.body.appendChild(element);
element.setAttribute('id', 'notificationSystem');
notificationSystem = ReactDOM.render(React.createElement(NotificationSystem), wrapper);
}
setTimeout(() => {
const notification = notificationSystem.addNotification(obj);
console.log(notification);
// idify(notification, obj.id);
});
}
info (params: ToastParams | string): void { this.buildToast('info', params); }
success (params: ToastParams | string): void { this.buildToast('success', params); }
warning (params: ToastParams | string): void { this.buildToast('warning', params); }
error (params: ToastParams | string): void { this.buildToast('error', params); }
}
export default new Toast();
| buildToast | identifier_name |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notification: ToastParams, id: string) => {
// Get notification DOM element and stick an id to it.
const refs = { refs: {} };
const containerElement = notificationSystem.refs[`container-${notification.position}`] || refs;
const notificationElement = containerElement.refs[`notification-${notification.id}`] || refs;
const notificationNode = ReactDOM.findDOMNode(notificationElement);
if (notificationNode) {
const toastId = ['toast', notification.level, id];
notificationNode.setAttribute('id', toastId.join('-'));
}
};
class Toast implements IToastFactory {
private buildToast (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if (!notificationSystem) {
const element = document.createElement('div');
const wrapper = document.body.appendChild(element);
element.setAttribute('id', 'notificationSystem');
notificationSystem = ReactDOM.render(React.createElement(NotificationSystem), wrapper);
}
setTimeout(() => {
const notification = notificationSystem.addNotification(obj);
console.log(notification);
// idify(notification, obj.id);
});
}
info (params: ToastParams | string): void { this.buildToast('info', params); }
success (params: ToastParams | string): void |
warning (params: ToastParams | string): void { this.buildToast('warning', params); }
error (params: ToastParams | string): void { this.buildToast('error', params); }
}
export default new Toast();
| { this.buildToast('success', params); } | identifier_body |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notification: ToastParams, id: string) => {
// Get notification DOM element and stick an id to it.
const refs = { refs: {} };
const containerElement = notificationSystem.refs[`container-${notification.position}`] || refs;
const notificationElement = containerElement.refs[`notification-${notification.id}`] || refs;
const notificationNode = ReactDOM.findDOMNode(notificationElement);
if (notificationNode) {
const toastId = ['toast', notification.level, id];
notificationNode.setAttribute('id', toastId.join('-'));
} |
private buildToast (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if (!notificationSystem) {
const element = document.createElement('div');
const wrapper = document.body.appendChild(element);
element.setAttribute('id', 'notificationSystem');
notificationSystem = ReactDOM.render(React.createElement(NotificationSystem), wrapper);
}
setTimeout(() => {
const notification = notificationSystem.addNotification(obj);
console.log(notification);
// idify(notification, obj.id);
});
}
info (params: ToastParams | string): void { this.buildToast('info', params); }
success (params: ToastParams | string): void { this.buildToast('success', params); }
warning (params: ToastParams | string): void { this.buildToast('warning', params); }
error (params: ToastParams | string): void { this.buildToast('error', params); }
}
export default new Toast(); | };
class Toast implements IToastFactory { | random_line_split |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notification: ToastParams, id: string) => {
// Get notification DOM element and stick an id to it.
const refs = { refs: {} };
const containerElement = notificationSystem.refs[`container-${notification.position}`] || refs;
const notificationElement = containerElement.refs[`notification-${notification.id}`] || refs;
const notificationNode = ReactDOM.findDOMNode(notificationElement);
if (notificationNode) |
};
class Toast implements IToastFactory {
private buildToast (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if (!notificationSystem) {
const element = document.createElement('div');
const wrapper = document.body.appendChild(element);
element.setAttribute('id', 'notificationSystem');
notificationSystem = ReactDOM.render(React.createElement(NotificationSystem), wrapper);
}
setTimeout(() => {
const notification = notificationSystem.addNotification(obj);
console.log(notification);
// idify(notification, obj.id);
});
}
info (params: ToastParams | string): void { this.buildToast('info', params); }
success (params: ToastParams | string): void { this.buildToast('success', params); }
warning (params: ToastParams | string): void { this.buildToast('warning', params); }
error (params: ToastParams | string): void { this.buildToast('error', params); }
}
export default new Toast();
| {
const toastId = ['toast', notification.level, id];
notificationNode.setAttribute('id', toastId.join('-'));
} | conditional_block |
constants.py | # Copyright 2016 Twitter. All rights reserved.
#
# 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.
'''constants.py: constants for integration test for pyheron'''
INTEGRATION_TEST_MOCK_MESSAGE_ID = "__integration_test_mock_message_id"
INTEGRATION_TEST_TERMINAL = "__integration_test_mock_terminal"
INTEGRATION_TEST_CONTROL_STREAM_ID = "__integration_test_control_stream_id"
# internal config key
MAX_EXECUTIONS = 10
HTTP_POST_URL_KEY = "http.post.url"
# user defined config key
USER_SPOUT_CLASSPATH = "user.spout.classpath"
USER_BOLT_CLASSPATH = "user.bolt.classpath"
# user defined max executions
USER_MAX_EXECUTIONS = "user.max.exec" | random_line_split | |
password.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { AuthProvider } from '../../../providers/auth/auth';
@IonicPage({
name: 'auth-password'
})
@Component({
selector: 'page-password',
templateUrl: 'password.html',
})
export class Password {
form : FormGroup;
hasError: boolean;
errorMessage: string;
emailSent: boolean;
constructor(
private navCtrl: NavController,
private loadingCtrl: LoadingController,
private formBuilder: FormBuilder,
private auth: AuthProvider
) {
this.form = this.formBuilder.group({
email: ['', Validators.required]
});
}
signInWithEmail() | navigatePop() {
this.navCtrl.pop();
}
}
| {
const loading = this.loadingCtrl.create({
content: 'Por favor, aguarde...'
});
loading.present();
this.auth.sendPasswordResetEmail(this.form.value.email).then(() => {
loading.dismiss();
this.hasError = false;
this.emailSent = true;
}, (error) => {
loading.dismiss();
switch (error.code) {
case 'auth/invalid-email':
this.errorMessage = 'Insira um email válido.';
break;
case 'auth/user-not-found':
this.errorMessage = 'Nenhum usuário com este email encontrado.';
break;
default:
this.errorMessage = error;
break;
}
this.hasError = true;
});
}
| identifier_body |
password.ts | import { Component } from '@angular/core'; | import { AuthProvider } from '../../../providers/auth/auth';
@IonicPage({
name: 'auth-password'
})
@Component({
selector: 'page-password',
templateUrl: 'password.html',
})
export class Password {
form : FormGroup;
hasError: boolean;
errorMessage: string;
emailSent: boolean;
constructor(
private navCtrl: NavController,
private loadingCtrl: LoadingController,
private formBuilder: FormBuilder,
private auth: AuthProvider
) {
this.form = this.formBuilder.group({
email: ['', Validators.required]
});
}
signInWithEmail() {
const loading = this.loadingCtrl.create({
content: 'Por favor, aguarde...'
});
loading.present();
this.auth.sendPasswordResetEmail(this.form.value.email).then(() => {
loading.dismiss();
this.hasError = false;
this.emailSent = true;
}, (error) => {
loading.dismiss();
switch (error.code) {
case 'auth/invalid-email':
this.errorMessage = 'Insira um email válido.';
break;
case 'auth/user-not-found':
this.errorMessage = 'Nenhum usuário com este email encontrado.';
break;
default:
this.errorMessage = error;
break;
}
this.hasError = true;
});
}
navigatePop() {
this.navCtrl.pop();
}
} | import { IonicPage, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
| random_line_split |
password.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { AuthProvider } from '../../../providers/auth/auth';
@IonicPage({
name: 'auth-password'
})
@Component({
selector: 'page-password',
templateUrl: 'password.html',
})
export class Password {
form : FormGroup;
hasError: boolean;
errorMessage: string;
emailSent: boolean;
| (
private navCtrl: NavController,
private loadingCtrl: LoadingController,
private formBuilder: FormBuilder,
private auth: AuthProvider
) {
this.form = this.formBuilder.group({
email: ['', Validators.required]
});
}
signInWithEmail() {
const loading = this.loadingCtrl.create({
content: 'Por favor, aguarde...'
});
loading.present();
this.auth.sendPasswordResetEmail(this.form.value.email).then(() => {
loading.dismiss();
this.hasError = false;
this.emailSent = true;
}, (error) => {
loading.dismiss();
switch (error.code) {
case 'auth/invalid-email':
this.errorMessage = 'Insira um email válido.';
break;
case 'auth/user-not-found':
this.errorMessage = 'Nenhum usuário com este email encontrado.';
break;
default:
this.errorMessage = error;
break;
}
this.hasError = true;
});
}
navigatePop() {
this.navCtrl.pop();
}
}
| constructor | identifier_name |
lib.rs | struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer {
Lexer { src: src, pos: 0 }
}
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn | (&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
loop {
if self.eof() {
break
}
match self.ch() {
b' ' => break,
b'\t' => break,
b'\r' => break,
b'\n' => break,
b'"' => break,
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn quoted_string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
self.pos += 1;
loop {
if self.eof() {
break;
}
match self.ch() {
b'"' => { self.pos += 1; break; },
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn valid_ws(&self) -> bool {
if self.eof() {
return false;
}
match self.ch() {
b' ' => true,
b'\t' => true,
b'\r' => true,
b'\n' => true,
_ => false
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
self.skip_ws();
if self.eof() {
return None;
}
match self.ch() {
b'"' => self.quoted_string(),
_ => self.string()
}
}
}
#[test]
fn tokenize() {
let src = b" foo bar \"a b\" baz ";
let lexer = Lexer::new(src);
let tokens: Vec<_> = lexer.collect();
assert_eq!(4, tokens.len());
assert_eq!("foo".to_string(), tokens[0]);
assert_eq!("bar".to_string(), tokens[1]);
assert_eq!("a b".to_string(), tokens[2]);
assert_eq!("baz".to_string(), tokens[3]);
} | eof | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.