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 |
|---|---|---|---|---|
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
def __init__(self, parent, graphic_view=None):
self.peak = []
super().__init__(parent)
self.scene = GridScene(parent=graphic_view)
self.scene.setBackgroundBrush(settings.BGCOLOR)
self.peak_item = self.scene.addPath(QPainterPath(), QPen(settings.PEAK_COLOR, 0)) # type: QGraphicsPathItem
def show_scene_section(self, x1: float, x2: float, subpath_ranges=None, colors=None):
start = int(x1) if x1 > 0 else 0
end = int(x2) if x2 < self.num_samples else self.num_samples
paths = path_creator.create_path(np.log10(self.plot_data), start, end)
self.set_path(paths, colors=None)
try:
if len(self.peak) > 0:
peak_path = path_creator.create_path(np.log10(self.peak), start, end)[0]
self.peak_item.setPath(peak_path)
except RuntimeWarning:
pass
def init_scene(self, draw_grid=True):
self.scene.draw_grid = draw_grid
self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data)
self.scene.setSceneRect(0, -5, self.num_samples, 10)
def clear_path(self):
for item in self.scene.items():
if isinstance(item, QGraphicsPathItem) and item != self.peak_item:
|
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath())
def eliminate(self):
super().eliminate()
self.peak = None
self.peak_item = None
| self.scene.removeItem(item)
item.setParentItem(None)
del item | conditional_block |
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
def __init__(self, parent, graphic_view=None):
self.peak = []
super().__init__(parent)
self.scene = GridScene(parent=graphic_view)
self.scene.setBackgroundBrush(settings.BGCOLOR)
self.peak_item = self.scene.addPath(QPainterPath(), QPen(settings.PEAK_COLOR, 0)) # type: QGraphicsPathItem
def show_scene_section(self, x1: float, x2: float, subpath_ranges=None, colors=None):
start = int(x1) if x1 > 0 else 0
end = int(x2) if x2 < self.num_samples else self.num_samples
paths = path_creator.create_path(np.log10(self.plot_data), start, end)
self.set_path(paths, colors=None)
try:
if len(self.peak) > 0:
peak_path = path_creator.create_path(np.log10(self.peak), start, end)[0]
self.peak_item.setPath(peak_path)
except RuntimeWarning:
pass
def init_scene(self, draw_grid=True):
self.scene.draw_grid = draw_grid
self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data)
self.scene.setSceneRect(0, -5, self.num_samples, 10)
def clear_path(self):
for item in self.scene.items():
if isinstance(item, QGraphicsPathItem) and item != self.peak_item:
self.scene.removeItem(item)
item.setParentItem(None)
del item
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath())
def | (self):
super().eliminate()
self.peak = None
self.peak_item = None
| eliminate | identifier_name |
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
def __init__(self, parent, graphic_view=None):
self.peak = []
super().__init__(parent)
self.scene = GridScene(parent=graphic_view)
self.scene.setBackgroundBrush(settings.BGCOLOR)
self.peak_item = self.scene.addPath(QPainterPath(), QPen(settings.PEAK_COLOR, 0)) # type: QGraphicsPathItem
def show_scene_section(self, x1: float, x2: float, subpath_ranges=None, colors=None):
start = int(x1) if x1 > 0 else 0
end = int(x2) if x2 < self.num_samples else self.num_samples
paths = path_creator.create_path(np.log10(self.plot_data), start, end)
self.set_path(paths, colors=None)
try:
if len(self.peak) > 0:
peak_path = path_creator.create_path(np.log10(self.peak), start, end)[0] | self.peak_item.setPath(peak_path)
except RuntimeWarning:
pass
def init_scene(self, draw_grid=True):
self.scene.draw_grid = draw_grid
self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data)
self.scene.setSceneRect(0, -5, self.num_samples, 10)
def clear_path(self):
for item in self.scene.items():
if isinstance(item, QGraphicsPathItem) and item != self.peak_item:
self.scene.removeItem(item)
item.setParentItem(None)
del item
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath())
def eliminate(self):
super().eliminate()
self.peak = None
self.peak_item = None | random_line_split | |
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
| def __init__(self, parent, graphic_view=None):
self.peak = []
super().__init__(parent)
self.scene = GridScene(parent=graphic_view)
self.scene.setBackgroundBrush(settings.BGCOLOR)
self.peak_item = self.scene.addPath(QPainterPath(), QPen(settings.PEAK_COLOR, 0)) # type: QGraphicsPathItem
def show_scene_section(self, x1: float, x2: float, subpath_ranges=None, colors=None):
start = int(x1) if x1 > 0 else 0
end = int(x2) if x2 < self.num_samples else self.num_samples
paths = path_creator.create_path(np.log10(self.plot_data), start, end)
self.set_path(paths, colors=None)
try:
if len(self.peak) > 0:
peak_path = path_creator.create_path(np.log10(self.peak), start, end)[0]
self.peak_item.setPath(peak_path)
except RuntimeWarning:
pass
def init_scene(self, draw_grid=True):
self.scene.draw_grid = draw_grid
self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data)
self.scene.setSceneRect(0, -5, self.num_samples, 10)
def clear_path(self):
for item in self.scene.items():
if isinstance(item, QGraphicsPathItem) and item != self.peak_item:
self.scene.removeItem(item)
item.setParentItem(None)
del item
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath())
def eliminate(self):
super().eliminate()
self.peak = None
self.peak_item = None | identifier_body | |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function PaymillResponseHandler(error, result) {
if (error) {
if(error.apierror == 'field_invalid_card_cvc'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cvc);
}else if(error.apierror == 'field_invalid_card_exp') | else if(error.apierror == 'field_invalid_card_holder'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cardholder);
}else{
jQuery("#paymill_checkout_errors").text(error.apierror);
}
} else {
jQuery("#paymill_checkout_errors").text("");
var form = jQuery("#mp_payment_form");
// Token
var token = result.token;
// Insert Paymill token field into form in order to post it
form.append("<input type='hidden' name='paymillToken' value='" + token + "'/>");
jQuery("#mp_payment_form").get(0).submit();
}
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
jQuery('#paymill_processing').hide();
}
jQuery("#mp_payment_form").submit(function (event) {
jQuery('#paymill_processing').show();
// Deactivate submit button on click
jQuery('#mp_payment_confirm').attr("disabled", "disabled");
if (false == paymill.validateCardNumber(jQuery('.card-number').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cc_number);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
if (false == paymill.validateExpiry(jQuery('.card-expiry-month').val(), jQuery('.card-expiry-year').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_expiration);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
paymill.createToken({
number:jQuery('.card-number').val(),
exp_month:jQuery('.card-expiry-month').val(),
exp_year:jQuery('.card-expiry-year').val(),
cvc:jQuery('.card-cvc').val(),
cardholdername:jQuery('.card-holdername').val(),
amount:jQuery('.amount').val(),
currency:jQuery('.currency').val()
}, PaymillResponseHandler);
return false;
});
});
jQuery("#mp_payment_form").submit(function(event) {
// We need to only process if the payment
// type is Paymill or Paymill payment gateway is the only option
// If we have the radio buttons allowing the user to select the payment method? ...
// IF the length is zero then Paymill or some other payment gateway is the only one defined.
if ( jQuery('input.mp_choose_gateway').length ) {
// If the payment option selected is not Paymill then return and bypass input validations
if ( jQuery('input.mp_choose_gateway:checked').val() != "paymill" ) {
return true;
}
}
//clear errors
jQuery("#paymill_checkout_errors").empty();
if (is_error) return false;
// disable the submit button to prevent repeated clicks
jQuery('#mp_payment_confirm').attr("disabled", "disabled").hide();
jQuery('#paymill_processing').show();
});
}); | {
jQuery("#paymill_checkout_errors").text(paymill_token.expired_card);
} | conditional_block |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function | (error, result) {
if (error) {
if(error.apierror == 'field_invalid_card_cvc'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cvc);
}else if(error.apierror == 'field_invalid_card_exp'){
jQuery("#paymill_checkout_errors").text(paymill_token.expired_card);
}else if(error.apierror == 'field_invalid_card_holder'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cardholder);
}else{
jQuery("#paymill_checkout_errors").text(error.apierror);
}
} else {
jQuery("#paymill_checkout_errors").text("");
var form = jQuery("#mp_payment_form");
// Token
var token = result.token;
// Insert Paymill token field into form in order to post it
form.append("<input type='hidden' name='paymillToken' value='" + token + "'/>");
jQuery("#mp_payment_form").get(0).submit();
}
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
jQuery('#paymill_processing').hide();
}
jQuery("#mp_payment_form").submit(function (event) {
jQuery('#paymill_processing').show();
// Deactivate submit button on click
jQuery('#mp_payment_confirm').attr("disabled", "disabled");
if (false == paymill.validateCardNumber(jQuery('.card-number').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cc_number);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
if (false == paymill.validateExpiry(jQuery('.card-expiry-month').val(), jQuery('.card-expiry-year').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_expiration);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
paymill.createToken({
number:jQuery('.card-number').val(),
exp_month:jQuery('.card-expiry-month').val(),
exp_year:jQuery('.card-expiry-year').val(),
cvc:jQuery('.card-cvc').val(),
cardholdername:jQuery('.card-holdername').val(),
amount:jQuery('.amount').val(),
currency:jQuery('.currency').val()
}, PaymillResponseHandler);
return false;
});
});
jQuery("#mp_payment_form").submit(function(event) {
// We need to only process if the payment
// type is Paymill or Paymill payment gateway is the only option
// If we have the radio buttons allowing the user to select the payment method? ...
// IF the length is zero then Paymill or some other payment gateway is the only one defined.
if ( jQuery('input.mp_choose_gateway').length ) {
// If the payment option selected is not Paymill then return and bypass input validations
if ( jQuery('input.mp_choose_gateway:checked').val() != "paymill" ) {
return true;
}
}
//clear errors
jQuery("#paymill_checkout_errors").empty();
if (is_error) return false;
// disable the submit button to prevent repeated clicks
jQuery('#mp_payment_confirm').attr("disabled", "disabled").hide();
jQuery('#paymill_processing').show();
});
}); | PaymillResponseHandler | identifier_name |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function PaymillResponseHandler(error, result) {
if (error) {
if(error.apierror == 'field_invalid_card_cvc'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cvc);
}else if(error.apierror == 'field_invalid_card_exp'){
jQuery("#paymill_checkout_errors").text(paymill_token.expired_card);
}else if(error.apierror == 'field_invalid_card_holder'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cardholder);
}else{
jQuery("#paymill_checkout_errors").text(error.apierror);
}
} else {
jQuery("#paymill_checkout_errors").text("");
var form = jQuery("#mp_payment_form");
// Token
var token = result.token;
// Insert Paymill token field into form in order to post it
form.append("<input type='hidden' name='paymillToken' value='" + token + "'/>");
jQuery("#mp_payment_form").get(0).submit();
}
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
jQuery('#paymill_processing').hide();
}
jQuery("#mp_payment_form").submit(function (event) {
jQuery('#paymill_processing').show();
// Deactivate submit button on click
jQuery('#mp_payment_confirm').attr("disabled", "disabled");
if (false == paymill.validateCardNumber(jQuery('.card-number').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cc_number);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
if (false == paymill.validateExpiry(jQuery('.card-expiry-month').val(), jQuery('.card-expiry-year').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_expiration);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
paymill.createToken({
number:jQuery('.card-number').val(),
exp_month:jQuery('.card-expiry-month').val(),
exp_year:jQuery('.card-expiry-year').val(),
cvc:jQuery('.card-cvc').val(),
cardholdername:jQuery('.card-holdername').val(),
amount:jQuery('.amount').val(),
currency:jQuery('.currency').val()
}, PaymillResponseHandler);
return false;
});
});
jQuery("#mp_payment_form").submit(function(event) {
// We need to only process if the payment
// type is Paymill or Paymill payment gateway is the only option
// If we have the radio buttons allowing the user to select the payment method? ...
| return true;
}
}
//clear errors
jQuery("#paymill_checkout_errors").empty();
if (is_error) return false;
// disable the submit button to prevent repeated clicks
jQuery('#mp_payment_confirm').attr("disabled", "disabled").hide();
jQuery('#paymill_processing').show();
});
}); | // IF the length is zero then Paymill or some other payment gateway is the only one defined.
if ( jQuery('input.mp_choose_gateway').length ) {
// If the payment option selected is not Paymill then return and bypass input validations
if ( jQuery('input.mp_choose_gateway:checked').val() != "paymill" ) {
| random_line_split |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function PaymillResponseHandler(error, result) |
jQuery("#mp_payment_form").submit(function (event) {
jQuery('#paymill_processing').show();
// Deactivate submit button on click
jQuery('#mp_payment_confirm').attr("disabled", "disabled");
if (false == paymill.validateCardNumber(jQuery('.card-number').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cc_number);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
if (false == paymill.validateExpiry(jQuery('.card-expiry-month').val(), jQuery('.card-expiry-year').val())) {
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_expiration);
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
is_error = true;
jQuery('#paymill_processing').hide();
return false;
}
paymill.createToken({
number:jQuery('.card-number').val(),
exp_month:jQuery('.card-expiry-month').val(),
exp_year:jQuery('.card-expiry-year').val(),
cvc:jQuery('.card-cvc').val(),
cardholdername:jQuery('.card-holdername').val(),
amount:jQuery('.amount').val(),
currency:jQuery('.currency').val()
}, PaymillResponseHandler);
return false;
});
});
jQuery("#mp_payment_form").submit(function(event) {
// We need to only process if the payment
// type is Paymill or Paymill payment gateway is the only option
// If we have the radio buttons allowing the user to select the payment method? ...
// IF the length is zero then Paymill or some other payment gateway is the only one defined.
if ( jQuery('input.mp_choose_gateway').length ) {
// If the payment option selected is not Paymill then return and bypass input validations
if ( jQuery('input.mp_choose_gateway:checked').val() != "paymill" ) {
return true;
}
}
//clear errors
jQuery("#paymill_checkout_errors").empty();
if (is_error) return false;
// disable the submit button to prevent repeated clicks
jQuery('#mp_payment_confirm').attr("disabled", "disabled").hide();
jQuery('#paymill_processing').show();
});
}); | {
if (error) {
if(error.apierror == 'field_invalid_card_cvc'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cvc);
}else if(error.apierror == 'field_invalid_card_exp'){
jQuery("#paymill_checkout_errors").text(paymill_token.expired_card);
}else if(error.apierror == 'field_invalid_card_holder'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cardholder);
}else{
jQuery("#paymill_checkout_errors").text(error.apierror);
}
} else {
jQuery("#paymill_checkout_errors").text("");
var form = jQuery("#mp_payment_form");
// Token
var token = result.token;
// Insert Paymill token field into form in order to post it
form.append("<input type='hidden' name='paymillToken' value='" + token + "'/>");
jQuery("#mp_payment_form").get(0).submit();
}
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
jQuery('#paymill_processing').hide();
} | identifier_body |
defaults-nl_NL.min.js | /*!
* Bootstrap-select v1.7.3 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) | */
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(){!function(a){a.fn.selectpicker.defaults={noneSelectedText:"Niets geselecteerd",noneResultsText:"Geen resultaten gevonden voor {0}",countSelectedText:"{0} van {1} geselecteerd",maxOptionsText:["Limiet bereikt ({n} {var} max)","Groep limiet bereikt ({n} {var} max)",["items","item"]],multipleSeparator:", "}}(jQuery)}); | random_line_split | |
const.py | """Constants for the pi_hole intergration."""
from datetime import timedelta
DOMAIN = "pi_hole"
CONF_LOCATION = "location"
CONF_SLUG = "slug"
DEFAULT_LOCATION = "admin"
DEFAULT_METHOD = "GET"
DEFAULT_NAME = "Pi-Hole"
DEFAULT_SSL = False
DEFAULT_VERIFY_SSL = True
SERVICE_DISABLE = "disable"
SERVICE_DISABLE_ATTR_DURATION = "duration"
SERVICE_DISABLE_ATTR_NAME = "name"
SERVICE_ENABLE = "enable"
SERVICE_ENABLE_ATTR_NAME = SERVICE_DISABLE_ATTR_NAME
ATTR_BLOCKED_DOMAINS = "domains_blocked"
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)
| SENSOR_DICT = {
"ads_blocked_today": ["Ads Blocked Today", "ads", "mdi:close-octagon-outline"],
"ads_percentage_today": [
"Ads Percentage Blocked Today",
"%",
"mdi:close-octagon-outline",
],
"clients_ever_seen": ["Seen Clients", "clients", "mdi:account-outline"],
"dns_queries_today": [
"DNS Queries Today",
"queries",
"mdi:comment-question-outline",
],
"domains_being_blocked": ["Domains Blocked", "domains", "mdi:block-helper"],
"queries_cached": ["DNS Queries Cached", "queries", "mdi:comment-question-outline"],
"queries_forwarded": [
"DNS Queries Forwarded",
"queries",
"mdi:comment-question-outline",
],
"unique_clients": ["DNS Unique Clients", "clients", "mdi:account-outline"],
"unique_domains": ["DNS Unique Domains", "domains", "mdi:domain"],
}
SENSOR_LIST = list(SENSOR_DICT) | random_line_split | |
variables_11.js | var searchData=
[ | ['remoteaddress',['remoteAddress',['../d4/d33/classSocket.html#aea5a56e9aa58cd921df2d28693aa52c7',1,'Socket']]],
['remoteport',['remotePort',['../d4/d33/classSocket.html#a4ad81f48d21bceda7bc1c27389685c6f',1,'Socket']]],
['response',['response',['../d6/d28/classMessage.html#a78167fa1a78f782d15ea7122333eb53d',1,'Message']]],
['result',['result',['../d6/d28/classMessage.html#aff37dc807536324e1b576ffec75770b0',1,'Message']]],
['right',['RIGHT',['../d5/d5d/classgd.html#ad38a3f38117a471e8075602e1427a573',1,'gd']]],
['ripemd160',['RIPEMD160',['../d5/df6/classhash.html#a85ec8a916512172c1d29e659acde0c20',1,'hash']]],
['rxbuffersize',['rxBufferSize',['../d3/da8/classMySQL.html#afb0238955b2dd36d2b3882661e1bde8d',1,'MySQL']]]
]; | random_line_split | |
button07.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] 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.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level1/html/button07";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "button");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
The type of button
The value of attribute type of the button element is read and checked against the expected value.
* @author Netscape
* @author Sivakiran Tummala
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-27430092
*/
function butt |
var success;
if(checkInitialization(builder, "button07") != null) return;
var nodeList;
var testNode;
var vtype;
var doc;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "button");
nodeList = doc.getElementsByTagName("button");
assertSize("Asize",2,nodeList);
testNode = nodeList.item(0);
vtype = testNode.type;
assertEquals("typeLink","reset",vtype);
}
function runTest() {
button07();
}
| on07() { | identifier_name |
button07.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] 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.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level1/html/button07";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "button");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
The type of button
The value of attribute type of the button element is read and checked against the expected value.
* @author Netscape
* @author Sivakiran Tummala
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-27430092
*/
function button07() {
var success;
if(checkInitialization(builder, "button07") != null) return;
var nodeList;
var testNode;
var vtype;
var doc;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "button");
nodeList = doc.getElementsByTagName("button");
assertSize("Asize",2,nodeList);
testNode = nodeList.item(0);
vtype = testNode.type;
assertEquals("typeLink","reset",vtype);
}
function runTest() {
| button07();
}
| identifier_body | |
button07.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] 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.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level1/html/button07";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "button");
| if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
The type of button
The value of attribute type of the button element is read and checked against the expected value.
* @author Netscape
* @author Sivakiran Tummala
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-27430092
*/
function button07() {
var success;
if(checkInitialization(builder, "button07") != null) return;
var nodeList;
var testNode;
var vtype;
var doc;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "button");
nodeList = doc.getElementsByTagName("button");
assertSize("Asize",2,nodeList);
testNode = nodeList.item(0);
vtype = testNode.type;
assertEquals("typeLink","reset",vtype);
}
function runTest() {
button07();
} | random_line_split | |
models.py | """
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TaggedItem(models.Model):
"""A tag on an item."""
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ["tag", "content_type__model"]
def __str__(self):
return self.tag
class ValuableTaggedItem(TaggedItem):
value = models.PositiveIntegerField()
class AbstractComparison(models.Model):
comparative = models.CharField(max_length=50)
content_type1 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative1_set")
object_id1 = models.PositiveIntegerField()
first_obj = GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
@python_2_unicode_compatible
class Comparison(AbstractComparison):
"""
A model that tests having multiple GenericForeignKeys. One is defined
through an inherited abstract model and one defined directly on this class.
"""
content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set")
object_id2 = models.PositiveIntegerField()
other_obj = GenericForeignKey(ct_field="content_type2", fk_field="object_id2")
def __str__(self):
return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)
@python_2_unicode_compatible
class Animal(models.Model):
common_name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
tags = GenericRelation(TaggedItem, related_query_name='animal')
comparisons = GenericRelation(Comparison,
object_id_field="object_id1", |
@python_2_unicode_compatible
class Vegetable(models.Model):
name = models.CharField(max_length=150)
is_yucky = models.BooleanField(default=True)
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Mineral(models.Model):
name = models.CharField(max_length=150)
hardness = models.PositiveSmallIntegerField()
# note the lack of an explicit GenericRelation here...
def __str__(self):
return self.name
class GeckoManager(models.Manager):
def get_queryset(self):
return super(GeckoManager, self).get_queryset().filter(has_tail=True)
class Gecko(models.Model):
has_tail = models.BooleanField(default=False)
objects = GeckoManager()
# To test fix for #11263
class Rock(Mineral):
tags = GenericRelation(TaggedItem)
class ManualPK(models.Model):
id = models.IntegerField(primary_key=True)
tags = GenericRelation(TaggedItem, related_query_name='manualpk')
class ForProxyModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey(for_concrete_model=False)
title = models.CharField(max_length=255, null=True)
class ForConcreteModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey()
class ConcreteRelatedModel(models.Model):
bases = GenericRelation(ForProxyModelModel, for_concrete_model=False)
class ProxyRelatedModel(ConcreteRelatedModel):
class Meta:
proxy = True
# To test fix for #7551
class AllowsNullGFK(models.Model):
content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey() | content_type_field="content_type1")
def __str__(self):
return self.common_name | random_line_split |
models.py | """
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TaggedItem(models.Model):
"""A tag on an item."""
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ["tag", "content_type__model"]
def __str__(self):
return self.tag
class ValuableTaggedItem(TaggedItem):
value = models.PositiveIntegerField()
class AbstractComparison(models.Model):
comparative = models.CharField(max_length=50)
content_type1 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative1_set")
object_id1 = models.PositiveIntegerField()
first_obj = GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
@python_2_unicode_compatible
class Comparison(AbstractComparison):
"""
A model that tests having multiple GenericForeignKeys. One is defined
through an inherited abstract model and one defined directly on this class.
"""
content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set")
object_id2 = models.PositiveIntegerField()
other_obj = GenericForeignKey(ct_field="content_type2", fk_field="object_id2")
def __str__(self):
return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)
@python_2_unicode_compatible
class Animal(models.Model):
common_name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
tags = GenericRelation(TaggedItem, related_query_name='animal')
comparisons = GenericRelation(Comparison,
object_id_field="object_id1",
content_type_field="content_type1")
def __str__(self):
return self.common_name
@python_2_unicode_compatible
class Vegetable(models.Model):
name = models.CharField(max_length=150)
is_yucky = models.BooleanField(default=True)
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Mineral(models.Model):
name = models.CharField(max_length=150)
hardness = models.PositiveSmallIntegerField()
# note the lack of an explicit GenericRelation here...
def | (self):
return self.name
class GeckoManager(models.Manager):
def get_queryset(self):
return super(GeckoManager, self).get_queryset().filter(has_tail=True)
class Gecko(models.Model):
has_tail = models.BooleanField(default=False)
objects = GeckoManager()
# To test fix for #11263
class Rock(Mineral):
tags = GenericRelation(TaggedItem)
class ManualPK(models.Model):
id = models.IntegerField(primary_key=True)
tags = GenericRelation(TaggedItem, related_query_name='manualpk')
class ForProxyModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey(for_concrete_model=False)
title = models.CharField(max_length=255, null=True)
class ForConcreteModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey()
class ConcreteRelatedModel(models.Model):
bases = GenericRelation(ForProxyModelModel, for_concrete_model=False)
class ProxyRelatedModel(ConcreteRelatedModel):
class Meta:
proxy = True
# To test fix for #7551
class AllowsNullGFK(models.Model):
content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey()
| __str__ | identifier_name |
models.py | """
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TaggedItem(models.Model):
|
class ValuableTaggedItem(TaggedItem):
value = models.PositiveIntegerField()
class AbstractComparison(models.Model):
comparative = models.CharField(max_length=50)
content_type1 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative1_set")
object_id1 = models.PositiveIntegerField()
first_obj = GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
@python_2_unicode_compatible
class Comparison(AbstractComparison):
"""
A model that tests having multiple GenericForeignKeys. One is defined
through an inherited abstract model and one defined directly on this class.
"""
content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set")
object_id2 = models.PositiveIntegerField()
other_obj = GenericForeignKey(ct_field="content_type2", fk_field="object_id2")
def __str__(self):
return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)
@python_2_unicode_compatible
class Animal(models.Model):
common_name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
tags = GenericRelation(TaggedItem, related_query_name='animal')
comparisons = GenericRelation(Comparison,
object_id_field="object_id1",
content_type_field="content_type1")
def __str__(self):
return self.common_name
@python_2_unicode_compatible
class Vegetable(models.Model):
name = models.CharField(max_length=150)
is_yucky = models.BooleanField(default=True)
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Mineral(models.Model):
name = models.CharField(max_length=150)
hardness = models.PositiveSmallIntegerField()
# note the lack of an explicit GenericRelation here...
def __str__(self):
return self.name
class GeckoManager(models.Manager):
def get_queryset(self):
return super(GeckoManager, self).get_queryset().filter(has_tail=True)
class Gecko(models.Model):
has_tail = models.BooleanField(default=False)
objects = GeckoManager()
# To test fix for #11263
class Rock(Mineral):
tags = GenericRelation(TaggedItem)
class ManualPK(models.Model):
id = models.IntegerField(primary_key=True)
tags = GenericRelation(TaggedItem, related_query_name='manualpk')
class ForProxyModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey(for_concrete_model=False)
title = models.CharField(max_length=255, null=True)
class ForConcreteModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey()
class ConcreteRelatedModel(models.Model):
bases = GenericRelation(ForProxyModelModel, for_concrete_model=False)
class ProxyRelatedModel(ConcreteRelatedModel):
class Meta:
proxy = True
# To test fix for #7551
class AllowsNullGFK(models.Model):
content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey()
| """A tag on an item."""
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ["tag", "content_type__model"]
def __str__(self):
return self.tag | identifier_body |
update.js | /**
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* tests/db/model/profile/update.js
*/
'use strict';
const expect = require('chai').expect;
const tu = require('../../../testUtils');
const u = require('./utils');
const Profile = tu.db.Profile;
const adminProfile = require('../../../../config').db.adminProfile;
const Op = require('sequelize').Op;
describe('tests/db/model/profile/update.js >', () => {
const pname = `${tu.namePrefix}1`;
beforeEach((done) => {
Profile.create({
name: pname,
})
.then(() => done())
.catch(done);
});
afterEach(u.forceDelete);
it('ok, profile subjectAccess updated', (done) => {
Profile.findOne({ where: { name: pname } })
.then((o) => o.update({ subjectAccess: 'rw' }))
.then(() => Profile.findOne({ where: { name: pname } }))
.then((o) => {
expect(o).to.have.property('subjectAccess').to.equal('rw');
done();
})
.catch(done);
});
it('fail, profile aspectAccess bad', (done) => {
Profile.findOne({ where: { name: pname } })
.then((o) => o.update({ aspectAccess: true }))
.then(() => Profile.findOne({ where: { name: pname } }))
.catch((err) => { | })
.catch(done);
});
it('fail, profile aspectAccess bad', (done) => {
Profile.findOne({ where: { name: pname } })
.then((o) => o.update({ aspectAccess: true }))
.catch((err) => {
expect(err.name).to.equal(tu.dbErrorName);
done();
})
.catch(done);
});
it('fail, admin profile cannot be changed', (done) => {
Profile.findOne({
where: {
name: {
[Op.iLike]: adminProfile.name,
},
},
})
.then((o) => o.update({ aspectAccess: 'r' }))
.catch((err) => {
expect(err.name).to.equal('AdminUpdateDeleteForbidden');
done();
})
.catch(done);
});
}); | expect(err.name).to.equal(tu.dbErrorName);
done(); | random_line_split |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> |
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len() != 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
}
| {
lt as *mut Vec<*mut cef_string_t>
} | identifier_body |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn | (lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len() != 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
}
| cef_string_list_clear | identifier_name |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set}; | use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len() != 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
} | random_line_split | |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) |
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len() != 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
}
| { return; } | conditional_block |
all_e.js | ['vrefsh_103',['VREFSH',['../namespace_a_d_c__settings.html#a8c2a64f3fca3ac6b82e8df8cf44f6ca2ad1809a5c0e700d83d66cd3c96f5b414f',1,'ADC_settings']]]
]; | var searchData=
[
['very_5fhigh_5fspeed_101',['VERY_HIGH_SPEED',['../namespace_a_d_c__settings.html#af0d80a1aae7288f77b13f0e01d9da0d3a605020f3fad4a24098fbbb0fa4a293f1',1,'ADC_settings']]],
['very_5flow_5fspeed_102',['VERY_LOW_SPEED',['../namespace_a_d_c__settings.html#af0d80a1aae7288f77b13f0e01d9da0d3a5afd4ce3e51232e5889cfd918354ff2d',1,'ADC_settings']]], | random_line_split | |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use dom::bindings::codegen::Bindings::ResponseBinding;
use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType};
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::{ByteString, USVString};
use dom::globalscope::GlobalScope;
use dom::headers::{Headers, Guard};
use dom::headers::{is_vchar, is_obs_text};
use dom::promise::Promise;
use dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
#[dom_struct]
pub struct Response {
reflector_: Reflector,
headers_reflector: MutNullableJS<Headers>,
mime_type: DOMRefCell<Vec<u8>>,
body_used: Cell<bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
body_promise: DOMRefCell<Option<(Rc<Promise>, BodyType)>>,
}
impl Response {
pub fn new_inherited() -> Response {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::new(Some((200, b"OK".to_vec()))),
response_type: DOMRefCell::new(DOMResponseType::Default),
url: DOMRefCell::new(None),
url_list: DOMRefCell::new(vec![]),
body: DOMRefCell::new(NetTraitsResponseBody::Empty),
body_promise: DOMRefCell::new(None),
}
}
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
-> Fallible<Root<Response>> {
// Step 1
if init.status < 200 || init.status > 599 {
return Err(Error::Range( | format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if !is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase token production"
.to_string()));
}
// Step 3
let r = Response::new(global);
// Step 4
*r.status.borrow_mut() = Some(StatusCode::from_u16(init.status));
// Step 5
*r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));
// Step 6
if let Some(ref headers_member) = init.headers {
// Step 6.1
r.Headers().empty_header_list();
// Step 6.2
try!(r.Headers().fill(Some(headers_member.clone())));
}
// Step 7
if let Some(ref body) = body {
// Step 7.1
if is_null_body_status(init.status) {
return Err(Error::Type(
"Body is non-null but init's status member is a null body status".to_string()));
};
// Step 7.3
let (extracted_body, content_type) = body.extract();
*r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);
// Step 7.4
if let Some(content_type_contents) = content_type {
if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec())));
}
};
}
// Step 8
*r.mime_type.borrow_mut() = r.Headers().extract_mime_type();
// Step 9
// TODO: `entry settings object` is not implemented in Servo yet.
// Step 10
// TODO: Write this step once Promises are merged in
// Step 11
Ok(r)
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> Root<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
if !is_redirect_status(status) {
return Err(Error::Range("status is not a redirect status".to_string()));
}
// Step 4
// see Step 4 continued
let r = Response::new(global);
// Step 5
*r.status.borrow_mut() = Some(StatusCode::from_u16(status));
*r.raw_status.borrow_mut() = Some((status, b"".to_vec()));
// Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring));
// Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6
r.Headers().set_guard(Guard::Immutable);
// Step 7
Ok(r)
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn locked(&self) -> bool {
// TODO: ReadableStream is unimplemented. Just return false
// for now.
false
}
}
impl BodyOperations for Response {
fn get_body_used(&self) -> bool {
self.BodyUsed()
}
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
}
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => {
Some(bytes)
},
body => {
mem::replace(&mut *self.body.borrow_mut(), body);
None
},
}
}
fn get_mime_type(&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow()//into()
}
// https://fetch.spec.whatwg.org/#dom-response-url
fn Url(&self) -> USVString {
USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or("")))
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
fn Redirected(&self) -> bool {
let url_list_len = self.url_list.borrow().len();
url_list_len > 1
}
// https://fetch.spec.whatwg.org/#dom-response-status
fn Status(&self) -> u16 {
match *self.raw_status.borrow() {
Some((s, _)) => s,
None => 0,
}
}
// https://fetch.spec.whatwg.org/#dom-response-ok
fn Ok(&self) -> bool {
match *self.status.borrow() {
Some(s) => {
let status_num = s.to_u16();
return status_num >= 200 && status_num <= 299;
}
None => false,
}
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
fn StatusText(&self) -> ByteString {
match *self.raw_status.borrow() {
Some((_, ref st)) => ByteString::new(st.clone()),
None => ByteString::new(b"OK".to_vec()),
}
}
// https://fetch.spec.whatwg.org/#dom-response-headers
fn Headers(&self) -> Root<Headers> {
self.headers_reflector.or_init(|| Headers::for_response(&self.global()))
}
// https://fetch.spec.whatwg.org/#dom-response-clone
fn Clone(&self) -> Fallible<Root<Response>> {
// Step 1
if self.is_locked() || self.body_used.get() {
return Err(Error::Type("cannot clone a disturbed response".to_string()));
}
// Step 2
let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers()))));
// https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we
// only store the relevant fields, and only clone them here
*new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
*new_response.status.borrow_mut() = self.status.borrow().clone();
*new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
*new_response.url.borrow_mut() = self.url.borrow().clone();
*new_response.url_list.borrow_mut() = self.url_list.borrow().clone();
if *self.body.borrow() != NetTraitsResponseBody::Empty {
*new_response.body.borrow_mut() = self.body.borrow().clone();
}
// Step 3
// TODO: This step relies on promises, which are still unimplemented.
// Step 4
Ok(new_response)
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
fn BodyUsed(&self) -> bool {
self.body_used.get()
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-text
fn Text(&self) -> Rc<Promise> {
consume_body(self, BodyType::Text)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-blob
fn Blob(&self) -> Rc<Promise> {
consume_body(self, BodyType::Blob)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-formdata
fn FormData(&self) -> Rc<Promise> {
consume_body(self, BodyType::FormData)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-json
fn Json(&self) -> Rc<Promise> {
consume_body(self, BodyType::Json)
}
}
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url[..Position::AfterQuery]
}
impl Response {
pub fn set_type(&self, new_response_type: DOMResponseType) {
*self.response_type.borrow_mut() = new_response_type;
}
pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
self.Headers().set_headers(match option_hyper_headers {
Some(hyper_headers) => hyper_headers.into_inner(),
None => HyperHeaders::new(),
});
}
pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}
#[allow(unrooted_must_root)]
pub fn finish(&self, body: Vec<u8>) {
*self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
consume_body_with_promise(self, body_type, &p);
}
}
} | random_line_split | |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use dom::bindings::codegen::Bindings::ResponseBinding;
use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType};
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::{ByteString, USVString};
use dom::globalscope::GlobalScope;
use dom::headers::{Headers, Guard};
use dom::headers::{is_vchar, is_obs_text};
use dom::promise::Promise;
use dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
#[dom_struct]
pub struct Response {
reflector_: Reflector,
headers_reflector: MutNullableJS<Headers>,
mime_type: DOMRefCell<Vec<u8>>,
body_used: Cell<bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
body_promise: DOMRefCell<Option<(Rc<Promise>, BodyType)>>,
}
impl Response {
pub fn new_inherited() -> Response |
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
-> Fallible<Root<Response>> {
// Step 1
if init.status < 200 || init.status > 599 {
return Err(Error::Range(
format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if !is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase token production"
.to_string()));
}
// Step 3
let r = Response::new(global);
// Step 4
*r.status.borrow_mut() = Some(StatusCode::from_u16(init.status));
// Step 5
*r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));
// Step 6
if let Some(ref headers_member) = init.headers {
// Step 6.1
r.Headers().empty_header_list();
// Step 6.2
try!(r.Headers().fill(Some(headers_member.clone())));
}
// Step 7
if let Some(ref body) = body {
// Step 7.1
if is_null_body_status(init.status) {
return Err(Error::Type(
"Body is non-null but init's status member is a null body status".to_string()));
};
// Step 7.3
let (extracted_body, content_type) = body.extract();
*r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);
// Step 7.4
if let Some(content_type_contents) = content_type {
if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec())));
}
};
}
// Step 8
*r.mime_type.borrow_mut() = r.Headers().extract_mime_type();
// Step 9
// TODO: `entry settings object` is not implemented in Servo yet.
// Step 10
// TODO: Write this step once Promises are merged in
// Step 11
Ok(r)
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> Root<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
if !is_redirect_status(status) {
return Err(Error::Range("status is not a redirect status".to_string()));
}
// Step 4
// see Step 4 continued
let r = Response::new(global);
// Step 5
*r.status.borrow_mut() = Some(StatusCode::from_u16(status));
*r.raw_status.borrow_mut() = Some((status, b"".to_vec()));
// Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring));
// Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6
r.Headers().set_guard(Guard::Immutable);
// Step 7
Ok(r)
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn locked(&self) -> bool {
// TODO: ReadableStream is unimplemented. Just return false
// for now.
false
}
}
impl BodyOperations for Response {
fn get_body_used(&self) -> bool {
self.BodyUsed()
}
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
}
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => {
Some(bytes)
},
body => {
mem::replace(&mut *self.body.borrow_mut(), body);
None
},
}
}
fn get_mime_type(&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow()//into()
}
// https://fetch.spec.whatwg.org/#dom-response-url
fn Url(&self) -> USVString {
USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or("")))
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
fn Redirected(&self) -> bool {
let url_list_len = self.url_list.borrow().len();
url_list_len > 1
}
// https://fetch.spec.whatwg.org/#dom-response-status
fn Status(&self) -> u16 {
match *self.raw_status.borrow() {
Some((s, _)) => s,
None => 0,
}
}
// https://fetch.spec.whatwg.org/#dom-response-ok
fn Ok(&self) -> bool {
match *self.status.borrow() {
Some(s) => {
let status_num = s.to_u16();
return status_num >= 200 && status_num <= 299;
}
None => false,
}
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
fn StatusText(&self) -> ByteString {
match *self.raw_status.borrow() {
Some((_, ref st)) => ByteString::new(st.clone()),
None => ByteString::new(b"OK".to_vec()),
}
}
// https://fetch.spec.whatwg.org/#dom-response-headers
fn Headers(&self) -> Root<Headers> {
self.headers_reflector.or_init(|| Headers::for_response(&self.global()))
}
// https://fetch.spec.whatwg.org/#dom-response-clone
fn Clone(&self) -> Fallible<Root<Response>> {
// Step 1
if self.is_locked() || self.body_used.get() {
return Err(Error::Type("cannot clone a disturbed response".to_string()));
}
// Step 2
let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers()))));
// https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we
// only store the relevant fields, and only clone them here
*new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
*new_response.status.borrow_mut() = self.status.borrow().clone();
*new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
*new_response.url.borrow_mut() = self.url.borrow().clone();
*new_response.url_list.borrow_mut() = self.url_list.borrow().clone();
if *self.body.borrow() != NetTraitsResponseBody::Empty {
*new_response.body.borrow_mut() = self.body.borrow().clone();
}
// Step 3
// TODO: This step relies on promises, which are still unimplemented.
// Step 4
Ok(new_response)
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
fn BodyUsed(&self) -> bool {
self.body_used.get()
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-text
fn Text(&self) -> Rc<Promise> {
consume_body(self, BodyType::Text)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-blob
fn Blob(&self) -> Rc<Promise> {
consume_body(self, BodyType::Blob)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-formdata
fn FormData(&self) -> Rc<Promise> {
consume_body(self, BodyType::FormData)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-json
fn Json(&self) -> Rc<Promise> {
consume_body(self, BodyType::Json)
}
}
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url[..Position::AfterQuery]
}
impl Response {
pub fn set_type(&self, new_response_type: DOMResponseType) {
*self.response_type.borrow_mut() = new_response_type;
}
pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
self.Headers().set_headers(match option_hyper_headers {
Some(hyper_headers) => hyper_headers.into_inner(),
None => HyperHeaders::new(),
});
}
pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}
#[allow(unrooted_must_root)]
pub fn finish(&self, body: Vec<u8>) {
*self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
consume_body_with_promise(self, body_type, &p);
}
}
}
| {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::new(Some((200, b"OK".to_vec()))),
response_type: DOMRefCell::new(DOMResponseType::Default),
url: DOMRefCell::new(None),
url_list: DOMRefCell::new(vec![]),
body: DOMRefCell::new(NetTraitsResponseBody::Empty),
body_promise: DOMRefCell::new(None),
}
} | identifier_body |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use dom::bindings::codegen::Bindings::ResponseBinding;
use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType};
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::{ByteString, USVString};
use dom::globalscope::GlobalScope;
use dom::headers::{Headers, Guard};
use dom::headers::{is_vchar, is_obs_text};
use dom::promise::Promise;
use dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
#[dom_struct]
pub struct Response {
reflector_: Reflector,
headers_reflector: MutNullableJS<Headers>,
mime_type: DOMRefCell<Vec<u8>>,
body_used: Cell<bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
body_promise: DOMRefCell<Option<(Rc<Promise>, BodyType)>>,
}
impl Response {
pub fn new_inherited() -> Response {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::new(Some((200, b"OK".to_vec()))),
response_type: DOMRefCell::new(DOMResponseType::Default),
url: DOMRefCell::new(None),
url_list: DOMRefCell::new(vec![]),
body: DOMRefCell::new(NetTraitsResponseBody::Empty),
body_promise: DOMRefCell::new(None),
}
}
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
-> Fallible<Root<Response>> {
// Step 1
if init.status < 200 || init.status > 599 {
return Err(Error::Range(
format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if !is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase token production"
.to_string()));
}
// Step 3
let r = Response::new(global);
// Step 4
*r.status.borrow_mut() = Some(StatusCode::from_u16(init.status));
// Step 5
*r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));
// Step 6
if let Some(ref headers_member) = init.headers {
// Step 6.1
r.Headers().empty_header_list();
// Step 6.2
try!(r.Headers().fill(Some(headers_member.clone())));
}
// Step 7
if let Some(ref body) = body {
// Step 7.1
if is_null_body_status(init.status) {
return Err(Error::Type(
"Body is non-null but init's status member is a null body status".to_string()));
};
// Step 7.3
let (extracted_body, content_type) = body.extract();
*r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);
// Step 7.4
if let Some(content_type_contents) = content_type {
if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec())));
}
};
}
// Step 8
*r.mime_type.borrow_mut() = r.Headers().extract_mime_type();
// Step 9
// TODO: `entry settings object` is not implemented in Servo yet.
// Step 10
// TODO: Write this step once Promises are merged in
// Step 11
Ok(r)
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> Root<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
if !is_redirect_status(status) {
return Err(Error::Range("status is not a redirect status".to_string()));
}
// Step 4
// see Step 4 continued
let r = Response::new(global);
// Step 5
*r.status.borrow_mut() = Some(StatusCode::from_u16(status));
*r.raw_status.borrow_mut() = Some((status, b"".to_vec()));
// Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring));
// Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6
r.Headers().set_guard(Guard::Immutable);
// Step 7
Ok(r)
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn locked(&self) -> bool {
// TODO: ReadableStream is unimplemented. Just return false
// for now.
false
}
}
impl BodyOperations for Response {
fn get_body_used(&self) -> bool {
self.BodyUsed()
}
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
}
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => {
Some(bytes)
},
body => {
mem::replace(&mut *self.body.borrow_mut(), body);
None
},
}
}
fn | (&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow()//into()
}
// https://fetch.spec.whatwg.org/#dom-response-url
fn Url(&self) -> USVString {
USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or("")))
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
fn Redirected(&self) -> bool {
let url_list_len = self.url_list.borrow().len();
url_list_len > 1
}
// https://fetch.spec.whatwg.org/#dom-response-status
fn Status(&self) -> u16 {
match *self.raw_status.borrow() {
Some((s, _)) => s,
None => 0,
}
}
// https://fetch.spec.whatwg.org/#dom-response-ok
fn Ok(&self) -> bool {
match *self.status.borrow() {
Some(s) => {
let status_num = s.to_u16();
return status_num >= 200 && status_num <= 299;
}
None => false,
}
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
fn StatusText(&self) -> ByteString {
match *self.raw_status.borrow() {
Some((_, ref st)) => ByteString::new(st.clone()),
None => ByteString::new(b"OK".to_vec()),
}
}
// https://fetch.spec.whatwg.org/#dom-response-headers
fn Headers(&self) -> Root<Headers> {
self.headers_reflector.or_init(|| Headers::for_response(&self.global()))
}
// https://fetch.spec.whatwg.org/#dom-response-clone
fn Clone(&self) -> Fallible<Root<Response>> {
// Step 1
if self.is_locked() || self.body_used.get() {
return Err(Error::Type("cannot clone a disturbed response".to_string()));
}
// Step 2
let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers()))));
// https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we
// only store the relevant fields, and only clone them here
*new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
*new_response.status.borrow_mut() = self.status.borrow().clone();
*new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
*new_response.url.borrow_mut() = self.url.borrow().clone();
*new_response.url_list.borrow_mut() = self.url_list.borrow().clone();
if *self.body.borrow() != NetTraitsResponseBody::Empty {
*new_response.body.borrow_mut() = self.body.borrow().clone();
}
// Step 3
// TODO: This step relies on promises, which are still unimplemented.
// Step 4
Ok(new_response)
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
fn BodyUsed(&self) -> bool {
self.body_used.get()
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-text
fn Text(&self) -> Rc<Promise> {
consume_body(self, BodyType::Text)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-blob
fn Blob(&self) -> Rc<Promise> {
consume_body(self, BodyType::Blob)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-formdata
fn FormData(&self) -> Rc<Promise> {
consume_body(self, BodyType::FormData)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-json
fn Json(&self) -> Rc<Promise> {
consume_body(self, BodyType::Json)
}
}
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url[..Position::AfterQuery]
}
impl Response {
pub fn set_type(&self, new_response_type: DOMResponseType) {
*self.response_type.borrow_mut() = new_response_type;
}
pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
self.Headers().set_headers(match option_hyper_headers {
Some(hyper_headers) => hyper_headers.into_inner(),
None => HyperHeaders::new(),
});
}
pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}
#[allow(unrooted_must_root)]
pub fn finish(&self, body: Vec<u8>) {
*self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
consume_body_with_promise(self, body_type, &p);
}
}
}
| get_mime_type | identifier_name |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
scheme
schemes -- if your scheme has +'s in it, then this will contain a list of schemes split by +
path
paths -- the path segment split by /, so "/foo/bar" would be ["foo", "bar"]
host -- same as hostname (I just like host better)
hostname
hostloc -- host:port
username
password
netloc
query -- a dict of the query string
query_str -- the raw query string
port
fragment
'''
DSN_REGEXP = re.compile(r'^\S+://\S+')
FIELDS = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')
def __init__(self, dsn, **defaults):
''' Parse a dsn to parts similar to urlparse.
This is a nuts function that can serve as a good basis to parsing a custom dsn
:param dsn: the dsn to parse
:type dsn: str
:param defaults: any values you want to have defaults for if they aren't in the dsn
:type defaults: dict
'''
assert self.DSN_REGEXP.match(dsn), \
"{} is invalid, only full dsn urls (scheme://host...) allowed".format(dsn)
first_colon = dsn.find(':')
scheme = dsn[0:first_colon]
dsn_url = dsn[first_colon+1:]
url = urlparse.urlparse(dsn_url)
options = {}
if url.query:
for k, kv in urlparse.parse_qs(url.query, True, True).iteritems():
if len(kv) > 1:
options[k] = kv
else:
options[k] = kv[0]
self.scheme = scheme
self.hostname = url.hostname
self.path = url.path
self.params = url.params
self.query = options
self.fragment = url.fragment
self.username = url.username
self.password = url.password
self.port = url.port
self.query_str = url.query
for k, v in defaults.iteritems():
self.set_default(k, v)
def __iter__(self):
for f in self.FIELDS:
yield getattr(self, f, '')
def __len__(self):
return len(iter(self))
def __getitem__(self, field):
|
def __setitem__(self, field, value):
setattr(self, field, value)
def __delitem__(self, field):
delattr(self, field)
@property
def schemes(self):
'''the scheme, split by plus signs'''
return self.scheme.split('+')
@property
def netloc(self):
'''return username:password@hostname:port'''
s = ''
prefix = ''
if self.username:
s += self.username
prefix = '@'
if self.password:
s += ":{}".format(self.password)
prefix = '@'
s += "{}{}".format(prefix, self.hostloc)
return s
@property
def paths(self):
'''the path attribute split by /'''
return filter(None, self.path.split('/'))
@property
def host(self):
'''the hostname, but I like host better'''
return self.hostname
@property
def hostloc(self):
'''return host:port'''
hostloc = self.hostname
if self.port:
hostloc = '{}:{}'.format(hostloc, self.port)
return hostloc
def set_default(self, key, value):
''' Set a default value for key.
This is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None will value will be updated.
:param key: the item to update
:type key: str
:param value: the items new value if key has a current value that evaluates to False
'''
if not getattr(self, key, None):
setattr(self, key, value)
def get_url(self):
'''return the dsn back into url form'''
return urlparse.urlunparse((
self.scheme,
self.netloc,
self.path,
self.params,
self.query_str,
self.fragment,
))
def copy(self):
return DSN(self.get_url())
def __str__(self):
return self.get_url()
| return getattr(self, field, None) | identifier_body |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
scheme
schemes -- if your scheme has +'s in it, then this will contain a list of schemes split by +
path
paths -- the path segment split by /, so "/foo/bar" would be ["foo", "bar"]
host -- same as hostname (I just like host better)
hostname
hostloc -- host:port
username
password
netloc
query -- a dict of the query string
query_str -- the raw query string
port
fragment
'''
DSN_REGEXP = re.compile(r'^\S+://\S+')
FIELDS = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')
def __init__(self, dsn, **defaults):
''' Parse a dsn to parts similar to urlparse.
This is a nuts function that can serve as a good basis to parsing a custom dsn
:param dsn: the dsn to parse
:type dsn: str
:param defaults: any values you want to have defaults for if they aren't in the dsn
:type defaults: dict
'''
assert self.DSN_REGEXP.match(dsn), \
"{} is invalid, only full dsn urls (scheme://host...) allowed".format(dsn)
first_colon = dsn.find(':')
scheme = dsn[0:first_colon]
dsn_url = dsn[first_colon+1:]
url = urlparse.urlparse(dsn_url)
options = {}
if url.query:
for k, kv in urlparse.parse_qs(url.query, True, True).iteritems():
if len(kv) > 1:
options[k] = kv
else:
options[k] = kv[0]
self.scheme = scheme
self.hostname = url.hostname
self.path = url.path
self.params = url.params
self.query = options
self.fragment = url.fragment
self.username = url.username
self.password = url.password
self.port = url.port
self.query_str = url.query
for k, v in defaults.iteritems():
self.set_default(k, v)
def __iter__(self):
for f in self.FIELDS:
yield getattr(self, f, '')
def __len__(self):
return len(iter(self))
def __getitem__(self, field):
return getattr(self, field, None)
def | (self, field, value):
setattr(self, field, value)
def __delitem__(self, field):
delattr(self, field)
@property
def schemes(self):
'''the scheme, split by plus signs'''
return self.scheme.split('+')
@property
def netloc(self):
'''return username:password@hostname:port'''
s = ''
prefix = ''
if self.username:
s += self.username
prefix = '@'
if self.password:
s += ":{}".format(self.password)
prefix = '@'
s += "{}{}".format(prefix, self.hostloc)
return s
@property
def paths(self):
'''the path attribute split by /'''
return filter(None, self.path.split('/'))
@property
def host(self):
'''the hostname, but I like host better'''
return self.hostname
@property
def hostloc(self):
'''return host:port'''
hostloc = self.hostname
if self.port:
hostloc = '{}:{}'.format(hostloc, self.port)
return hostloc
def set_default(self, key, value):
''' Set a default value for key.
This is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None will value will be updated.
:param key: the item to update
:type key: str
:param value: the items new value if key has a current value that evaluates to False
'''
if not getattr(self, key, None):
setattr(self, key, value)
def get_url(self):
'''return the dsn back into url form'''
return urlparse.urlunparse((
self.scheme,
self.netloc,
self.path,
self.params,
self.query_str,
self.fragment,
))
def copy(self):
return DSN(self.get_url())
def __str__(self):
return self.get_url()
| __setitem__ | identifier_name |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
scheme
schemes -- if your scheme has +'s in it, then this will contain a list of schemes split by +
path
paths -- the path segment split by /, so "/foo/bar" would be ["foo", "bar"]
host -- same as hostname (I just like host better)
hostname
hostloc -- host:port
username
password
netloc
query -- a dict of the query string
query_str -- the raw query string
port
fragment
'''
DSN_REGEXP = re.compile(r'^\S+://\S+')
FIELDS = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')
def __init__(self, dsn, **defaults):
''' Parse a dsn to parts similar to urlparse.
This is a nuts function that can serve as a good basis to parsing a custom dsn
:param dsn: the dsn to parse
:type dsn: str
:param defaults: any values you want to have defaults for if they aren't in the dsn
:type defaults: dict
'''
assert self.DSN_REGEXP.match(dsn), \
"{} is invalid, only full dsn urls (scheme://host...) allowed".format(dsn)
first_colon = dsn.find(':')
scheme = dsn[0:first_colon]
dsn_url = dsn[first_colon+1:]
url = urlparse.urlparse(dsn_url)
options = {}
if url.query:
for k, kv in urlparse.parse_qs(url.query, True, True).iteritems():
if len(kv) > 1:
options[k] = kv
else:
options[k] = kv[0]
self.scheme = scheme
self.hostname = url.hostname
self.path = url.path
self.params = url.params
self.query = options
self.fragment = url.fragment
self.username = url.username
self.password = url.password
self.port = url.port
self.query_str = url.query
for k, v in defaults.iteritems():
self.set_default(k, v)
def __iter__(self):
for f in self.FIELDS:
yield getattr(self, f, '')
def __len__(self):
return len(iter(self))
def __getitem__(self, field):
return getattr(self, field, None)
def __setitem__(self, field, value):
setattr(self, field, value)
def __delitem__(self, field):
delattr(self, field)
@property
def schemes(self):
'''the scheme, split by plus signs'''
return self.scheme.split('+')
@property
def netloc(self):
'''return username:password@hostname:port'''
s = ''
prefix = ''
if self.username:
s += self.username
prefix = '@'
if self.password:
s += ":{}".format(self.password)
prefix = '@'
s += "{}{}".format(prefix, self.hostloc)
return s
@property
def paths(self):
'''the path attribute split by /'''
return filter(None, self.path.split('/'))
@property
def host(self):
'''the hostname, but I like host better'''
return self.hostname
@property
def hostloc(self):
'''return host:port'''
hostloc = self.hostname
if self.port:
|
return hostloc
def set_default(self, key, value):
''' Set a default value for key.
This is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None will value will be updated.
:param key: the item to update
:type key: str
:param value: the items new value if key has a current value that evaluates to False
'''
if not getattr(self, key, None):
setattr(self, key, value)
def get_url(self):
'''return the dsn back into url form'''
return urlparse.urlunparse((
self.scheme,
self.netloc,
self.path,
self.params,
self.query_str,
self.fragment,
))
def copy(self):
return DSN(self.get_url())
def __str__(self):
return self.get_url()
| hostloc = '{}:{}'.format(hostloc, self.port) | conditional_block |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
scheme
schemes -- if your scheme has +'s in it, then this will contain a list of schemes split by +
path
paths -- the path segment split by /, so "/foo/bar" would be ["foo", "bar"]
host -- same as hostname (I just like host better)
hostname
hostloc -- host:port
username
password
netloc
query -- a dict of the query string
query_str -- the raw query string
port
fragment
'''
DSN_REGEXP = re.compile(r'^\S+://\S+')
FIELDS = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')
def __init__(self, dsn, **defaults):
''' Parse a dsn to parts similar to urlparse.
This is a nuts function that can serve as a good basis to parsing a custom dsn
:param dsn: the dsn to parse
:type dsn: str
:param defaults: any values you want to have defaults for if they aren't in the dsn
:type defaults: dict
'''
assert self.DSN_REGEXP.match(dsn), \
"{} is invalid, only full dsn urls (scheme://host...) allowed".format(dsn)
first_colon = dsn.find(':')
scheme = dsn[0:first_colon]
dsn_url = dsn[first_colon+1:]
url = urlparse.urlparse(dsn_url)
options = {}
if url.query:
for k, kv in urlparse.parse_qs(url.query, True, True).iteritems():
if len(kv) > 1:
options[k] = kv
else:
options[k] = kv[0]
self.scheme = scheme
self.hostname = url.hostname
self.path = url.path
self.params = url.params
self.query = options
self.fragment = url.fragment
self.username = url.username
self.password = url.password
self.port = url.port
self.query_str = url.query
for k, v in defaults.iteritems():
self.set_default(k, v)
def __iter__(self):
for f in self.FIELDS:
yield getattr(self, f, '')
def __len__(self):
return len(iter(self))
def __getitem__(self, field):
return getattr(self, field, None)
def __setitem__(self, field, value):
setattr(self, field, value)
def __delitem__(self, field):
delattr(self, field)
@property
def schemes(self):
'''the scheme, split by plus signs'''
return self.scheme.split('+')
@property
def netloc(self):
'''return username:password@hostname:port'''
s = ''
prefix = ''
if self.username:
s += self.username
prefix = '@'
if self.password:
s += ":{}".format(self.password)
prefix = '@'
s += "{}{}".format(prefix, self.hostloc)
return s
@property
def paths(self):
'''the path attribute split by /'''
return filter(None, self.path.split('/'))
@property
def host(self):
'''the hostname, but I like host better'''
return self.hostname
@property
def hostloc(self):
'''return host:port'''
hostloc = self.hostname
if self.port:
hostloc = '{}:{}'.format(hostloc, self.port)
return hostloc
def set_default(self, key, value):
''' Set a default value for key.
This is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None will value will be updated.
:param key: the item to update
:type key: str
:param value: the items new value if key has a current value that evaluates to False
'''
if not getattr(self, key, None):
setattr(self, key, value)
def get_url(self):
'''return the dsn back into url form'''
return urlparse.urlunparse((
self.scheme,
self.netloc,
self.path,
self.params,
self.query_str,
self.fragment,
)) | return DSN(self.get_url())
def __str__(self):
return self.get_url() |
def copy(self): | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser'
import { NgModule } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http'
import { RouterModule } from '@angular/router'
import { StoreModule } from '@ngrx/store'
import { StoreDevtoolsModule } from '@ngrx/store-devtools'
import { AppCommonModule, coursesReducer, userReducer } from './common/index'
import { BaseModule } from './base/index'
import { AppComponent } from './app.component'
import { LoginComponent } from './login/login.component'
import { AddCourseComponent } from './add-course/add-course.component'
import { CoursesComponent } from './courses/courses.component'
import { CourseDetailsComponent } from './course-details/course-details.component'
import { ToolboxComponent } from './courses/toolbox.component'
import { CourseItemComponent } from './courses/course-item.component'
import { CreateDateHighlighterDirective } from './courses/create-date-highlighter.directive'
import { routes } from './app.routes'
import { NotFoundComponent } from './not-found/not-found.component'
import { DetailsResolverService } from './course-details/details-resolver.service'
import { AuthorsResolverService } from './common/components/details/authors-resolver.service'
@NgModule({
declarations: [
AppComponent,
LoginComponent,
CoursesComponent,
CourseDetailsComponent,
ToolboxComponent,
CourseItemComponent,
CreateDateHighlighterDirective,
AddCourseComponent,
NotFoundComponent
],
imports: [
RouterModule.forRoot(routes),
StoreModule.provideStore({
page: coursesReducer,
user: userReducer
}),
StoreDevtoolsModule.instrumentOnlyWithExtension({
maxAge: 5
}),
BrowserModule,
FormsModule,
HttpModule,
AppCommonModule,
BaseModule,
ReactiveFormsModule
],
providers: [DetailsResolverService, AuthorsResolverService],
bootstrap: [AppComponent]
})
export class | { }
| AppModule | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser'
import { NgModule } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http'
import { RouterModule } from '@angular/router'
import { StoreModule } from '@ngrx/store'
import { StoreDevtoolsModule } from '@ngrx/store-devtools'
import { AppCommonModule, coursesReducer, userReducer } from './common/index'
import { BaseModule } from './base/index'
import { AppComponent } from './app.component'
import { LoginComponent } from './login/login.component'
import { AddCourseComponent } from './add-course/add-course.component'
import { CoursesComponent } from './courses/courses.component'
import { CourseDetailsComponent } from './course-details/course-details.component'
import { ToolboxComponent } from './courses/toolbox.component'
import { CourseItemComponent } from './courses/course-item.component'
import { CreateDateHighlighterDirective } from './courses/create-date-highlighter.directive'
import { routes } from './app.routes'
import { NotFoundComponent } from './not-found/not-found.component'
import { DetailsResolverService } from './course-details/details-resolver.service'
import { AuthorsResolverService } from './common/components/details/authors-resolver.service'
@NgModule({
declarations: [
AppComponent,
LoginComponent,
CoursesComponent,
CourseDetailsComponent,
ToolboxComponent,
CourseItemComponent,
CreateDateHighlighterDirective,
AddCourseComponent, | ],
imports: [
RouterModule.forRoot(routes),
StoreModule.provideStore({
page: coursesReducer,
user: userReducer
}),
StoreDevtoolsModule.instrumentOnlyWithExtension({
maxAge: 5
}),
BrowserModule,
FormsModule,
HttpModule,
AppCommonModule,
BaseModule,
ReactiveFormsModule
],
providers: [DetailsResolverService, AuthorsResolverService],
bootstrap: [AppComponent]
})
export class AppModule { } | NotFoundComponent | random_line_split |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider
from .reverse_proxy import ReverseProxied
# Initialize app
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
# Generate or load secret key
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
try:
app.secret_key = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
app.secret_key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(app.secret_key)
secret.close()
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE)
# Load config
config_path = os.getenv('CONFIG_PATH', 'mass_flask_config.config_development.DevelopmentConfig')
app.config.from_object(config_path)
# Init db
db = MongoEngine(app)
# Init flask-bootstrap
Bootstrap(app)
# Init auth system
def setup_session_auth(user_loader):
app.session_provider = SessionBasedAuthProvider(user_loader)
auth_manager.register_auth_provider(app.session_provider)
def setup_key_based_auth(key_loader):
|
def unauthorized_callback():
if current_authenticated_entity.is_authenticated:
flash('You are not authorized to access this resource!', 'warning')
return redirect(url_for('mass_flask_webui.index'))
else:
return redirect(url_for('mass_flask_webui.login', next=request.url))
auth_manager = AuthManager(app, unauthorized_callback=unauthorized_callback)
# Set the version number. For the future we should probably read it from a file.
app.version = '1.0-alpha1'
| app.key_based_provider = KeyBasedAuthProvider(key_loader)
auth_manager.register_auth_provider(app.key_based_provider) | identifier_body |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider
from .reverse_proxy import ReverseProxied
# Initialize app
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
# Generate or load secret key
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
try:
app.secret_key = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
app.secret_key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(app.secret_key)
secret.close()
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE)
# Load config
config_path = os.getenv('CONFIG_PATH', 'mass_flask_config.config_development.DevelopmentConfig')
app.config.from_object(config_path)
# Init db
db = MongoEngine(app)
# Init flask-bootstrap
Bootstrap(app)
# Init auth system
def | (user_loader):
app.session_provider = SessionBasedAuthProvider(user_loader)
auth_manager.register_auth_provider(app.session_provider)
def setup_key_based_auth(key_loader):
app.key_based_provider = KeyBasedAuthProvider(key_loader)
auth_manager.register_auth_provider(app.key_based_provider)
def unauthorized_callback():
if current_authenticated_entity.is_authenticated:
flash('You are not authorized to access this resource!', 'warning')
return redirect(url_for('mass_flask_webui.index'))
else:
return redirect(url_for('mass_flask_webui.login', next=request.url))
auth_manager = AuthManager(app, unauthorized_callback=unauthorized_callback)
# Set the version number. For the future we should probably read it from a file.
app.version = '1.0-alpha1'
| setup_session_auth | identifier_name |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider
from .reverse_proxy import ReverseProxied
# Initialize app
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
# Generate or load secret key
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
try:
app.secret_key = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
app.secret_key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(app.secret_key)
secret.close()
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE)
# Load config
config_path = os.getenv('CONFIG_PATH', 'mass_flask_config.config_development.DevelopmentConfig')
app.config.from_object(config_path)
# Init db
db = MongoEngine(app)
# Init flask-bootstrap
Bootstrap(app)
# Init auth system
def setup_session_auth(user_loader):
app.session_provider = SessionBasedAuthProvider(user_loader)
auth_manager.register_auth_provider(app.session_provider)
def setup_key_based_auth(key_loader):
app.key_based_provider = KeyBasedAuthProvider(key_loader)
auth_manager.register_auth_provider(app.key_based_provider)
def unauthorized_callback():
if current_authenticated_entity.is_authenticated:
flash('You are not authorized to access this resource!', 'warning')
return redirect(url_for('mass_flask_webui.index'))
else:
|
auth_manager = AuthManager(app, unauthorized_callback=unauthorized_callback)
# Set the version number. For the future we should probably read it from a file.
app.version = '1.0-alpha1'
| return redirect(url_for('mass_flask_webui.login', next=request.url)) | conditional_block |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider
from .reverse_proxy import ReverseProxied
# Initialize app
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
# Generate or load secret key
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')
try:
app.secret_key = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
app.secret_key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(app.secret_key) |
# Load config
config_path = os.getenv('CONFIG_PATH', 'mass_flask_config.config_development.DevelopmentConfig')
app.config.from_object(config_path)
# Init db
db = MongoEngine(app)
# Init flask-bootstrap
Bootstrap(app)
# Init auth system
def setup_session_auth(user_loader):
app.session_provider = SessionBasedAuthProvider(user_loader)
auth_manager.register_auth_provider(app.session_provider)
def setup_key_based_auth(key_loader):
app.key_based_provider = KeyBasedAuthProvider(key_loader)
auth_manager.register_auth_provider(app.key_based_provider)
def unauthorized_callback():
if current_authenticated_entity.is_authenticated:
flash('You are not authorized to access this resource!', 'warning')
return redirect(url_for('mass_flask_webui.index'))
else:
return redirect(url_for('mass_flask_webui.login', next=request.url))
auth_manager = AuthManager(app, unauthorized_callback=unauthorized_callback)
# Set the version number. For the future we should probably read it from a file.
app.version = '1.0-alpha1' | secret.close()
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE) | random_line_split |
option.js | function Option ( name, options ) |
var cafe = (function ( game ) {
game.bean = new Option ( 'bean', ['gourmet', 'hipster', 'good', 'cheap', 'actual']);
game.price = new Option ('price', ['well below', 'below', 'at', 'above', 'well above']);
return game;
} ( cafe || {})); | {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) {
this.element.value = string;
}
};
this.get = function () {
return this.element.value;
};
this.callback = function ( event ) {
context.set(event.target.value);
event.stopPropagation();
};
this.listen = function() {
context.element.addEventListener('change', this.callback);
};
this.unlisten = function() {
context.element.removeEventListener('change', this.callback);
};
} | identifier_body |
option.js | function Option ( name, options ) {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) |
};
this.get = function () {
return this.element.value;
};
this.callback = function ( event ) {
context.set(event.target.value);
event.stopPropagation();
};
this.listen = function() {
context.element.addEventListener('change', this.callback);
};
this.unlisten = function() {
context.element.removeEventListener('change', this.callback);
};
}
var cafe = (function ( game ) {
game.bean = new Option ( 'bean', ['gourmet', 'hipster', 'good', 'cheap', 'actual']);
game.price = new Option ('price', ['well below', 'below', 'at', 'above', 'well above']);
return game;
} ( cafe || {})); | {
this.element.value = string;
} | conditional_block |
option.js | function | ( name, options ) {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) {
this.element.value = string;
}
};
this.get = function () {
return this.element.value;
};
this.callback = function ( event ) {
context.set(event.target.value);
event.stopPropagation();
};
this.listen = function() {
context.element.addEventListener('change', this.callback);
};
this.unlisten = function() {
context.element.removeEventListener('change', this.callback);
};
}
var cafe = (function ( game ) {
game.bean = new Option ( 'bean', ['gourmet', 'hipster', 'good', 'cheap', 'actual']);
game.price = new Option ('price', ['well below', 'below', 'at', 'above', 'well above']);
return game;
} ( cafe || {})); | Option | identifier_name |
option.js | function Option ( name, options ) {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) {
this.element.value = string;
}
};
this.get = function () {
return this.element.value;
};
this.callback = function ( event ) {
context.set(event.target.value);
event.stopPropagation();
};
this.listen = function() {
context.element.addEventListener('change', this.callback);
};
this.unlisten = function() {
context.element.removeEventListener('change', this.callback);
}; |
var cafe = (function ( game ) {
game.bean = new Option ( 'bean', ['gourmet', 'hipster', 'good', 'cheap', 'actual']);
game.price = new Option ('price', ['well below', 'below', 'at', 'above', 'well above']);
return game;
} ( cafe || {})); | } | random_line_split |
classify.py | # This file is part of Bioy
#
# Bioy 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.
#
# Bioy 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 Bioy. If not, see <http://www.gnu.org/licenses/>.
"""DEPRECATED: use the classifier subcommand
Classify sequences by grouping blast output by matching taxonomic names
Optional grouping by specimen and query sequences
"""
import sys
import logging
from csv import DictReader, DictWriter
from collections import defaultdict
from math import ceil
from operator import itemgetter
from bioy_pkg import sequtils
from bioy_pkg.utils import Opener, opener, Csv2Dict, groupbyl
log = logging.getLogger(__name__)
def build_parser(parser):
parser.add_argument('blast_file',
nargs = '?',
default = sys.stdin,
type = Opener('r'),
help = 'CSV tabular blast file of query and subject hits')
parser.add_argument('--all-one-group',
dest = 'all_one_group',
action = 'store_true',
help = """If --map is not provided, the default behavior is to treat
all reads as one group; use this option to treat
each read as a separate group [%(default)s]""")
parser.add_argument('-a', '--asterisk',
default = 100,
metavar='PERCENT',
type = float,
help = 'Next to any species above a certain threshold [%(default)s]')
parser.add_argument('--copy-numbers',
metavar = 'CSV',
type = Opener(),
help = 'columns: tax_id, median')
parser.add_argument('-c', '--coverage',
default = 95,
metavar = 'PERCENT',
type = float,
help = 'percent of alignment coverage of blast result [%(default)s]')
parser.add_argument('--details-identity',
metavar = 'PERCENT',
help = 'Minimum identity to include blast hits in details file',
type = float,
default = 90)
parser.add_argument('--details-full',
action = 'store_true',
help = 'do not limit out_details to only larget cluster per assignment')
parser.add_argument('--exclude-by-taxid',
metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
help = """define a group threshold for a particular rank overriding
--target-max-group-size. example: genus:2""")
parser.add_argument('--group-label',
metavar = 'LABEL',
default = 'all',
help = 'Single group label for reads')
parser.add_argument('-o', '--out',
default = sys.stdout,
type = Opener('w'),
metavar = 'CSV',
help = """columns: specimen, max_percent, min_percent, max_coverage,
min_coverage, assignment_id, assignment, clusters, reads,
pct_reads, corrected, pct_corrected, target_rank, hi, low, tax_ids""")
parser.add_argument('-m', '--map',
metavar = 'CSV',
type = Opener(),
default = {},
help = 'columns: name, specimen')
parser.add_argument('--max-ambiguous',
metavar = 'INT',
default = 3,
type = int,
help = 'Maximum ambiguous count in reference sequences [%(default)s]')
parser.add_argument('--max-identity',
default = 100,
metavar = 'PERCENT',
type = float,
help = 'maximum identity threshold for accepting matches [<= %(default)s]')
parser.add_argument('--min-cluster-size',
default = 0,
metavar = 'INT',
type = int,
help = 'minimum cluster size to include in classification output')
parser.add_argument('--min-identity',
default = 99,
metavar = 'PERCENT',
type = float,
help = 'minimum identity threshold for accepting matches [> %(default)s]')
parser.add_argument('-s', '--seq-info',
required = True,
metavar = 'CSV',
type = Opener(),
help = 'seq info file(s) to match sequence ids to taxids [%(default)s]')
parser.add_argument('-t', '--taxonomy',
required = True,
metavar = 'CSV',
type = Csv2Dict('tax_id'),
help = 'tax table of taxids and species names [%(default)s]')
parser.add_argument('-O', '--out-detail',
type = lambda f: DictWriter(opener(f, 'w'), extrasaction = 'ignore', fieldnames = [
'specimen', 'assignment', 'assignment_id', 'qseqid', 'sseqid', 'pident', 'coverage', 'ambig_count',
'accession', 'tax_id', 'tax_name', 'target_rank', 'rank', 'hi', 'low'
]),
metavar = 'CSV',
help = """columns: specimen, assignment, assignment_id,
qseqid, sseqid, pident, coverage, ambig_count,
accession, tax_id, tax_name, target_rank, rank, hi, low""")
parser.add_argument('--target-max-group-size',
metavar = 'INTEGER',
default = 3,
type = int,
help = """group multiple target-rank assignments that
excede a threshold to a higher rank [%(default)s]""")
parser.add_argument('--target-rank',
metavar='RANK',
help = 'Rank at which to classify. Default: "%(default)s"',
default = 'species')
parser.add_argument('-w', '--weights',
metavar = 'CSV',
type = Opener(),
help = 'columns: name, weight')
### csv.Sniffer.has_header is *not* reliable enough
parser.add_argument('--has-header', action = 'store_true',
help = 'specify this if blast data has a header')
def coverage(start, end, length):
return (float(end) - float(start) + 1) / float(length) * 100
def mean(l):
l = list(l)
return float(sum(l)) / len(l) if len(l) > 0 else 0
def condense(queries, floor_rank, max_size, ranks, rank_thresholds, target_rank = None):
|
def action(args):
### format format blast data and add additional available information
fieldnames = None if args.has_header else sequtils.BLAST_HEADER_DEFAULT
blast_results = DictReader(args.blast_file, fieldnames = fieldnames)
blast_results = list(blast_results)
sseqids = set(s['sseqid'] for s in blast_results)
qseqids = set(s['qseqid'] for s in blast_results)
# load seq_info and map file
mapfile = DictReader(args.map, fieldnames = ['name', 'specimen'])
mapfile = {m['name']:m['specimen'] for m in mapfile if m['name'] in qseqids}
seq_info = DictReader(args.seq_info)
seq_info = {s['seqname']:s for s in seq_info if s['seqname'] in sseqids}
# pident
def pident(b):
return dict(b, pident = float(b['pident'])) if b['sseqid'] else b
blast_results = (pident(b) for b in blast_results)
# coverage
def cov(b):
if b['sseqid'] and b['qcovs']:
b['coverage'] = float(b['qcovs'])
return b
elif b['sseqid']:
c = coverage(b['qstart'], b['qend'], b['qlen'])
return dict(b, coverage = c)
else:
return b
blast_results = (cov(b) for b in blast_results)
# seq info
def info(b):
return dict(seq_info[b['sseqid']], **b) if b['sseqid'] else b
blast_results = (info(b) for b in blast_results)
# tax info
def tax_info(b):
return dict(args.taxonomy[b['tax_id']], **b) if b['sseqid'] else b
blast_results = (tax_info(b) for b in blast_results)
### output file headers
fieldnames = ['specimen', 'max_percent', 'min_percent', 'max_coverage',
'min_coverage', 'assignment_id', 'assignment']
if args.weights:
weights = DictReader(args.weights, fieldnames = ['name', 'weight'])
weights = {d['name']:d['weight'] for d in weights if d['name'] in qseqids}
fieldnames += ['clusters', 'reads', 'pct_reads']
else:
weights = {}
if args.copy_numbers:
copy_numbers = DictReader(args.copy_numbers)
copy_numbers = {d['tax_id']:float(d['median']) for d in copy_numbers}
fieldnames += ['corrected', 'pct_corrected']
else:
copy_numbers = {}
# TODO: take out target_rank, hi, low and provide in pipeline using csvmod
# TODO: option to include tax_ids (default no)
fieldnames += ['target_rank', 'hi', 'low', 'tax_ids']
### Columns
out = DictWriter(args.out,
extrasaction = 'ignore',
fieldnames = fieldnames)
out.writeheader()
if args.out_detail:
args.out_detail.writeheader()
def blast_hit(hit, args):
return hit['sseqid'] and \
hit[args.target_rank] and \
hit['coverage'] >= args.coverage and \
float(weights.get(hit['qseqid'], 1)) >= args.min_cluster_size and \
hit[args.target_rank] not in args.exclude_by_taxid and \
hit['qseqid'] != hit['sseqid'] and \
int(hit['ambig_count']) <= args.max_ambiguous
### Rows
etc = '[no blast result]' # This row will hold all unmatched
# groups have list position prioritization
groups = [
('> {}%'.format(args.max_identity),
lambda h: blast_hit(h, args) and h['pident'] > args.max_identity),
(None,
lambda h: blast_hit(h, args) and args.max_identity >= h['pident'] > args.min_identity),
('<= {}%'.format(args.min_identity),
lambda h: blast_hit(h, args) and h['pident'] <= args.min_identity),
]
# used later for results output
group_cats = map(itemgetter(0), groups)
group_cats.append(etc)
# assignment rank thresholds
rank_thresholds = (d.split(':') for d in args.group_def)
rank_thresholds = dict((k, int(v)) for k,v in rank_thresholds)
# rt = {k: int(v) for k, v in (d.split(':') for d in args.group_def)}
# group by specimen
if args.map:
specimen_grouper = lambda s: mapfile[s['qseqid']]
elif args.all_one_group:
specimen_grouper = lambda s: args.group_label
else:
specimen_grouper = lambda s: s['qseqid']
blast_results = groupbyl(blast_results, key = specimen_grouper)
assignments = [] # assignment list for assignment ids
for specimen, hits in blast_results:
categories = defaultdict(list)
# clusters will hold the query ids as hits are matched to categories
clusters = set()
# filter out categories
for cat, fltr in groups:
matches = filter(fltr, hits)
if cat:
categories[cat] = matches
else:
# create sets of tax_rank_id
query_group = groupbyl(matches, key = itemgetter('qseqid'))
target_cats = defaultdict(list)
for _,queries in query_group:
queries = condense(
queries,
args.target_rank,
args.target_max_group_size,
sequtils.RANKS,
rank_thresholds)
cat = map(itemgetter('target_rank_id'), queries)
cat = frozenset(cat)
target_cats[cat].extend(queries)
categories = dict(categories, **target_cats)
# add query ids that were matched to a filter
clusters |= set(map(itemgetter('qseqid'), matches))
# remove all hits corresponding to a matched query id (cluster)
hits = filter(lambda h: h['qseqid'] not in clusters, hits)
# remaining hits go in the etc ('no match') category
categories[etc] = hits
# calculate read counts
read_counts = dict()
for k,v in categories.items():
qseqids = set(map(itemgetter('qseqid'), v))
weight = sum(float(weights.get(q, 1)) for q in qseqids)
read_counts[k] = weight
taxids = set()
for k,v in categories.items():
if k is not etc:
for h in v:
taxids.add(h['tax_id'])
### list of assigned ids for count corrections
assigned_ids = dict()
for k,v in categories.items():
if k is not etc and v:
assigned_ids[k] = set(map(itemgetter('tax_id'), v))
# correction counts
corrected_counts = dict()
for k,v in categories.items():
if k is not etc and v:
av = mean(copy_numbers.get(t, 1) for t in assigned_ids[k])
corrected_counts[k] = ceil(read_counts[k] / av)
# finally take the root value for the etc category
corrected_counts[etc] = ceil(read_counts[etc] / copy_numbers.get('1', 1))
# totals for percent calculations later
total_reads = sum(v for v in read_counts.values())
total_corrected = sum(v for v in corrected_counts.values())
# Print classifications per specimen sorted by # of reads in reverse (descending) order
sort_by_reads_assign = lambda (c,h): corrected_counts.get(c, None)
for cat, hits in sorted(categories.items(), key = sort_by_reads_assign, reverse = True):
# continue if their are hits
if hits:
# for incrementing assignment id's
if cat not in assignments:
assignments.append(cat)
assignment_id = assignments.index(cat)
reads = read_counts[cat]
reads_corrected = corrected_counts[cat]
clusters = set(map(itemgetter('qseqid'), hits))
results = dict(
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
specimen = specimen,
assignment_id = assignment_id,
reads = int(reads),
pct_reads = '{0:.2f}'.format(reads / total_reads * 100),
corrected = int(reads_corrected),
pct_corrected = '{0:.2f}'.format(reads_corrected / total_corrected * 100),
clusters = len(clusters))
if cat is etc:
assignment = etc
results = dict(results, assignment = assignment)
else:
taxids = set(map(itemgetter('tax_id'), hits))
coverages = set(map(itemgetter('coverage'), hits))
percents = set(map(itemgetter('pident'), hits))
if cat in group_cats:
assignment = cat
else:
names = [args.taxonomy[h['target_rank_id']]['tax_name'] for h in hits]
selectors = [h['pident'] >= args.asterisk for h in hits]
assignment = sequtils.format_taxonomy(names, selectors, '*')
results = dict(results,
assignment = assignment,
max_percent = '{0:.2f}'.format(max(percents)),
min_percent = '{0:.2f}'.format(min(percents)),
max_coverage = '{0:.2f}'.format(max(coverages)),
min_coverage = '{0:.2f}'.format(min(coverages)),
tax_ids = ' '.join(taxids))
out.writerow(results)
if args.out_detail:
if not args.details_full:
# drop the no_hits
hits = [h for h in hits if 'tax_id' in h]
# only report heaviest centroid
clusters_and_sizes = [(float(weights.get(c, 1.0)), c) for c in clusters]
_, largest = max(clusters_and_sizes)
hits = (h for h in hits if h['qseqid'] == largest)
for h in hits:
args.out_detail.writerow(dict(
specimen = specimen,
assignment = assignment,
assignment_id = assignment_id,
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
**h))
| target_rank = target_rank or ranks[0]
groups = list(groupbyl(queries, key = itemgetter(target_rank)))
num_groups = len(groups)
if rank_thresholds.get(target_rank, max_size) < num_groups:
return queries
# assign where available target_rank_ids
# groups without 'i' values remain assigned at previous (higher) rank
for g in (g for i,g in groups if i):
for q in g:
q['target_rank_id'] = q[target_rank]
# return if we hit the floor
if target_rank == floor_rank:
return queries
# else move down a rank
target_rank = ranks[ranks.index(target_rank) + 1]
# recurse down the tax tree
condensed = []
for _,g in groups:
c = condense(g, floor_rank, max_size, ranks, rank_thresholds, target_rank)
condensed.extend(c)
return condensed | identifier_body |
classify.py | # This file is part of Bioy
#
# Bioy 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.
#
# Bioy 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 Bioy. If not, see <http://www.gnu.org/licenses/>.
"""DEPRECATED: use the classifier subcommand
Classify sequences by grouping blast output by matching taxonomic names
Optional grouping by specimen and query sequences
"""
import sys
import logging
from csv import DictReader, DictWriter
from collections import defaultdict
from math import ceil
from operator import itemgetter
from bioy_pkg import sequtils
from bioy_pkg.utils import Opener, opener, Csv2Dict, groupbyl
log = logging.getLogger(__name__)
def build_parser(parser):
parser.add_argument('blast_file',
nargs = '?',
default = sys.stdin,
type = Opener('r'),
help = 'CSV tabular blast file of query and subject hits')
parser.add_argument('--all-one-group',
dest = 'all_one_group',
action = 'store_true',
help = """If --map is not provided, the default behavior is to treat
all reads as one group; use this option to treat
each read as a separate group [%(default)s]""")
parser.add_argument('-a', '--asterisk',
default = 100,
metavar='PERCENT',
type = float,
help = 'Next to any species above a certain threshold [%(default)s]')
parser.add_argument('--copy-numbers',
metavar = 'CSV',
type = Opener(),
help = 'columns: tax_id, median')
parser.add_argument('-c', '--coverage',
default = 95,
metavar = 'PERCENT',
type = float,
help = 'percent of alignment coverage of blast result [%(default)s]')
parser.add_argument('--details-identity',
metavar = 'PERCENT',
help = 'Minimum identity to include blast hits in details file',
type = float,
default = 90)
parser.add_argument('--details-full',
action = 'store_true',
help = 'do not limit out_details to only larget cluster per assignment')
parser.add_argument('--exclude-by-taxid',
metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
help = """define a group threshold for a particular rank overriding
--target-max-group-size. example: genus:2""")
parser.add_argument('--group-label',
metavar = 'LABEL',
default = 'all',
help = 'Single group label for reads')
parser.add_argument('-o', '--out',
default = sys.stdout,
type = Opener('w'),
metavar = 'CSV',
help = """columns: specimen, max_percent, min_percent, max_coverage,
min_coverage, assignment_id, assignment, clusters, reads,
pct_reads, corrected, pct_corrected, target_rank, hi, low, tax_ids""")
parser.add_argument('-m', '--map',
metavar = 'CSV',
type = Opener(),
default = {},
help = 'columns: name, specimen')
parser.add_argument('--max-ambiguous',
metavar = 'INT',
default = 3,
type = int,
help = 'Maximum ambiguous count in reference sequences [%(default)s]')
parser.add_argument('--max-identity',
default = 100,
metavar = 'PERCENT',
type = float,
help = 'maximum identity threshold for accepting matches [<= %(default)s]')
parser.add_argument('--min-cluster-size',
default = 0,
metavar = 'INT',
type = int,
help = 'minimum cluster size to include in classification output')
parser.add_argument('--min-identity',
default = 99,
metavar = 'PERCENT',
type = float,
help = 'minimum identity threshold for accepting matches [> %(default)s]')
parser.add_argument('-s', '--seq-info',
required = True,
metavar = 'CSV',
type = Opener(),
help = 'seq info file(s) to match sequence ids to taxids [%(default)s]')
parser.add_argument('-t', '--taxonomy',
required = True,
metavar = 'CSV',
type = Csv2Dict('tax_id'),
help = 'tax table of taxids and species names [%(default)s]')
parser.add_argument('-O', '--out-detail',
type = lambda f: DictWriter(opener(f, 'w'), extrasaction = 'ignore', fieldnames = [
'specimen', 'assignment', 'assignment_id', 'qseqid', 'sseqid', 'pident', 'coverage', 'ambig_count',
'accession', 'tax_id', 'tax_name', 'target_rank', 'rank', 'hi', 'low'
]),
metavar = 'CSV',
help = """columns: specimen, assignment, assignment_id,
qseqid, sseqid, pident, coverage, ambig_count,
accession, tax_id, tax_name, target_rank, rank, hi, low""")
parser.add_argument('--target-max-group-size',
metavar = 'INTEGER',
default = 3,
type = int,
help = """group multiple target-rank assignments that
excede a threshold to a higher rank [%(default)s]""")
parser.add_argument('--target-rank',
metavar='RANK',
help = 'Rank at which to classify. Default: "%(default)s"',
default = 'species')
parser.add_argument('-w', '--weights',
metavar = 'CSV',
type = Opener(),
help = 'columns: name, weight')
### csv.Sniffer.has_header is *not* reliable enough
parser.add_argument('--has-header', action = 'store_true',
help = 'specify this if blast data has a header')
def coverage(start, end, length):
return (float(end) - float(start) + 1) / float(length) * 100
def mean(l):
l = list(l)
return float(sum(l)) / len(l) if len(l) > 0 else 0
def condense(queries, floor_rank, max_size, ranks, rank_thresholds, target_rank = None):
target_rank = target_rank or ranks[0]
groups = list(groupbyl(queries, key = itemgetter(target_rank)))
num_groups = len(groups)
if rank_thresholds.get(target_rank, max_size) < num_groups:
return queries
# assign where available target_rank_ids
# groups without 'i' values remain assigned at previous (higher) rank
for g in (g for i,g in groups if i):
for q in g:
q['target_rank_id'] = q[target_rank]
# return if we hit the floor
if target_rank == floor_rank:
return queries
# else move down a rank
target_rank = ranks[ranks.index(target_rank) + 1]
# recurse down the tax tree
condensed = []
for _,g in groups:
c = condense(g, floor_rank, max_size, ranks, rank_thresholds, target_rank)
condensed.extend(c)
return condensed
def action(args):
### format format blast data and add additional available information
fieldnames = None if args.has_header else sequtils.BLAST_HEADER_DEFAULT
blast_results = DictReader(args.blast_file, fieldnames = fieldnames)
blast_results = list(blast_results)
sseqids = set(s['sseqid'] for s in blast_results)
qseqids = set(s['qseqid'] for s in blast_results)
# load seq_info and map file
mapfile = DictReader(args.map, fieldnames = ['name', 'specimen'])
mapfile = {m['name']:m['specimen'] for m in mapfile if m['name'] in qseqids}
seq_info = DictReader(args.seq_info)
seq_info = {s['seqname']:s for s in seq_info if s['seqname'] in sseqids}
# pident
def pident(b):
return dict(b, pident = float(b['pident'])) if b['sseqid'] else b
blast_results = (pident(b) for b in blast_results)
# coverage
def cov(b):
if b['sseqid'] and b['qcovs']:
b['coverage'] = float(b['qcovs'])
return b
elif b['sseqid']:
c = coverage(b['qstart'], b['qend'], b['qlen'])
return dict(b, coverage = c)
else:
return b
blast_results = (cov(b) for b in blast_results)
# seq info
def | (b):
return dict(seq_info[b['sseqid']], **b) if b['sseqid'] else b
blast_results = (info(b) for b in blast_results)
# tax info
def tax_info(b):
return dict(args.taxonomy[b['tax_id']], **b) if b['sseqid'] else b
blast_results = (tax_info(b) for b in blast_results)
### output file headers
fieldnames = ['specimen', 'max_percent', 'min_percent', 'max_coverage',
'min_coverage', 'assignment_id', 'assignment']
if args.weights:
weights = DictReader(args.weights, fieldnames = ['name', 'weight'])
weights = {d['name']:d['weight'] for d in weights if d['name'] in qseqids}
fieldnames += ['clusters', 'reads', 'pct_reads']
else:
weights = {}
if args.copy_numbers:
copy_numbers = DictReader(args.copy_numbers)
copy_numbers = {d['tax_id']:float(d['median']) for d in copy_numbers}
fieldnames += ['corrected', 'pct_corrected']
else:
copy_numbers = {}
# TODO: take out target_rank, hi, low and provide in pipeline using csvmod
# TODO: option to include tax_ids (default no)
fieldnames += ['target_rank', 'hi', 'low', 'tax_ids']
### Columns
out = DictWriter(args.out,
extrasaction = 'ignore',
fieldnames = fieldnames)
out.writeheader()
if args.out_detail:
args.out_detail.writeheader()
def blast_hit(hit, args):
return hit['sseqid'] and \
hit[args.target_rank] and \
hit['coverage'] >= args.coverage and \
float(weights.get(hit['qseqid'], 1)) >= args.min_cluster_size and \
hit[args.target_rank] not in args.exclude_by_taxid and \
hit['qseqid'] != hit['sseqid'] and \
int(hit['ambig_count']) <= args.max_ambiguous
### Rows
etc = '[no blast result]' # This row will hold all unmatched
# groups have list position prioritization
groups = [
('> {}%'.format(args.max_identity),
lambda h: blast_hit(h, args) and h['pident'] > args.max_identity),
(None,
lambda h: blast_hit(h, args) and args.max_identity >= h['pident'] > args.min_identity),
('<= {}%'.format(args.min_identity),
lambda h: blast_hit(h, args) and h['pident'] <= args.min_identity),
]
# used later for results output
group_cats = map(itemgetter(0), groups)
group_cats.append(etc)
# assignment rank thresholds
rank_thresholds = (d.split(':') for d in args.group_def)
rank_thresholds = dict((k, int(v)) for k,v in rank_thresholds)
# rt = {k: int(v) for k, v in (d.split(':') for d in args.group_def)}
# group by specimen
if args.map:
specimen_grouper = lambda s: mapfile[s['qseqid']]
elif args.all_one_group:
specimen_grouper = lambda s: args.group_label
else:
specimen_grouper = lambda s: s['qseqid']
blast_results = groupbyl(blast_results, key = specimen_grouper)
assignments = [] # assignment list for assignment ids
for specimen, hits in blast_results:
categories = defaultdict(list)
# clusters will hold the query ids as hits are matched to categories
clusters = set()
# filter out categories
for cat, fltr in groups:
matches = filter(fltr, hits)
if cat:
categories[cat] = matches
else:
# create sets of tax_rank_id
query_group = groupbyl(matches, key = itemgetter('qseqid'))
target_cats = defaultdict(list)
for _,queries in query_group:
queries = condense(
queries,
args.target_rank,
args.target_max_group_size,
sequtils.RANKS,
rank_thresholds)
cat = map(itemgetter('target_rank_id'), queries)
cat = frozenset(cat)
target_cats[cat].extend(queries)
categories = dict(categories, **target_cats)
# add query ids that were matched to a filter
clusters |= set(map(itemgetter('qseqid'), matches))
# remove all hits corresponding to a matched query id (cluster)
hits = filter(lambda h: h['qseqid'] not in clusters, hits)
# remaining hits go in the etc ('no match') category
categories[etc] = hits
# calculate read counts
read_counts = dict()
for k,v in categories.items():
qseqids = set(map(itemgetter('qseqid'), v))
weight = sum(float(weights.get(q, 1)) for q in qseqids)
read_counts[k] = weight
taxids = set()
for k,v in categories.items():
if k is not etc:
for h in v:
taxids.add(h['tax_id'])
### list of assigned ids for count corrections
assigned_ids = dict()
for k,v in categories.items():
if k is not etc and v:
assigned_ids[k] = set(map(itemgetter('tax_id'), v))
# correction counts
corrected_counts = dict()
for k,v in categories.items():
if k is not etc and v:
av = mean(copy_numbers.get(t, 1) for t in assigned_ids[k])
corrected_counts[k] = ceil(read_counts[k] / av)
# finally take the root value for the etc category
corrected_counts[etc] = ceil(read_counts[etc] / copy_numbers.get('1', 1))
# totals for percent calculations later
total_reads = sum(v for v in read_counts.values())
total_corrected = sum(v for v in corrected_counts.values())
# Print classifications per specimen sorted by # of reads in reverse (descending) order
sort_by_reads_assign = lambda (c,h): corrected_counts.get(c, None)
for cat, hits in sorted(categories.items(), key = sort_by_reads_assign, reverse = True):
# continue if their are hits
if hits:
# for incrementing assignment id's
if cat not in assignments:
assignments.append(cat)
assignment_id = assignments.index(cat)
reads = read_counts[cat]
reads_corrected = corrected_counts[cat]
clusters = set(map(itemgetter('qseqid'), hits))
results = dict(
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
specimen = specimen,
assignment_id = assignment_id,
reads = int(reads),
pct_reads = '{0:.2f}'.format(reads / total_reads * 100),
corrected = int(reads_corrected),
pct_corrected = '{0:.2f}'.format(reads_corrected / total_corrected * 100),
clusters = len(clusters))
if cat is etc:
assignment = etc
results = dict(results, assignment = assignment)
else:
taxids = set(map(itemgetter('tax_id'), hits))
coverages = set(map(itemgetter('coverage'), hits))
percents = set(map(itemgetter('pident'), hits))
if cat in group_cats:
assignment = cat
else:
names = [args.taxonomy[h['target_rank_id']]['tax_name'] for h in hits]
selectors = [h['pident'] >= args.asterisk for h in hits]
assignment = sequtils.format_taxonomy(names, selectors, '*')
results = dict(results,
assignment = assignment,
max_percent = '{0:.2f}'.format(max(percents)),
min_percent = '{0:.2f}'.format(min(percents)),
max_coverage = '{0:.2f}'.format(max(coverages)),
min_coverage = '{0:.2f}'.format(min(coverages)),
tax_ids = ' '.join(taxids))
out.writerow(results)
if args.out_detail:
if not args.details_full:
# drop the no_hits
hits = [h for h in hits if 'tax_id' in h]
# only report heaviest centroid
clusters_and_sizes = [(float(weights.get(c, 1.0)), c) for c in clusters]
_, largest = max(clusters_and_sizes)
hits = (h for h in hits if h['qseqid'] == largest)
for h in hits:
args.out_detail.writerow(dict(
specimen = specimen,
assignment = assignment,
assignment_id = assignment_id,
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
**h))
| info | identifier_name |
classify.py | # This file is part of Bioy
#
# Bioy 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.
#
# Bioy 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 Bioy. If not, see <http://www.gnu.org/licenses/>.
"""DEPRECATED: use the classifier subcommand
Classify sequences by grouping blast output by matching taxonomic names
Optional grouping by specimen and query sequences
"""
import sys
import logging
from csv import DictReader, DictWriter
from collections import defaultdict
from math import ceil
from operator import itemgetter
from bioy_pkg import sequtils
from bioy_pkg.utils import Opener, opener, Csv2Dict, groupbyl
log = logging.getLogger(__name__)
def build_parser(parser):
parser.add_argument('blast_file',
nargs = '?',
default = sys.stdin,
type = Opener('r'),
help = 'CSV tabular blast file of query and subject hits')
parser.add_argument('--all-one-group',
dest = 'all_one_group',
action = 'store_true',
help = """If --map is not provided, the default behavior is to treat
all reads as one group; use this option to treat
each read as a separate group [%(default)s]""")
parser.add_argument('-a', '--asterisk',
default = 100,
metavar='PERCENT',
type = float,
help = 'Next to any species above a certain threshold [%(default)s]')
parser.add_argument('--copy-numbers',
metavar = 'CSV',
type = Opener(),
help = 'columns: tax_id, median')
parser.add_argument('-c', '--coverage',
default = 95,
metavar = 'PERCENT',
type = float,
help = 'percent of alignment coverage of blast result [%(default)s]')
parser.add_argument('--details-identity',
metavar = 'PERCENT',
help = 'Minimum identity to include blast hits in details file',
type = float,
default = 90)
parser.add_argument('--details-full',
action = 'store_true',
help = 'do not limit out_details to only larget cluster per assignment')
parser.add_argument('--exclude-by-taxid',
metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
help = """define a group threshold for a particular rank overriding
--target-max-group-size. example: genus:2""")
parser.add_argument('--group-label',
metavar = 'LABEL',
default = 'all',
help = 'Single group label for reads')
parser.add_argument('-o', '--out',
default = sys.stdout,
type = Opener('w'),
metavar = 'CSV',
help = """columns: specimen, max_percent, min_percent, max_coverage,
min_coverage, assignment_id, assignment, clusters, reads,
pct_reads, corrected, pct_corrected, target_rank, hi, low, tax_ids""")
parser.add_argument('-m', '--map',
metavar = 'CSV',
type = Opener(),
default = {},
help = 'columns: name, specimen')
parser.add_argument('--max-ambiguous',
metavar = 'INT',
default = 3,
type = int,
help = 'Maximum ambiguous count in reference sequences [%(default)s]')
parser.add_argument('--max-identity',
default = 100,
metavar = 'PERCENT',
type = float,
help = 'maximum identity threshold for accepting matches [<= %(default)s]')
parser.add_argument('--min-cluster-size',
default = 0,
metavar = 'INT',
type = int,
help = 'minimum cluster size to include in classification output')
parser.add_argument('--min-identity',
default = 99,
metavar = 'PERCENT',
type = float,
help = 'minimum identity threshold for accepting matches [> %(default)s]')
parser.add_argument('-s', '--seq-info',
required = True,
metavar = 'CSV',
type = Opener(),
help = 'seq info file(s) to match sequence ids to taxids [%(default)s]')
parser.add_argument('-t', '--taxonomy',
required = True,
metavar = 'CSV',
type = Csv2Dict('tax_id'),
help = 'tax table of taxids and species names [%(default)s]')
parser.add_argument('-O', '--out-detail',
type = lambda f: DictWriter(opener(f, 'w'), extrasaction = 'ignore', fieldnames = [
'specimen', 'assignment', 'assignment_id', 'qseqid', 'sseqid', 'pident', 'coverage', 'ambig_count',
'accession', 'tax_id', 'tax_name', 'target_rank', 'rank', 'hi', 'low'
]),
metavar = 'CSV',
help = """columns: specimen, assignment, assignment_id,
qseqid, sseqid, pident, coverage, ambig_count,
accession, tax_id, tax_name, target_rank, rank, hi, low""")
parser.add_argument('--target-max-group-size',
metavar = 'INTEGER',
default = 3,
type = int,
help = """group multiple target-rank assignments that
excede a threshold to a higher rank [%(default)s]""")
parser.add_argument('--target-rank',
metavar='RANK',
help = 'Rank at which to classify. Default: "%(default)s"',
default = 'species')
parser.add_argument('-w', '--weights',
metavar = 'CSV',
type = Opener(),
help = 'columns: name, weight')
### csv.Sniffer.has_header is *not* reliable enough
parser.add_argument('--has-header', action = 'store_true',
help = 'specify this if blast data has a header')
def coverage(start, end, length):
return (float(end) - float(start) + 1) / float(length) * 100
def mean(l):
l = list(l)
return float(sum(l)) / len(l) if len(l) > 0 else 0
def condense(queries, floor_rank, max_size, ranks, rank_thresholds, target_rank = None):
target_rank = target_rank or ranks[0]
groups = list(groupbyl(queries, key = itemgetter(target_rank)))
num_groups = len(groups)
if rank_thresholds.get(target_rank, max_size) < num_groups:
return queries
# assign where available target_rank_ids
# groups without 'i' values remain assigned at previous (higher) rank
for g in (g for i,g in groups if i):
for q in g:
q['target_rank_id'] = q[target_rank]
# return if we hit the floor
if target_rank == floor_rank:
return queries
# else move down a rank
target_rank = ranks[ranks.index(target_rank) + 1]
# recurse down the tax tree
condensed = []
for _,g in groups:
c = condense(g, floor_rank, max_size, ranks, rank_thresholds, target_rank)
condensed.extend(c)
return condensed
def action(args):
### format format blast data and add additional available information
fieldnames = None if args.has_header else sequtils.BLAST_HEADER_DEFAULT
blast_results = DictReader(args.blast_file, fieldnames = fieldnames)
blast_results = list(blast_results)
sseqids = set(s['sseqid'] for s in blast_results)
qseqids = set(s['qseqid'] for s in blast_results)
# load seq_info and map file
mapfile = DictReader(args.map, fieldnames = ['name', 'specimen'])
mapfile = {m['name']:m['specimen'] for m in mapfile if m['name'] in qseqids}
seq_info = DictReader(args.seq_info)
seq_info = {s['seqname']:s for s in seq_info if s['seqname'] in sseqids}
# pident
def pident(b):
return dict(b, pident = float(b['pident'])) if b['sseqid'] else b
blast_results = (pident(b) for b in blast_results)
# coverage
def cov(b):
if b['sseqid'] and b['qcovs']:
b['coverage'] = float(b['qcovs'])
return b
elif b['sseqid']:
c = coverage(b['qstart'], b['qend'], b['qlen'])
return dict(b, coverage = c)
else:
return b
blast_results = (cov(b) for b in blast_results)
# seq info
def info(b):
return dict(seq_info[b['sseqid']], **b) if b['sseqid'] else b
blast_results = (info(b) for b in blast_results)
# tax info
def tax_info(b):
return dict(args.taxonomy[b['tax_id']], **b) if b['sseqid'] else b
blast_results = (tax_info(b) for b in blast_results)
### output file headers
fieldnames = ['specimen', 'max_percent', 'min_percent', 'max_coverage',
'min_coverage', 'assignment_id', 'assignment']
if args.weights:
weights = DictReader(args.weights, fieldnames = ['name', 'weight'])
weights = {d['name']:d['weight'] for d in weights if d['name'] in qseqids}
fieldnames += ['clusters', 'reads', 'pct_reads']
else:
weights = {}
if args.copy_numbers:
copy_numbers = DictReader(args.copy_numbers)
copy_numbers = {d['tax_id']:float(d['median']) for d in copy_numbers}
fieldnames += ['corrected', 'pct_corrected']
else:
copy_numbers = {}
# TODO: take out target_rank, hi, low and provide in pipeline using csvmod
# TODO: option to include tax_ids (default no)
fieldnames += ['target_rank', 'hi', 'low', 'tax_ids']
### Columns
out = DictWriter(args.out,
extrasaction = 'ignore',
fieldnames = fieldnames)
out.writeheader()
if args.out_detail:
args.out_detail.writeheader()
def blast_hit(hit, args):
return hit['sseqid'] and \
hit[args.target_rank] and \
hit['coverage'] >= args.coverage and \
float(weights.get(hit['qseqid'], 1)) >= args.min_cluster_size and \
hit[args.target_rank] not in args.exclude_by_taxid and \
hit['qseqid'] != hit['sseqid'] and \
int(hit['ambig_count']) <= args.max_ambiguous
### Rows
etc = '[no blast result]' # This row will hold all unmatched
| groups = [
('> {}%'.format(args.max_identity),
lambda h: blast_hit(h, args) and h['pident'] > args.max_identity),
(None,
lambda h: blast_hit(h, args) and args.max_identity >= h['pident'] > args.min_identity),
('<= {}%'.format(args.min_identity),
lambda h: blast_hit(h, args) and h['pident'] <= args.min_identity),
]
# used later for results output
group_cats = map(itemgetter(0), groups)
group_cats.append(etc)
# assignment rank thresholds
rank_thresholds = (d.split(':') for d in args.group_def)
rank_thresholds = dict((k, int(v)) for k,v in rank_thresholds)
# rt = {k: int(v) for k, v in (d.split(':') for d in args.group_def)}
# group by specimen
if args.map:
specimen_grouper = lambda s: mapfile[s['qseqid']]
elif args.all_one_group:
specimen_grouper = lambda s: args.group_label
else:
specimen_grouper = lambda s: s['qseqid']
blast_results = groupbyl(blast_results, key = specimen_grouper)
assignments = [] # assignment list for assignment ids
for specimen, hits in blast_results:
categories = defaultdict(list)
# clusters will hold the query ids as hits are matched to categories
clusters = set()
# filter out categories
for cat, fltr in groups:
matches = filter(fltr, hits)
if cat:
categories[cat] = matches
else:
# create sets of tax_rank_id
query_group = groupbyl(matches, key = itemgetter('qseqid'))
target_cats = defaultdict(list)
for _,queries in query_group:
queries = condense(
queries,
args.target_rank,
args.target_max_group_size,
sequtils.RANKS,
rank_thresholds)
cat = map(itemgetter('target_rank_id'), queries)
cat = frozenset(cat)
target_cats[cat].extend(queries)
categories = dict(categories, **target_cats)
# add query ids that were matched to a filter
clusters |= set(map(itemgetter('qseqid'), matches))
# remove all hits corresponding to a matched query id (cluster)
hits = filter(lambda h: h['qseqid'] not in clusters, hits)
# remaining hits go in the etc ('no match') category
categories[etc] = hits
# calculate read counts
read_counts = dict()
for k,v in categories.items():
qseqids = set(map(itemgetter('qseqid'), v))
weight = sum(float(weights.get(q, 1)) for q in qseqids)
read_counts[k] = weight
taxids = set()
for k,v in categories.items():
if k is not etc:
for h in v:
taxids.add(h['tax_id'])
### list of assigned ids for count corrections
assigned_ids = dict()
for k,v in categories.items():
if k is not etc and v:
assigned_ids[k] = set(map(itemgetter('tax_id'), v))
# correction counts
corrected_counts = dict()
for k,v in categories.items():
if k is not etc and v:
av = mean(copy_numbers.get(t, 1) for t in assigned_ids[k])
corrected_counts[k] = ceil(read_counts[k] / av)
# finally take the root value for the etc category
corrected_counts[etc] = ceil(read_counts[etc] / copy_numbers.get('1', 1))
# totals for percent calculations later
total_reads = sum(v for v in read_counts.values())
total_corrected = sum(v for v in corrected_counts.values())
# Print classifications per specimen sorted by # of reads in reverse (descending) order
sort_by_reads_assign = lambda (c,h): corrected_counts.get(c, None)
for cat, hits in sorted(categories.items(), key = sort_by_reads_assign, reverse = True):
# continue if their are hits
if hits:
# for incrementing assignment id's
if cat not in assignments:
assignments.append(cat)
assignment_id = assignments.index(cat)
reads = read_counts[cat]
reads_corrected = corrected_counts[cat]
clusters = set(map(itemgetter('qseqid'), hits))
results = dict(
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
specimen = specimen,
assignment_id = assignment_id,
reads = int(reads),
pct_reads = '{0:.2f}'.format(reads / total_reads * 100),
corrected = int(reads_corrected),
pct_corrected = '{0:.2f}'.format(reads_corrected / total_corrected * 100),
clusters = len(clusters))
if cat is etc:
assignment = etc
results = dict(results, assignment = assignment)
else:
taxids = set(map(itemgetter('tax_id'), hits))
coverages = set(map(itemgetter('coverage'), hits))
percents = set(map(itemgetter('pident'), hits))
if cat in group_cats:
assignment = cat
else:
names = [args.taxonomy[h['target_rank_id']]['tax_name'] for h in hits]
selectors = [h['pident'] >= args.asterisk for h in hits]
assignment = sequtils.format_taxonomy(names, selectors, '*')
results = dict(results,
assignment = assignment,
max_percent = '{0:.2f}'.format(max(percents)),
min_percent = '{0:.2f}'.format(min(percents)),
max_coverage = '{0:.2f}'.format(max(coverages)),
min_coverage = '{0:.2f}'.format(min(coverages)),
tax_ids = ' '.join(taxids))
out.writerow(results)
if args.out_detail:
if not args.details_full:
# drop the no_hits
hits = [h for h in hits if 'tax_id' in h]
# only report heaviest centroid
clusters_and_sizes = [(float(weights.get(c, 1.0)), c) for c in clusters]
_, largest = max(clusters_and_sizes)
hits = (h for h in hits if h['qseqid'] == largest)
for h in hits:
args.out_detail.writerow(dict(
specimen = specimen,
assignment = assignment,
assignment_id = assignment_id,
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
**h)) | # groups have list position prioritization | random_line_split |
classify.py | # This file is part of Bioy
#
# Bioy 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.
#
# Bioy 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 Bioy. If not, see <http://www.gnu.org/licenses/>.
"""DEPRECATED: use the classifier subcommand
Classify sequences by grouping blast output by matching taxonomic names
Optional grouping by specimen and query sequences
"""
import sys
import logging
from csv import DictReader, DictWriter
from collections import defaultdict
from math import ceil
from operator import itemgetter
from bioy_pkg import sequtils
from bioy_pkg.utils import Opener, opener, Csv2Dict, groupbyl
log = logging.getLogger(__name__)
def build_parser(parser):
parser.add_argument('blast_file',
nargs = '?',
default = sys.stdin,
type = Opener('r'),
help = 'CSV tabular blast file of query and subject hits')
parser.add_argument('--all-one-group',
dest = 'all_one_group',
action = 'store_true',
help = """If --map is not provided, the default behavior is to treat
all reads as one group; use this option to treat
each read as a separate group [%(default)s]""")
parser.add_argument('-a', '--asterisk',
default = 100,
metavar='PERCENT',
type = float,
help = 'Next to any species above a certain threshold [%(default)s]')
parser.add_argument('--copy-numbers',
metavar = 'CSV',
type = Opener(),
help = 'columns: tax_id, median')
parser.add_argument('-c', '--coverage',
default = 95,
metavar = 'PERCENT',
type = float,
help = 'percent of alignment coverage of blast result [%(default)s]')
parser.add_argument('--details-identity',
metavar = 'PERCENT',
help = 'Minimum identity to include blast hits in details file',
type = float,
default = 90)
parser.add_argument('--details-full',
action = 'store_true',
help = 'do not limit out_details to only larget cluster per assignment')
parser.add_argument('--exclude-by-taxid',
metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
help = """define a group threshold for a particular rank overriding
--target-max-group-size. example: genus:2""")
parser.add_argument('--group-label',
metavar = 'LABEL',
default = 'all',
help = 'Single group label for reads')
parser.add_argument('-o', '--out',
default = sys.stdout,
type = Opener('w'),
metavar = 'CSV',
help = """columns: specimen, max_percent, min_percent, max_coverage,
min_coverage, assignment_id, assignment, clusters, reads,
pct_reads, corrected, pct_corrected, target_rank, hi, low, tax_ids""")
parser.add_argument('-m', '--map',
metavar = 'CSV',
type = Opener(),
default = {},
help = 'columns: name, specimen')
parser.add_argument('--max-ambiguous',
metavar = 'INT',
default = 3,
type = int,
help = 'Maximum ambiguous count in reference sequences [%(default)s]')
parser.add_argument('--max-identity',
default = 100,
metavar = 'PERCENT',
type = float,
help = 'maximum identity threshold for accepting matches [<= %(default)s]')
parser.add_argument('--min-cluster-size',
default = 0,
metavar = 'INT',
type = int,
help = 'minimum cluster size to include in classification output')
parser.add_argument('--min-identity',
default = 99,
metavar = 'PERCENT',
type = float,
help = 'minimum identity threshold for accepting matches [> %(default)s]')
parser.add_argument('-s', '--seq-info',
required = True,
metavar = 'CSV',
type = Opener(),
help = 'seq info file(s) to match sequence ids to taxids [%(default)s]')
parser.add_argument('-t', '--taxonomy',
required = True,
metavar = 'CSV',
type = Csv2Dict('tax_id'),
help = 'tax table of taxids and species names [%(default)s]')
parser.add_argument('-O', '--out-detail',
type = lambda f: DictWriter(opener(f, 'w'), extrasaction = 'ignore', fieldnames = [
'specimen', 'assignment', 'assignment_id', 'qseqid', 'sseqid', 'pident', 'coverage', 'ambig_count',
'accession', 'tax_id', 'tax_name', 'target_rank', 'rank', 'hi', 'low'
]),
metavar = 'CSV',
help = """columns: specimen, assignment, assignment_id,
qseqid, sseqid, pident, coverage, ambig_count,
accession, tax_id, tax_name, target_rank, rank, hi, low""")
parser.add_argument('--target-max-group-size',
metavar = 'INTEGER',
default = 3,
type = int,
help = """group multiple target-rank assignments that
excede a threshold to a higher rank [%(default)s]""")
parser.add_argument('--target-rank',
metavar='RANK',
help = 'Rank at which to classify. Default: "%(default)s"',
default = 'species')
parser.add_argument('-w', '--weights',
metavar = 'CSV',
type = Opener(),
help = 'columns: name, weight')
### csv.Sniffer.has_header is *not* reliable enough
parser.add_argument('--has-header', action = 'store_true',
help = 'specify this if blast data has a header')
def coverage(start, end, length):
return (float(end) - float(start) + 1) / float(length) * 100
def mean(l):
l = list(l)
return float(sum(l)) / len(l) if len(l) > 0 else 0
def condense(queries, floor_rank, max_size, ranks, rank_thresholds, target_rank = None):
target_rank = target_rank or ranks[0]
groups = list(groupbyl(queries, key = itemgetter(target_rank)))
num_groups = len(groups)
if rank_thresholds.get(target_rank, max_size) < num_groups:
return queries
# assign where available target_rank_ids
# groups without 'i' values remain assigned at previous (higher) rank
for g in (g for i,g in groups if i):
for q in g:
q['target_rank_id'] = q[target_rank]
# return if we hit the floor
if target_rank == floor_rank:
return queries
# else move down a rank
target_rank = ranks[ranks.index(target_rank) + 1]
# recurse down the tax tree
condensed = []
for _,g in groups:
c = condense(g, floor_rank, max_size, ranks, rank_thresholds, target_rank)
condensed.extend(c)
return condensed
def action(args):
### format format blast data and add additional available information
fieldnames = None if args.has_header else sequtils.BLAST_HEADER_DEFAULT
blast_results = DictReader(args.blast_file, fieldnames = fieldnames)
blast_results = list(blast_results)
sseqids = set(s['sseqid'] for s in blast_results)
qseqids = set(s['qseqid'] for s in blast_results)
# load seq_info and map file
mapfile = DictReader(args.map, fieldnames = ['name', 'specimen'])
mapfile = {m['name']:m['specimen'] for m in mapfile if m['name'] in qseqids}
seq_info = DictReader(args.seq_info)
seq_info = {s['seqname']:s for s in seq_info if s['seqname'] in sseqids}
# pident
def pident(b):
return dict(b, pident = float(b['pident'])) if b['sseqid'] else b
blast_results = (pident(b) for b in blast_results)
# coverage
def cov(b):
if b['sseqid'] and b['qcovs']:
b['coverage'] = float(b['qcovs'])
return b
elif b['sseqid']:
c = coverage(b['qstart'], b['qend'], b['qlen'])
return dict(b, coverage = c)
else:
return b
blast_results = (cov(b) for b in blast_results)
# seq info
def info(b):
return dict(seq_info[b['sseqid']], **b) if b['sseqid'] else b
blast_results = (info(b) for b in blast_results)
# tax info
def tax_info(b):
return dict(args.taxonomy[b['tax_id']], **b) if b['sseqid'] else b
blast_results = (tax_info(b) for b in blast_results)
### output file headers
fieldnames = ['specimen', 'max_percent', 'min_percent', 'max_coverage',
'min_coverage', 'assignment_id', 'assignment']
if args.weights:
weights = DictReader(args.weights, fieldnames = ['name', 'weight'])
weights = {d['name']:d['weight'] for d in weights if d['name'] in qseqids}
fieldnames += ['clusters', 'reads', 'pct_reads']
else:
weights = {}
if args.copy_numbers:
copy_numbers = DictReader(args.copy_numbers)
copy_numbers = {d['tax_id']:float(d['median']) for d in copy_numbers}
fieldnames += ['corrected', 'pct_corrected']
else:
copy_numbers = {}
# TODO: take out target_rank, hi, low and provide in pipeline using csvmod
# TODO: option to include tax_ids (default no)
fieldnames += ['target_rank', 'hi', 'low', 'tax_ids']
### Columns
out = DictWriter(args.out,
extrasaction = 'ignore',
fieldnames = fieldnames)
out.writeheader()
if args.out_detail:
args.out_detail.writeheader()
def blast_hit(hit, args):
return hit['sseqid'] and \
hit[args.target_rank] and \
hit['coverage'] >= args.coverage and \
float(weights.get(hit['qseqid'], 1)) >= args.min_cluster_size and \
hit[args.target_rank] not in args.exclude_by_taxid and \
hit['qseqid'] != hit['sseqid'] and \
int(hit['ambig_count']) <= args.max_ambiguous
### Rows
etc = '[no blast result]' # This row will hold all unmatched
# groups have list position prioritization
groups = [
('> {}%'.format(args.max_identity),
lambda h: blast_hit(h, args) and h['pident'] > args.max_identity),
(None,
lambda h: blast_hit(h, args) and args.max_identity >= h['pident'] > args.min_identity),
('<= {}%'.format(args.min_identity),
lambda h: blast_hit(h, args) and h['pident'] <= args.min_identity),
]
# used later for results output
group_cats = map(itemgetter(0), groups)
group_cats.append(etc)
# assignment rank thresholds
rank_thresholds = (d.split(':') for d in args.group_def)
rank_thresholds = dict((k, int(v)) for k,v in rank_thresholds)
# rt = {k: int(v) for k, v in (d.split(':') for d in args.group_def)}
# group by specimen
if args.map:
specimen_grouper = lambda s: mapfile[s['qseqid']]
elif args.all_one_group:
specimen_grouper = lambda s: args.group_label
else:
specimen_grouper = lambda s: s['qseqid']
blast_results = groupbyl(blast_results, key = specimen_grouper)
assignments = [] # assignment list for assignment ids
for specimen, hits in blast_results:
categories = defaultdict(list)
# clusters will hold the query ids as hits are matched to categories
clusters = set()
# filter out categories
for cat, fltr in groups:
matches = filter(fltr, hits)
if cat:
categories[cat] = matches
else:
# create sets of tax_rank_id
query_group = groupbyl(matches, key = itemgetter('qseqid'))
target_cats = defaultdict(list)
for _,queries in query_group:
queries = condense(
queries,
args.target_rank,
args.target_max_group_size,
sequtils.RANKS,
rank_thresholds)
cat = map(itemgetter('target_rank_id'), queries)
cat = frozenset(cat)
target_cats[cat].extend(queries)
categories = dict(categories, **target_cats)
# add query ids that were matched to a filter
clusters |= set(map(itemgetter('qseqid'), matches))
# remove all hits corresponding to a matched query id (cluster)
hits = filter(lambda h: h['qseqid'] not in clusters, hits)
# remaining hits go in the etc ('no match') category
categories[etc] = hits
# calculate read counts
read_counts = dict()
for k,v in categories.items():
qseqids = set(map(itemgetter('qseqid'), v))
weight = sum(float(weights.get(q, 1)) for q in qseqids)
read_counts[k] = weight
taxids = set()
for k,v in categories.items():
if k is not etc:
for h in v:
taxids.add(h['tax_id'])
### list of assigned ids for count corrections
assigned_ids = dict()
for k,v in categories.items():
if k is not etc and v:
assigned_ids[k] = set(map(itemgetter('tax_id'), v))
# correction counts
corrected_counts = dict()
for k,v in categories.items():
if k is not etc and v:
av = mean(copy_numbers.get(t, 1) for t in assigned_ids[k])
corrected_counts[k] = ceil(read_counts[k] / av)
# finally take the root value for the etc category
corrected_counts[etc] = ceil(read_counts[etc] / copy_numbers.get('1', 1))
# totals for percent calculations later
total_reads = sum(v for v in read_counts.values())
total_corrected = sum(v for v in corrected_counts.values())
# Print classifications per specimen sorted by # of reads in reverse (descending) order
sort_by_reads_assign = lambda (c,h): corrected_counts.get(c, None)
for cat, hits in sorted(categories.items(), key = sort_by_reads_assign, reverse = True):
# continue if their are hits
if hits:
# for incrementing assignment id's
if cat not in assignments:
assignments.append(cat)
assignment_id = assignments.index(cat)
reads = read_counts[cat]
reads_corrected = corrected_counts[cat]
clusters = set(map(itemgetter('qseqid'), hits))
results = dict(
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
specimen = specimen,
assignment_id = assignment_id,
reads = int(reads),
pct_reads = '{0:.2f}'.format(reads / total_reads * 100),
corrected = int(reads_corrected),
pct_corrected = '{0:.2f}'.format(reads_corrected / total_corrected * 100),
clusters = len(clusters))
if cat is etc:
assignment = etc
results = dict(results, assignment = assignment)
else:
taxids = set(map(itemgetter('tax_id'), hits))
coverages = set(map(itemgetter('coverage'), hits))
percents = set(map(itemgetter('pident'), hits))
if cat in group_cats:
assignment = cat
else:
names = [args.taxonomy[h['target_rank_id']]['tax_name'] for h in hits]
selectors = [h['pident'] >= args.asterisk for h in hits]
assignment = sequtils.format_taxonomy(names, selectors, '*')
results = dict(results,
assignment = assignment,
max_percent = '{0:.2f}'.format(max(percents)),
min_percent = '{0:.2f}'.format(min(percents)),
max_coverage = '{0:.2f}'.format(max(coverages)),
min_coverage = '{0:.2f}'.format(min(coverages)),
tax_ids = ' '.join(taxids))
out.writerow(results)
if args.out_detail:
if not args.details_full:
# drop the no_hits
hits = [h for h in hits if 'tax_id' in h]
# only report heaviest centroid
clusters_and_sizes = [(float(weights.get(c, 1.0)), c) for c in clusters]
_, largest = max(clusters_and_sizes)
hits = (h for h in hits if h['qseqid'] == largest)
for h in hits:
| args.out_detail.writerow(dict(
specimen = specimen,
assignment = assignment,
assignment_id = assignment_id,
hi = args.max_identity,
low = args.min_identity,
target_rank = args.target_rank,
**h)) | conditional_block | |
HomeController.ts | 'use strict';
// Import certain style elements here so that webpack picks them up
import '@fortawesome/fontawesome-free/js/all';
import { StateOrName, StateParams, StateService } from '@uirouter/core';
import angular, { IController, IRootScopeService } from 'angular';
import '../../../../public/sass/theme.scss';
import { IAuthenticationService } from '../../../users/client/services/AuthenticationService';
import '../css/bl_checkbox.css';
import '../css/core.css';
class HomeController implements IController {
public static $inject = ['AuthenticationService', '$state', '$rootScope'];
public isUser: boolean;
constructor(private AuthenticationService: IAuthenticationService, private $state: StateService, private $rootScope: IRootScopeService) {
this.isUser = !!this.AuthenticationService.user;
if (sessionStorage.prevState) |
}
}
angular.module('core').controller('HomeController', HomeController);
| {
const prevState = sessionStorage.prevState as StateOrName;
const prevParams = JSON.parse(sessionStorage.prevParams) as StateParams;
delete sessionStorage.prevState;
delete sessionStorage.prevParams;
this.$state.go(prevState, prevParams);
} | conditional_block |
HomeController.ts | 'use strict';
// Import certain style elements here so that webpack picks them up
import '@fortawesome/fontawesome-free/js/all';
import { StateOrName, StateParams, StateService } from '@uirouter/core';
import angular, { IController, IRootScopeService } from 'angular';
import '../../../../public/sass/theme.scss';
import { IAuthenticationService } from '../../../users/client/services/AuthenticationService';
import '../css/bl_checkbox.css';
import '../css/core.css';
class HomeController implements IController {
public static $inject = ['AuthenticationService', '$state', '$rootScope'];
public isUser: boolean;
| const prevState = sessionStorage.prevState as StateOrName;
const prevParams = JSON.parse(sessionStorage.prevParams) as StateParams;
delete sessionStorage.prevState;
delete sessionStorage.prevParams;
this.$state.go(prevState, prevParams);
}
}
}
angular.module('core').controller('HomeController', HomeController); | constructor(private AuthenticationService: IAuthenticationService, private $state: StateService, private $rootScope: IRootScopeService) {
this.isUser = !!this.AuthenticationService.user;
if (sessionStorage.prevState) { | random_line_split |
HomeController.ts | 'use strict';
// Import certain style elements here so that webpack picks them up
import '@fortawesome/fontawesome-free/js/all';
import { StateOrName, StateParams, StateService } from '@uirouter/core';
import angular, { IController, IRootScopeService } from 'angular';
import '../../../../public/sass/theme.scss';
import { IAuthenticationService } from '../../../users/client/services/AuthenticationService';
import '../css/bl_checkbox.css';
import '../css/core.css';
class HomeController implements IController {
public static $inject = ['AuthenticationService', '$state', '$rootScope'];
public isUser: boolean;
| (private AuthenticationService: IAuthenticationService, private $state: StateService, private $rootScope: IRootScopeService) {
this.isUser = !!this.AuthenticationService.user;
if (sessionStorage.prevState) {
const prevState = sessionStorage.prevState as StateOrName;
const prevParams = JSON.parse(sessionStorage.prevParams) as StateParams;
delete sessionStorage.prevState;
delete sessionStorage.prevParams;
this.$state.go(prevState, prevParams);
}
}
}
angular.module('core').controller('HomeController', HomeController);
| constructor | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Null engine params deserialization.
use uint::Uint;
/// Authority params deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngineParams {
/// Block reward.
#[serde(rename="blockReward")]
pub block_reward: Option<Uint>,
}
/// Null engine descriptor
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngine {
/// Ethash params.
pub params: NullEngineParams,
}
#[cfg(test)]
mod tests {
use serde_json;
use uint::Uint;
use bigint::prelude::U256;
use super::*;
#[test]
fn | () {
let s = r#"{
"params": {
"blockReward": "0x0d"
}
}"#;
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
}
| null_engine_deserialization | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Null engine params deserialization.
use uint::Uint;
/// Authority params deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngineParams {
/// Block reward.
#[serde(rename="blockReward")]
pub block_reward: Option<Uint>,
}
/// Null engine descriptor
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngine {
/// Ethash params.
pub params: NullEngineParams,
}
#[cfg(test)]
mod tests {
use serde_json;
use uint::Uint;
use bigint::prelude::U256;
use super::*;
#[test]
fn null_engine_deserialization() {
let s = r#"{ |
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
} | "params": {
"blockReward": "0x0d"
}
}"#; | random_line_split |
sk.js | OC.L10N.register(
"workflowengine",
{
"Successfully saved" : "Úspešne uložené",
"Saving failed:" : "Ukladanie neúspešné:",
"File mime type" : "Mime typ súboru",
"is" : "je",
"is not" : "nie je",
"matches" : "súhlasí",
"does not match" : "nesúhlasí",
"Example: {placeholder}" : "Napríklad: {placeholder}",
"File size (upload)" : "Veľkosť súboru (upload)",
"less" : "menej",
"less or equals" : "menej alebo rovné",
"greater or equals" : "viac alebo rovné",
"greater" : "viac",
"File system tag" : "Štítok súborového systému",
"is tagged with" : "je označený",
"is not tagged with" : "nie je označený",
"Select tag…" : "Vyber štítok...",
"Request remote address" : "Vyžiadať vzdialenú adresu",
"matches IPv4" : "súhlasí s IPv4",
"does not match IPv4" : "nesúhlasí s IPv4",
"matches IPv6" : "súhlasí s IPv6",
"does not match IPv6" : "nesúhlasí s IPv6",
"between" : "medzi",
"not between" : "nie je medzi",
"Start" : "Začiatok", | "Request URL" : "Vyžiadať URL",
"Files WebDAV" : "WebDAV súbory",
"Sync clients" : "Synchronizovať klientov",
"Android client" : "Android klient",
"iOS client" : "iOS klient",
"Desktop client" : "Desktopový klient",
"is member of" : "Je členom",
"is not member of" : "Nie je členom",
"The given file size is invalid" : "Zadaná veľkosť súboru je neplatná",
"The given tag id is invalid" : "Zadaný identifikátor štítku je neplatný",
"The given IP range is invalid" : "Zadaný rozsah IP je neplatný",
"The given IP range is not valid for IPv4" : "Zadaný IP rozsah nie je platný pre IPv4",
"The given IP range is not valid for IPv6" : "Zadaný IP rozsah nie je platný pre IPv6",
"The given time span is invalid" : "Zadané časové rozpätie nie je platné",
"The given start time is invalid" : "Zadaný čas začatia nie je platný",
"The given end time is invalid" : "Zadaný čas ukončenia nie je platný",
"The given group does not exist" : "Zadaná skupina neexistuje",
"Operation #%s does not exist" : "Operácia #%s neexistuje",
"Operation %s does not exist" : "Operácia %s neexistuje",
"Operation %s is invalid" : "Operácia #%s nie je platná",
"Open documentation" : "Otvoriť dokumentáciu",
"Add rule group" : "Pridať skupinu pravidiel",
"Short rule description" : "Zobraziť popis pravidla",
"Add rule" : "Pridať pravidlo",
"Reset" : "Vynulovať",
"Save" : "Uložiť",
"Saving…" : "Ukladá sa...",
"Loading…" : "Načítava sa..."
},
"nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"); | "End" : "Koniec", | random_line_split |
coluslife.js | 'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";
var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", {
level: 7,
building: false,
point: false
});
var marker = new AMap.Marker({
position: new AMap.LngLat(120.58, 31.335),
title: 'SuZhouLeYuan'
});
marker.setMap(mapObj);
};
$('#btnLocation').on("click", function(){
var locations = null; | $http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++){
var loc = locations[i];
placeMarker(loc);
}
},
function errorCallback(error){
console.error(error);
});
}
});
var placeMarker = function(location){
var marker = new AMap.Marker({
position: new AMap.LngLat(location.fields.gislng, location.fields.gislat),
title: location.fields.name
});
marker.setMap(mapObj);
}
}); | if (null === locations){ | random_line_split |
coluslife.js | 'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";
var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", {
level: 7,
building: false,
point: false
});
var marker = new AMap.Marker({
position: new AMap.LngLat(120.58, 31.335),
title: 'SuZhouLeYuan'
});
marker.setMap(mapObj);
};
$('#btnLocation').on("click", function(){
var locations = null;
if (null === locations) |
});
var placeMarker = function(location){
var marker = new AMap.Marker({
position: new AMap.LngLat(location.fields.gislng, location.fields.gislat),
title: location.fields.name
});
marker.setMap(mapObj);
}
});
| {
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++){
var loc = locations[i];
placeMarker(loc);
}
},
function errorCallback(error){
console.error(error);
});
} | conditional_block |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class DropdownToggle implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;
@HostBinding('class.dropdown-toggle')
@HostBinding('attr.aria-haspopup')
public addClass:boolean = true; | this.dropdown = dropdown;
this.el = el;
}
public ngOnInit():void {
this.dropdown.dropDownToggle = this;
}
@HostBinding('attr.aria-expanded')
public get isOpen():boolean {
return this.dropdown.isOpen;
}
@HostListener('click', ['$event'])
public toggleDropdown(event:MouseEvent):boolean {
event.stopPropagation();
if (!this.disabled) {
this.dropdown.toggle();
}
return false;
}
} |
public dropdown:Dropdown;
public el:ElementRef;
public constructor(@Host() dropdown:Dropdown, el:ElementRef) { | random_line_split |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class DropdownToggle implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;
@HostBinding('class.dropdown-toggle')
@HostBinding('attr.aria-haspopup')
public addClass:boolean = true;
public dropdown:Dropdown;
public el:ElementRef;
public constructor(@Host() dropdown:Dropdown, el:ElementRef) {
this.dropdown = dropdown;
this.el = el;
}
public ngOnInit():void {
this.dropdown.dropDownToggle = this;
}
@HostBinding('attr.aria-expanded')
public get isOpen():boolean {
return this.dropdown.isOpen;
}
@HostListener('click', ['$event'])
public toggleDropdown(event:MouseEvent):boolean {
event.stopPropagation();
if (!this.disabled) |
return false;
}
}
| {
this.dropdown.toggle();
} | conditional_block |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class | implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;
@HostBinding('class.dropdown-toggle')
@HostBinding('attr.aria-haspopup')
public addClass:boolean = true;
public dropdown:Dropdown;
public el:ElementRef;
public constructor(@Host() dropdown:Dropdown, el:ElementRef) {
this.dropdown = dropdown;
this.el = el;
}
public ngOnInit():void {
this.dropdown.dropDownToggle = this;
}
@HostBinding('attr.aria-expanded')
public get isOpen():boolean {
return this.dropdown.isOpen;
}
@HostListener('click', ['$event'])
public toggleDropdown(event:MouseEvent):boolean {
event.stopPropagation();
if (!this.disabled) {
this.dropdown.toggle();
}
return false;
}
}
| DropdownToggle | identifier_name |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class DropdownToggle implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;
@HostBinding('class.dropdown-toggle')
@HostBinding('attr.aria-haspopup')
public addClass:boolean = true;
public dropdown:Dropdown;
public el:ElementRef;
public constructor(@Host() dropdown:Dropdown, el:ElementRef) {
this.dropdown = dropdown;
this.el = el;
}
public ngOnInit():void |
@HostBinding('attr.aria-expanded')
public get isOpen():boolean {
return this.dropdown.isOpen;
}
@HostListener('click', ['$event'])
public toggleDropdown(event:MouseEvent):boolean {
event.stopPropagation();
if (!this.disabled) {
this.dropdown.toggle();
}
return false;
}
}
| {
this.dropdown.dropDownToggle = this;
} | identifier_body |
UserInfoObjectFactory.ts | // Copyright 2018 The Oppia Authors. 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.
/**
* @fileoverview Factory for creating and instances of frontend user UserInfo
* domain objects.
*/
import { Injectable } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';
interface UserInfoBackendDict {
'is_moderator': boolean;
'is_admin': boolean;
'is_super_admin': boolean;
'is_topic_manager': boolean;
'can_create_collections': boolean;
'preferred_site_language_code': string;
'username': string;
'email': string;
'user_is_logged_in': boolean;
}
export class UserInfo {
_isModerator: boolean;
_isAdmin: boolean;
_isTopicManager: boolean;
_isSuperAdmin: boolean;
_canCreateCollections: boolean;
_preferredSiteLanguageCode: string;
_username: string;
_email: string;
_isLoggedIn: boolean;
constructor(
isModerator: boolean, isAdmin: boolean, isSuperAdmin: boolean,
isTopicManager: boolean, canCreateCollections: boolean,
preferredSiteLanguageCode: string, username: string,
email: string, isLoggedIn: boolean) {
this._isModerator = isModerator;
this._isAdmin = isAdmin;
this._isTopicManager = isTopicManager;
this._isSuperAdmin = isSuperAdmin;
this._canCreateCollections = canCreateCollections;
this._preferredSiteLanguageCode = preferredSiteLanguageCode;
this._username = username;
this._email = email;
this._isLoggedIn = isLoggedIn;
}
isModerator(): boolean {
return this._isModerator;
}
| (): boolean {
return this._isAdmin;
}
isTopicManager(): boolean {
return this._isTopicManager;
}
isSuperAdmin(): boolean {
return this._isSuperAdmin;
}
canCreateCollections(): boolean {
return this._canCreateCollections;
}
getPreferredSiteLanguageCode(): string {
return this._preferredSiteLanguageCode;
}
getUsername(): string {
return this._username;
}
getEmail(): string {
return this._email;
}
isLoggedIn(): boolean {
return this._isLoggedIn;
}
}
@Injectable({
providedIn: 'root'
})
export class UserInfoObjectFactory {
createFromBackendDict(
data: UserInfoBackendDict): UserInfo {
return new UserInfo(
data.is_moderator, data.is_admin, data.is_super_admin,
data.is_topic_manager, data.can_create_collections,
data.preferred_site_language_code, data.username,
data.email, data.user_is_logged_in);
}
createDefault(): UserInfo {
return new UserInfo(
false, false, false, false, false, null, null, null, false);
}
}
angular.module('oppia').factory(
'UserInfoObjectFactory',
downgradeInjectable(UserInfoObjectFactory));
| isAdmin | identifier_name |
UserInfoObjectFactory.ts | // Copyright 2018 The Oppia Authors. 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.
/**
* @fileoverview Factory for creating and instances of frontend user UserInfo
* domain objects.
*/
import { Injectable } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';
interface UserInfoBackendDict {
'is_moderator': boolean;
'is_admin': boolean;
'is_super_admin': boolean;
'is_topic_manager': boolean;
'can_create_collections': boolean;
'preferred_site_language_code': string;
'username': string;
'email': string;
'user_is_logged_in': boolean;
}
export class UserInfo {
_isModerator: boolean;
_isAdmin: boolean;
_isTopicManager: boolean;
_isSuperAdmin: boolean;
_canCreateCollections: boolean;
_preferredSiteLanguageCode: string;
_username: string;
_email: string;
_isLoggedIn: boolean;
constructor(
isModerator: boolean, isAdmin: boolean, isSuperAdmin: boolean,
isTopicManager: boolean, canCreateCollections: boolean,
preferredSiteLanguageCode: string, username: string,
email: string, isLoggedIn: boolean) {
this._isModerator = isModerator;
this._isAdmin = isAdmin;
this._isTopicManager = isTopicManager;
this._isSuperAdmin = isSuperAdmin;
this._canCreateCollections = canCreateCollections;
this._preferredSiteLanguageCode = preferredSiteLanguageCode;
this._username = username;
this._email = email;
this._isLoggedIn = isLoggedIn;
}
isModerator(): boolean {
return this._isModerator;
}
isAdmin(): boolean {
return this._isAdmin;
}
isTopicManager(): boolean {
return this._isTopicManager;
}
isSuperAdmin(): boolean { | return this._canCreateCollections;
}
getPreferredSiteLanguageCode(): string {
return this._preferredSiteLanguageCode;
}
getUsername(): string {
return this._username;
}
getEmail(): string {
return this._email;
}
isLoggedIn(): boolean {
return this._isLoggedIn;
}
}
@Injectable({
providedIn: 'root'
})
export class UserInfoObjectFactory {
createFromBackendDict(
data: UserInfoBackendDict): UserInfo {
return new UserInfo(
data.is_moderator, data.is_admin, data.is_super_admin,
data.is_topic_manager, data.can_create_collections,
data.preferred_site_language_code, data.username,
data.email, data.user_is_logged_in);
}
createDefault(): UserInfo {
return new UserInfo(
false, false, false, false, false, null, null, null, false);
}
}
angular.module('oppia').factory(
'UserInfoObjectFactory',
downgradeInjectable(UserInfoObjectFactory)); | return this._isSuperAdmin;
}
canCreateCollections(): boolean { | random_line_split |
UserInfoObjectFactory.ts | // Copyright 2018 The Oppia Authors. 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.
/**
* @fileoverview Factory for creating and instances of frontend user UserInfo
* domain objects.
*/
import { Injectable } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';
interface UserInfoBackendDict {
'is_moderator': boolean;
'is_admin': boolean;
'is_super_admin': boolean;
'is_topic_manager': boolean;
'can_create_collections': boolean;
'preferred_site_language_code': string;
'username': string;
'email': string;
'user_is_logged_in': boolean;
}
export class UserInfo {
_isModerator: boolean;
_isAdmin: boolean;
_isTopicManager: boolean;
_isSuperAdmin: boolean;
_canCreateCollections: boolean;
_preferredSiteLanguageCode: string;
_username: string;
_email: string;
_isLoggedIn: boolean;
constructor(
isModerator: boolean, isAdmin: boolean, isSuperAdmin: boolean,
isTopicManager: boolean, canCreateCollections: boolean,
preferredSiteLanguageCode: string, username: string,
email: string, isLoggedIn: boolean) {
this._isModerator = isModerator;
this._isAdmin = isAdmin;
this._isTopicManager = isTopicManager;
this._isSuperAdmin = isSuperAdmin;
this._canCreateCollections = canCreateCollections;
this._preferredSiteLanguageCode = preferredSiteLanguageCode;
this._username = username;
this._email = email;
this._isLoggedIn = isLoggedIn;
}
isModerator(): boolean |
isAdmin(): boolean {
return this._isAdmin;
}
isTopicManager(): boolean {
return this._isTopicManager;
}
isSuperAdmin(): boolean {
return this._isSuperAdmin;
}
canCreateCollections(): boolean {
return this._canCreateCollections;
}
getPreferredSiteLanguageCode(): string {
return this._preferredSiteLanguageCode;
}
getUsername(): string {
return this._username;
}
getEmail(): string {
return this._email;
}
isLoggedIn(): boolean {
return this._isLoggedIn;
}
}
@Injectable({
providedIn: 'root'
})
export class UserInfoObjectFactory {
createFromBackendDict(
data: UserInfoBackendDict): UserInfo {
return new UserInfo(
data.is_moderator, data.is_admin, data.is_super_admin,
data.is_topic_manager, data.can_create_collections,
data.preferred_site_language_code, data.username,
data.email, data.user_is_logged_in);
}
createDefault(): UserInfo {
return new UserInfo(
false, false, false, false, false, null, null, null, false);
}
}
angular.module('oppia').factory(
'UserInfoObjectFactory',
downgradeInjectable(UserInfoObjectFactory));
| {
return this._isModerator;
} | identifier_body |
position-animation.ts | /**
* Copyright 2018 The AMP HTML Authors. 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.
*/
import {Curve, curveToString} from '../bezier-curve-utils.js';
import {Size} from '../size.js';
import {getPositioningTranslate} from '../object-position.js';
/**
* Prepares an animation for position (i.e. for object-position). This function
* sets up the animation by setting the appropriate style properties on the
* desired Element. The returned style text needs to be inserted for the
* animation to run.
* @param options
* @param options.element The element to apply the position to.
* @param options.largerRect The larger of the start/end element container
* rects.
* @param options.largerDimensions The larger of the start/end element
* dimensions.
* @param options.smallerDimensions The smaller of the start/end element
* dimensions.
* @param options.largerObjectPosition The object position for the larger
* element.
* @param options.smallerObjectPosition The object position for the smaller
* element.
* @param options.curve The timing curve for the scaling.
* @param options.style The styles to apply to `element`.
* @param options.keyframesPrefix A prefix to use for the generated
* keyframes to ensure they do not clash with existing keyframes.
* @param options.toLarger Whether or not `largerImgDimensions` are the
* dimensions are we are animating to.
* @return CSS style text to perform the animation.
*/
export function preparePositionAnimation({
element,
largerRect,
smallerRect,
largerDimensions,
smallerDimensions,
largerObjectPosition,
smallerObjectPosition,
curve, | element: HTMLElement,
largerRect: ClientRect,
smallerRect: ClientRect,
largerDimensions: Size,
smallerDimensions: Size,
largerObjectPosition: string,
smallerObjectPosition: string,
curve: Curve,
styles: Object,
keyframesPrefix: string,
toLarger: boolean,
}): string {
const curveString = curveToString(curve);
const keyframesName = `${keyframesPrefix}-object-position`;
const largerTranslate = getPositioningTranslate(
largerObjectPosition, largerRect, largerDimensions);
const smallerTranslate = getPositioningTranslate(
smallerObjectPosition, smallerRect, smallerDimensions);
const startTranslate = toLarger ? smallerTranslate : largerTranslate;
const endTranslate = toLarger ? largerTranslate : smallerTranslate;
Object.assign(element.style, styles, {
'willChange': 'transform',
'animationName': keyframesName,
'animationTimingFunction': curveString,
'animationFillMode': 'forwards',
});
return `
@keyframes ${keyframesName} {
from {
transform: translate(${startTranslate.left}px, ${startTranslate.top}px);
}
to {
transform: translate(${endTranslate.left}px, ${endTranslate.top}px);
}
}
`;
} | styles,
keyframesPrefix,
toLarger,
} : { | random_line_split |
position-animation.ts | /**
* Copyright 2018 The AMP HTML Authors. 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.
*/
import {Curve, curveToString} from '../bezier-curve-utils.js';
import {Size} from '../size.js';
import {getPositioningTranslate} from '../object-position.js';
/**
* Prepares an animation for position (i.e. for object-position). This function
* sets up the animation by setting the appropriate style properties on the
* desired Element. The returned style text needs to be inserted for the
* animation to run.
* @param options
* @param options.element The element to apply the position to.
* @param options.largerRect The larger of the start/end element container
* rects.
* @param options.largerDimensions The larger of the start/end element
* dimensions.
* @param options.smallerDimensions The smaller of the start/end element
* dimensions.
* @param options.largerObjectPosition The object position for the larger
* element.
* @param options.smallerObjectPosition The object position for the smaller
* element.
* @param options.curve The timing curve for the scaling.
* @param options.style The styles to apply to `element`.
* @param options.keyframesPrefix A prefix to use for the generated
* keyframes to ensure they do not clash with existing keyframes.
* @param options.toLarger Whether or not `largerImgDimensions` are the
* dimensions are we are animating to.
* @return CSS style text to perform the animation.
*/
export function | ({
element,
largerRect,
smallerRect,
largerDimensions,
smallerDimensions,
largerObjectPosition,
smallerObjectPosition,
curve,
styles,
keyframesPrefix,
toLarger,
} : {
element: HTMLElement,
largerRect: ClientRect,
smallerRect: ClientRect,
largerDimensions: Size,
smallerDimensions: Size,
largerObjectPosition: string,
smallerObjectPosition: string,
curve: Curve,
styles: Object,
keyframesPrefix: string,
toLarger: boolean,
}): string {
const curveString = curveToString(curve);
const keyframesName = `${keyframesPrefix}-object-position`;
const largerTranslate = getPositioningTranslate(
largerObjectPosition, largerRect, largerDimensions);
const smallerTranslate = getPositioningTranslate(
smallerObjectPosition, smallerRect, smallerDimensions);
const startTranslate = toLarger ? smallerTranslate : largerTranslate;
const endTranslate = toLarger ? largerTranslate : smallerTranslate;
Object.assign(element.style, styles, {
'willChange': 'transform',
'animationName': keyframesName,
'animationTimingFunction': curveString,
'animationFillMode': 'forwards',
});
return `
@keyframes ${keyframesName} {
from {
transform: translate(${startTranslate.left}px, ${startTranslate.top}px);
}
to {
transform: translate(${endTranslate.left}px, ${endTranslate.top}px);
}
}
`;
}
| preparePositionAnimation | identifier_name |
position-animation.ts | /**
* Copyright 2018 The AMP HTML Authors. 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.
*/
import {Curve, curveToString} from '../bezier-curve-utils.js';
import {Size} from '../size.js';
import {getPositioningTranslate} from '../object-position.js';
/**
* Prepares an animation for position (i.e. for object-position). This function
* sets up the animation by setting the appropriate style properties on the
* desired Element. The returned style text needs to be inserted for the
* animation to run.
* @param options
* @param options.element The element to apply the position to.
* @param options.largerRect The larger of the start/end element container
* rects.
* @param options.largerDimensions The larger of the start/end element
* dimensions.
* @param options.smallerDimensions The smaller of the start/end element
* dimensions.
* @param options.largerObjectPosition The object position for the larger
* element.
* @param options.smallerObjectPosition The object position for the smaller
* element.
* @param options.curve The timing curve for the scaling.
* @param options.style The styles to apply to `element`.
* @param options.keyframesPrefix A prefix to use for the generated
* keyframes to ensure they do not clash with existing keyframes.
* @param options.toLarger Whether or not `largerImgDimensions` are the
* dimensions are we are animating to.
* @return CSS style text to perform the animation.
*/
export function preparePositionAnimation({
element,
largerRect,
smallerRect,
largerDimensions,
smallerDimensions,
largerObjectPosition,
smallerObjectPosition,
curve,
styles,
keyframesPrefix,
toLarger,
} : {
element: HTMLElement,
largerRect: ClientRect,
smallerRect: ClientRect,
largerDimensions: Size,
smallerDimensions: Size,
largerObjectPosition: string,
smallerObjectPosition: string,
curve: Curve,
styles: Object,
keyframesPrefix: string,
toLarger: boolean,
}): string | {
const curveString = curveToString(curve);
const keyframesName = `${keyframesPrefix}-object-position`;
const largerTranslate = getPositioningTranslate(
largerObjectPosition, largerRect, largerDimensions);
const smallerTranslate = getPositioningTranslate(
smallerObjectPosition, smallerRect, smallerDimensions);
const startTranslate = toLarger ? smallerTranslate : largerTranslate;
const endTranslate = toLarger ? largerTranslate : smallerTranslate;
Object.assign(element.style, styles, {
'willChange': 'transform',
'animationName': keyframesName,
'animationTimingFunction': curveString,
'animationFillMode': 'forwards',
});
return `
@keyframes ${keyframesName} {
from {
transform: translate(${startTranslate.left}px, ${startTranslate.top}px);
}
to {
transform: translate(${endTranslate.left}px, ${endTranslate.top}px);
}
}
`;
} | identifier_body | |
web_planner_crm.js | odoo.define('planner_crm.planner', function (require) {
"use strict";
var planner = require('web.planner.common');
var core = require('web.core');
var _t = core._t;
planner.PlannerDialog.include({
prepare_planner_event: function () {
this._super.apply(this, arguments);
if (this.planner['planner_application'] === 'planner_crm') {
var stages = {
'solution_selling': [
_t('Territory'), _t('Qualified'), _t('Qualified Sponsor'),
_t('Proposal'), _t('Negotiation'), _t('Won'), '',
_t('New propspect assigned to the right salesperson'),
_t('Set fields: Expected Revenue, Expected Closing Date, Next Action'),
_t('You are in discussion with the decision maker and HE agreed on his pain points'),
_t('Quotation sent to customer'), _t('The customer came back to you to discuss your quotation'),
_t('Quotation signed by the customer'), ''],
'b2c': [
_t('New'), _t('Initial Contact'), _t('Product Demonstration'), _t('Proposal'), _t('Won'), '', '',
'', _t('Phone call with following questions: ...'),
_t('Meeting with a demo. Set Fields: expected revenue, closing date'),
_t('Quotation sent'), '', '', ''],
'b2b': [
_t('New'), _t('Qualified'), _t('Needs assessment'), _t('POC Sold'), _t('Demonstration'), _t('Proposal'), _t('Won'),
_t('Set fields: Expected Revenue, Expected Closing Date, Next Action'),
_t('Close opportunity if: "pre-sales days * $500" < "expected revenue" * probability'),
_t('GAP analysis with customer'), _t('Create a Proof of Concept with consultants'),
_t('POC demonstration to the customer'), _t('Final Proposal sent'), ''],
'odoo_default': [
_t('New'), _t('Qualified'), _t('Proposition'), _t('Negotiation'), _t('Won'), _t('Lost'), '',
'', '', '', '', '', '', '']
};
this.$el.on('change', '#input_element_pipeline', function(ev) { | for(var i=0; i<values.length; i++) {
$('#input_element_stage_'+i).val(values[i]);
}
}
});
}
}
});
}); | var option = $(ev.target).find(":selected").val();
if (_.has(stages, option)) {
var values = stages[option]; | random_line_split |
web_planner_crm.js | odoo.define('planner_crm.planner', function (require) {
"use strict";
var planner = require('web.planner.common');
var core = require('web.core');
var _t = core._t;
planner.PlannerDialog.include({
prepare_planner_event: function () {
this._super.apply(this, arguments);
if (this.planner['planner_application'] === 'planner_crm') |
}
});
});
| {
var stages = {
'solution_selling': [
_t('Territory'), _t('Qualified'), _t('Qualified Sponsor'),
_t('Proposal'), _t('Negotiation'), _t('Won'), '',
_t('New propspect assigned to the right salesperson'),
_t('Set fields: Expected Revenue, Expected Closing Date, Next Action'),
_t('You are in discussion with the decision maker and HE agreed on his pain points'),
_t('Quotation sent to customer'), _t('The customer came back to you to discuss your quotation'),
_t('Quotation signed by the customer'), ''],
'b2c': [
_t('New'), _t('Initial Contact'), _t('Product Demonstration'), _t('Proposal'), _t('Won'), '', '',
'', _t('Phone call with following questions: ...'),
_t('Meeting with a demo. Set Fields: expected revenue, closing date'),
_t('Quotation sent'), '', '', ''],
'b2b': [
_t('New'), _t('Qualified'), _t('Needs assessment'), _t('POC Sold'), _t('Demonstration'), _t('Proposal'), _t('Won'),
_t('Set fields: Expected Revenue, Expected Closing Date, Next Action'),
_t('Close opportunity if: "pre-sales days * $500" < "expected revenue" * probability'),
_t('GAP analysis with customer'), _t('Create a Proof of Concept with consultants'),
_t('POC demonstration to the customer'), _t('Final Proposal sent'), ''],
'odoo_default': [
_t('New'), _t('Qualified'), _t('Proposition'), _t('Negotiation'), _t('Won'), _t('Lost'), '',
'', '', '', '', '', '', '']
};
this.$el.on('change', '#input_element_pipeline', function(ev) {
var option = $(ev.target).find(":selected").val();
if (_.has(stages, option)) {
var values = stages[option];
for(var i=0; i<values.length; i++) {
$('#input_element_stage_'+i).val(values[i]);
}
}
});
} | conditional_block |
course.py | """
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture
class XBlockFixtureDesc(object):
"""
Description of an XBlock, used to configure a course fixture.
"""
def __init__(self, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`
* `data`
* `metadata`
* `grader_type`
* `publish`
"""
self.category = category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Add child XBlocks to this XBlock.
Each item in `args` is an `XBlockFixtureDesc` object.
Returns the `xblock_desc` instance to allow chaining.
"""
self.children.extend(args)
return self
def serialize(self):
"""
Return a JSON representation of the XBlock, suitable
for sending as POST data to /xblock
XBlocks are always set to public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(returned_data)
def __str__(self):
"""
Return a string representation of the description.
Useful for error messages.
"""
return dedent(u"""
<XBlockFixtureDescriptor:
category={0},
data={1},
metadata={2},
grader_type={3},
publish={4},
children={5},
locator={6},
>
""").strip().format(
self.category, self.data, self.metadata,
self.grader_type, self.publish, self.children, self.locator
)
# Description of course updates to add to the course
# `date` is a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
between tests, you should use unique course identifiers for each fixture.
"""
def __init__(self, org, number, run, display_name, start_date=None, end_date=None, settings=None):
|
def __str__(self):
"""
String representation of the course fixture, useful for debugging.
"""
return u"<CourseFixture: org='{org}', number='{number}', run='{run}'>".format(**self._course_dict)
def add_course_details(self, course_details):
"""
Add course details to dict of course details to be updated when configure_course or install is called.
Arguments:
Dictionary containing key value pairs for course updates,
e.g. {'start_date': datetime.now() }
"""
if 'start_date' in course_details:
course_details['start_date'] = course_details['start_date'].isoformat()
if 'end_date' in course_details:
course_details['end_date'] = course_details['end_date'].isoformat()
self._course_details.update(course_details)
def add_update(self, update):
"""
Add an update to the course. `update` should be a `CourseUpdateDesc`.
"""
self._updates.append(update)
def add_handout(self, asset_name):
"""
Add the handout named `asset_name` to the course info page.
Note that this does not actually *create* the static asset; it only links to it.
"""
self._handouts.append(asset_name)
def add_asset(self, asset_name):
"""
Add the asset to the list of assets to be uploaded when the install method is called.
"""
self._assets.extend(asset_name)
def add_textbook(self, book_title, chapters):
"""
Add textbook to the list of textbooks to be added when the install method is called.
"""
self._textbooks.append({"chapters": chapters, "tab_title": book_title})
def add_advanced_settings(self, settings):
"""
Adds advanced settings to be set on the course when the install method is called.
"""
self._advanced_settings.update(settings)
def install(self):
"""
Create the course and XBlocks within the course.
This is NOT an idempotent method; if the course already exists, this will
raise a `FixtureError`. You should use unique course identifiers to avoid
conflicts between tests.
"""
self._create_course()
self._install_course_updates()
self._install_course_handouts()
self._install_course_textbooks()
self._configure_course()
self._upload_assets()
self._add_advanced_settings()
self._create_xblock_children(self._course_location, self.children)
return self
def configure_course(self):
"""
Configure Course Settings, take new course settings from self._course_details dict object
"""
self._configure_course()
@property
def studio_course_outline_as_json(self):
"""
Retrieves Studio course outline in JSON format.
"""
url = STUDIO_BASE_URL + '/course/' + self._course_key + "?format=json"
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course outline json. Status was {0}".format(
response.status_code))
try:
course_outline_json = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course outline as JSON: '{0}'".format(response)
)
return course_outline_json
@property
def _course_location(self):
"""
Return the locator string for the course.
"""
course_key = CourseKey.from_string(self._course_key)
if getattr(course_key, 'deprecated', False):
block_id = self._course_dict['run']
else:
block_id = 'course'
return unicode(course_key.make_usage_key('course', block_id))
@property
def _assets_url(self):
"""
Return the url string for the assets
"""
return "/assets/" + self._course_key + "/"
@property
def _handouts_loc(self):
"""
Return the locator string for the course handouts
"""
course_key = CourseKey.from_string(self._course_key)
return unicode(course_key.make_usage_key('course_info', 'handouts'))
def _create_course(self):
"""
Create the course described in the fixture.
"""
# If the course already exists, this will respond
# with a 200 and an error message, which we ignore.
response = self.session.post(
STUDIO_BASE_URL + '/course/',
data=self._encode_post_dict(self._course_dict),
headers=self.headers
)
try:
err = response.json().get('ErrMsg')
except ValueError:
raise FixtureError(
u"Could not parse response from course request as JSON: '{0}'".format(
response.content))
# This will occur if the course identifier is not unique
if err is not None:
raise FixtureError(u"Could not create course {0}. Error message: '{1}'".format(self, err))
if response.ok:
self._course_key = response.json()['course_key']
else:
raise FixtureError(
u"Could not create course {0}. Status was {1}\nResponse content was: {2}".format(
self._course_dict, response.status_code, response.content))
def _configure_course(self):
"""
Configure course settings (e.g. start and end date)
"""
url = STUDIO_BASE_URL + '/settings/details/' + self._course_key
# First, get the current values
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course details. Status was {0}".format(
response.status_code))
try:
details = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course details as JSON: '{0}'".format(details)
)
# Update the old details with our overrides
details.update(self._course_details)
# POST the updated details to Studio
response = self.session.post(
url, data=self._encode_post_dict(details),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update course details to '{0}' with {1}: Status was {2}.".format(
self._course_details, url, response.status_code))
def _install_course_handouts(self):
"""
Add handouts to the course info page.
"""
url = STUDIO_BASE_URL + '/xblock/' + self._handouts_loc
# Construct HTML with each of the handout links
handouts_li = [
u'<li><a href="/static/{handout}">Example Handout</a></li>'.format(handout=handout)
for handout in self._handouts
]
handouts_html = u'<ol class="treeview-handoutsnav">{}</ol>'.format("".join(handouts_li))
# Update the course's handouts HTML
payload = json.dumps({
'children': None,
'data': handouts_html,
'id': self._handouts_loc,
'metadata': dict(),
})
response = self.session.post(url, data=payload, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not update course handouts with {0}. Status was {1}".format(url, response.status_code))
def _install_course_updates(self):
"""
Add updates to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/course_info_update/' + self._course_key + '/'
for update in self._updates:
# Add the update to the course
date, content = update
payload = json.dumps({'date': date, 'content': content})
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add update to course: {0} with {1}. Status was {2}".format(
update, url, response.status_code))
def _upload_assets(self):
"""
Upload assets
:raise FixtureError:
"""
url = STUDIO_BASE_URL + self._assets_url
test_dir = Path(__file__).abspath().dirname().dirname().dirname()
for asset_name in self._assets:
asset_file_path = test_dir + '/data/uploads/' + asset_name
asset_file = open(asset_file_path)
files = {'file': (asset_name, asset_file, mimetypes.guess_type(asset_file_path)[0])}
headers = {
'Accept': 'application/json',
'X-CSRFToken': self.session_cookies.get('csrftoken', '')
}
upload_response = self.session.post(url, files=files, headers=headers)
if not upload_response.ok:
raise FixtureError(u'Could not upload {asset_name} with {url}. Status code: {code}'.format(
asset_name=asset_name, url=url, code=upload_response.status_code))
def _install_course_textbooks(self):
"""
Add textbooks to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/textbooks/' + self._course_key
for book in self._textbooks:
payload = json.dumps(book)
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add book to course: {0} with {1}. Status was {2}".format(
book, url, response.status_code))
def _add_advanced_settings(self):
"""
Add advanced settings.
"""
url = STUDIO_BASE_URL + "/settings/advanced/" + self._course_key
# POST advanced settings to Studio
response = self.session.post(
url, data=self._encode_post_dict(self._advanced_settings),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update advanced details to '{0}' with {1}: Status was {2}.".format(
self._advanced_settings, url, response.status_code))
def _create_xblock_children(self, parent_loc, xblock_descriptions):
"""
Recursively create XBlock children.
"""
super(CourseFixture, self)._create_xblock_children(parent_loc, xblock_descriptions)
self._publish_xblock(parent_loc)
| """
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is generally what
we want for testing so students can enroll.
`settings` can be any additional course settings needs to be enabled. for example
to enable entrance exam settings would be a dict like this {"entrance_exam_enabled": "true"}
These have the same meaning as in the Studio restful API /course end-point.
"""
super(CourseFixture, self).__init__()
self._course_dict = {
'org': org,
'number': number,
'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
if end_date is not None:
self._course_details['end_date'] = end_date.isoformat()
if settings is not None:
self._course_details.update(settings)
self._updates = []
self._handouts = []
self._assets = []
self._textbooks = []
self._advanced_settings = {}
self._course_key = None | identifier_body |
course.py | """
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture
class XBlockFixtureDesc(object):
"""
Description of an XBlock, used to configure a course fixture.
"""
def __init__(self, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`
* `data`
* `metadata`
* `grader_type`
* `publish`
"""
self.category = category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Add child XBlocks to this XBlock.
Each item in `args` is an `XBlockFixtureDesc` object.
Returns the `xblock_desc` instance to allow chaining.
"""
self.children.extend(args)
return self
def serialize(self):
"""
Return a JSON representation of the XBlock, suitable
for sending as POST data to /xblock
XBlocks are always set to public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(returned_data)
def __str__(self):
"""
Return a string representation of the description.
Useful for error messages.
"""
return dedent(u"""
<XBlockFixtureDescriptor:
category={0},
data={1},
metadata={2},
grader_type={3},
publish={4},
children={5},
locator={6},
>
""").strip().format(
self.category, self.data, self.metadata,
self.grader_type, self.publish, self.children, self.locator
)
# Description of course updates to add to the course
# `date` is a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
between tests, you should use unique course identifiers for each fixture.
"""
def __init__(self, org, number, run, display_name, start_date=None, end_date=None, settings=None):
"""
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is generally what
we want for testing so students can enroll.
`settings` can be any additional course settings needs to be enabled. for example
to enable entrance exam settings would be a dict like this {"entrance_exam_enabled": "true"}
These have the same meaning as in the Studio restful API /course end-point.
"""
super(CourseFixture, self).__init__()
self._course_dict = {
'org': org,
'number': number,
'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
if end_date is not None:
self._course_details['end_date'] = end_date.isoformat()
if settings is not None:
self._course_details.update(settings)
self._updates = []
self._handouts = []
self._assets = []
self._textbooks = []
self._advanced_settings = {}
self._course_key = None
def __str__(self):
"""
String representation of the course fixture, useful for debugging.
"""
return u"<CourseFixture: org='{org}', number='{number}', run='{run}'>".format(**self._course_dict)
def add_course_details(self, course_details):
"""
Add course details to dict of course details to be updated when configure_course or install is called.
Arguments:
Dictionary containing key value pairs for course updates,
e.g. {'start_date': datetime.now() }
"""
if 'start_date' in course_details:
course_details['start_date'] = course_details['start_date'].isoformat()
if 'end_date' in course_details:
course_details['end_date'] = course_details['end_date'].isoformat()
self._course_details.update(course_details)
def add_update(self, update):
"""
Add an update to the course. `update` should be a `CourseUpdateDesc`.
"""
self._updates.append(update)
def add_handout(self, asset_name):
"""
Add the handout named `asset_name` to the course info page.
Note that this does not actually *create* the static asset; it only links to it.
"""
self._handouts.append(asset_name)
def add_asset(self, asset_name):
"""
Add the asset to the list of assets to be uploaded when the install method is called.
"""
self._assets.extend(asset_name)
def add_textbook(self, book_title, chapters):
"""
Add textbook to the list of textbooks to be added when the install method is called.
"""
self._textbooks.append({"chapters": chapters, "tab_title": book_title})
def add_advanced_settings(self, settings):
"""
Adds advanced settings to be set on the course when the install method is called.
"""
self._advanced_settings.update(settings)
def install(self):
"""
Create the course and XBlocks within the course.
This is NOT an idempotent method; if the course already exists, this will
raise a `FixtureError`. You should use unique course identifiers to avoid
conflicts between tests.
"""
self._create_course()
self._install_course_updates()
self._install_course_handouts()
self._install_course_textbooks()
self._configure_course()
self._upload_assets()
self._add_advanced_settings()
self._create_xblock_children(self._course_location, self.children)
return self
def configure_course(self):
"""
Configure Course Settings, take new course settings from self._course_details dict object
"""
self._configure_course()
@property
def studio_course_outline_as_json(self):
"""
Retrieves Studio course outline in JSON format.
"""
url = STUDIO_BASE_URL + '/course/' + self._course_key + "?format=json"
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course outline json. Status was {0}".format(
response.status_code))
try:
course_outline_json = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course outline as JSON: '{0}'".format(response)
)
return course_outline_json
@property
def _course_location(self):
"""
Return the locator string for the course.
"""
course_key = CourseKey.from_string(self._course_key)
if getattr(course_key, 'deprecated', False):
block_id = self._course_dict['run']
else:
block_id = 'course'
return unicode(course_key.make_usage_key('course', block_id))
@property
def _assets_url(self):
"""
Return the url string for the assets
"""
return "/assets/" + self._course_key + "/"
@property
def _handouts_loc(self):
"""
Return the locator string for the course handouts
"""
course_key = CourseKey.from_string(self._course_key)
return unicode(course_key.make_usage_key('course_info', 'handouts'))
def _create_course(self):
"""
Create the course described in the fixture.
"""
# If the course already exists, this will respond
# with a 200 and an error message, which we ignore.
response = self.session.post(
STUDIO_BASE_URL + '/course/',
data=self._encode_post_dict(self._course_dict),
headers=self.headers
)
try:
err = response.json().get('ErrMsg')
except ValueError:
raise FixtureError(
u"Could not parse response from course request as JSON: '{0}'".format(
response.content))
# This will occur if the course identifier is not unique
if err is not None:
raise FixtureError(u"Could not create course {0}. Error message: '{1}'".format(self, err))
if response.ok:
self._course_key = response.json()['course_key']
else:
raise FixtureError(
u"Could not create course {0}. Status was {1}\nResponse content was: {2}".format(
self._course_dict, response.status_code, response.content))
def _configure_course(self):
"""
Configure course settings (e.g. start and end date)
"""
url = STUDIO_BASE_URL + '/settings/details/' + self._course_key
# First, get the current values
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course details. Status was {0}".format(
response.status_code))
try:
details = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course details as JSON: '{0}'".format(details)
)
# Update the old details with our overrides
details.update(self._course_details)
# POST the updated details to Studio
response = self.session.post(
url, data=self._encode_post_dict(details),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update course details to '{0}' with {1}: Status was {2}.".format(
self._course_details, url, response.status_code))
def _install_course_handouts(self):
"""
Add handouts to the course info page.
"""
url = STUDIO_BASE_URL + '/xblock/' + self._handouts_loc
# Construct HTML with each of the handout links
handouts_li = [
u'<li><a href="/static/{handout}">Example Handout</a></li>'.format(handout=handout)
for handout in self._handouts
]
handouts_html = u'<ol class="treeview-handoutsnav">{}</ol>'.format("".join(handouts_li))
# Update the course's handouts HTML
payload = json.dumps({
'children': None,
'data': handouts_html,
'id': self._handouts_loc,
'metadata': dict(),
})
response = self.session.post(url, data=payload, headers=self.headers)
if not response.ok:
|
def _install_course_updates(self):
"""
Add updates to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/course_info_update/' + self._course_key + '/'
for update in self._updates:
# Add the update to the course
date, content = update
payload = json.dumps({'date': date, 'content': content})
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add update to course: {0} with {1}. Status was {2}".format(
update, url, response.status_code))
def _upload_assets(self):
"""
Upload assets
:raise FixtureError:
"""
url = STUDIO_BASE_URL + self._assets_url
test_dir = Path(__file__).abspath().dirname().dirname().dirname()
for asset_name in self._assets:
asset_file_path = test_dir + '/data/uploads/' + asset_name
asset_file = open(asset_file_path)
files = {'file': (asset_name, asset_file, mimetypes.guess_type(asset_file_path)[0])}
headers = {
'Accept': 'application/json',
'X-CSRFToken': self.session_cookies.get('csrftoken', '')
}
upload_response = self.session.post(url, files=files, headers=headers)
if not upload_response.ok:
raise FixtureError(u'Could not upload {asset_name} with {url}. Status code: {code}'.format(
asset_name=asset_name, url=url, code=upload_response.status_code))
def _install_course_textbooks(self):
"""
Add textbooks to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/textbooks/' + self._course_key
for book in self._textbooks:
payload = json.dumps(book)
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add book to course: {0} with {1}. Status was {2}".format(
book, url, response.status_code))
def _add_advanced_settings(self):
"""
Add advanced settings.
"""
url = STUDIO_BASE_URL + "/settings/advanced/" + self._course_key
# POST advanced settings to Studio
response = self.session.post(
url, data=self._encode_post_dict(self._advanced_settings),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update advanced details to '{0}' with {1}: Status was {2}.".format(
self._advanced_settings, url, response.status_code))
def _create_xblock_children(self, parent_loc, xblock_descriptions):
"""
Recursively create XBlock children.
"""
super(CourseFixture, self)._create_xblock_children(parent_loc, xblock_descriptions)
self._publish_xblock(parent_loc)
| raise FixtureError(
u"Could not update course handouts with {0}. Status was {1}".format(url, response.status_code)) | conditional_block |
course.py | """
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture
class XBlockFixtureDesc(object):
"""
Description of an XBlock, used to configure a course fixture.
"""
def __init__(self, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`
* `data`
* `metadata`
* `grader_type`
* `publish`
"""
self.category = category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Add child XBlocks to this XBlock.
Each item in `args` is an `XBlockFixtureDesc` object.
Returns the `xblock_desc` instance to allow chaining.
"""
self.children.extend(args)
return self
def serialize(self):
"""
Return a JSON representation of the XBlock, suitable
for sending as POST data to /xblock
XBlocks are always set to public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(returned_data)
def __str__(self):
"""
Return a string representation of the description.
Useful for error messages.
"""
return dedent(u"""
<XBlockFixtureDescriptor:
category={0},
data={1},
metadata={2},
grader_type={3},
publish={4},
children={5},
locator={6},
>
""").strip().format(
self.category, self.data, self.metadata,
self.grader_type, self.publish, self.children, self.locator
)
# Description of course updates to add to the course
# `date` is a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
between tests, you should use unique course identifiers for each fixture.
"""
def __init__(self, org, number, run, display_name, start_date=None, end_date=None, settings=None):
"""
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is generally what
we want for testing so students can enroll.
`settings` can be any additional course settings needs to be enabled. for example
to enable entrance exam settings would be a dict like this {"entrance_exam_enabled": "true"}
These have the same meaning as in the Studio restful API /course end-point.
"""
super(CourseFixture, self).__init__()
self._course_dict = {
'org': org,
'number': number,
'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
if end_date is not None:
self._course_details['end_date'] = end_date.isoformat()
if settings is not None:
self._course_details.update(settings)
self._updates = []
self._handouts = []
self._assets = []
self._textbooks = []
self._advanced_settings = {}
self._course_key = None
def __str__(self):
"""
String representation of the course fixture, useful for debugging.
"""
return u"<CourseFixture: org='{org}', number='{number}', run='{run}'>".format(**self._course_dict)
def add_course_details(self, course_details):
"""
Add course details to dict of course details to be updated when configure_course or install is called.
Arguments:
Dictionary containing key value pairs for course updates,
e.g. {'start_date': datetime.now() }
"""
if 'start_date' in course_details:
course_details['start_date'] = course_details['start_date'].isoformat()
if 'end_date' in course_details:
course_details['end_date'] = course_details['end_date'].isoformat()
self._course_details.update(course_details)
def add_update(self, update):
"""
Add an update to the course. `update` should be a `CourseUpdateDesc`.
"""
self._updates.append(update)
def add_handout(self, asset_name):
"""
Add the handout named `asset_name` to the course info page.
Note that this does not actually *create* the static asset; it only links to it.
"""
self._handouts.append(asset_name)
def add_asset(self, asset_name):
"""
Add the asset to the list of assets to be uploaded when the install method is called.
"""
self._assets.extend(asset_name)
def add_textbook(self, book_title, chapters):
"""
Add textbook to the list of textbooks to be added when the install method is called.
"""
self._textbooks.append({"chapters": chapters, "tab_title": book_title})
def add_advanced_settings(self, settings):
"""
Adds advanced settings to be set on the course when the install method is called.
"""
self._advanced_settings.update(settings)
def install(self):
"""
Create the course and XBlocks within the course.
This is NOT an idempotent method; if the course already exists, this will
raise a `FixtureError`. You should use unique course identifiers to avoid
conflicts between tests.
"""
self._create_course()
self._install_course_updates()
self._install_course_handouts()
self._install_course_textbooks()
self._configure_course()
self._upload_assets()
self._add_advanced_settings()
self._create_xblock_children(self._course_location, self.children)
return self
def configure_course(self):
"""
Configure Course Settings, take new course settings from self._course_details dict object
"""
self._configure_course()
@property
def studio_course_outline_as_json(self):
"""
Retrieves Studio course outline in JSON format.
"""
url = STUDIO_BASE_URL + '/course/' + self._course_key + "?format=json"
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course outline json. Status was {0}".format(
response.status_code))
try:
course_outline_json = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course outline as JSON: '{0}'".format(response)
)
return course_outline_json
@property
def _course_location(self):
"""
Return the locator string for the course.
"""
course_key = CourseKey.from_string(self._course_key)
if getattr(course_key, 'deprecated', False):
block_id = self._course_dict['run']
else:
block_id = 'course'
return unicode(course_key.make_usage_key('course', block_id))
@property
def _assets_url(self):
"""
Return the url string for the assets
"""
return "/assets/" + self._course_key + "/"
@property
def _handouts_loc(self):
"""
Return the locator string for the course handouts
"""
course_key = CourseKey.from_string(self._course_key)
return unicode(course_key.make_usage_key('course_info', 'handouts'))
def | (self):
"""
Create the course described in the fixture.
"""
# If the course already exists, this will respond
# with a 200 and an error message, which we ignore.
response = self.session.post(
STUDIO_BASE_URL + '/course/',
data=self._encode_post_dict(self._course_dict),
headers=self.headers
)
try:
err = response.json().get('ErrMsg')
except ValueError:
raise FixtureError(
u"Could not parse response from course request as JSON: '{0}'".format(
response.content))
# This will occur if the course identifier is not unique
if err is not None:
raise FixtureError(u"Could not create course {0}. Error message: '{1}'".format(self, err))
if response.ok:
self._course_key = response.json()['course_key']
else:
raise FixtureError(
u"Could not create course {0}. Status was {1}\nResponse content was: {2}".format(
self._course_dict, response.status_code, response.content))
def _configure_course(self):
"""
Configure course settings (e.g. start and end date)
"""
url = STUDIO_BASE_URL + '/settings/details/' + self._course_key
# First, get the current values
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course details. Status was {0}".format(
response.status_code))
try:
details = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course details as JSON: '{0}'".format(details)
)
# Update the old details with our overrides
details.update(self._course_details)
# POST the updated details to Studio
response = self.session.post(
url, data=self._encode_post_dict(details),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update course details to '{0}' with {1}: Status was {2}.".format(
self._course_details, url, response.status_code))
def _install_course_handouts(self):
"""
Add handouts to the course info page.
"""
url = STUDIO_BASE_URL + '/xblock/' + self._handouts_loc
# Construct HTML with each of the handout links
handouts_li = [
u'<li><a href="/static/{handout}">Example Handout</a></li>'.format(handout=handout)
for handout in self._handouts
]
handouts_html = u'<ol class="treeview-handoutsnav">{}</ol>'.format("".join(handouts_li))
# Update the course's handouts HTML
payload = json.dumps({
'children': None,
'data': handouts_html,
'id': self._handouts_loc,
'metadata': dict(),
})
response = self.session.post(url, data=payload, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not update course handouts with {0}. Status was {1}".format(url, response.status_code))
def _install_course_updates(self):
"""
Add updates to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/course_info_update/' + self._course_key + '/'
for update in self._updates:
# Add the update to the course
date, content = update
payload = json.dumps({'date': date, 'content': content})
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add update to course: {0} with {1}. Status was {2}".format(
update, url, response.status_code))
def _upload_assets(self):
"""
Upload assets
:raise FixtureError:
"""
url = STUDIO_BASE_URL + self._assets_url
test_dir = Path(__file__).abspath().dirname().dirname().dirname()
for asset_name in self._assets:
asset_file_path = test_dir + '/data/uploads/' + asset_name
asset_file = open(asset_file_path)
files = {'file': (asset_name, asset_file, mimetypes.guess_type(asset_file_path)[0])}
headers = {
'Accept': 'application/json',
'X-CSRFToken': self.session_cookies.get('csrftoken', '')
}
upload_response = self.session.post(url, files=files, headers=headers)
if not upload_response.ok:
raise FixtureError(u'Could not upload {asset_name} with {url}. Status code: {code}'.format(
asset_name=asset_name, url=url, code=upload_response.status_code))
def _install_course_textbooks(self):
"""
Add textbooks to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/textbooks/' + self._course_key
for book in self._textbooks:
payload = json.dumps(book)
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add book to course: {0} with {1}. Status was {2}".format(
book, url, response.status_code))
def _add_advanced_settings(self):
"""
Add advanced settings.
"""
url = STUDIO_BASE_URL + "/settings/advanced/" + self._course_key
# POST advanced settings to Studio
response = self.session.post(
url, data=self._encode_post_dict(self._advanced_settings),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update advanced details to '{0}' with {1}: Status was {2}.".format(
self._advanced_settings, url, response.status_code))
def _create_xblock_children(self, parent_loc, xblock_descriptions):
"""
Recursively create XBlock children.
"""
super(CourseFixture, self)._create_xblock_children(parent_loc, xblock_descriptions)
self._publish_xblock(parent_loc)
| _create_course | identifier_name |
course.py | """
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture
class XBlockFixtureDesc(object):
"""
Description of an XBlock, used to configure a course fixture.
"""
def __init__(self, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`
* `data`
* `metadata`
* `grader_type`
* `publish`
"""
self.category = category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Add child XBlocks to this XBlock.
Each item in `args` is an `XBlockFixtureDesc` object.
Returns the `xblock_desc` instance to allow chaining.
"""
self.children.extend(args)
return self
def serialize(self):
"""
Return a JSON representation of the XBlock, suitable
for sending as POST data to /xblock
XBlocks are always set to public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(returned_data)
def __str__(self):
"""
Return a string representation of the description.
Useful for error messages.
"""
return dedent(u"""
<XBlockFixtureDescriptor:
category={0},
data={1},
metadata={2},
grader_type={3},
publish={4},
children={5},
locator={6},
>
""").strip().format(
self.category, self.data, self.metadata,
self.grader_type, self.publish, self.children, self.locator
)
# Description of course updates to add to the course
# `date` is a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
between tests, you should use unique course identifiers for each fixture.
"""
def __init__(self, org, number, run, display_name, start_date=None, end_date=None, settings=None):
"""
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is generally what
we want for testing so students can enroll.
`settings` can be any additional course settings needs to be enabled. for example
to enable entrance exam settings would be a dict like this {"entrance_exam_enabled": "true"}
These have the same meaning as in the Studio restful API /course end-point. | 'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
if end_date is not None:
self._course_details['end_date'] = end_date.isoformat()
if settings is not None:
self._course_details.update(settings)
self._updates = []
self._handouts = []
self._assets = []
self._textbooks = []
self._advanced_settings = {}
self._course_key = None
def __str__(self):
"""
String representation of the course fixture, useful for debugging.
"""
return u"<CourseFixture: org='{org}', number='{number}', run='{run}'>".format(**self._course_dict)
def add_course_details(self, course_details):
"""
Add course details to dict of course details to be updated when configure_course or install is called.
Arguments:
Dictionary containing key value pairs for course updates,
e.g. {'start_date': datetime.now() }
"""
if 'start_date' in course_details:
course_details['start_date'] = course_details['start_date'].isoformat()
if 'end_date' in course_details:
course_details['end_date'] = course_details['end_date'].isoformat()
self._course_details.update(course_details)
def add_update(self, update):
"""
Add an update to the course. `update` should be a `CourseUpdateDesc`.
"""
self._updates.append(update)
def add_handout(self, asset_name):
"""
Add the handout named `asset_name` to the course info page.
Note that this does not actually *create* the static asset; it only links to it.
"""
self._handouts.append(asset_name)
def add_asset(self, asset_name):
"""
Add the asset to the list of assets to be uploaded when the install method is called.
"""
self._assets.extend(asset_name)
def add_textbook(self, book_title, chapters):
"""
Add textbook to the list of textbooks to be added when the install method is called.
"""
self._textbooks.append({"chapters": chapters, "tab_title": book_title})
def add_advanced_settings(self, settings):
"""
Adds advanced settings to be set on the course when the install method is called.
"""
self._advanced_settings.update(settings)
def install(self):
"""
Create the course and XBlocks within the course.
This is NOT an idempotent method; if the course already exists, this will
raise a `FixtureError`. You should use unique course identifiers to avoid
conflicts between tests.
"""
self._create_course()
self._install_course_updates()
self._install_course_handouts()
self._install_course_textbooks()
self._configure_course()
self._upload_assets()
self._add_advanced_settings()
self._create_xblock_children(self._course_location, self.children)
return self
def configure_course(self):
"""
Configure Course Settings, take new course settings from self._course_details dict object
"""
self._configure_course()
@property
def studio_course_outline_as_json(self):
"""
Retrieves Studio course outline in JSON format.
"""
url = STUDIO_BASE_URL + '/course/' + self._course_key + "?format=json"
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course outline json. Status was {0}".format(
response.status_code))
try:
course_outline_json = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course outline as JSON: '{0}'".format(response)
)
return course_outline_json
@property
def _course_location(self):
"""
Return the locator string for the course.
"""
course_key = CourseKey.from_string(self._course_key)
if getattr(course_key, 'deprecated', False):
block_id = self._course_dict['run']
else:
block_id = 'course'
return unicode(course_key.make_usage_key('course', block_id))
@property
def _assets_url(self):
"""
Return the url string for the assets
"""
return "/assets/" + self._course_key + "/"
@property
def _handouts_loc(self):
"""
Return the locator string for the course handouts
"""
course_key = CourseKey.from_string(self._course_key)
return unicode(course_key.make_usage_key('course_info', 'handouts'))
def _create_course(self):
"""
Create the course described in the fixture.
"""
# If the course already exists, this will respond
# with a 200 and an error message, which we ignore.
response = self.session.post(
STUDIO_BASE_URL + '/course/',
data=self._encode_post_dict(self._course_dict),
headers=self.headers
)
try:
err = response.json().get('ErrMsg')
except ValueError:
raise FixtureError(
u"Could not parse response from course request as JSON: '{0}'".format(
response.content))
# This will occur if the course identifier is not unique
if err is not None:
raise FixtureError(u"Could not create course {0}. Error message: '{1}'".format(self, err))
if response.ok:
self._course_key = response.json()['course_key']
else:
raise FixtureError(
u"Could not create course {0}. Status was {1}\nResponse content was: {2}".format(
self._course_dict, response.status_code, response.content))
def _configure_course(self):
"""
Configure course settings (e.g. start and end date)
"""
url = STUDIO_BASE_URL + '/settings/details/' + self._course_key
# First, get the current values
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course details. Status was {0}".format(
response.status_code))
try:
details = response.json()
except ValueError:
raise FixtureError(
u"Could not decode course details as JSON: '{0}'".format(details)
)
# Update the old details with our overrides
details.update(self._course_details)
# POST the updated details to Studio
response = self.session.post(
url, data=self._encode_post_dict(details),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update course details to '{0}' with {1}: Status was {2}.".format(
self._course_details, url, response.status_code))
def _install_course_handouts(self):
"""
Add handouts to the course info page.
"""
url = STUDIO_BASE_URL + '/xblock/' + self._handouts_loc
# Construct HTML with each of the handout links
handouts_li = [
u'<li><a href="/static/{handout}">Example Handout</a></li>'.format(handout=handout)
for handout in self._handouts
]
handouts_html = u'<ol class="treeview-handoutsnav">{}</ol>'.format("".join(handouts_li))
# Update the course's handouts HTML
payload = json.dumps({
'children': None,
'data': handouts_html,
'id': self._handouts_loc,
'metadata': dict(),
})
response = self.session.post(url, data=payload, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not update course handouts with {0}. Status was {1}".format(url, response.status_code))
def _install_course_updates(self):
"""
Add updates to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/course_info_update/' + self._course_key + '/'
for update in self._updates:
# Add the update to the course
date, content = update
payload = json.dumps({'date': date, 'content': content})
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add update to course: {0} with {1}. Status was {2}".format(
update, url, response.status_code))
def _upload_assets(self):
"""
Upload assets
:raise FixtureError:
"""
url = STUDIO_BASE_URL + self._assets_url
test_dir = Path(__file__).abspath().dirname().dirname().dirname()
for asset_name in self._assets:
asset_file_path = test_dir + '/data/uploads/' + asset_name
asset_file = open(asset_file_path)
files = {'file': (asset_name, asset_file, mimetypes.guess_type(asset_file_path)[0])}
headers = {
'Accept': 'application/json',
'X-CSRFToken': self.session_cookies.get('csrftoken', '')
}
upload_response = self.session.post(url, files=files, headers=headers)
if not upload_response.ok:
raise FixtureError(u'Could not upload {asset_name} with {url}. Status code: {code}'.format(
asset_name=asset_name, url=url, code=upload_response.status_code))
def _install_course_textbooks(self):
"""
Add textbooks to the course, if any are configured.
"""
url = STUDIO_BASE_URL + '/textbooks/' + self._course_key
for book in self._textbooks:
payload = json.dumps(book)
response = self.session.post(url, headers=self.headers, data=payload)
if not response.ok:
raise FixtureError(
u"Could not add book to course: {0} with {1}. Status was {2}".format(
book, url, response.status_code))
def _add_advanced_settings(self):
"""
Add advanced settings.
"""
url = STUDIO_BASE_URL + "/settings/advanced/" + self._course_key
# POST advanced settings to Studio
response = self.session.post(
url, data=self._encode_post_dict(self._advanced_settings),
headers=self.headers,
)
if not response.ok:
raise FixtureError(
u"Could not update advanced details to '{0}' with {1}: Status was {2}.".format(
self._advanced_settings, url, response.status_code))
def _create_xblock_children(self, parent_loc, xblock_descriptions):
"""
Recursively create XBlock children.
"""
super(CourseFixture, self)._create_xblock_children(parent_loc, xblock_descriptions)
self._publish_xblock(parent_loc) | """
super(CourseFixture, self).__init__()
self._course_dict = {
'org': org,
'number': number, | random_line_split |
fs.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::sync::{atomic, RwLock, RwLockReadGuard};
use std::{fmt, fs, io};
use futures::future::{self, BoxFuture, Future};
use futures_cpupool::{self, CpuFuture, CpuPool};
use glob::Pattern;
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use ignore;
use ordermap::OrderMap;
use tar;
use tempdir::TempDir;
use hash::{Fingerprint, WriterHasher};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Stat {
Link(Link),
Dir(Dir),
File(File),
}
impl Stat {
pub fn path(&self) -> &Path {
match self {
&Stat::Dir(Dir(ref p)) => p.as_path(),
&Stat::File(File(ref p)) => p.as_path(),
&Stat::Link(Link(ref p)) => p.as_path(),
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Link(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Dir(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct File(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PathStat {
Dir {
// The symbolic name of some filesystem Path, which is context specific.
path: PathBuf,
// The canonical Stat that underlies the Path.
stat: Dir,
},
File {
// The symbolic name of some filesystem Path, which is context specific.
path: PathBuf,
// The canonical Stat that underlies the Path.
stat: File,
}
}
impl PathStat {
fn dir(path: PathBuf, stat: Dir) -> PathStat {
PathStat::Dir {
path: path,
stat: stat,
}
}
fn file(path: PathBuf, stat: File) -> PathStat {
PathStat::File {
path: path,
stat: stat,
}
}
pub fn path(&self) -> &Path {
match self {
&PathStat::Dir { ref path, .. } => path.as_path(),
&PathStat::File { ref path, .. } => path.as_path(),
}
}
}
lazy_static! {
static ref PARENT_DIR: &'static str = "..";
static ref SINGLE_STAR_GLOB: Pattern = Pattern::new("*").unwrap();
static ref DOUBLE_STAR: &'static str = "**";
static ref DOUBLE_STAR_GLOB: Pattern = Pattern::new("**").unwrap();
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PathGlob {
Wildcard {
canonical_dir: Dir,
symbolic_path: PathBuf,
wildcard: Pattern,
},
DirWildcard {
canonical_dir: Dir,
symbolic_path: PathBuf,
wildcard: Pattern,
remainder: Vec<Pattern>,
},
}
impl PathGlob {
fn wildcard(canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> PathGlob {
PathGlob::Wildcard {
canonical_dir: canonical_dir,
symbolic_path: symbolic_path,
wildcard: wildcard,
}
}
fn dir_wildcard(canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern, remainder: Vec<Pattern>) -> PathGlob {
PathGlob::DirWildcard {
canonical_dir: canonical_dir,
symbolic_path: symbolic_path,
wildcard: wildcard,
remainder: remainder,
}
}
pub fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
Ok(path_globs)
}
/**
* Given a filespec String relative to a canonical Dir and path, split it into path components
* while eliminating consecutive '**'s (to avoid repetitive traversing), and parse it to a
* series of PathGlob objects.
*/
fn parse(canonical_dir: Dir, symbolic_path: PathBuf, filespec: &str) -> Result<Vec<PathGlob>, String> {
let mut parts = Vec::new();
let mut prev_was_doublestar = false;
for component in Path::new(filespec).components() {
let part =
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", filespec)),
Component::CurDir =>
continue,
c => c.as_os_str(),
};
// Ignore repeated doublestar instances.
let cur_is_doublestar = *DOUBLE_STAR == part;
if prev_was_doublestar && cur_is_doublestar {
continue;
}
prev_was_doublestar = cur_is_doublestar;
// NB: Because the filespec is a String input, calls to `to_str_lossy` are not lossy; the
// use of `Path` is strictly for os-independent Path parsing.
parts.push(
Pattern::new(&part.to_string_lossy())
.map_err(|e| format!("Could not parse {:?} as a glob: {:?}", filespec, e))?
);
}
PathGlob::parse_globs(canonical_dir, symbolic_path, &parts)
}
/**
* Given a filespec as Patterns, create a series of PathGlob objects.
*/
fn parse_globs(
canonical_dir: Dir,
symbolic_path: PathBuf,
parts: &[Pattern]
) -> Result<Vec<PathGlob>, String> {
if parts.is_empty() {
Ok(vec![])
} else if *DOUBLE_STAR == parts[0].as_str() {
if parts.len() == 1 {
// Per https://git-scm.com/docs/gitignore:
// "A trailing '/**' matches everything inside. For example, 'abc/**' matches all files inside
// directory "abc", relative to the location of the .gitignore file, with infinite depth."
return Ok(
vec![
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
vec![DOUBLE_STAR_GLOB.clone()]
),
PathGlob::wildcard(canonical_dir, symbolic_path, SINGLE_STAR_GLOB.clone()),
]
);
}
// There is a double-wildcard in a dirname of the path: double wildcards are recursive,
// so there are two remainder possibilities: one with the double wildcard included, and the
// other without.
let pathglob_with_doublestar =
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
parts[0..].to_vec()
);
let pathglob_no_doublestar =
if parts.len() == 2 {
PathGlob::wildcard(canonical_dir, symbolic_path, parts[1].clone())
} else {
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[1].clone(), parts[2..].to_vec())
};
Ok(vec![pathglob_with_doublestar, pathglob_no_doublestar])
} else if *PARENT_DIR == parts[0].as_str() {
// A request for the parent of `canonical_dir`: since we've already expanded the directory
// to make it canonical, we can safely drop it directly and recurse without this component.
// The resulting symbolic path will continue to contain a literal `..`.
let mut canonical_dir_parent = canonical_dir;
let mut symbolic_path_parent = symbolic_path;
if !canonical_dir_parent.0.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", parts));
}
symbolic_path_parent.push(Path::new(*PARENT_DIR));
PathGlob::parse_globs(canonical_dir_parent, symbolic_path_parent, &parts[1..])
} else if parts.len() == 1 {
// This is the path basename.
Ok(
vec![
PathGlob::wildcard(canonical_dir, symbolic_path, parts[0].clone())
]
)
} else {
// This is a path dirname.
Ok(
vec![
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[0].clone(), parts[1..].to_vec())
]
)
}
}
}
#[derive(Debug)]
pub struct PathGlobs {
include: Vec<PathGlob>,
exclude: Vec<PathGlob>,
}
impl PathGlobs {
pub fn create(include: &[String], exclude: &[String]) -> Result<PathGlobs, String> {
Ok(
PathGlobs {
include: PathGlob::create(include)?,
exclude: PathGlob::create(exclude)?,
}
)
}
}
#[derive(Debug)]
struct PathGlobsExpansion<T: Sized> {
context: T,
// Globs that have yet to be expanded, in order.
todo: Vec<PathGlob>,
// Globs that have already been expanded.
completed: HashSet<PathGlob>,
// Unique Paths that have been matched, in order.
outputs: OrderMap<PathStat, ()>,
}
pub struct PosixFS {
build_root: Dir,
// The pool needs to be reinitialized after a fork, so it is protected by a lock.
pool: RwLock<CpuPool>,
ignore: Gitignore,
}
impl PosixFS {
pub fn new(
build_root: PathBuf,
ignore_patterns: Vec<String>,
) -> Result<PosixFS, String> {
let pool = RwLock::new(PosixFS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
}
)
)
.map_err(|e| format!("Could not canonicalize build root {:?}: {:?}", build_root, e))?;
let ignore =
PosixFS::create_ignore(&canonical_build_root, &ignore_patterns)
.map_err(|e|
format!("Could not parse build ignore inputs {:?}: {:?}", ignore_patterns, e)
)?;
Ok(
PosixFS {
build_root: canonical_build_root,
pool: pool,
ignore: ignore,
}
)
}
fn create_pool() -> CpuPool {
futures_cpupool::Builder::new()
.name_prefix("vfs-")
.create()
}
fn | (root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf) -> Result<Vec<Stat>, io::Error> {
let mut stats = Vec::new();
for dir_entry_res in dir_abs.read_dir()? {
let dir_entry = dir_entry_res?;
let path = dir.0.join(dir_entry.file_name());
let file_type = dir_entry.file_type()?;
if file_type.is_dir() {
stats.push(Stat::Dir(Dir(path)));
} else if file_type.is_file() {
stats.push(Stat::File(File(path)));
} else if file_type.is_symlink() {
stats.push(Stat::Link(Link(path)));
}
// Else: ignore.
}
stats.sort_by(|s1, s2| s1.path().cmp(s2.path()));
Ok(stats)
}
fn pool(&self) -> RwLockReadGuard<CpuPool> {
self.pool.read().unwrap()
}
pub fn post_fork(&self) {
let mut pool = self.pool.write().unwrap();
*pool = PosixFS::create_pool();
}
pub fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool {
match self.ignore.matched(path, is_dir) {
ignore::Match::None | ignore::Match::Whitelist(_) => false,
ignore::Match::Ignore(_) => true,
}
}
pub fn read_link(&self, link: &Link) -> BoxFuture<PathBuf, io::Error> {
let link_parent = link.0.parent().map(|p| p.to_owned());
let link_abs = self.build_root.0.join(link.0.as_path()).to_owned();
self.pool()
.spawn_fn(move || {
link_abs
.read_link()
.and_then(|path_buf| {
if path_buf.is_absolute() {
Err(
io::Error::new(
io::ErrorKind::InvalidData, format!("Absolute symlink: {:?}", link_abs)
)
)
} else {
link_parent
.map(|parent| parent.join(path_buf))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData, format!("Symlink without a parent?: {:?}", link_abs)
)
})
}
})
})
.boxed()
}
pub fn scandir(&self, dir: &Dir) -> BoxFuture<Vec<Stat>, io::Error> {
let dir = dir.to_owned();
let dir_abs = self.build_root.0.join(dir.0.as_path());
self.pool()
.spawn_fn(move || {
PosixFS::scandir_sync(dir, dir_abs)
})
.boxed()
}
}
/**
* A context for filesystem operations parameterized on an error type 'E'.
*/
pub trait VFS<E: Send + Sync + 'static> : Clone + Send + Sync + 'static {
fn read_link(&self, link: Link) -> BoxFuture<PathBuf, E>;
fn scandir(&self, dir: Dir) -> BoxFuture<Vec<Stat>, E>;
fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool;
fn mk_error(msg: &str) -> E;
/**
* Canonicalize the Link for the given Path to an underlying File or Dir. May result
* in None if the PathStat represents a broken Link.
*
* Skips ignored paths both before and after expansion.
*
* TODO: Should handle symlink loops (which would exhibit as an infinite loop in expand_multi).
*/
fn canonicalize(&self, symbolic_path: PathBuf, link: Link) -> BoxFuture<Option<PathStat>, E> {
// Read the link, which may result in PathGlob(s) that match 0 or 1 Path.
let context = self.clone();
self.read_link(link)
.map(|dest_path| {
// If the link destination can't be parsed as PathGlob(s), it is broken.
dest_path.to_str()
.and_then(|dest_str| {
let escaped = Pattern::escape(dest_str);
PathGlob::create(&[escaped]).ok()
})
.unwrap_or_else(|| vec![])
})
.and_then(move |link_globs| {
context.expand_multi(link_globs)
})
.map(|mut path_stats| {
// Since we've escaped any globs in the parsed path, expect either 0 or 1 destination.
path_stats.pop().map(|ps| match ps {
PathStat::Dir { stat, .. } => PathStat::dir(symbolic_path, stat),
PathStat::File { stat, .. } => PathStat::file(symbolic_path, stat),
})
})
.boxed()
}
fn directory_listing(&self, canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> BoxFuture<Vec<PathStat>, E> {
// List the directory.
let context = self.clone();
self.scandir(canonical_dir)
.and_then(move |dir_listing| {
// Match any relevant Stats, and join them into PathStats.
future::join_all(
dir_listing.into_iter()
.filter(|stat| {
// Match relevant filenames.
stat.path().file_name()
.map(|file_name| wildcard.matches_path(Path::new(file_name)))
.unwrap_or(false)
})
.filter_map(|stat| {
// Append matched filenames.
stat.path().file_name()
.map(|file_name| {
symbolic_path.join(file_name)
})
.map(|symbolic_stat_path| {
(symbolic_stat_path, stat)
})
})
.map(|(stat_symbolic_path, stat)| {
// Canonicalize matched PathStats, and filter ignored paths. Note that we ignore
// links both before and after expansion.
match stat {
Stat::Link(l) => {
if context.ignore(l.0.as_path(), false) {
future::ok(None).boxed()
} else {
context.canonicalize(stat_symbolic_path, l)
}
},
Stat::Dir(d) => {
let res =
if context.ignore(d.0.as_path(), true) {
None
} else {
Some(PathStat::dir(stat_symbolic_path.to_owned(), d))
};
future::ok(res).boxed()
},
Stat::File(f) => {
let res =
if context.ignore(f.0.as_path(), false) {
None
} else {
Some(PathStat::file(stat_symbolic_path.to_owned(), f))
};
future::ok(res).boxed()
},
}
})
.collect::<Vec<_>>()
)
})
.map(|path_stats| {
// See the TODO above.
path_stats.into_iter().filter_map(|pso| pso).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats while applying excludes.
*
* TODO: Eventually, it would be nice to be able to apply excludes as we go, to
* avoid walking into directories that aren't relevant.
*/
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i| !exclude_set.contains(i)).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path_globs,
completed: HashSet::default(),
outputs: OrderMap::default()
};
future::loop_fn(init, |mut expansion| {
// Request the expansion of all outstanding PathGlobs as a batch.
let round =
future::join_all({
let context = &expansion.context;
expansion.todo.drain(..)
.map(|path_glob| context.expand_single(path_glob))
.collect::<Vec<_>>()
});
round
.map(move |paths_and_globs| {
// Collect distinct new PathStats and PathGlobs
for (paths, globs) in paths_and_globs.into_iter() {
expansion.outputs.extend(paths.into_iter().map(|p| (p, ())));
let completed = &mut expansion.completed;
expansion.todo.extend(
globs.into_iter()
.filter(|pg| completed.insert(pg.clone()))
);
}
// If there were any new PathGlobs, continue the expansion.
if expansion.todo.is_empty() {
future::Loop::Break(expansion)
} else {
future::Loop::Continue(expansion)
}
})
})
.map(|expansion| {
assert!(
expansion.todo.is_empty(),
"Loop shouldn't have exited with work to do: {:?}",
expansion.todo,
);
// Finally, capture the resulting PathStats from the expansion.
expansion.outputs.into_iter().map(|(k, _)| k).collect()
})
.boxed()
}
/**
* Apply a PathGlob, returning PathStats and additional PathGlobs that are needed for the
* expansion.
*/
fn expand_single(&self, path_glob: PathGlob) -> BoxFuture<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path_stats, vec![]))
.boxed(),
PathGlob::DirWildcard { canonical_dir, symbolic_path, wildcard, remainder } =>
// Filter directory listing and request additional PathGlobs for matched Dirs.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.and_then(move |path_stats| {
path_stats.into_iter()
.filter_map(|ps| match ps {
PathStat::Dir { path, stat } =>
Some(
PathGlob::parse_globs(stat, path, &remainder)
.map_err(|e| Self::mk_error(e.as_str()))
),
PathStat::File { .. } => None,
})
.collect::<Result<Vec<_>, E>>()
})
.map(|path_globs| {
let flattened =
path_globs.into_iter()
.flat_map(|path_globs| path_globs.into_iter())
.collect();
(vec![], flattened)
})
.boxed(),
}
}
}
pub struct FileContent {
pub path: PathBuf,
pub content: Vec<u8>,
}
#[derive(Clone)]
pub struct Snapshot {
pub fingerprint: Fingerprint,
pub path_stats: Vec<PathStat>,
}
impl fmt::Debug for Snapshot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Snapshot({}, entries={})", self.fingerprint.to_hex(), self.path_stats.len())
}
}
/**
* A facade for the snapshot directory, which is currently thrown away at the end of each run.
*/
pub struct Snapshots {
temp_dir: TempDir,
next_temp_id: atomic::AtomicUsize,
}
impl Snapshots {
pub fn new() -> Result<Snapshots, io::Error> {
Ok(
Snapshots {
// TODO: see https://github.com/pantsbuild/pants/issues/4299
temp_dir: TempDir::new("snapshots")?,
next_temp_id: atomic::AtomicUsize::new(0),
}
)
}
pub fn path(&self) -> &Path {
self.temp_dir.path()
}
/**
* A non-canonical (does not expand symlinks) in-memory form of normalize. Used to collapse
* parent and cur components, which are legal in symbolic paths in PathStats, but not in
* Tar files.
*/
fn normalize(path: &Path) -> Result<PathBuf, String> {
let mut res = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", path)),
Component::CurDir =>
continue,
Component::ParentDir => {
// Pop the previous component.
if !res.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", path));
} else {
continue
}
},
Component::Normal(p) =>
res.push(p),
}
}
Ok(res)
}
/**
* Create a tar file on the given Write instance containing the given paths, or
* return an error string.
*/
fn tar_create<W: io::Write>(
dest: W,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<W, String> {
let mut tar_builder = tar::Builder::new(dest);
tar_builder.mode(tar::HeaderMode::Deterministic);
for path_stat in paths {
// Append the PathStat using the symbolic name and underlying stat.
let append_res =
match path_stat {
&PathStat::File { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
let mut input =
fs::File::open(relative_to.0.join(stat.0.as_path()))
.map_err(|e| format!("Failed to open {:?}: {:?}", path_stat, e))?;
tar_builder.append_file(normalized, &mut input)
},
&PathStat::Dir { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
tar_builder.append_dir(normalized, relative_to.0.join(stat.0.as_path()))
},
};
append_res
.map_err(|e| format!("Failed to tar {:?}: {:?}", path_stat, e))?;
}
// Finish the tar file, returning ownership of the stream to the caller.
Ok(
tar_builder.into_inner()
.map_err(|e| format!("Failed to finalize snapshot tar: {:?}", e))?
)
}
/**
* Create a tar file at the given dest Path containing the given paths, while
* fingerprinting the written stream.
*/
fn tar_create_fingerprinted(
dest: &Path,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<Fingerprint, String> {
// Wrap buffering around a fingerprinted stream above a File.
let stream =
io::BufWriter::new(
WriterHasher::new(
fs::File::create(dest)
.map_err(|e| format!("Failed to create destination file: {:?}", e))?
)
);
// Then append the tar to the stream, and retrieve the Fingerprint to flush all writers.
Ok(
Snapshots::tar_create(stream, paths, relative_to)?
.into_inner()
.map_err(|e| format!("Failed to flush to {:?}: {:?}", dest, e.error()))?
.finish()
)
}
fn path_for(&self, fingerprint: &Fingerprint) -> PathBuf {
Snapshots::path_under_for(self.temp_dir.path(), fingerprint)
}
fn path_under_for(path: &Path, fingerprint: &Fingerprint) -> PathBuf {
let hex = fingerprint.to_hex();
path.join(&hex[0..2]).join(&hex[2..4]).join(format!("{}.tar", hex))
}
/**
* Retries create_dir_all up to N times before failing. Necessary in concurrent environments.
*/
fn create_dir_all(dir: &Path) -> Result<(), String> {
let mut attempts = 16;
loop {
let res = fs::create_dir_all(dir);
if res.is_ok() {
return Ok(());
} else if attempts <= 0 {
return {
res.map_err(|e| format!("Failed to create directory {:?}: {:?}", dir, e))
}
}
attempts -= 1;
}
}
/**
* Attempts to rename src to dst, and _succeeds_ if dst already exists. This is safe in
* the case of Snapshots because the destination path is unique to its content.
*/
fn finalize(temp_path: &Path, dest_path: &Path) -> Result<(), String> {
if dest_path.is_file() {
// The Snapshot has already been created.
fs::remove_file(temp_path).unwrap_or(());
Ok(())
} else {
let dest_dir = dest_path.parent().expect("All snapshot paths must have parent directories.");
// As long as the destination file gets created, we've succeeded.
Snapshots::create_dir_all(dest_dir)?;
match fs::rename(temp_path, dest_path) {
Ok(_) => Ok(()),
Err(_) if dest_path.is_file() => Ok(()),
Err(e) => Err(format!("Failed to finalize snapshot at {:?}: {:?}", dest_path, e))
}
}
}
/**
* Creates a Snapshot for the given paths under the given VFS.
*/
pub fn create(&self, fs: &PosixFS, paths: Vec<PathStat>) -> CpuFuture<Snapshot, String> {
let dest_dir = self.temp_dir.path().to_owned();
let build_root = fs.build_root.clone();
let temp_path = {
let next_temp_id = self.next_temp_id.fetch_add(1, atomic::Ordering::SeqCst);
self.temp_dir.path().join(format!("{}.tar.tmp", next_temp_id))
};
fs.pool().spawn_fn(move || {
// Write the tar deterministically to a temporary file while fingerprinting.
let fingerprint =
Snapshots::tar_create_fingerprinted(temp_path.as_path(), &paths, &build_root)?;
// Rename to the final path if it does not already exist.
Snapshots::finalize(
temp_path.as_path(),
Snapshots::path_under_for(&dest_dir, &fingerprint).as_path()
)?;
Ok(
Snapshot {
fingerprint: fingerprint,
path_stats: paths,
}
)
})
}
fn contents_for_sync(snapshot: Snapshot, path: PathBuf) -> Result<Vec<FileContent>, io::Error> {
let mut archive = fs::File::open(path).map(|f| tar::Archive::new(f))?;
// Zip the in-memory Snapshot to the on disk representation, validating as we go.
let mut files_content = Vec::new();
for (entry_res, path_stat) in archive.entries()?.zip(snapshot.path_stats.into_iter()) {
let mut entry = entry_res?;
if entry.header().entry_type() == tar::EntryType::file() {
let path =
match path_stat {
PathStat::File { path, .. } => path,
PathStat::Dir { .. } => panic!("Snapshot contents changed after storage."),
};
let mut content = Vec::new();
io::Read::read_to_end(&mut entry, &mut content)?;
files_content.push(
FileContent {
path: path,
content: content,
}
);
}
}
Ok(files_content)
}
pub fn contents_for(&self, fs: &PosixFS, snapshot: Snapshot) -> CpuFuture<Vec<FileContent>, String> {
let archive_path = self.path_for(&snapshot.fingerprint);
fs.pool().spawn_fn(move || {
let snapshot_str = format!("{:?}", snapshot);
Snapshots::contents_for_sync(snapshot, archive_path)
.map_err(|e| format!("Failed to open Snapshot {}: {:?}", snapshot_str, e))
})
}
}
| create_ignore | identifier_name |
fs.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::sync::{atomic, RwLock, RwLockReadGuard};
use std::{fmt, fs, io};
use futures::future::{self, BoxFuture, Future};
use futures_cpupool::{self, CpuFuture, CpuPool};
use glob::Pattern;
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use ignore;
use ordermap::OrderMap;
use tar;
use tempdir::TempDir;
use hash::{Fingerprint, WriterHasher};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Stat {
Link(Link),
Dir(Dir),
File(File),
}
impl Stat {
pub fn path(&self) -> &Path {
match self {
&Stat::Dir(Dir(ref p)) => p.as_path(),
&Stat::File(File(ref p)) => p.as_path(),
&Stat::Link(Link(ref p)) => p.as_path(),
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Link(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Dir(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct File(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PathStat {
Dir {
// The symbolic name of some filesystem Path, which is context specific.
path: PathBuf,
// The canonical Stat that underlies the Path.
stat: Dir,
},
File {
// The symbolic name of some filesystem Path, which is context specific.
path: PathBuf,
// The canonical Stat that underlies the Path.
stat: File,
}
}
impl PathStat {
fn dir(path: PathBuf, stat: Dir) -> PathStat {
PathStat::Dir {
path: path,
stat: stat,
}
}
fn file(path: PathBuf, stat: File) -> PathStat {
PathStat::File {
path: path,
stat: stat,
}
}
pub fn path(&self) -> &Path {
match self {
&PathStat::Dir { ref path, .. } => path.as_path(),
&PathStat::File { ref path, .. } => path.as_path(),
}
}
}
lazy_static! {
static ref PARENT_DIR: &'static str = "..";
static ref SINGLE_STAR_GLOB: Pattern = Pattern::new("*").unwrap();
static ref DOUBLE_STAR: &'static str = "**";
static ref DOUBLE_STAR_GLOB: Pattern = Pattern::new("**").unwrap();
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PathGlob {
Wildcard {
canonical_dir: Dir,
symbolic_path: PathBuf,
wildcard: Pattern,
},
DirWildcard {
canonical_dir: Dir,
symbolic_path: PathBuf,
wildcard: Pattern,
remainder: Vec<Pattern>,
},
}
impl PathGlob {
fn wildcard(canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> PathGlob {
PathGlob::Wildcard {
canonical_dir: canonical_dir,
symbolic_path: symbolic_path,
wildcard: wildcard,
}
}
fn dir_wildcard(canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern, remainder: Vec<Pattern>) -> PathGlob {
PathGlob::DirWildcard {
canonical_dir: canonical_dir,
symbolic_path: symbolic_path,
wildcard: wildcard,
remainder: remainder,
}
}
pub fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
Ok(path_globs)
}
/**
* Given a filespec String relative to a canonical Dir and path, split it into path components
* while eliminating consecutive '**'s (to avoid repetitive traversing), and parse it to a
* series of PathGlob objects.
*/
fn parse(canonical_dir: Dir, symbolic_path: PathBuf, filespec: &str) -> Result<Vec<PathGlob>, String> {
let mut parts = Vec::new();
let mut prev_was_doublestar = false;
for component in Path::new(filespec).components() {
let part =
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", filespec)),
Component::CurDir =>
continue,
c => c.as_os_str(),
};
// Ignore repeated doublestar instances.
let cur_is_doublestar = *DOUBLE_STAR == part;
if prev_was_doublestar && cur_is_doublestar {
continue;
}
prev_was_doublestar = cur_is_doublestar;
// NB: Because the filespec is a String input, calls to `to_str_lossy` are not lossy; the
// use of `Path` is strictly for os-independent Path parsing.
parts.push(
Pattern::new(&part.to_string_lossy())
.map_err(|e| format!("Could not parse {:?} as a glob: {:?}", filespec, e))?
);
}
PathGlob::parse_globs(canonical_dir, symbolic_path, &parts)
}
/**
* Given a filespec as Patterns, create a series of PathGlob objects.
*/
fn parse_globs(
canonical_dir: Dir,
symbolic_path: PathBuf,
parts: &[Pattern]
) -> Result<Vec<PathGlob>, String> {
if parts.is_empty() {
Ok(vec![])
} else if *DOUBLE_STAR == parts[0].as_str() {
if parts.len() == 1 {
// Per https://git-scm.com/docs/gitignore:
// "A trailing '/**' matches everything inside. For example, 'abc/**' matches all files inside
// directory "abc", relative to the location of the .gitignore file, with infinite depth."
return Ok(
vec![
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
vec![DOUBLE_STAR_GLOB.clone()]
),
PathGlob::wildcard(canonical_dir, symbolic_path, SINGLE_STAR_GLOB.clone()),
]
);
}
// There is a double-wildcard in a dirname of the path: double wildcards are recursive,
// so there are two remainder possibilities: one with the double wildcard included, and the
// other without.
let pathglob_with_doublestar =
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
parts[0..].to_vec()
);
let pathglob_no_doublestar =
if parts.len() == 2 {
PathGlob::wildcard(canonical_dir, symbolic_path, parts[1].clone())
} else {
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[1].clone(), parts[2..].to_vec())
};
Ok(vec![pathglob_with_doublestar, pathglob_no_doublestar])
} else if *PARENT_DIR == parts[0].as_str() {
// A request for the parent of `canonical_dir`: since we've already expanded the directory
// to make it canonical, we can safely drop it directly and recurse without this component.
// The resulting symbolic path will continue to contain a literal `..`.
let mut canonical_dir_parent = canonical_dir;
let mut symbolic_path_parent = symbolic_path;
if !canonical_dir_parent.0.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", parts));
}
symbolic_path_parent.push(Path::new(*PARENT_DIR));
PathGlob::parse_globs(canonical_dir_parent, symbolic_path_parent, &parts[1..])
} else if parts.len() == 1 {
// This is the path basename.
Ok(
vec![
PathGlob::wildcard(canonical_dir, symbolic_path, parts[0].clone())
]
)
} else {
// This is a path dirname.
Ok(
vec![
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[0].clone(), parts[1..].to_vec())
]
)
}
}
}
#[derive(Debug)]
pub struct PathGlobs {
include: Vec<PathGlob>,
exclude: Vec<PathGlob>,
}
impl PathGlobs {
pub fn create(include: &[String], exclude: &[String]) -> Result<PathGlobs, String> {
Ok(
PathGlobs {
include: PathGlob::create(include)?,
exclude: PathGlob::create(exclude)?,
}
)
}
}
#[derive(Debug)]
struct PathGlobsExpansion<T: Sized> {
context: T,
// Globs that have yet to be expanded, in order.
todo: Vec<PathGlob>,
// Globs that have already been expanded.
completed: HashSet<PathGlob>,
// Unique Paths that have been matched, in order.
outputs: OrderMap<PathStat, ()>,
}
pub struct PosixFS {
build_root: Dir,
// The pool needs to be reinitialized after a fork, so it is protected by a lock.
pool: RwLock<CpuPool>,
ignore: Gitignore,
}
impl PosixFS {
pub fn new(
build_root: PathBuf,
ignore_patterns: Vec<String>,
) -> Result<PosixFS, String> {
let pool = RwLock::new(PosixFS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
}
)
)
.map_err(|e| format!("Could not canonicalize build root {:?}: {:?}", build_root, e))?;
let ignore =
PosixFS::create_ignore(&canonical_build_root, &ignore_patterns)
.map_err(|e|
format!("Could not parse build ignore inputs {:?}: {:?}", ignore_patterns, e)
)?;
Ok(
PosixFS {
build_root: canonical_build_root,
pool: pool,
ignore: ignore,
}
)
}
fn create_pool() -> CpuPool {
futures_cpupool::Builder::new()
.name_prefix("vfs-")
.create()
}
fn create_ignore(root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf) -> Result<Vec<Stat>, io::Error> {
let mut stats = Vec::new();
for dir_entry_res in dir_abs.read_dir()? {
let dir_entry = dir_entry_res?;
let path = dir.0.join(dir_entry.file_name());
let file_type = dir_entry.file_type()?;
if file_type.is_dir() {
stats.push(Stat::Dir(Dir(path)));
} else if file_type.is_file() {
stats.push(Stat::File(File(path)));
} else if file_type.is_symlink() {
stats.push(Stat::Link(Link(path)));
}
// Else: ignore.
}
stats.sort_by(|s1, s2| s1.path().cmp(s2.path()));
Ok(stats)
}
fn pool(&self) -> RwLockReadGuard<CpuPool> {
self.pool.read().unwrap()
}
pub fn post_fork(&self) {
let mut pool = self.pool.write().unwrap();
*pool = PosixFS::create_pool();
}
pub fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool {
match self.ignore.matched(path, is_dir) {
ignore::Match::None | ignore::Match::Whitelist(_) => false,
ignore::Match::Ignore(_) => true,
}
}
pub fn read_link(&self, link: &Link) -> BoxFuture<PathBuf, io::Error> {
let link_parent = link.0.parent().map(|p| p.to_owned());
let link_abs = self.build_root.0.join(link.0.as_path()).to_owned();
self.pool()
.spawn_fn(move || {
link_abs
.read_link()
.and_then(|path_buf| {
if path_buf.is_absolute() {
Err(
io::Error::new(
io::ErrorKind::InvalidData, format!("Absolute symlink: {:?}", link_abs)
)
)
} else {
link_parent
.map(|parent| parent.join(path_buf))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData, format!("Symlink without a parent?: {:?}", link_abs)
)
})
}
})
})
.boxed()
}
pub fn scandir(&self, dir: &Dir) -> BoxFuture<Vec<Stat>, io::Error> {
let dir = dir.to_owned();
let dir_abs = self.build_root.0.join(dir.0.as_path());
self.pool()
.spawn_fn(move || {
PosixFS::scandir_sync(dir, dir_abs)
})
.boxed()
}
}
/**
* A context for filesystem operations parameterized on an error type 'E'.
*/
pub trait VFS<E: Send + Sync + 'static> : Clone + Send + Sync + 'static {
fn read_link(&self, link: Link) -> BoxFuture<PathBuf, E>;
fn scandir(&self, dir: Dir) -> BoxFuture<Vec<Stat>, E>;
fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool;
fn mk_error(msg: &str) -> E;
/**
* Canonicalize the Link for the given Path to an underlying File or Dir. May result
* in None if the PathStat represents a broken Link.
*
* Skips ignored paths both before and after expansion.
*
* TODO: Should handle symlink loops (which would exhibit as an infinite loop in expand_multi).
*/
fn canonicalize(&self, symbolic_path: PathBuf, link: Link) -> BoxFuture<Option<PathStat>, E> {
// Read the link, which may result in PathGlob(s) that match 0 or 1 Path.
let context = self.clone();
self.read_link(link)
.map(|dest_path| {
// If the link destination can't be parsed as PathGlob(s), it is broken.
dest_path.to_str()
.and_then(|dest_str| {
let escaped = Pattern::escape(dest_str);
PathGlob::create(&[escaped]).ok()
})
.unwrap_or_else(|| vec![])
})
.and_then(move |link_globs| {
context.expand_multi(link_globs)
})
.map(|mut path_stats| {
// Since we've escaped any globs in the parsed path, expect either 0 or 1 destination.
path_stats.pop().map(|ps| match ps {
PathStat::Dir { stat, .. } => PathStat::dir(symbolic_path, stat),
PathStat::File { stat, .. } => PathStat::file(symbolic_path, stat),
})
})
.boxed()
}
fn directory_listing(&self, canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> BoxFuture<Vec<PathStat>, E> {
// List the directory.
let context = self.clone();
self.scandir(canonical_dir)
.and_then(move |dir_listing| {
// Match any relevant Stats, and join them into PathStats.
future::join_all(
dir_listing.into_iter()
.filter(|stat| {
// Match relevant filenames.
stat.path().file_name()
.map(|file_name| wildcard.matches_path(Path::new(file_name)))
.unwrap_or(false)
})
.filter_map(|stat| {
// Append matched filenames.
stat.path().file_name()
.map(|file_name| {
symbolic_path.join(file_name)
})
.map(|symbolic_stat_path| {
(symbolic_stat_path, stat)
})
})
.map(|(stat_symbolic_path, stat)| {
// Canonicalize matched PathStats, and filter ignored paths. Note that we ignore
// links both before and after expansion.
match stat {
Stat::Link(l) => {
if context.ignore(l.0.as_path(), false) {
future::ok(None).boxed()
} else {
context.canonicalize(stat_symbolic_path, l)
}
},
Stat::Dir(d) => {
let res =
if context.ignore(d.0.as_path(), true) {
None
} else {
Some(PathStat::dir(stat_symbolic_path.to_owned(), d))
};
future::ok(res).boxed()
},
Stat::File(f) => {
let res =
if context.ignore(f.0.as_path(), false) {
None
} else {
Some(PathStat::file(stat_symbolic_path.to_owned(), f))
};
future::ok(res).boxed()
},
}
})
.collect::<Vec<_>>()
)
})
.map(|path_stats| {
// See the TODO above.
path_stats.into_iter().filter_map(|pso| pso).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats while applying excludes.
*
* TODO: Eventually, it would be nice to be able to apply excludes as we go, to
* avoid walking into directories that aren't relevant.
*/
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i| !exclude_set.contains(i)).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path_globs,
completed: HashSet::default(),
outputs: OrderMap::default()
};
future::loop_fn(init, |mut expansion| {
// Request the expansion of all outstanding PathGlobs as a batch.
let round =
future::join_all({
let context = &expansion.context;
expansion.todo.drain(..)
.map(|path_glob| context.expand_single(path_glob))
.collect::<Vec<_>>()
});
round
.map(move |paths_and_globs| {
// Collect distinct new PathStats and PathGlobs
for (paths, globs) in paths_and_globs.into_iter() {
expansion.outputs.extend(paths.into_iter().map(|p| (p, ())));
let completed = &mut expansion.completed;
expansion.todo.extend(
globs.into_iter()
.filter(|pg| completed.insert(pg.clone()))
);
}
// If there were any new PathGlobs, continue the expansion.
if expansion.todo.is_empty() {
future::Loop::Break(expansion)
} else {
future::Loop::Continue(expansion)
}
})
})
.map(|expansion| {
assert!(
expansion.todo.is_empty(),
"Loop shouldn't have exited with work to do: {:?}",
expansion.todo,
);
// Finally, capture the resulting PathStats from the expansion.
expansion.outputs.into_iter().map(|(k, _)| k).collect()
})
.boxed()
}
/**
* Apply a PathGlob, returning PathStats and additional PathGlobs that are needed for the
* expansion.
*/
fn expand_single(&self, path_glob: PathGlob) -> BoxFuture<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path_stats, vec![]))
.boxed(),
PathGlob::DirWildcard { canonical_dir, symbolic_path, wildcard, remainder } =>
// Filter directory listing and request additional PathGlobs for matched Dirs.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.and_then(move |path_stats| {
path_stats.into_iter()
.filter_map(|ps| match ps {
PathStat::Dir { path, stat } =>
Some(
PathGlob::parse_globs(stat, path, &remainder)
.map_err(|e| Self::mk_error(e.as_str()))
),
PathStat::File { .. } => None,
})
.collect::<Result<Vec<_>, E>>()
})
.map(|path_globs| {
let flattened =
path_globs.into_iter()
.flat_map(|path_globs| path_globs.into_iter())
.collect();
(vec![], flattened)
})
.boxed(),
}
}
}
pub struct FileContent {
pub path: PathBuf,
pub content: Vec<u8>,
}
#[derive(Clone)]
pub struct Snapshot {
pub fingerprint: Fingerprint,
pub path_stats: Vec<PathStat>,
}
impl fmt::Debug for Snapshot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Snapshot({}, entries={})", self.fingerprint.to_hex(), self.path_stats.len())
}
}
/**
* A facade for the snapshot directory, which is currently thrown away at the end of each run.
*/
pub struct Snapshots {
temp_dir: TempDir,
next_temp_id: atomic::AtomicUsize,
}
impl Snapshots {
pub fn new() -> Result<Snapshots, io::Error> {
Ok(
Snapshots {
// TODO: see https://github.com/pantsbuild/pants/issues/4299
temp_dir: TempDir::new("snapshots")?,
next_temp_id: atomic::AtomicUsize::new(0),
}
)
}
pub fn path(&self) -> &Path {
self.temp_dir.path()
}
/**
* A non-canonical (does not expand symlinks) in-memory form of normalize. Used to collapse
* parent and cur components, which are legal in symbolic paths in PathStats, but not in
* Tar files.
*/
fn normalize(path: &Path) -> Result<PathBuf, String> {
let mut res = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", path)),
Component::CurDir =>
continue,
Component::ParentDir => {
// Pop the previous component.
if !res.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", path));
} else {
continue
}
},
Component::Normal(p) =>
res.push(p),
}
}
Ok(res)
}
/**
* Create a tar file on the given Write instance containing the given paths, or
* return an error string.
*/
fn tar_create<W: io::Write>(
dest: W,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<W, String> {
let mut tar_builder = tar::Builder::new(dest);
tar_builder.mode(tar::HeaderMode::Deterministic);
for path_stat in paths {
// Append the PathStat using the symbolic name and underlying stat.
let append_res =
match path_stat {
&PathStat::File { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
let mut input =
fs::File::open(relative_to.0.join(stat.0.as_path()))
.map_err(|e| format!("Failed to open {:?}: {:?}", path_stat, e))?;
tar_builder.append_file(normalized, &mut input)
},
&PathStat::Dir { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
tar_builder.append_dir(normalized, relative_to.0.join(stat.0.as_path()))
},
};
append_res
.map_err(|e| format!("Failed to tar {:?}: {:?}", path_stat, e))?;
}
// Finish the tar file, returning ownership of the stream to the caller.
Ok(
tar_builder.into_inner()
.map_err(|e| format!("Failed to finalize snapshot tar: {:?}", e))?
)
}
/**
* Create a tar file at the given dest Path containing the given paths, while
* fingerprinting the written stream.
*/
fn tar_create_fingerprinted(
dest: &Path,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<Fingerprint, String> {
// Wrap buffering around a fingerprinted stream above a File.
let stream =
io::BufWriter::new(
WriterHasher::new(
fs::File::create(dest)
.map_err(|e| format!("Failed to create destination file: {:?}", e))?
)
);
// Then append the tar to the stream, and retrieve the Fingerprint to flush all writers.
Ok(
Snapshots::tar_create(stream, paths, relative_to)?
.into_inner()
.map_err(|e| format!("Failed to flush to {:?}: {:?}", dest, e.error()))?
.finish()
)
}
fn path_for(&self, fingerprint: &Fingerprint) -> PathBuf {
Snapshots::path_under_for(self.temp_dir.path(), fingerprint)
}
fn path_under_for(path: &Path, fingerprint: &Fingerprint) -> PathBuf {
let hex = fingerprint.to_hex();
path.join(&hex[0..2]).join(&hex[2..4]).join(format!("{}.tar", hex))
}
/**
* Retries create_dir_all up to N times before failing. Necessary in concurrent environments.
*/
fn create_dir_all(dir: &Path) -> Result<(), String> {
let mut attempts = 16;
loop {
let res = fs::create_dir_all(dir);
if res.is_ok() {
return Ok(());
} else if attempts <= 0 {
return {
res.map_err(|e| format!("Failed to create directory {:?}: {:?}", dir, e))
}
}
attempts -= 1;
}
}
/**
* Attempts to rename src to dst, and _succeeds_ if dst already exists. This is safe in
* the case of Snapshots because the destination path is unique to its content.
*/
fn finalize(temp_path: &Path, dest_path: &Path) -> Result<(), String> {
if dest_path.is_file() {
// The Snapshot has already been created.
fs::remove_file(temp_path).unwrap_or(());
Ok(())
} else {
let dest_dir = dest_path.parent().expect("All snapshot paths must have parent directories.");
// As long as the destination file gets created, we've succeeded.
Snapshots::create_dir_all(dest_dir)?;
match fs::rename(temp_path, dest_path) {
Ok(_) => Ok(()),
Err(_) if dest_path.is_file() => Ok(()),
Err(e) => Err(format!("Failed to finalize snapshot at {:?}: {:?}", dest_path, e))
}
}
}
/**
* Creates a Snapshot for the given paths under the given VFS.
*/
pub fn create(&self, fs: &PosixFS, paths: Vec<PathStat>) -> CpuFuture<Snapshot, String> {
let dest_dir = self.temp_dir.path().to_owned();
let build_root = fs.build_root.clone();
let temp_path = {
let next_temp_id = self.next_temp_id.fetch_add(1, atomic::Ordering::SeqCst);
self.temp_dir.path().join(format!("{}.tar.tmp", next_temp_id))
};
fs.pool().spawn_fn(move || {
// Write the tar deterministically to a temporary file while fingerprinting.
let fingerprint =
Snapshots::tar_create_fingerprinted(temp_path.as_path(), &paths, &build_root)?;
// Rename to the final path if it does not already exist.
Snapshots::finalize(
temp_path.as_path(),
Snapshots::path_under_for(&dest_dir, &fingerprint).as_path()
)?;
Ok(
Snapshot {
fingerprint: fingerprint,
path_stats: paths,
}
)
})
}
fn contents_for_sync(snapshot: Snapshot, path: PathBuf) -> Result<Vec<FileContent>, io::Error> {
let mut archive = fs::File::open(path).map(|f| tar::Archive::new(f))?;
// Zip the in-memory Snapshot to the on disk representation, validating as we go.
let mut files_content = Vec::new();
for (entry_res, path_stat) in archive.entries()?.zip(snapshot.path_stats.into_iter()) { | match path_stat {
PathStat::File { path, .. } => path,
PathStat::Dir { .. } => panic!("Snapshot contents changed after storage."),
};
let mut content = Vec::new();
io::Read::read_to_end(&mut entry, &mut content)?;
files_content.push(
FileContent {
path: path,
content: content,
}
);
}
}
Ok(files_content)
}
pub fn contents_for(&self, fs: &PosixFS, snapshot: Snapshot) -> CpuFuture<Vec<FileContent>, String> {
let archive_path = self.path_for(&snapshot.fingerprint);
fs.pool().spawn_fn(move || {
let snapshot_str = format!("{:?}", snapshot);
Snapshots::contents_for_sync(snapshot, archive_path)
.map_err(|e| format!("Failed to open Snapshot {}: {:?}", snapshot_str, e))
})
}
} | let mut entry = entry_res?;
if entry.header().entry_type() == tar::EntryType::file() {
let path = | random_line_split |
fs.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::sync::{atomic, RwLock, RwLockReadGuard};
use std::{fmt, fs, io};
use futures::future::{self, BoxFuture, Future};
use futures_cpupool::{self, CpuFuture, CpuPool};
use glob::Pattern;
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use ignore;
use ordermap::OrderMap;
use tar;
use tempdir::TempDir;
use hash::{Fingerprint, WriterHasher};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Stat {
Link(Link),
Dir(Dir),
File(File),
}
impl Stat {
pub fn path(&self) -> &Path {
match self {
&Stat::Dir(Dir(ref p)) => p.as_path(),
&Stat::File(File(ref p)) => p.as_path(),
&Stat::Link(Link(ref p)) => p.as_path(),
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Link(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Dir(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct File(pub PathBuf);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PathStat {
Dir {
// The symbolic name of some filesystem Path, which is context specific.
path: PathBuf,
// The canonical Stat that underlies the Path.
stat: Dir,
},
File {
// The symbolic name of some filesystem Path, which is context specific.
path: PathBuf,
// The canonical Stat that underlies the Path.
stat: File,
}
}
impl PathStat {
fn dir(path: PathBuf, stat: Dir) -> PathStat {
PathStat::Dir {
path: path,
stat: stat,
}
}
fn file(path: PathBuf, stat: File) -> PathStat {
PathStat::File {
path: path,
stat: stat,
}
}
pub fn path(&self) -> &Path {
match self {
&PathStat::Dir { ref path, .. } => path.as_path(),
&PathStat::File { ref path, .. } => path.as_path(),
}
}
}
lazy_static! {
static ref PARENT_DIR: &'static str = "..";
static ref SINGLE_STAR_GLOB: Pattern = Pattern::new("*").unwrap();
static ref DOUBLE_STAR: &'static str = "**";
static ref DOUBLE_STAR_GLOB: Pattern = Pattern::new("**").unwrap();
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PathGlob {
Wildcard {
canonical_dir: Dir,
symbolic_path: PathBuf,
wildcard: Pattern,
},
DirWildcard {
canonical_dir: Dir,
symbolic_path: PathBuf,
wildcard: Pattern,
remainder: Vec<Pattern>,
},
}
impl PathGlob {
fn wildcard(canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> PathGlob {
PathGlob::Wildcard {
canonical_dir: canonical_dir,
symbolic_path: symbolic_path,
wildcard: wildcard,
}
}
fn dir_wildcard(canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern, remainder: Vec<Pattern>) -> PathGlob {
PathGlob::DirWildcard {
canonical_dir: canonical_dir,
symbolic_path: symbolic_path,
wildcard: wildcard,
remainder: remainder,
}
}
pub fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
Ok(path_globs)
}
/**
* Given a filespec String relative to a canonical Dir and path, split it into path components
* while eliminating consecutive '**'s (to avoid repetitive traversing), and parse it to a
* series of PathGlob objects.
*/
fn parse(canonical_dir: Dir, symbolic_path: PathBuf, filespec: &str) -> Result<Vec<PathGlob>, String> {
let mut parts = Vec::new();
let mut prev_was_doublestar = false;
for component in Path::new(filespec).components() {
let part =
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", filespec)),
Component::CurDir =>
continue,
c => c.as_os_str(),
};
// Ignore repeated doublestar instances.
let cur_is_doublestar = *DOUBLE_STAR == part;
if prev_was_doublestar && cur_is_doublestar {
continue;
}
prev_was_doublestar = cur_is_doublestar;
// NB: Because the filespec is a String input, calls to `to_str_lossy` are not lossy; the
// use of `Path` is strictly for os-independent Path parsing.
parts.push(
Pattern::new(&part.to_string_lossy())
.map_err(|e| format!("Could not parse {:?} as a glob: {:?}", filespec, e))?
);
}
PathGlob::parse_globs(canonical_dir, symbolic_path, &parts)
}
/**
* Given a filespec as Patterns, create a series of PathGlob objects.
*/
fn parse_globs(
canonical_dir: Dir,
symbolic_path: PathBuf,
parts: &[Pattern]
) -> Result<Vec<PathGlob>, String> {
if parts.is_empty() {
Ok(vec![])
} else if *DOUBLE_STAR == parts[0].as_str() {
if parts.len() == 1 {
// Per https://git-scm.com/docs/gitignore:
// "A trailing '/**' matches everything inside. For example, 'abc/**' matches all files inside
// directory "abc", relative to the location of the .gitignore file, with infinite depth."
return Ok(
vec![
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
vec![DOUBLE_STAR_GLOB.clone()]
),
PathGlob::wildcard(canonical_dir, symbolic_path, SINGLE_STAR_GLOB.clone()),
]
);
}
// There is a double-wildcard in a dirname of the path: double wildcards are recursive,
// so there are two remainder possibilities: one with the double wildcard included, and the
// other without.
let pathglob_with_doublestar =
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
parts[0..].to_vec()
);
let pathglob_no_doublestar =
if parts.len() == 2 {
PathGlob::wildcard(canonical_dir, symbolic_path, parts[1].clone())
} else {
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[1].clone(), parts[2..].to_vec())
};
Ok(vec![pathglob_with_doublestar, pathglob_no_doublestar])
} else if *PARENT_DIR == parts[0].as_str() {
// A request for the parent of `canonical_dir`: since we've already expanded the directory
// to make it canonical, we can safely drop it directly and recurse without this component.
// The resulting symbolic path will continue to contain a literal `..`.
let mut canonical_dir_parent = canonical_dir;
let mut symbolic_path_parent = symbolic_path;
if !canonical_dir_parent.0.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", parts));
}
symbolic_path_parent.push(Path::new(*PARENT_DIR));
PathGlob::parse_globs(canonical_dir_parent, symbolic_path_parent, &parts[1..])
} else if parts.len() == 1 {
// This is the path basename.
Ok(
vec![
PathGlob::wildcard(canonical_dir, symbolic_path, parts[0].clone())
]
)
} else {
// This is a path dirname.
Ok(
vec![
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[0].clone(), parts[1..].to_vec())
]
)
}
}
}
#[derive(Debug)]
pub struct PathGlobs {
include: Vec<PathGlob>,
exclude: Vec<PathGlob>,
}
impl PathGlobs {
pub fn create(include: &[String], exclude: &[String]) -> Result<PathGlobs, String> {
Ok(
PathGlobs {
include: PathGlob::create(include)?,
exclude: PathGlob::create(exclude)?,
}
)
}
}
#[derive(Debug)]
struct PathGlobsExpansion<T: Sized> {
context: T,
// Globs that have yet to be expanded, in order.
todo: Vec<PathGlob>,
// Globs that have already been expanded.
completed: HashSet<PathGlob>,
// Unique Paths that have been matched, in order.
outputs: OrderMap<PathStat, ()>,
}
pub struct PosixFS {
build_root: Dir,
// The pool needs to be reinitialized after a fork, so it is protected by a lock.
pool: RwLock<CpuPool>,
ignore: Gitignore,
}
impl PosixFS {
pub fn new(
build_root: PathBuf,
ignore_patterns: Vec<String>,
) -> Result<PosixFS, String> {
let pool = RwLock::new(PosixFS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
}
)
)
.map_err(|e| format!("Could not canonicalize build root {:?}: {:?}", build_root, e))?;
let ignore =
PosixFS::create_ignore(&canonical_build_root, &ignore_patterns)
.map_err(|e|
format!("Could not parse build ignore inputs {:?}: {:?}", ignore_patterns, e)
)?;
Ok(
PosixFS {
build_root: canonical_build_root,
pool: pool,
ignore: ignore,
}
)
}
fn create_pool() -> CpuPool {
futures_cpupool::Builder::new()
.name_prefix("vfs-")
.create()
}
fn create_ignore(root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf) -> Result<Vec<Stat>, io::Error> {
let mut stats = Vec::new();
for dir_entry_res in dir_abs.read_dir()? {
let dir_entry = dir_entry_res?;
let path = dir.0.join(dir_entry.file_name());
let file_type = dir_entry.file_type()?;
if file_type.is_dir() {
stats.push(Stat::Dir(Dir(path)));
} else if file_type.is_file() {
stats.push(Stat::File(File(path)));
} else if file_type.is_symlink() {
stats.push(Stat::Link(Link(path)));
}
// Else: ignore.
}
stats.sort_by(|s1, s2| s1.path().cmp(s2.path()));
Ok(stats)
}
fn pool(&self) -> RwLockReadGuard<CpuPool> {
self.pool.read().unwrap()
}
pub fn post_fork(&self) {
let mut pool = self.pool.write().unwrap();
*pool = PosixFS::create_pool();
}
pub fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool {
match self.ignore.matched(path, is_dir) {
ignore::Match::None | ignore::Match::Whitelist(_) => false,
ignore::Match::Ignore(_) => true,
}
}
pub fn read_link(&self, link: &Link) -> BoxFuture<PathBuf, io::Error> {
let link_parent = link.0.parent().map(|p| p.to_owned());
let link_abs = self.build_root.0.join(link.0.as_path()).to_owned();
self.pool()
.spawn_fn(move || {
link_abs
.read_link()
.and_then(|path_buf| {
if path_buf.is_absolute() {
Err(
io::Error::new(
io::ErrorKind::InvalidData, format!("Absolute symlink: {:?}", link_abs)
)
)
} else {
link_parent
.map(|parent| parent.join(path_buf))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData, format!("Symlink without a parent?: {:?}", link_abs)
)
})
}
})
})
.boxed()
}
pub fn scandir(&self, dir: &Dir) -> BoxFuture<Vec<Stat>, io::Error> {
let dir = dir.to_owned();
let dir_abs = self.build_root.0.join(dir.0.as_path());
self.pool()
.spawn_fn(move || {
PosixFS::scandir_sync(dir, dir_abs)
})
.boxed()
}
}
/**
* A context for filesystem operations parameterized on an error type 'E'.
*/
pub trait VFS<E: Send + Sync + 'static> : Clone + Send + Sync + 'static {
fn read_link(&self, link: Link) -> BoxFuture<PathBuf, E>;
fn scandir(&self, dir: Dir) -> BoxFuture<Vec<Stat>, E>;
fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool;
fn mk_error(msg: &str) -> E;
/**
* Canonicalize the Link for the given Path to an underlying File or Dir. May result
* in None if the PathStat represents a broken Link.
*
* Skips ignored paths both before and after expansion.
*
* TODO: Should handle symlink loops (which would exhibit as an infinite loop in expand_multi).
*/
fn canonicalize(&self, symbolic_path: PathBuf, link: Link) -> BoxFuture<Option<PathStat>, E> {
// Read the link, which may result in PathGlob(s) that match 0 or 1 Path.
let context = self.clone();
self.read_link(link)
.map(|dest_path| {
// If the link destination can't be parsed as PathGlob(s), it is broken.
dest_path.to_str()
.and_then(|dest_str| {
let escaped = Pattern::escape(dest_str);
PathGlob::create(&[escaped]).ok()
})
.unwrap_or_else(|| vec![])
})
.and_then(move |link_globs| {
context.expand_multi(link_globs)
})
.map(|mut path_stats| {
// Since we've escaped any globs in the parsed path, expect either 0 or 1 destination.
path_stats.pop().map(|ps| match ps {
PathStat::Dir { stat, .. } => PathStat::dir(symbolic_path, stat),
PathStat::File { stat, .. } => PathStat::file(symbolic_path, stat),
})
})
.boxed()
}
fn directory_listing(&self, canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> BoxFuture<Vec<PathStat>, E> {
// List the directory.
let context = self.clone();
self.scandir(canonical_dir)
.and_then(move |dir_listing| {
// Match any relevant Stats, and join them into PathStats.
future::join_all(
dir_listing.into_iter()
.filter(|stat| {
// Match relevant filenames.
stat.path().file_name()
.map(|file_name| wildcard.matches_path(Path::new(file_name)))
.unwrap_or(false)
})
.filter_map(|stat| {
// Append matched filenames.
stat.path().file_name()
.map(|file_name| {
symbolic_path.join(file_name)
})
.map(|symbolic_stat_path| {
(symbolic_stat_path, stat)
})
})
.map(|(stat_symbolic_path, stat)| {
// Canonicalize matched PathStats, and filter ignored paths. Note that we ignore
// links both before and after expansion.
match stat {
Stat::Link(l) => {
if context.ignore(l.0.as_path(), false) {
future::ok(None).boxed()
} else {
context.canonicalize(stat_symbolic_path, l)
}
},
Stat::Dir(d) => {
let res =
if context.ignore(d.0.as_path(), true) {
None
} else {
Some(PathStat::dir(stat_symbolic_path.to_owned(), d))
};
future::ok(res).boxed()
},
Stat::File(f) => {
let res =
if context.ignore(f.0.as_path(), false) {
None
} else {
Some(PathStat::file(stat_symbolic_path.to_owned(), f))
};
future::ok(res).boxed()
},
}
})
.collect::<Vec<_>>()
)
})
.map(|path_stats| {
// See the TODO above.
path_stats.into_iter().filter_map(|pso| pso).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats while applying excludes.
*
* TODO: Eventually, it would be nice to be able to apply excludes as we go, to
* avoid walking into directories that aren't relevant.
*/
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> |
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path_globs,
completed: HashSet::default(),
outputs: OrderMap::default()
};
future::loop_fn(init, |mut expansion| {
// Request the expansion of all outstanding PathGlobs as a batch.
let round =
future::join_all({
let context = &expansion.context;
expansion.todo.drain(..)
.map(|path_glob| context.expand_single(path_glob))
.collect::<Vec<_>>()
});
round
.map(move |paths_and_globs| {
// Collect distinct new PathStats and PathGlobs
for (paths, globs) in paths_and_globs.into_iter() {
expansion.outputs.extend(paths.into_iter().map(|p| (p, ())));
let completed = &mut expansion.completed;
expansion.todo.extend(
globs.into_iter()
.filter(|pg| completed.insert(pg.clone()))
);
}
// If there were any new PathGlobs, continue the expansion.
if expansion.todo.is_empty() {
future::Loop::Break(expansion)
} else {
future::Loop::Continue(expansion)
}
})
})
.map(|expansion| {
assert!(
expansion.todo.is_empty(),
"Loop shouldn't have exited with work to do: {:?}",
expansion.todo,
);
// Finally, capture the resulting PathStats from the expansion.
expansion.outputs.into_iter().map(|(k, _)| k).collect()
})
.boxed()
}
/**
* Apply a PathGlob, returning PathStats and additional PathGlobs that are needed for the
* expansion.
*/
fn expand_single(&self, path_glob: PathGlob) -> BoxFuture<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path_stats, vec![]))
.boxed(),
PathGlob::DirWildcard { canonical_dir, symbolic_path, wildcard, remainder } =>
// Filter directory listing and request additional PathGlobs for matched Dirs.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.and_then(move |path_stats| {
path_stats.into_iter()
.filter_map(|ps| match ps {
PathStat::Dir { path, stat } =>
Some(
PathGlob::parse_globs(stat, path, &remainder)
.map_err(|e| Self::mk_error(e.as_str()))
),
PathStat::File { .. } => None,
})
.collect::<Result<Vec<_>, E>>()
})
.map(|path_globs| {
let flattened =
path_globs.into_iter()
.flat_map(|path_globs| path_globs.into_iter())
.collect();
(vec![], flattened)
})
.boxed(),
}
}
}
pub struct FileContent {
pub path: PathBuf,
pub content: Vec<u8>,
}
#[derive(Clone)]
pub struct Snapshot {
pub fingerprint: Fingerprint,
pub path_stats: Vec<PathStat>,
}
impl fmt::Debug for Snapshot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Snapshot({}, entries={})", self.fingerprint.to_hex(), self.path_stats.len())
}
}
/**
* A facade for the snapshot directory, which is currently thrown away at the end of each run.
*/
pub struct Snapshots {
temp_dir: TempDir,
next_temp_id: atomic::AtomicUsize,
}
impl Snapshots {
pub fn new() -> Result<Snapshots, io::Error> {
Ok(
Snapshots {
// TODO: see https://github.com/pantsbuild/pants/issues/4299
temp_dir: TempDir::new("snapshots")?,
next_temp_id: atomic::AtomicUsize::new(0),
}
)
}
pub fn path(&self) -> &Path {
self.temp_dir.path()
}
/**
* A non-canonical (does not expand symlinks) in-memory form of normalize. Used to collapse
* parent and cur components, which are legal in symbolic paths in PathStats, but not in
* Tar files.
*/
fn normalize(path: &Path) -> Result<PathBuf, String> {
let mut res = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", path)),
Component::CurDir =>
continue,
Component::ParentDir => {
// Pop the previous component.
if !res.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", path));
} else {
continue
}
},
Component::Normal(p) =>
res.push(p),
}
}
Ok(res)
}
/**
* Create a tar file on the given Write instance containing the given paths, or
* return an error string.
*/
fn tar_create<W: io::Write>(
dest: W,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<W, String> {
let mut tar_builder = tar::Builder::new(dest);
tar_builder.mode(tar::HeaderMode::Deterministic);
for path_stat in paths {
// Append the PathStat using the symbolic name and underlying stat.
let append_res =
match path_stat {
&PathStat::File { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
let mut input =
fs::File::open(relative_to.0.join(stat.0.as_path()))
.map_err(|e| format!("Failed to open {:?}: {:?}", path_stat, e))?;
tar_builder.append_file(normalized, &mut input)
},
&PathStat::Dir { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
tar_builder.append_dir(normalized, relative_to.0.join(stat.0.as_path()))
},
};
append_res
.map_err(|e| format!("Failed to tar {:?}: {:?}", path_stat, e))?;
}
// Finish the tar file, returning ownership of the stream to the caller.
Ok(
tar_builder.into_inner()
.map_err(|e| format!("Failed to finalize snapshot tar: {:?}", e))?
)
}
/**
* Create a tar file at the given dest Path containing the given paths, while
* fingerprinting the written stream.
*/
fn tar_create_fingerprinted(
dest: &Path,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<Fingerprint, String> {
// Wrap buffering around a fingerprinted stream above a File.
let stream =
io::BufWriter::new(
WriterHasher::new(
fs::File::create(dest)
.map_err(|e| format!("Failed to create destination file: {:?}", e))?
)
);
// Then append the tar to the stream, and retrieve the Fingerprint to flush all writers.
Ok(
Snapshots::tar_create(stream, paths, relative_to)?
.into_inner()
.map_err(|e| format!("Failed to flush to {:?}: {:?}", dest, e.error()))?
.finish()
)
}
fn path_for(&self, fingerprint: &Fingerprint) -> PathBuf {
Snapshots::path_under_for(self.temp_dir.path(), fingerprint)
}
fn path_under_for(path: &Path, fingerprint: &Fingerprint) -> PathBuf {
let hex = fingerprint.to_hex();
path.join(&hex[0..2]).join(&hex[2..4]).join(format!("{}.tar", hex))
}
/**
* Retries create_dir_all up to N times before failing. Necessary in concurrent environments.
*/
fn create_dir_all(dir: &Path) -> Result<(), String> {
let mut attempts = 16;
loop {
let res = fs::create_dir_all(dir);
if res.is_ok() {
return Ok(());
} else if attempts <= 0 {
return {
res.map_err(|e| format!("Failed to create directory {:?}: {:?}", dir, e))
}
}
attempts -= 1;
}
}
/**
* Attempts to rename src to dst, and _succeeds_ if dst already exists. This is safe in
* the case of Snapshots because the destination path is unique to its content.
*/
fn finalize(temp_path: &Path, dest_path: &Path) -> Result<(), String> {
if dest_path.is_file() {
// The Snapshot has already been created.
fs::remove_file(temp_path).unwrap_or(());
Ok(())
} else {
let dest_dir = dest_path.parent().expect("All snapshot paths must have parent directories.");
// As long as the destination file gets created, we've succeeded.
Snapshots::create_dir_all(dest_dir)?;
match fs::rename(temp_path, dest_path) {
Ok(_) => Ok(()),
Err(_) if dest_path.is_file() => Ok(()),
Err(e) => Err(format!("Failed to finalize snapshot at {:?}: {:?}", dest_path, e))
}
}
}
/**
* Creates a Snapshot for the given paths under the given VFS.
*/
pub fn create(&self, fs: &PosixFS, paths: Vec<PathStat>) -> CpuFuture<Snapshot, String> {
let dest_dir = self.temp_dir.path().to_owned();
let build_root = fs.build_root.clone();
let temp_path = {
let next_temp_id = self.next_temp_id.fetch_add(1, atomic::Ordering::SeqCst);
self.temp_dir.path().join(format!("{}.tar.tmp", next_temp_id))
};
fs.pool().spawn_fn(move || {
// Write the tar deterministically to a temporary file while fingerprinting.
let fingerprint =
Snapshots::tar_create_fingerprinted(temp_path.as_path(), &paths, &build_root)?;
// Rename to the final path if it does not already exist.
Snapshots::finalize(
temp_path.as_path(),
Snapshots::path_under_for(&dest_dir, &fingerprint).as_path()
)?;
Ok(
Snapshot {
fingerprint: fingerprint,
path_stats: paths,
}
)
})
}
fn contents_for_sync(snapshot: Snapshot, path: PathBuf) -> Result<Vec<FileContent>, io::Error> {
let mut archive = fs::File::open(path).map(|f| tar::Archive::new(f))?;
// Zip the in-memory Snapshot to the on disk representation, validating as we go.
let mut files_content = Vec::new();
for (entry_res, path_stat) in archive.entries()?.zip(snapshot.path_stats.into_iter()) {
let mut entry = entry_res?;
if entry.header().entry_type() == tar::EntryType::file() {
let path =
match path_stat {
PathStat::File { path, .. } => path,
PathStat::Dir { .. } => panic!("Snapshot contents changed after storage."),
};
let mut content = Vec::new();
io::Read::read_to_end(&mut entry, &mut content)?;
files_content.push(
FileContent {
path: path,
content: content,
}
);
}
}
Ok(files_content)
}
pub fn contents_for(&self, fs: &PosixFS, snapshot: Snapshot) -> CpuFuture<Vec<FileContent>, String> {
let archive_path = self.path_for(&snapshot.fingerprint);
fs.pool().spawn_fn(move || {
let snapshot_str = format!("{:?}", snapshot);
Snapshots::contents_for_sync(snapshot, archive_path)
.map_err(|e| format!("Failed to open Snapshot {}: {:?}", snapshot_str, e))
})
}
}
| {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i| !exclude_set.contains(i)).collect()
})
.boxed()
} | identifier_body |
tests.js | //async icin yardimci fonksiyon
function | (milliseconds, resolve) {
return new Promise(function (resolve) {
setTimeout(resolve, milliseconds);
});
}
//Burdaki T ODO ödev icin bir önemi yok, sadece gelecek icin kodu düzeltme acisindan yapilacaklar
//TODO: For Instructors only -> Replace all Maps with Set's
//TODO: For Instructors only -> Null checks
//TODO: For Instructors only -> Reduction of function chaining
//TODO: For Instructors only -> Simplify jQuery statements
//Testler birbiriyle alakalidir, isole degildir! Bu dosyada hicbisey degistirmenize gerek yok.
describe("Test Suite jQuery => Each Test depends on the one above! Don't be fooled by passing greens in the beginning.", function () {
this.timeout(20000);
it('01) should hide all the images from the view', () => {
hideAllImages();
$("img:visible").size().should.be.equal(0);
});
it('02) should show all the images again', () => {
showAllImages();
let visibleImages = Array.from($("img")).filter(function(pElm){
$(pElm).css('display') === 'none';
});
visibleImages.length.should.be.equal(0);
});
it('03) should change the heading to "The Best Collection"', () => {
changeHeadingToTheBestCollection();
let headingNew = $(".container > h4:first").text();
headingNew.should.equal("The Best Collection");
});
it('04) should make the hr (.line) element bolder', () => {
let hrLine = $("hr.line");
let boldnessHrLineBefore = hrLine.first().css("border-width");
makeHrLineElementBolder();
let boldnessHrLineAfter = hrLine.first().css("border-width");
boldnessHrLineAfter.should.be.above(boldnessHrLineBefore);
});
it('05) should change the background of each product title with a different color', () => {
changeBackgroundColorOfEachProductTitleWithDifferentColor();
let productTitles = $("span.thumbnail").find("h4");
let colors =
Array.from(productTitles)
.map((tag) => {
return $(tag).css("background-color");
})
.reduce((acc, value) => {
return acc.add(value);
}, new Set());
colors.size.should.equal(productTitles.length);
});
it('06) should remove the "BUY ITEM" buttons', () => {
removeBuyItemButtons();
let removeBuyItemButtonQuery = $("button[class='btn btn-info right']");
let buttonVisibility = removeBuyItemButtonQuery.map((index, tag) => {
return $(tag).css("display") !== "none";
}).toArray();
let filteredButtons = buttonVisibility.filter((value, index) => {
return value;
});
filteredButtons.length.should.equal(0);
});
it('07) should remove the last three item from the view', () => {
removeLastThreeItemsFromView();
let items = $(".container").children("div").children("div");
let lastItem = items[7];
let secondLastItem = items[6];
items.length.should.equal(5);
should.not.exist(lastItem);
should.not.exist(secondLastItem);
});
it('08) should make 10% reduction on all products', () => {
let prices = $('.price');
let pricesBefore = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
makeTenPercentPriceReductionOnAllProducts();
let pricesAfter = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
pricesAfter.should.be.eql(pricesBefore.map((value, index) => {
let currencyVal = parseFloat(value.substring(1));
return "$" + (currencyVal * 0.9);
}));
});
it('10) should rename the product shirt to "Fish-Shirt"', () => {
renameTheProductShirtToFishShirt();
let firstShirtText = $("#firstProduct").find("h4").text();
firstShirtText.should.equal("Fish-Shirt");
});
it('11) should rename the first rock item to "Bird-Rock"', () => {
renameTheFirstRockItemToBirdRock();
let firstShirtText = $("#secondProduct").find("h4").text();
firstShirtText.should.equal("Bird-Rock");
});
it('12) should add 5 stars to the product shirt', () => {
addFiveStarsToTheProductShirt();
let firstShirtLastStar = $("#firstProduct").find(".ratings").children("span:last-child");
firstShirtLastStar.attr("class").should.equal("glyphicon glyphicon-star");
});
it('13) should change the title name with a random name (use alg. for randomly generating chars)', () => {
changeTheTitleNameWithARandomName();
let title = $(".container").children().first().text();
title.should.not.equal("NEW COLLECTION");
});
it('14) should color the stars of the third product with green', () => {
colorTheStarsOfTheThirdProductWithGreen();
let thirdProductStars = $("#secondProduct").next().find(".ratings").children();
let starColors = thirdProductStars.map((index, tag) => {
return $(tag).css("color");
}).toArray().reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
starColors.size.should.not.be.above(1);
starColors.has("rgb(0, 128, 0)").should.eql(true);
});
it('15) should reset the last two images to the url "http://bit.ly/2xq8ev0"', () => {
resetLastTwoImagesToUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 1]).find("img").attr("src");
urlLastImage.should.equal("http://bit.ly/2xq8ev0");
urlSecondLastImage.should.equal("http://bit.ly/2xq8ev0");
});
it('16) should constantly change the price (#changingPrice), increment it by one in each 3 secs.', () => {
constantlyChangeThePriceAndIncrementItByOneInEachThreeSeconds();
let changingPrices = [];
let changingPriceElem = $("#changingPrice");
changingPrices.push(changingPriceElem.text());
return delay(3000).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices[0].should.not.be.eql(changingPrices[1]);
changingPrices[0].should.not.be.eql(changingPrices[2]);
changingPrices[2].should.not.be.eql(changingPrices[1]);
});
});
it('17) should show the "BUY ITEM" again with a green background, gray border and a thin shadow', () => {
showTheBuyItemAgainWithAGreenBackgroundGrayBorderAndThinShadow();
delay(3000).then(function () {
let removeBuyItemButtonQuery = $("button[class='btn btn-info right js-newButtonStyle']");
let mapOfGrayBorders = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("border-color");
});
mapOfGrayBorders = mapOfGrayBorders.reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
let mapOfShadows = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("box-shadow");
}).reduce((acc, value) => {
return acc.set(value, 0);
}, new Map());
removeBuyItemButtonQuery.size().should.be.above(4);
mapOfGrayBorders.size.should.equal(1);
mapOfShadows.size.should.equal(1);
console.dir(mapOfGrayBorders.entries())
mapOfGrayBorders.entries().next().value[0].should.be.equal("rgb(192, 192, 192)");
mapOfShadows.entries().next().value[0].should.not.be.equal("none");
})
});
it('18) should add an event handler to the "BUY ITEM" buttons and after a click it should show an alert', () => {
addAnEventHandlerToTheBuyItemButtonsAndAfterClickShowAlert();
let removeBuyItemButtonQuery = $("button");
let clickEvents = removeBuyItemButtonQuery.map((index, tag) => {
return $._data($(tag).get(0), 'events');
}).toArray().reduce((acc, value) => {
if (value.click !== "undefined") {
return acc.concat("true");
}
}, []);
clickEvents.length.should.equal(removeBuyItemButtonQuery.length);
});
it('19) should bring back the initial image again, instead of "http://bit.ly/2xq8ev0"', () => {
bringBackTheInitialImageAgainInsteadOfUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 2]).find("img").attr("src");
urlLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
urlSecondLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
});
it('20) should change every product desctiption to any text with at least 50 charakters', () => {
changeEveryProductDescriptionToAnyTextWithAtLeast50Characters();
let descriptions = $(".thumbnail").find(" > p");
let newDescriptions = descriptions.map((index, tag) => {
return $(tag).text() !== "Lorem Ipsum is simply dummy text of the printing and typesetting industry. "
&& $(tag).text().length >= 50;
});
let filteredNewDescriptions = newDescriptions.filter((index, value) => {
return value;
});
filteredNewDescriptions.length.should.equal(descriptions.length);
});
it('21) should randomly change all of the prices', () => {
randomlyChangeAllOfThePrices();
let prices = $('.price');
let changedPrices = prices.map((index, tag) => {
return $(tag).text() !== "$26.91";
});
let filteredChangedPrices = changedPrices.filter((index, value) => {
return value;
});
filteredChangedPrices.length.should.equal(prices.length);
});
it('22) should mark the background with the color yellow of the two cheapest products', () => {
markTheBackgroundWithTheColorYellowOfTheTwoCheapestProducts();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let firstLowPrice = $(".price:contains('" + valuePrices[0] + "')");
let secondLowPrice = $(".price:contains('" + valuePrices[1] + "')");
firstLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
secondLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
});
it('23) should sort all the products ascendantly based on the the new prices', () => {
sortAllOfTheProductsAscendantlyBasedOnTheNewPrices();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
let properlySorted = true;
for (let i = 1; i < valuePrices.length; i++) {
if (valuePrices[i - 1] > valuePrices[i]) {
properlySorted = false;
}
}
properlySorted.should.be.eql(true);
});
it('24) should add an mouse over event only the highest two products which logs in console the price (place on div)', () => {
addAnMouseOverEventOnlyTheHighestTwoProductsWhichLogsInConsoleThePrice();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let highestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 1] + "')")
.parents(".thumbnail").parent();
let secondHighestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 2] + "')")
.parents(".thumbnail").parent();
let highestPriceEvents = $._data($(highestPriceParent).get(0), "events");
let secondHighestPriceEvents = $._data($(secondHighestPriceParent).get(0), "events");
(typeof highestPriceEvents !== "undefined"
&& typeof highestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
(typeof secondHighestPriceEvents !== "undefined"
&& typeof secondHighestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
});
it('25) should add three new products to the list like the existing one', ()=>{
addThreeNewProductsToTheEndOfTheProductList();
let containers = $(".thumbnail").parent();
containers.length.should.equal(8);
});
});
| delay | identifier_name |
tests.js | //async icin yardimci fonksiyon
function delay(milliseconds, resolve) |
//Burdaki T ODO ödev icin bir önemi yok, sadece gelecek icin kodu düzeltme acisindan yapilacaklar
//TODO: For Instructors only -> Replace all Maps with Set's
//TODO: For Instructors only -> Null checks
//TODO: For Instructors only -> Reduction of function chaining
//TODO: For Instructors only -> Simplify jQuery statements
//Testler birbiriyle alakalidir, isole degildir! Bu dosyada hicbisey degistirmenize gerek yok.
describe("Test Suite jQuery => Each Test depends on the one above! Don't be fooled by passing greens in the beginning.", function () {
this.timeout(20000);
it('01) should hide all the images from the view', () => {
hideAllImages();
$("img:visible").size().should.be.equal(0);
});
it('02) should show all the images again', () => {
showAllImages();
let visibleImages = Array.from($("img")).filter(function(pElm){
$(pElm).css('display') === 'none';
});
visibleImages.length.should.be.equal(0);
});
it('03) should change the heading to "The Best Collection"', () => {
changeHeadingToTheBestCollection();
let headingNew = $(".container > h4:first").text();
headingNew.should.equal("The Best Collection");
});
it('04) should make the hr (.line) element bolder', () => {
let hrLine = $("hr.line");
let boldnessHrLineBefore = hrLine.first().css("border-width");
makeHrLineElementBolder();
let boldnessHrLineAfter = hrLine.first().css("border-width");
boldnessHrLineAfter.should.be.above(boldnessHrLineBefore);
});
it('05) should change the background of each product title with a different color', () => {
changeBackgroundColorOfEachProductTitleWithDifferentColor();
let productTitles = $("span.thumbnail").find("h4");
let colors =
Array.from(productTitles)
.map((tag) => {
return $(tag).css("background-color");
})
.reduce((acc, value) => {
return acc.add(value);
}, new Set());
colors.size.should.equal(productTitles.length);
});
it('06) should remove the "BUY ITEM" buttons', () => {
removeBuyItemButtons();
let removeBuyItemButtonQuery = $("button[class='btn btn-info right']");
let buttonVisibility = removeBuyItemButtonQuery.map((index, tag) => {
return $(tag).css("display") !== "none";
}).toArray();
let filteredButtons = buttonVisibility.filter((value, index) => {
return value;
});
filteredButtons.length.should.equal(0);
});
it('07) should remove the last three item from the view', () => {
removeLastThreeItemsFromView();
let items = $(".container").children("div").children("div");
let lastItem = items[7];
let secondLastItem = items[6];
items.length.should.equal(5);
should.not.exist(lastItem);
should.not.exist(secondLastItem);
});
it('08) should make 10% reduction on all products', () => {
let prices = $('.price');
let pricesBefore = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
makeTenPercentPriceReductionOnAllProducts();
let pricesAfter = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
pricesAfter.should.be.eql(pricesBefore.map((value, index) => {
let currencyVal = parseFloat(value.substring(1));
return "$" + (currencyVal * 0.9);
}));
});
it('10) should rename the product shirt to "Fish-Shirt"', () => {
renameTheProductShirtToFishShirt();
let firstShirtText = $("#firstProduct").find("h4").text();
firstShirtText.should.equal("Fish-Shirt");
});
it('11) should rename the first rock item to "Bird-Rock"', () => {
renameTheFirstRockItemToBirdRock();
let firstShirtText = $("#secondProduct").find("h4").text();
firstShirtText.should.equal("Bird-Rock");
});
it('12) should add 5 stars to the product shirt', () => {
addFiveStarsToTheProductShirt();
let firstShirtLastStar = $("#firstProduct").find(".ratings").children("span:last-child");
firstShirtLastStar.attr("class").should.equal("glyphicon glyphicon-star");
});
it('13) should change the title name with a random name (use alg. for randomly generating chars)', () => {
changeTheTitleNameWithARandomName();
let title = $(".container").children().first().text();
title.should.not.equal("NEW COLLECTION");
});
it('14) should color the stars of the third product with green', () => {
colorTheStarsOfTheThirdProductWithGreen();
let thirdProductStars = $("#secondProduct").next().find(".ratings").children();
let starColors = thirdProductStars.map((index, tag) => {
return $(tag).css("color");
}).toArray().reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
starColors.size.should.not.be.above(1);
starColors.has("rgb(0, 128, 0)").should.eql(true);
});
it('15) should reset the last two images to the url "http://bit.ly/2xq8ev0"', () => {
resetLastTwoImagesToUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 1]).find("img").attr("src");
urlLastImage.should.equal("http://bit.ly/2xq8ev0");
urlSecondLastImage.should.equal("http://bit.ly/2xq8ev0");
});
it('16) should constantly change the price (#changingPrice), increment it by one in each 3 secs.', () => {
constantlyChangeThePriceAndIncrementItByOneInEachThreeSeconds();
let changingPrices = [];
let changingPriceElem = $("#changingPrice");
changingPrices.push(changingPriceElem.text());
return delay(3000).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices[0].should.not.be.eql(changingPrices[1]);
changingPrices[0].should.not.be.eql(changingPrices[2]);
changingPrices[2].should.not.be.eql(changingPrices[1]);
});
});
it('17) should show the "BUY ITEM" again with a green background, gray border and a thin shadow', () => {
showTheBuyItemAgainWithAGreenBackgroundGrayBorderAndThinShadow();
delay(3000).then(function () {
let removeBuyItemButtonQuery = $("button[class='btn btn-info right js-newButtonStyle']");
let mapOfGrayBorders = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("border-color");
});
mapOfGrayBorders = mapOfGrayBorders.reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
let mapOfShadows = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("box-shadow");
}).reduce((acc, value) => {
return acc.set(value, 0);
}, new Map());
removeBuyItemButtonQuery.size().should.be.above(4);
mapOfGrayBorders.size.should.equal(1);
mapOfShadows.size.should.equal(1);
console.dir(mapOfGrayBorders.entries())
mapOfGrayBorders.entries().next().value[0].should.be.equal("rgb(192, 192, 192)");
mapOfShadows.entries().next().value[0].should.not.be.equal("none");
})
});
it('18) should add an event handler to the "BUY ITEM" buttons and after a click it should show an alert', () => {
addAnEventHandlerToTheBuyItemButtonsAndAfterClickShowAlert();
let removeBuyItemButtonQuery = $("button");
let clickEvents = removeBuyItemButtonQuery.map((index, tag) => {
return $._data($(tag).get(0), 'events');
}).toArray().reduce((acc, value) => {
if (value.click !== "undefined") {
return acc.concat("true");
}
}, []);
clickEvents.length.should.equal(removeBuyItemButtonQuery.length);
});
it('19) should bring back the initial image again, instead of "http://bit.ly/2xq8ev0"', () => {
bringBackTheInitialImageAgainInsteadOfUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 2]).find("img").attr("src");
urlLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
urlSecondLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
});
it('20) should change every product desctiption to any text with at least 50 charakters', () => {
changeEveryProductDescriptionToAnyTextWithAtLeast50Characters();
let descriptions = $(".thumbnail").find(" > p");
let newDescriptions = descriptions.map((index, tag) => {
return $(tag).text() !== "Lorem Ipsum is simply dummy text of the printing and typesetting industry. "
&& $(tag).text().length >= 50;
});
let filteredNewDescriptions = newDescriptions.filter((index, value) => {
return value;
});
filteredNewDescriptions.length.should.equal(descriptions.length);
});
it('21) should randomly change all of the prices', () => {
randomlyChangeAllOfThePrices();
let prices = $('.price');
let changedPrices = prices.map((index, tag) => {
return $(tag).text() !== "$26.91";
});
let filteredChangedPrices = changedPrices.filter((index, value) => {
return value;
});
filteredChangedPrices.length.should.equal(prices.length);
});
it('22) should mark the background with the color yellow of the two cheapest products', () => {
markTheBackgroundWithTheColorYellowOfTheTwoCheapestProducts();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let firstLowPrice = $(".price:contains('" + valuePrices[0] + "')");
let secondLowPrice = $(".price:contains('" + valuePrices[1] + "')");
firstLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
secondLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
});
it('23) should sort all the products ascendantly based on the the new prices', () => {
sortAllOfTheProductsAscendantlyBasedOnTheNewPrices();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
let properlySorted = true;
for (let i = 1; i < valuePrices.length; i++) {
if (valuePrices[i - 1] > valuePrices[i]) {
properlySorted = false;
}
}
properlySorted.should.be.eql(true);
});
it('24) should add an mouse over event only the highest two products which logs in console the price (place on div)', () => {
addAnMouseOverEventOnlyTheHighestTwoProductsWhichLogsInConsoleThePrice();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let highestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 1] + "')")
.parents(".thumbnail").parent();
let secondHighestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 2] + "')")
.parents(".thumbnail").parent();
let highestPriceEvents = $._data($(highestPriceParent).get(0), "events");
let secondHighestPriceEvents = $._data($(secondHighestPriceParent).get(0), "events");
(typeof highestPriceEvents !== "undefined"
&& typeof highestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
(typeof secondHighestPriceEvents !== "undefined"
&& typeof secondHighestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
});
it('25) should add three new products to the list like the existing one', ()=>{
addThreeNewProductsToTheEndOfTheProductList();
let containers = $(".thumbnail").parent();
containers.length.should.equal(8);
});
});
| {
return new Promise(function (resolve) {
setTimeout(resolve, milliseconds);
});
} | identifier_body |
tests.js | //async icin yardimci fonksiyon
function delay(milliseconds, resolve) {
return new Promise(function (resolve) {
setTimeout(resolve, milliseconds);
});
}
//Burdaki T ODO ödev icin bir önemi yok, sadece gelecek icin kodu düzeltme acisindan yapilacaklar
//TODO: For Instructors only -> Replace all Maps with Set's
//TODO: For Instructors only -> Null checks
//TODO: For Instructors only -> Reduction of function chaining
//TODO: For Instructors only -> Simplify jQuery statements
//Testler birbiriyle alakalidir, isole degildir! Bu dosyada hicbisey degistirmenize gerek yok.
describe("Test Suite jQuery => Each Test depends on the one above! Don't be fooled by passing greens in the beginning.", function () {
this.timeout(20000);
it('01) should hide all the images from the view', () => {
hideAllImages();
$("img:visible").size().should.be.equal(0);
});
it('02) should show all the images again', () => {
showAllImages();
let visibleImages = Array.from($("img")).filter(function(pElm){
$(pElm).css('display') === 'none';
});
visibleImages.length.should.be.equal(0);
});
it('03) should change the heading to "The Best Collection"', () => {
changeHeadingToTheBestCollection();
let headingNew = $(".container > h4:first").text();
headingNew.should.equal("The Best Collection");
});
it('04) should make the hr (.line) element bolder', () => {
let hrLine = $("hr.line");
let boldnessHrLineBefore = hrLine.first().css("border-width");
makeHrLineElementBolder();
let boldnessHrLineAfter = hrLine.first().css("border-width");
boldnessHrLineAfter.should.be.above(boldnessHrLineBefore);
});
it('05) should change the background of each product title with a different color', () => {
changeBackgroundColorOfEachProductTitleWithDifferentColor();
let productTitles = $("span.thumbnail").find("h4");
let colors =
Array.from(productTitles)
.map((tag) => {
return $(tag).css("background-color");
})
.reduce((acc, value) => {
return acc.add(value);
}, new Set());
colors.size.should.equal(productTitles.length);
});
it('06) should remove the "BUY ITEM" buttons', () => {
removeBuyItemButtons();
let removeBuyItemButtonQuery = $("button[class='btn btn-info right']");
let buttonVisibility = removeBuyItemButtonQuery.map((index, tag) => {
return $(tag).css("display") !== "none";
}).toArray();
let filteredButtons = buttonVisibility.filter((value, index) => {
return value;
});
filteredButtons.length.should.equal(0);
});
it('07) should remove the last three item from the view', () => {
removeLastThreeItemsFromView();
let items = $(".container").children("div").children("div");
let lastItem = items[7];
let secondLastItem = items[6];
items.length.should.equal(5);
should.not.exist(lastItem);
should.not.exist(secondLastItem);
});
it('08) should make 10% reduction on all products', () => {
let prices = $('.price');
let pricesBefore = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
makeTenPercentPriceReductionOnAllProducts();
let pricesAfter = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
pricesAfter.should.be.eql(pricesBefore.map((value, index) => {
let currencyVal = parseFloat(value.substring(1));
return "$" + (currencyVal * 0.9);
}));
});
it('10) should rename the product shirt to "Fish-Shirt"', () => {
renameTheProductShirtToFishShirt();
let firstShirtText = $("#firstProduct").find("h4").text();
firstShirtText.should.equal("Fish-Shirt");
});
it('11) should rename the first rock item to "Bird-Rock"', () => {
renameTheFirstRockItemToBirdRock();
let firstShirtText = $("#secondProduct").find("h4").text();
firstShirtText.should.equal("Bird-Rock");
});
it('12) should add 5 stars to the product shirt', () => {
addFiveStarsToTheProductShirt();
let firstShirtLastStar = $("#firstProduct").find(".ratings").children("span:last-child");
firstShirtLastStar.attr("class").should.equal("glyphicon glyphicon-star");
});
it('13) should change the title name with a random name (use alg. for randomly generating chars)', () => {
changeTheTitleNameWithARandomName();
let title = $(".container").children().first().text();
title.should.not.equal("NEW COLLECTION");
});
it('14) should color the stars of the third product with green', () => {
colorTheStarsOfTheThirdProductWithGreen();
let thirdProductStars = $("#secondProduct").next().find(".ratings").children();
let starColors = thirdProductStars.map((index, tag) => {
return $(tag).css("color");
}).toArray().reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
starColors.size.should.not.be.above(1);
starColors.has("rgb(0, 128, 0)").should.eql(true);
});
it('15) should reset the last two images to the url "http://bit.ly/2xq8ev0"', () => {
resetLastTwoImagesToUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 1]).find("img").attr("src");
urlLastImage.should.equal("http://bit.ly/2xq8ev0");
urlSecondLastImage.should.equal("http://bit.ly/2xq8ev0");
});
it('16) should constantly change the price (#changingPrice), increment it by one in each 3 secs.', () => {
constantlyChangeThePriceAndIncrementItByOneInEachThreeSeconds();
let changingPrices = [];
let changingPriceElem = $("#changingPrice");
changingPrices.push(changingPriceElem.text());
return delay(3000).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices[0].should.not.be.eql(changingPrices[1]);
changingPrices[0].should.not.be.eql(changingPrices[2]);
changingPrices[2].should.not.be.eql(changingPrices[1]);
});
});
it('17) should show the "BUY ITEM" again with a green background, gray border and a thin shadow', () => {
showTheBuyItemAgainWithAGreenBackgroundGrayBorderAndThinShadow();
delay(3000).then(function () {
let removeBuyItemButtonQuery = $("button[class='btn btn-info right js-newButtonStyle']");
let mapOfGrayBorders = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("border-color");
});
mapOfGrayBorders = mapOfGrayBorders.reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
let mapOfShadows = Array.from(removeBuyItemButtonQuery).map((tag) => { | return acc.set(value, 0);
}, new Map());
removeBuyItemButtonQuery.size().should.be.above(4);
mapOfGrayBorders.size.should.equal(1);
mapOfShadows.size.should.equal(1);
console.dir(mapOfGrayBorders.entries())
mapOfGrayBorders.entries().next().value[0].should.be.equal("rgb(192, 192, 192)");
mapOfShadows.entries().next().value[0].should.not.be.equal("none");
})
});
it('18) should add an event handler to the "BUY ITEM" buttons and after a click it should show an alert', () => {
addAnEventHandlerToTheBuyItemButtonsAndAfterClickShowAlert();
let removeBuyItemButtonQuery = $("button");
let clickEvents = removeBuyItemButtonQuery.map((index, tag) => {
return $._data($(tag).get(0), 'events');
}).toArray().reduce((acc, value) => {
if (value.click !== "undefined") {
return acc.concat("true");
}
}, []);
clickEvents.length.should.equal(removeBuyItemButtonQuery.length);
});
it('19) should bring back the initial image again, instead of "http://bit.ly/2xq8ev0"', () => {
bringBackTheInitialImageAgainInsteadOfUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 2]).find("img").attr("src");
urlLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
urlSecondLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
});
it('20) should change every product desctiption to any text with at least 50 charakters', () => {
changeEveryProductDescriptionToAnyTextWithAtLeast50Characters();
let descriptions = $(".thumbnail").find(" > p");
let newDescriptions = descriptions.map((index, tag) => {
return $(tag).text() !== "Lorem Ipsum is simply dummy text of the printing and typesetting industry. "
&& $(tag).text().length >= 50;
});
let filteredNewDescriptions = newDescriptions.filter((index, value) => {
return value;
});
filteredNewDescriptions.length.should.equal(descriptions.length);
});
it('21) should randomly change all of the prices', () => {
randomlyChangeAllOfThePrices();
let prices = $('.price');
let changedPrices = prices.map((index, tag) => {
return $(tag).text() !== "$26.91";
});
let filteredChangedPrices = changedPrices.filter((index, value) => {
return value;
});
filteredChangedPrices.length.should.equal(prices.length);
});
it('22) should mark the background with the color yellow of the two cheapest products', () => {
markTheBackgroundWithTheColorYellowOfTheTwoCheapestProducts();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let firstLowPrice = $(".price:contains('" + valuePrices[0] + "')");
let secondLowPrice = $(".price:contains('" + valuePrices[1] + "')");
firstLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
secondLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
});
it('23) should sort all the products ascendantly based on the the new prices', () => {
sortAllOfTheProductsAscendantlyBasedOnTheNewPrices();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
let properlySorted = true;
for (let i = 1; i < valuePrices.length; i++) {
if (valuePrices[i - 1] > valuePrices[i]) {
properlySorted = false;
}
}
properlySorted.should.be.eql(true);
});
it('24) should add an mouse over event only the highest two products which logs in console the price (place on div)', () => {
addAnMouseOverEventOnlyTheHighestTwoProductsWhichLogsInConsoleThePrice();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let highestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 1] + "')")
.parents(".thumbnail").parent();
let secondHighestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 2] + "')")
.parents(".thumbnail").parent();
let highestPriceEvents = $._data($(highestPriceParent).get(0), "events");
let secondHighestPriceEvents = $._data($(secondHighestPriceParent).get(0), "events");
(typeof highestPriceEvents !== "undefined"
&& typeof highestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
(typeof secondHighestPriceEvents !== "undefined"
&& typeof secondHighestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
});
it('25) should add three new products to the list like the existing one', ()=>{
addThreeNewProductsToTheEndOfTheProductList();
let containers = $(".thumbnail").parent();
containers.length.should.equal(8);
});
}); | return $(tag).css("box-shadow");
}).reduce((acc, value) => { | random_line_split |
tests.js | //async icin yardimci fonksiyon
function delay(milliseconds, resolve) {
return new Promise(function (resolve) {
setTimeout(resolve, milliseconds);
});
}
//Burdaki T ODO ödev icin bir önemi yok, sadece gelecek icin kodu düzeltme acisindan yapilacaklar
//TODO: For Instructors only -> Replace all Maps with Set's
//TODO: For Instructors only -> Null checks
//TODO: For Instructors only -> Reduction of function chaining
//TODO: For Instructors only -> Simplify jQuery statements
//Testler birbiriyle alakalidir, isole degildir! Bu dosyada hicbisey degistirmenize gerek yok.
describe("Test Suite jQuery => Each Test depends on the one above! Don't be fooled by passing greens in the beginning.", function () {
this.timeout(20000);
it('01) should hide all the images from the view', () => {
hideAllImages();
$("img:visible").size().should.be.equal(0);
});
it('02) should show all the images again', () => {
showAllImages();
let visibleImages = Array.from($("img")).filter(function(pElm){
$(pElm).css('display') === 'none';
});
visibleImages.length.should.be.equal(0);
});
it('03) should change the heading to "The Best Collection"', () => {
changeHeadingToTheBestCollection();
let headingNew = $(".container > h4:first").text();
headingNew.should.equal("The Best Collection");
});
it('04) should make the hr (.line) element bolder', () => {
let hrLine = $("hr.line");
let boldnessHrLineBefore = hrLine.first().css("border-width");
makeHrLineElementBolder();
let boldnessHrLineAfter = hrLine.first().css("border-width");
boldnessHrLineAfter.should.be.above(boldnessHrLineBefore);
});
it('05) should change the background of each product title with a different color', () => {
changeBackgroundColorOfEachProductTitleWithDifferentColor();
let productTitles = $("span.thumbnail").find("h4");
let colors =
Array.from(productTitles)
.map((tag) => {
return $(tag).css("background-color");
})
.reduce((acc, value) => {
return acc.add(value);
}, new Set());
colors.size.should.equal(productTitles.length);
});
it('06) should remove the "BUY ITEM" buttons', () => {
removeBuyItemButtons();
let removeBuyItemButtonQuery = $("button[class='btn btn-info right']");
let buttonVisibility = removeBuyItemButtonQuery.map((index, tag) => {
return $(tag).css("display") !== "none";
}).toArray();
let filteredButtons = buttonVisibility.filter((value, index) => {
return value;
});
filteredButtons.length.should.equal(0);
});
it('07) should remove the last three item from the view', () => {
removeLastThreeItemsFromView();
let items = $(".container").children("div").children("div");
let lastItem = items[7];
let secondLastItem = items[6];
items.length.should.equal(5);
should.not.exist(lastItem);
should.not.exist(secondLastItem);
});
it('08) should make 10% reduction on all products', () => {
let prices = $('.price');
let pricesBefore = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
makeTenPercentPriceReductionOnAllProducts();
let pricesAfter = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
pricesAfter.should.be.eql(pricesBefore.map((value, index) => {
let currencyVal = parseFloat(value.substring(1));
return "$" + (currencyVal * 0.9);
}));
});
it('10) should rename the product shirt to "Fish-Shirt"', () => {
renameTheProductShirtToFishShirt();
let firstShirtText = $("#firstProduct").find("h4").text();
firstShirtText.should.equal("Fish-Shirt");
});
it('11) should rename the first rock item to "Bird-Rock"', () => {
renameTheFirstRockItemToBirdRock();
let firstShirtText = $("#secondProduct").find("h4").text();
firstShirtText.should.equal("Bird-Rock");
});
it('12) should add 5 stars to the product shirt', () => {
addFiveStarsToTheProductShirt();
let firstShirtLastStar = $("#firstProduct").find(".ratings").children("span:last-child");
firstShirtLastStar.attr("class").should.equal("glyphicon glyphicon-star");
});
it('13) should change the title name with a random name (use alg. for randomly generating chars)', () => {
changeTheTitleNameWithARandomName();
let title = $(".container").children().first().text();
title.should.not.equal("NEW COLLECTION");
});
it('14) should color the stars of the third product with green', () => {
colorTheStarsOfTheThirdProductWithGreen();
let thirdProductStars = $("#secondProduct").next().find(".ratings").children();
let starColors = thirdProductStars.map((index, tag) => {
return $(tag).css("color");
}).toArray().reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
starColors.size.should.not.be.above(1);
starColors.has("rgb(0, 128, 0)").should.eql(true);
});
it('15) should reset the last two images to the url "http://bit.ly/2xq8ev0"', () => {
resetLastTwoImagesToUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 1]).find("img").attr("src");
urlLastImage.should.equal("http://bit.ly/2xq8ev0");
urlSecondLastImage.should.equal("http://bit.ly/2xq8ev0");
});
it('16) should constantly change the price (#changingPrice), increment it by one in each 3 secs.', () => {
constantlyChangeThePriceAndIncrementItByOneInEachThreeSeconds();
let changingPrices = [];
let changingPriceElem = $("#changingPrice");
changingPrices.push(changingPriceElem.text());
return delay(3000).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices.push(changingPriceElem.text());
return delay(3000)
}).then(function () {
changingPrices[0].should.not.be.eql(changingPrices[1]);
changingPrices[0].should.not.be.eql(changingPrices[2]);
changingPrices[2].should.not.be.eql(changingPrices[1]);
});
});
it('17) should show the "BUY ITEM" again with a green background, gray border and a thin shadow', () => {
showTheBuyItemAgainWithAGreenBackgroundGrayBorderAndThinShadow();
delay(3000).then(function () {
let removeBuyItemButtonQuery = $("button[class='btn btn-info right js-newButtonStyle']");
let mapOfGrayBorders = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("border-color");
});
mapOfGrayBorders = mapOfGrayBorders.reduce((acc, value, index, arr) => {
return acc.set(value, 0);
}, new Map());
let mapOfShadows = Array.from(removeBuyItemButtonQuery).map((tag) => {
return $(tag).css("box-shadow");
}).reduce((acc, value) => {
return acc.set(value, 0);
}, new Map());
removeBuyItemButtonQuery.size().should.be.above(4);
mapOfGrayBorders.size.should.equal(1);
mapOfShadows.size.should.equal(1);
console.dir(mapOfGrayBorders.entries())
mapOfGrayBorders.entries().next().value[0].should.be.equal("rgb(192, 192, 192)");
mapOfShadows.entries().next().value[0].should.not.be.equal("none");
})
});
it('18) should add an event handler to the "BUY ITEM" buttons and after a click it should show an alert', () => {
addAnEventHandlerToTheBuyItemButtonsAndAfterClickShowAlert();
let removeBuyItemButtonQuery = $("button");
let clickEvents = removeBuyItemButtonQuery.map((index, tag) => {
return $._data($(tag).get(0), 'events');
}).toArray().reduce((acc, value) => {
if (value.click !== "undefined") {
return acc.concat("true");
}
}, []);
clickEvents.length.should.equal(removeBuyItemButtonQuery.length);
});
it('19) should bring back the initial image again, instead of "http://bit.ly/2xq8ev0"', () => {
bringBackTheInitialImageAgainInsteadOfUrl();
let items = $(".container").children("div").children("div");
let urlLastImage = $(items[items.length - 1]).find("img").attr("src");
let urlSecondLastImage = $(items[items.length - 2]).find("img").attr("src");
urlLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
urlSecondLastImage.should.equal("https://s12.postimg.org/dawwajl0d/item_3_180x200.png");
});
it('20) should change every product desctiption to any text with at least 50 charakters', () => {
changeEveryProductDescriptionToAnyTextWithAtLeast50Characters();
let descriptions = $(".thumbnail").find(" > p");
let newDescriptions = descriptions.map((index, tag) => {
return $(tag).text() !== "Lorem Ipsum is simply dummy text of the printing and typesetting industry. "
&& $(tag).text().length >= 50;
});
let filteredNewDescriptions = newDescriptions.filter((index, value) => {
return value;
});
filteredNewDescriptions.length.should.equal(descriptions.length);
});
it('21) should randomly change all of the prices', () => {
randomlyChangeAllOfThePrices();
let prices = $('.price');
let changedPrices = prices.map((index, tag) => {
return $(tag).text() !== "$26.91";
});
let filteredChangedPrices = changedPrices.filter((index, value) => {
return value;
});
filteredChangedPrices.length.should.equal(prices.length);
});
it('22) should mark the background with the color yellow of the two cheapest products', () => {
markTheBackgroundWithTheColorYellowOfTheTwoCheapestProducts();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let firstLowPrice = $(".price:contains('" + valuePrices[0] + "')");
let secondLowPrice = $(".price:contains('" + valuePrices[1] + "')");
firstLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
secondLowPrice.css("background-color").should.equal("rgb(255, 255, 0)");
});
it('23) should sort all the products ascendantly based on the the new prices', () => {
sortAllOfTheProductsAscendantlyBasedOnTheNewPrices();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
let properlySorted = true;
for (let i = 1; i < valuePrices.length; i++) {
| properlySorted.should.be.eql(true);
});
it('24) should add an mouse over event only the highest two products which logs in console the price (place on div)', () => {
addAnMouseOverEventOnlyTheHighestTwoProductsWhichLogsInConsoleThePrice();
let prices = $('.price');
let valuePrices = prices.map((index, tag) => {
return parseFloat($(tag).text().substring(1));
});
valuePrices.sort(function(a,b){return a > b});
let highestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 1] + "')")
.parents(".thumbnail").parent();
let secondHighestPriceParent = $(".price:contains('" + valuePrices[valuePrices.length - 2] + "')")
.parents(".thumbnail").parent();
let highestPriceEvents = $._data($(highestPriceParent).get(0), "events");
let secondHighestPriceEvents = $._data($(secondHighestPriceParent).get(0), "events");
(typeof highestPriceEvents !== "undefined"
&& typeof highestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
(typeof secondHighestPriceEvents !== "undefined"
&& typeof secondHighestPriceEvents["mouseover"] !== "undefined").should.be.eql(true);
});
it('25) should add three new products to the list like the existing one', ()=>{
addThreeNewProductsToTheEndOfTheProductList();
let containers = $(".thumbnail").parent();
containers.length.should.equal(8);
});
});
| if (valuePrices[i - 1] > valuePrices[i]) {
properlySorted = false;
}
}
| conditional_block |
utils.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the Utils provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Utils {
constructor(public http: Http) {
console.log('Hello Utils Provider');
}
serviceShareData(serviceType:string, serviceList:Array<any>, desc: string){
let data = {};
data['serviceType'] = serviceType;
data['serviceList'] = serviceList;
data['description'] = desc;
return data;
}
| (serviceData:any, selectedCity:string,
area:string, houseNo:string, locality:string,date:string, time:string){
let data = {};
data['serviceData'] = serviceData;
data['city'] = selectedCity;
data['area'] = area;
data['houseNo'] = houseNo;
data['locality'] = locality;
data['date'] = date;
data['time'] = time;
return data;
}
}
| serviceSharedAddressToPhone | identifier_name |
utils.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the Utils provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Utils {
constructor(public http: Http) {
console.log('Hello Utils Provider');
}
| data['description'] = desc;
return data;
}
serviceSharedAddressToPhone(serviceData:any, selectedCity:string,
area:string, houseNo:string, locality:string,date:string, time:string){
let data = {};
data['serviceData'] = serviceData;
data['city'] = selectedCity;
data['area'] = area;
data['houseNo'] = houseNo;
data['locality'] = locality;
data['date'] = date;
data['time'] = time;
return data;
}
} | serviceShareData(serviceType:string, serviceList:Array<any>, desc: string){
let data = {};
data['serviceType'] = serviceType;
data['serviceList'] = serviceList; | random_line_split |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
|
def render(self, requestdata):
if mode() == 'dm':
return JSON_Editor.render(self, requestdata)
else:
char = frontend.campaign.current_char()
return self.view(char.name())
def view(self, item):
page = Page()
if not item:
page.error('No item specified')
return page.render()
try:
debug('try %s/%s' % (self._name, item))
json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error('No files matching %s found in %s' % (item, self._name))
return page.render()
c = Character(json)
rendered = {}
rendered['json'] = c.render()
return page.tplrender('json_viewer.tpl', rendered)
| self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Character({}) | identifier_body |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Character({})
def render(self, requestdata):
if mode() == 'dm':
return JSON_Editor.render(self, requestdata)
else:
char = frontend.campaign.current_char()
return self.view(char.name())
def | (self, item):
page = Page()
if not item:
page.error('No item specified')
return page.render()
try:
debug('try %s/%s' % (self._name, item))
json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error('No files matching %s found in %s' % (item, self._name))
return page.render()
c = Character(json)
rendered = {}
rendered['json'] = c.render()
return page.tplrender('json_viewer.tpl', rendered)
| view | identifier_name |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Character({})
def render(self, requestdata):
if mode() == 'dm':
return JSON_Editor.render(self, requestdata)
else:
char = frontend.campaign.current_char()
return self.view(char.name())
def view(self, item):
page = Page()
if not item:
|
try:
debug('try %s/%s' % (self._name, item))
json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error('No files matching %s found in %s' % (item, self._name))
return page.render()
c = Character(json)
rendered = {}
rendered['json'] = c.render()
return page.tplrender('json_viewer.tpl', rendered)
| page.error('No item specified')
return page.render() | conditional_block |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Character({})
def render(self, requestdata):
if mode() == 'dm':
return JSON_Editor.render(self, requestdata)
else:
char = frontend.campaign.current_char()
return self.view(char.name())
def view(self, item):
page = Page()
if not item:
page.error('No item specified')
return page.render()
try: | json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error('No files matching %s found in %s' % (item, self._name))
return page.render()
c = Character(json)
rendered = {}
rendered['json'] = c.render()
return page.tplrender('json_viewer.tpl', rendered) | debug('try %s/%s' % (self._name, item)) | random_line_split |
exceptions.py | # Copyright 2016 Autodesk 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.
class ConvergenceFailure(Exception):
""" Raised when an iterative calculation fails to converge """
pass
class NotCalculatedError(Exception):
""" Raised when a molecular property is requested that hasn't been calculated """
pass
class UnhandledValenceError(Exception):
|
class QMConvergenceError(Exception):
""" Raised when an iterative QM calculation (typically SCF) fails to converge
"""
pass
| def __init__(self, atom):
self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence) | identifier_body |
exceptions.py | # Copyright 2016 Autodesk 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.
|
class NotCalculatedError(Exception):
""" Raised when a molecular property is requested that hasn't been calculated """
pass
class UnhandledValenceError(Exception):
def __init__(self, atom):
self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence)
class QMConvergenceError(Exception):
""" Raised when an iterative QM calculation (typically SCF) fails to converge
"""
pass |
class ConvergenceFailure(Exception):
""" Raised when an iterative calculation fails to converge """
pass
| random_line_split |
exceptions.py | # Copyright 2016 Autodesk 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.
class ConvergenceFailure(Exception):
""" Raised when an iterative calculation fails to converge """
pass
class | (Exception):
""" Raised when a molecular property is requested that hasn't been calculated """
pass
class UnhandledValenceError(Exception):
def __init__(self, atom):
self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence)
class QMConvergenceError(Exception):
""" Raised when an iterative QM calculation (typically SCF) fails to converge
"""
pass
| NotCalculatedError | identifier_name |
ModalLoading.js | import React,{
Component
} from 'react'
import {
View,
TouchableOpacity,
Modal,
Text,
DatePickerIOS,
StyleSheet,
Image,
ActivityIndicator,
}from 'react-native'
import { Actions } from 'react-native-router-flux';
import GlobalSize from '../common/GlobalSize'
export default class | extends Component{
constructor(props){
super(props);
// this.state={
// visible:false,
// }
}
render(){
console.log('加载modal是否显示'+this.props.visible);
return(
<Modal
animationType='fade'
transparent={true}
visible={this.props.visible}
onRequestClose={() => {}}
>
<View style={styles.container}>
<View style={styles.contentContainer}>
<ActivityIndicator
animation={true}
size='large'
/>
<Text style={{textAlign:'center'}}>
{this.props.loadingText?this.props.loadingText :"正在加载..."}
</Text>
</View>
</View>
</Modal>
);
}
}
var styles=StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'rgba(0,1,0,0.2)',
},
contentContainer:{
height:60,
},
})
| ModalLoading | identifier_name |
ModalLoading.js | import React,{
Component
} from 'react'
import {
View,
TouchableOpacity,
Modal,
Text,
DatePickerIOS,
StyleSheet,
Image,
ActivityIndicator,
}from 'react-native'
import { Actions } from 'react-native-router-flux';
import GlobalSize from '../common/GlobalSize'
export default class ModalLoading extends Component{
constructor(props){
super(props);
// this.state={
// visible:false,
// }
}
render() | Sheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'rgba(0,1,0,0.2)',
},
contentContainer:{
height:60,
},
})
| {
console.log('加载modal是否显示'+this.props.visible);
return(
<Modal
animationType='fade'
transparent={true}
visible={this.props.visible}
onRequestClose={() => {}}
>
<View style={styles.container}>
<View style={styles.contentContainer}>
<ActivityIndicator
animation={true}
size='large'
/>
<Text style={{textAlign:'center'}}>
{this.props.loadingText?this.props.loadingText :"正在加载..."}
</Text>
</View>
</View>
</Modal>
);
}
}
var styles=Style | identifier_body |
ModalLoading.js | import React,{
Component
} from 'react'
import {
View,
TouchableOpacity,
Modal,
Text,
DatePickerIOS,
StyleSheet,
Image,
ActivityIndicator,
}from 'react-native'
import { Actions } from 'react-native-router-flux';
import GlobalSize from '../common/GlobalSize'
export default class ModalLoading extends Component{
constructor(props){
super(props);
// this.state={
// visible:false,
// }
}
render(){
console.log('加载modal是否显示'+this.props.visible);
return(
<Modal
animationType='fade'
transparent={true}
visible={this.props.visible}
onRequestClose={() => {}}
>
<View style={styles.container}>
<View style={styles.contentContainer}>
<ActivityIndicator
animation={true}
size='large'
/>
<Text style={{textAlign:'center'}}>
{this.props.loadingText?this.props.loadingText :"正在加载..."} | );
}
}
var styles=StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'rgba(0,1,0,0.2)',
},
contentContainer:{
height:60,
},
}) | </Text>
</View>
</View>
</Modal> | random_line_split |
characters.js | var total_records = 0;
var url;
var total_groups;
var id;
var loading = false;
function initScroll(total_groups, url, id) {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
$(window).scroll(function() {
if(total_records >= total_groups) {
$(window).off('scroll');
}
if(($(window).scrollTop() + $(window).height() > $(document).height() - 100) && loading == false) {
if(total_records < total_groups) |
}
});
} | {
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
} | conditional_block |
characters.js | var total_records = 0;
var url; |
function initScroll(total_groups, url, id) {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
$(window).scroll(function() {
if(total_records >= total_groups) {
$(window).off('scroll');
}
if(($(window).scrollTop() + $(window).height() > $(document).height() - 100) && loading == false) {
if(total_records < total_groups) {
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
}
}
});
} | var total_groups;
var id;
var loading = false; | random_line_split |
characters.js | var total_records = 0;
var url;
var total_groups;
var id;
var loading = false;
function initScroll(total_groups, url, id) | {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
$(window).scroll(function() {
if(total_records >= total_groups) {
$(window).off('scroll');
}
if(($(window).scrollTop() + $(window).height() > $(document).height() - 100) && loading == false) {
if(total_records < total_groups) {
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
}
}
});
} | identifier_body | |
characters.js | var total_records = 0;
var url;
var total_groups;
var id;
var loading = false;
function | (total_groups, url, id) {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
$(window).scroll(function() {
if(total_records >= total_groups) {
$(window).off('scroll');
}
if(($(window).scrollTop() + $(window).height() > $(document).height() - 100) && loading == false) {
if(total_records < total_groups) {
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element).data('id') == 2) {
$("#main_characters_div div table tbody").append(element);
} else {
$("#secondary_characters_div div table tbody").append(element);
}
});
total_records++;
}
loading = false;
$('#loader_image_div').hide();
});
}
}
});
} | initScroll | identifier_name |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_without_at_bot
from wxpy.utils import enhance_connection
logger = logging.getLogger(__name__)
from wxpy.compatible import *
class XiaoI(object):
"""
与 wxpy 深度整合的小 i 机器人
"""
# noinspection SpellCheckingInspection
def __init__(self, key, secret):
"""
| 需要通过注册获得 key 和 secret
| 免费申请: http://cloud.xiaoi.com/
:param key: 你申请的 key
:param secret: 你申请的 secret
"""
self.key = key
self.secret = secret
self.realm = "xiaoi.com"
self.http_method = "POST"
self.uri = "/ask.do"
self.url = "http://nlp.xiaoi.com/ask.do?platform=custom"
xauth = self._make_http_header_xauth()
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
headers.update(xauth)
self.session = requests.Session()
self.session.headers.update(headers)
enhance_connection(self.session)
def _make_signature(self):
"""
生成请求签名
"""
# 40位随机字符
# nonce = "".join([str(randint(0, 9)) for _ in range(40)])
nonce = "4103657107305326101203516108016101205331"
sha1 = "{0}:{1}:{2}".format(self.key, self.realm, self.secret).encode("utf-8")
sha1 = hashlib.sha1(sha1).hexdigest()
sha2 = "{0}:{1}".format(self.http_method, self.uri).encode("utf-8")
sha2 = hashlib.sha1(sha2).hexdigest()
signature = "{0}:{1}:{2}".format(sha1, nonce, sha2).encode("utf-8")
signature = hashlib.sha1(signature).hexdigest()
ret = collections.namedtuple("signature_return", "signature nonce")
ret.signature = signature
ret.nonce = nonce
return ret
def _make_http_header_xauth(self):
"""
生成请求认证
"""
sign = self._make_signature()
ret = {
"X-Auth": "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format(
self.key, sign.nonce, sign.signature)
}
return ret
def do_reply(self, msg):
"""
回复消息,并返回答复文本
:param msg: Message 对象
:return: 答复文本
"""
ret = self.reply_text(msg)
msg.reply(ret)
return ret
def reply_text(self, msg):
"""
仅返回答复文本
:param msg: Message 对象,或消息文本
:return: 答复文本
"""
error_response = (
"主人还没给我设置这类话题的回复",
)
if isinstance(msg, Message):
user_id = get_context_user_id(msg)
question = get_text_without_at_bot(msg)
else:
user_id = "abc"
question = msg or ""
params = {
"quest | "userId": user_id,
}
resp = self.session.post(self.url, data=params)
text = resp.text
for err in error_response:
if err in text:
return next_topic()
return text
| ion": question,
"format": "json",
"platform": "custom",
| conditional_block |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_without_at_bot
from wxpy.utils import enhance_connection
logger = logging.getLogger(__name__)
from wxpy.compatible import *
class XiaoI(object):
"""
与 wxpy 深度整合的小 i 机器人
"""
# noinspection SpellCheckingInspection
def __init__(self, key, secret):
"""
| 需要通过注册获得 key 和 secret
| 免费申请: http://cloud.xiaoi.com/
:param key: 你申请的 key
:param secret: 你申请的 secret
"""
self.key = key
self.secret = secret
self.realm = "xiaoi.com"
self.http_method = "POST"
self.uri = "/ask.do"
self.url = "http://nlp.xiaoi.com/ask.do?platform=custom"
xauth = self._make_http_header_xauth()
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
headers.update(xauth)
self.session = requests.Session()
self.session.headers.update(headers)
enhance_connection(self.session)
def _make_signature(self):
"""
生成请求签名
"""
# 40位随机字符
# nonce = "".join([str(randint(0, 9)) for _ in range(40)])
nonce = "4103657107305326101203516108016101205331"
sha1 = "{0}:{1}:{2}".format(self.key, self.realm, self.secret).encode("utf-8")
sha1 = hashlib.sha1(sha1).hexdigest()
sha2 = "{0}:{1}".format(self.http_method, self.uri).encode("utf-8") | sha2 = hashlib.sha1(sha2).hexdigest()
signature = "{0}:{1}:{2}".format(sha1, nonce, sha2).encode("utf-8")
signature = hashlib.sha1(signature).hexdigest()
ret = collections.namedtuple("signature_return", "signature nonce")
ret.signature = signature
ret.nonce = nonce
return ret
def _make_http_header_xauth(self):
"""
生成请求认证
"""
sign = self._make_signature()
ret = {
"X-Auth": "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format(
self.key, sign.nonce, sign.signature)
}
return ret
def do_reply(self, msg):
"""
回复消息,并返回答复文本
:param msg: Message 对象
:return: 答复文本
"""
ret = self.reply_text(msg)
msg.reply(ret)
return ret
def reply_text(self, msg):
"""
仅返回答复文本
:param msg: Message 对象,或消息文本
:return: 答复文本
"""
error_response = (
"主人还没给我设置这类话题的回复",
)
if isinstance(msg, Message):
user_id = get_context_user_id(msg)
question = get_text_without_at_bot(msg)
else:
user_id = "abc"
question = msg or ""
params = {
"question": question,
"format": "json",
"platform": "custom",
"userId": user_id,
}
resp = self.session.post(self.url, data=params)
text = resp.text
for err in error_response:
if err in text:
return next_topic()
return text | random_line_split | |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_without_at_bot
from wxpy.utils import enhance_connection
logger = logging.getLogger(__name__)
from wxpy.compatible import *
class | (object):
"""
与 wxpy 深度整合的小 i 机器人
"""
# noinspection SpellCheckingInspection
def __init__(self, key, secret):
"""
| 需要通过注册获得 key 和 secret
| 免费申请: http://cloud.xiaoi.com/
:param key: 你申请的 key
:param secret: 你申请的 secret
"""
self.key = key
self.secret = secret
self.realm = "xiaoi.com"
self.http_method = "POST"
self.uri = "/ask.do"
self.url = "http://nlp.xiaoi.com/ask.do?platform=custom"
xauth = self._make_http_header_xauth()
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
headers.update(xauth)
self.session = requests.Session()
self.session.headers.update(headers)
enhance_connection(self.session)
def _make_signature(self):
"""
生成请求签名
"""
# 40位随机字符
# nonce = "".join([str(randint(0, 9)) for _ in range(40)])
nonce = "4103657107305326101203516108016101205331"
sha1 = "{0}:{1}:{2}".format(self.key, self.realm, self.secret).encode("utf-8")
sha1 = hashlib.sha1(sha1).hexdigest()
sha2 = "{0}:{1}".format(self.http_method, self.uri).encode("utf-8")
sha2 = hashlib.sha1(sha2).hexdigest()
signature = "{0}:{1}:{2}".format(sha1, nonce, sha2).encode("utf-8")
signature = hashlib.sha1(signature).hexdigest()
ret = collections.namedtuple("signature_return", "signature nonce")
ret.signature = signature
ret.nonce = nonce
return ret
def _make_http_header_xauth(self):
"""
生成请求认证
"""
sign = self._make_signature()
ret = {
"X-Auth": "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format(
self.key, sign.nonce, sign.signature)
}
return ret
def do_reply(self, msg):
"""
回复消息,并返回答复文本
:param msg: Message 对象
:return: 答复文本
"""
ret = self.reply_text(msg)
msg.reply(ret)
return ret
def reply_text(self, msg):
"""
仅返回答复文本
:param msg: Message 对象,或消息文本
:return: 答复文本
"""
error_response = (
"主人还没给我设置这类话题的回复",
)
if isinstance(msg, Message):
user_id = get_context_user_id(msg)
question = get_text_without_at_bot(msg)
else:
user_id = "abc"
question = msg or ""
params = {
"question": question,
"format": "json",
"platform": "custom",
"userId": user_id,
}
resp = self.session.post(self.url, data=params)
text = resp.text
for err in error_response:
if err in text:
return next_topic()
return text
| XiaoI | identifier_name |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_without_at_bot
from wxpy.utils import enhance_connection
logger = logging.getLogger(__name__)
from wxpy.compatible import *
class XiaoI(object):
"""
与 wxpy 深度整合的小 i 机器人
"""
# noinspection SpellCheckingInspection
def __init__(self, key, secret):
"""
| 需要通过注册获得 key 和 secret
| 免费申请: http://cloud.xiaoi.com/
:param key: 你申请的 key
:param secret: 你申请的 secret
"""
self.key = key
self.secret = secret
self.realm = "xiaoi.com"
self.http_method = "POST"
self.uri = "/ask.do"
self.url = "http://nlp.xiaoi.com/ask.do?platform=custom"
xauth = self._make_http_header_xauth()
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
headers.update(xauth)
self.session = requests.Session()
self.session.headers.update(headers)
enhance_connection(self.session)
def _make_signature(self):
"""
生成请求签名
"""
# 40位随机字符
# nonce = "".join([str(randint(0, 9)) for _ in range(40)])
nonce = "4103657107305326101203516108016101205331"
sha1 = "{0}:{1}:{2}".format(self.key, self.realm, self.secret).encode("utf-8")
sha1 = hashlib.sha1(sha1).hexdigest()
sha2 = "{0}:{1}".format(self.http_method, self.uri).encode("utf-8")
sha2 = hashlib.sha1(sha2).hexdigest()
signature = "{0}:{1}:{2}".format(sha1, nonce, sha2).encode("utf-8")
signature = hashlib.sha1(signature).hexdigest()
ret = collections.namedtuple("signature_return", "signature nonce")
ret.signature = signature
ret.nonce = nonce
return ret
def _make_http_header_xauth(self):
"""
生成请求认证
"""
sign = self._make_signature()
ret = {
"X-Auth": "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format(
self.key, sign.nonce, sign.signature)
}
return ret
def do_reply(self, msg):
"""
回复消息,并返回答复文本
:param msg: Message 对象
:return: 答复文本
"""
ret = self.reply_text(msg)
msg.reply(ret)
return ret
def reply_text(self, msg):
"""
仅返回答复文本
:param msg: Message 对象,或消息文本
:return: 答复文本
"""
error_response = (
| "主人还没给我设置这类话题的回复",
)
if isinstance(msg, Message):
user_id = get_context_user_id(msg)
question = get_text_without_at_bot(msg)
else:
user_id = "abc"
question = msg or ""
params = {
"question": question,
"format": "json",
"platform": "custom",
"userId": user_id,
}
resp = self.session.post(self.url, data=params)
text = resp.text
for err in error_response:
if err in text:
return next_topic()
return text
| identifier_body | |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cumValues.push(newValue);
chrPositions[newValue.chr] = newValue; | chromLengths[data[i][0]] = length;
}
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows; | random_line_split | |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) |
export default parseChromsizesRows;
| {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cumValues.push(newValue);
chrPositions[newValue.chr] = newValue;
chromLengths[data[i][0]] = length;
}
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
} | identifier_body |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function | (data) {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cumValues.push(newValue);
chrPositions[newValue.chr] = newValue;
chromLengths[data[i][0]] = length;
}
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows;
| parseChromsizesRows | identifier_name |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) |
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows;
| {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cumValues.push(newValue);
chrPositions[newValue.chr] = newValue;
chromLengths[data[i][0]] = length;
} | conditional_block |
util.ts | import { SearchParams, SearchResult, PageResultsMap } from '..'
/**
* @param resultEntries Map entries (2-el KVP arrays) of URL keys to latest times
* @return Sorted and trimmed version of `resultEntries` input.
*/
export const paginate = (
resultEntries: SearchResult[] | PageResultsMap,
{ skip = 0, limit = 10 }: Partial<SearchParams>,
): SearchResult[] =>
[...resultEntries]
.sort(([, a], [, b]) => b - a)
.slice(skip, skip + limit) as SearchResult[]
/**
* @param urlScoreMap Map of URL keys to score multipliers.
* @param latestVisitsMap Map of URL keys to latest event timestamp.
* @return Map of URL keys to derived score (multiplier * latest event timestamp).
*/
export const applyScores = (
urlScoreMap: PageResultsMap, | .map(
([url, multi]): [string, number, number] => [
url,
Math.trunc(latestVisitsMap.get(url) * multi),
latestVisitsMap.get(url),
],
) | latestVisitsMap: PageResultsMap,
): SearchResult[] =>
[...urlScoreMap]
// Visits may be filtered down by time; only keep URLs appearing in visits Map
.filter(([url]) => latestVisitsMap.has(url)) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.