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 |
|---|---|---|---|---|
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref lines) => lines.len()
}
}
/// Returns the line if there is only 1.
#[inline]
pub fn one(&self) -> Option<&[u8]> {
match self.0 {
Lines::One(ref line) => Some(line.as_ref()),
Lines::Many(ref lines) if lines.len() == 1 => Some(lines[0].as_ref()),
_ => None
}
}
/// Iterate the lines of raw bytes.
#[inline]
pub fn iter(&self) -> RawLines |
/// Append a line to this `Raw` header value.
pub fn push(&mut self, val: &[u8]) {
self.push_line(maybe_literal(val.into()));
}
fn push_line(&mut self, line: Line) {
let lines = ::std::mem::replace(&mut self.0, Lines::Many(Vec::new()));
match lines {
Lines::One(one) => {
self.0 = Lines::Many(vec![one, line]);
}
Lines::Many(mut lines) => {
lines.push(line);
self.0 = Lines::Many(lines);
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Lines {
One(Line),
Many(Vec<Line>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Line {
Static(&'static [u8]),
Owned(Vec<u8>),
Shared(MemSlice),
}
fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {
if a.len() != b.len() {
false
} else {
for (a, b) in a.iter().zip(b.iter()) {
if a.as_ref() != b.as_ref() {
return false
}
}
true
}
}
impl PartialEq<[Vec<u8>]> for Raw {
fn eq(&self, bytes: &[Vec<u8>]) -> bool {
match self.0 {
Lines::One(ref line) => eq(&[line], bytes),
Lines::Many(ref lines) => eq(lines, bytes)
}
}
}
impl PartialEq<[u8]> for Raw {
fn eq(&self, bytes: &[u8]) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == bytes,
Lines::Many(..) => false
}
}
}
impl PartialEq<str> for Raw {
fn eq(&self, s: &str) -> bool {
match self.0 {
Lines::One(ref line) => line.as_ref() == s.as_bytes(),
Lines::Many(..) => false
}
}
}
impl From<Vec<Vec<u8>>> for Raw {
#[inline]
fn from(val: Vec<Vec<u8>>) -> Raw {
Raw(Lines::Many(
val.into_iter()
.map(|vec| maybe_literal(vec.into()))
.collect()
))
}
}
impl From<String> for Raw {
#[inline]
fn from(val: String) -> Raw {
let vec: Vec<u8> = val.into();
vec.into()
}
}
impl From<Vec<u8>> for Raw {
#[inline]
fn from(val: Vec<u8>) -> Raw {
Raw(Lines::One(Line::from(val)))
}
}
impl From<&'static str> for Raw {
fn from(val: &'static str) -> Raw {
Raw(Lines::One(Line::Static(val.as_bytes())))
}
}
impl From<&'static [u8]> for Raw {
fn from(val: &'static [u8]) -> Raw {
Raw(Lines::One(Line::Static(val)))
}
}
impl From<MemSlice> for Raw {
#[inline]
fn from(val: MemSlice) -> Raw {
Raw(Lines::One(Line::Shared(val)))
}
}
impl From<Vec<u8>> for Line {
#[inline]
fn from(val: Vec<u8>) -> Line {
Line::Owned(val)
}
}
impl From<MemSlice> for Line {
#[inline]
fn from(val: MemSlice) -> Line {
Line::Shared(val)
}
}
impl AsRef<[u8]> for Line {
fn as_ref(&self) -> &[u8] {
match *self {
Line::Static(ref s) => s,
Line::Owned(ref v) => v.as_ref(),
Line::Shared(ref m) => m.as_ref(),
}
}
}
pub fn parsed(val: MemSlice) -> Raw {
Raw(Lines::One(From::from(val)))
}
pub fn push(raw: &mut Raw, val: MemSlice) {
raw.push_line(Line::from(val));
}
impl fmt::Debug for Raw {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Lines::One(ref line) => fmt::Debug::fmt(&[line], f),
Lines::Many(ref lines) => fmt::Debug::fmt(lines, f)
}
}
}
impl ::std::ops::Index<usize> for Raw {
type Output = [u8];
fn index(&self, idx: usize) -> &[u8] {
match self.0 {
Lines::One(ref line) => if idx == 0 {
line.as_ref()
} else {
panic!("index out of bounds: {}", idx)
},
Lines::Many(ref lines) => lines[idx].as_ref()
}
}
}
macro_rules! literals {
($($len:expr => $($value:expr),+;)+) => (
fn maybe_literal<'a>(s: Cow<'a, [u8]>) -> Line {
match s.len() {
$($len => {
$(
if s.as_ref() == $value {
return Line::Static($value);
}
)+
})+
_ => ()
}
Line::from(s.into_owned())
}
#[test]
fn test_literal_lens() {
$(
$({
let s = $value;
assert!(s.len() == $len, "{:?} has len of {}, listed as {}", s, s.len(), $len);
})+
)+
}
);
}
literals! {
1 => b"*", b"0";
3 => b"*/*";
4 => b"gzip";
5 => b"close";
7 => b"chunked";
10 => b"keep-alive";
}
impl<'a> IntoIterator for &'a Raw {
type IntoIter = RawLines<'a>;
type Item = &'a [u8];
fn into_iter(self) -> RawLines<'a> {
self.iter()
}
}
#[derive(Debug)]
pub struct RawLines<'a> {
inner: &'a Lines,
pos: usize,
}
impl<'a> Iterator for RawLines<'a> {
type Item = &'a [u8];
#[inline]
fn next(&mut self) -> Option<&'a [u8]> {
let current_pos = self.pos;
self.pos += 1;
match *self.inner {
Lines::One(ref line) => {
if current_pos == 0 {
Some(line.as_ref())
} else {
None
}
}
Lines::Many(ref lines) => lines.get(current_pos).map(|l| l.as_ref()),
}
}
}
| {
RawLines {
inner: &self.0,
pos: 0,
}
} | identifier_body |
media-change.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license | export type MediaQuerySubscriber = (changes: MediaChange) => void;
/**
* Class instances emitted [to observers] for each mql notification
*/
export class MediaChange {
property: string;
value: any;
constructor(public matches = false, // Is the mq currently activated
public mediaQuery = 'all', // e.g. (min-width: 600px) and (max-width: 959px)
public mqAlias = '', // e.g. gt-sm, md, gt-lg
public suffix = '' // e.g. GtSM, Md, GtLg
) { }
clone() {
return new MediaChange(this.matches, this.mediaQuery, this.mqAlias, this.suffix);
}
} | */ | random_line_split |
media-change.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export type MediaQuerySubscriber = (changes: MediaChange) => void;
/**
* Class instances emitted [to observers] for each mql notification
*/
export class MediaChange {
property: string;
value: any;
constructor(public matches = false, // Is the mq currently activated
public mediaQuery = 'all', // e.g. (min-width: 600px) and (max-width: 959px)
public mqAlias = '', // e.g. gt-sm, md, gt-lg
public suffix = '' // e.g. GtSM, Md, GtLg
) |
clone() {
return new MediaChange(this.matches, this.mediaQuery, this.mqAlias, this.suffix);
}
}
| { } | identifier_body |
media-change.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export type MediaQuerySubscriber = (changes: MediaChange) => void;
/**
* Class instances emitted [to observers] for each mql notification
*/
export class MediaChange {
property: string;
value: any;
| (public matches = false, // Is the mq currently activated
public mediaQuery = 'all', // e.g. (min-width: 600px) and (max-width: 959px)
public mqAlias = '', // e.g. gt-sm, md, gt-lg
public suffix = '' // e.g. GtSM, Md, GtLg
) { }
clone() {
return new MediaChange(this.matches, this.mediaQuery, this.mqAlias, this.suffix);
}
}
| constructor | identifier_name |
types.ts | import type { CartActionError } from './errors';
import type { Dispatch } from 'react';
export type ShoppingCartReducerDispatch = ( action: ShoppingCartAction ) => void;
export type ShoppingCartReducer = (
state: ShoppingCartState,
action: ShoppingCartAction
) => ShoppingCartState;
export type CartKey = number | 'no-user' | 'no-site';
export type GetCart = ( cartKey: CartKey ) => Promise< ResponseCart >;
export type SetCart = ( cartKey: CartKey, requestCart: RequestCart ) => Promise< ResponseCart >;
export interface ShoppingCartManagerOptions {
refetchOnWindowFocus?: boolean;
defaultCartKey?: CartKey;
}
export type GetManagerForKey = ( cartKey: CartKey | undefined ) => ShoppingCartManager;
export type GetCartKeyForSiteSlug = ( siteSlug: string ) => Promise< CartKey >;
export interface ShoppingCartManagerClient {
forCartKey: GetManagerForKey;
getCartKeyForSiteSlug: GetCartKeyForSiteSlug;
}
export type UnsubscribeFunction = () => void;
export type SubscribeCallback = () => void;
export type ShoppingCartManagerSubscribe = ( callback: SubscribeCallback ) => UnsubscribeFunction;
export interface SubscriptionManager {
subscribe: ShoppingCartManagerSubscribe;
notifySubscribers: () => void;
}
export interface ShoppingCartManagerState {
isLoading: boolean;
loadingError: string | null | undefined;
loadingErrorType: ShoppingCartError | undefined;
isPendingUpdate: boolean;
responseCart: ResponseCart;
couponStatus: CouponStatus;
}
type WaitForReady = () => Promise< ResponseCart >;
export type ShoppingCartManagerGetState = () => ShoppingCartManagerState;
export interface ShoppingCartManager {
getState: ShoppingCartManagerGetState;
subscribe: ShoppingCartManagerSubscribe;
actions: ShoppingCartManagerActions;
fetchInitialCart: WaitForReady;
}
export type UseShoppingCart = ShoppingCartManagerActions & ShoppingCartManagerState;
export type ReplaceProductInCart = (
uuidToReplace: string,
productPropertiesToChange: Partial< RequestCartProduct >
) => Promise< ResponseCart >;
export type ReloadCartFromServer = () => Promise< ResponseCart >;
export type ClearCartMessages = () => Promise< ResponseCart >;
export type ReplaceProductsInCart = (
products: MinimalRequestCartProduct[]
) => Promise< ResponseCart >;
export type AddProductsToCart = (
products: MinimalRequestCartProduct[]
) => Promise< ResponseCart >;
export type RemoveCouponFromCart = () => Promise< ResponseCart >;
export type ApplyCouponToCart = ( couponId: string ) => Promise< ResponseCart >;
export type RemoveProductFromCart = ( uuidToRemove: string ) => Promise< ResponseCart >;
export type UpdateTaxLocationInCart = ( location: CartLocation ) => Promise< ResponseCart >;
/**
* The custom hook keeps a cached version of the server cart, as well as a
* cache status.
*
* - 'fresh': Page has loaded and no requests have been sent.
* - 'fresh-pending': Page has loaded and we are waiting for the initial request.
* - 'invalid': Local cart data has been edited.
* - 'valid': Local cart has been reloaded from the server.
* - 'pending': Request has been sent, awaiting response.
* - 'error': Something went wrong.
*/
export type CacheStatus = 'fresh' | 'fresh-pending' | 'valid' | 'invalid' | 'pending' | 'error';
/**
* Possible states re. coupon submission.
*
* - 'fresh': User has not (yet) attempted to apply a coupon.
* - 'pending': Coupon request has been sent, awaiting response.
* - 'applied': Coupon has been applied to the cart.
* - 'rejected': Coupon code did not apply. The reason should be in the cart errors.
*/
export type CouponStatus = 'fresh' | 'pending' | 'applied' | 'rejected';
export type ShoppingCartAction =
| { type: 'CLEAR_QUEUED_ACTIONS' }
| { type: 'CLEAR_MESSAGES' }
| { type: 'UPDATE_LAST_VALID_CART' }
| { type: 'REMOVE_CART_ITEM'; uuidToRemove: string }
| { type: 'CART_PRODUCTS_ADD'; products: RequestCartProduct[] }
| { type: 'CART_PRODUCTS_REPLACE_ALL'; products: RequestCartProduct[] }
| { type: 'SET_LOCATION'; location: CartLocation }
| {
type: 'CART_PRODUCT_REPLACE';
uuidToReplace: string;
productPropertiesToChange: Partial< RequestCartProduct >;
}
| { type: 'ADD_COUPON'; couponToAdd: string }
| { type: 'REMOVE_COUPON' }
| { type: 'CART_RELOAD' }
| { type: 'RECEIVE_INITIAL_RESPONSE_CART'; initialResponseCart: ResponseCart }
| { type: 'FETCH_INITIAL_RESPONSE_CART' }
| { type: 'REQUEST_UPDATED_RESPONSE_CART' }
| { type: 'RECEIVE_UPDATED_RESPONSE_CART'; updatedResponseCart: ResponseCart }
| { type: 'RAISE_ERROR'; error: ShoppingCartError; message: string };
export interface ShoppingCartManagerActions {
addProductsToCart: AddProductsToCart;
removeProductFromCart: RemoveProductFromCart;
applyCoupon: ApplyCouponToCart;
removeCoupon: RemoveCouponFromCart;
updateLocation: UpdateTaxLocationInCart;
replaceProductInCart: ReplaceProductInCart;
replaceProductsInCart: ReplaceProductsInCart;
reloadFromServer: ReloadCartFromServer;
clearMessages: ClearCartMessages;
}
export type ShoppingCartError = 'GET_SERVER_CART_ERROR' | 'SET_SERVER_CART_ERROR';
export type ShoppingCartState = {
responseCart: TempResponseCart;
lastValidResponseCart: ResponseCart;
couponStatus: CouponStatus;
queuedActions: ShoppingCartAction[];
} & (
| {
cacheStatus: Exclude< CacheStatus, 'error' >;
loadingError?: undefined;
loadingErrorType?: undefined;
}
| {
cacheStatus: 'error';
loadingError: string;
loadingErrorType: ShoppingCartError;
}
);
export interface WithShoppingCartProps {
shoppingCartManager: UseShoppingCart;
cart: ResponseCart;
}
export type CartValidCallback = ( cart: ResponseCart ) => void;
export type DispatchAndWaitForValid = ( action: ShoppingCartAction ) => Promise< ResponseCart >;
export type SavedActionPromise = {
resolve: ( responseCart: ResponseCart ) => void;
reject: ( error: CartActionError ) => void;
};
export interface ActionPromises {
resolve: ( tempResponseCart: TempResponseCart ) => void;
reject: ( error: CartActionError ) => void;
add: ( actionPromise: SavedActionPromise ) => void;
}
export interface CartSyncManager {
syncPendingCartToServer: (
state: ShoppingCartState,
dispatch: Dispatch< ShoppingCartAction >
) => void;
fetchInitialCartFromServer: ( dispatch: Dispatch< ShoppingCartAction > ) => void;
}
export interface RequestCart {
products: RequestCartProduct[];
tax: RequestCartTaxData;
coupon: string;
temporary: false;
}
export type RequestCartTaxData = null | {
location: {
country_code: string | undefined;
postal_code: string | undefined;
subdivision_code: string | undefined;
};
};
export interface RequestCartProduct {
product_slug: string;
product_id?: number;
meta: string;
volume: number;
quantity: number | null;
extra: RequestCartProductExtra;
}
export type MinimalRequestCartProduct = Partial< RequestCartProduct > &
Pick< RequestCartProduct, 'product_slug' >;
export interface ResponseCart< P = ResponseCartProduct > {
blog_id: number | string;
create_new_blog: boolean;
cart_key: CartKey;
products: P[];
total_tax: string; // Please try not to use this
total_tax_integer: number;
total_tax_display: string;
total_tax_breakdown: TaxBreakdownItem[];
total_cost: number; // Please try not to use this
total_cost_integer: number;
total_cost_display: string;
coupon_savings_total_integer: number;
coupon_savings_total_display: string;
sub_total_with_taxes_integer: number;
sub_total_with_taxes_display: string;
sub_total_integer: number;
sub_total_display: string;
currency: string;
credits_integer: number;
credits_display: string;
allowed_payment_methods: string[];
coupon: string;
is_coupon_applied: boolean;
coupon_discounts_integer: number[];
locale: string;
is_signup: boolean;
messages?: ResponseCartMessages;
cart_generated_at_timestamp: number;
tax: ResponseCartTaxData;
next_domain_is_free: boolean;
next_domain_condition: '' | 'blog';
bundled_domain?: string;
has_bundle_credit?: boolean;
terms_of_service?: TermsOfServiceRecord[];
has_pending_payment?: boolean;
}
export interface ResponseCartTaxData {
location: {
country_code?: string;
postal_code?: string;
subdivision_code?: string;
};
display_taxes: boolean;
}
export interface TaxBreakdownItem {
tax_collected: number; | tax_collected_integer: number;
tax_collected_display: string;
label?: string;
rate: number;
rate_display: string;
}
/**
* Local schema for response cart that can contain incomplete products. This
* schema is only used inside the reducer and will only differ from a
* ResponseCart if the cacheStatus is invalid.
*/
export type TempResponseCart = ResponseCart< RequestCartProduct >;
export interface ResponseCartMessages {
errors?: ResponseCartMessage[];
success?: ResponseCartMessage[];
}
export interface ResponseCartMessage {
code: string;
message: string;
}
export interface ResponseCartProduct {
product_name: string;
product_slug: string;
product_id: number;
currency: string;
product_cost_integer: number;
product_cost_display: string;
item_original_cost_integer: number; // without discounts or volume, with quantity
item_original_cost_display: string; // without discounts or volume, with quantity
item_subtotal_monthly_cost_display: string;
item_subtotal_monthly_cost_integer: number;
item_original_subtotal_integer: number; // without discounts, with volume
item_original_subtotal_display: string; // without discounts, with volume
item_original_cost_for_quantity_one_integer: number; // without discounts or volume, and quantity 1
item_original_cost_for_quantity_one_display: string; // without discounts or volume, and quantity 1
item_subtotal_integer: number;
item_subtotal_display: string;
price_tier_minimum_units?: number | null;
price_tier_maximum_units?: number | null;
is_domain_registration: boolean;
is_bundled: boolean;
is_sale_coupon_applied: boolean;
meta: string;
time_added_to_cart: number;
bill_period: string;
months_per_bill_period: number | null;
volume: number;
quantity: number | null;
current_quantity: number | null;
extra: ResponseCartProductExtra;
uuid: string;
cost: number;
cost_before_coupon?: number;
coupon_savings?: number;
coupon_savings_display?: string;
coupon_savings_integer?: number;
price: number;
item_tax: number;
product_type: string;
included_domain_purchase_amount: number;
is_renewal?: boolean;
subscription_id?: string;
introductory_offer_terms?: IntroductoryOfferTerms;
// Temporary optional properties for the monthly pricing test
related_monthly_plan_cost_display?: string;
related_monthly_plan_cost_integer?: number;
}
export interface IntroductoryOfferTerms {
enabled: boolean;
interval_unit: string;
interval_count: number;
reason?: string;
transition_after_renewal_count: number;
should_prorate_when_offer_ends: boolean;
}
export interface CartLocation {
countryCode?: string;
postalCode?: string;
subdivisionCode?: string;
}
export interface ResponseCartProductExtra {
context?: string;
source?: string;
premium?: boolean;
new_quantity?: number;
domain_to_bundle?: string;
email_users?: TitanProductUser[];
google_apps_users?: GSuiteProductUser[];
google_apps_registration_data?: DomainContactDetails;
purchaseType?: string;
privacy?: boolean;
afterPurchaseUrl?: string;
isJetpackCheckout?: boolean;
is_marketplace_product?: boolean;
}
export interface RequestCartProductExtra extends ResponseCartProductExtra {
purchaseId?: string;
isJetpackCheckout?: boolean;
jetpackSiteSlug?: string;
jetpackPurchaseToken?: string;
auth_code?: string;
privacy_available?: boolean;
}
export interface GSuiteProductUser {
firstname: string;
lastname: string;
email: string;
password: string;
}
export interface TitanProductUser {
alternative_email?: string;
email: string;
encrypted_password?: string;
is_admin?: boolean;
name?: string;
password?: string;
}
export type DomainContactDetails = {
firstName?: string;
lastName?: string;
organization?: string;
email?: string;
alternateEmail?: string;
phone?: string;
address1?: string;
address2?: string;
city?: string;
state?: string;
postalCode?: string;
countryCode?: string;
fax?: string;
vatId?: string;
extra?: DomainContactDetailsExtra;
};
export type DomainContactDetailsExtra = {
ca?: CaDomainContactExtraDetails | null;
uk?: UkDomainContactExtraDetails | null;
fr?: FrDomainContactExtraDetails | null;
};
export type CaDomainContactExtraDetails = {
lang?: string;
legalType?: string;
ciraAgreementAccepted?: boolean;
};
export type UkDomainContactExtraDetails = {
registrantType?: string;
registrationNumber?: string;
tradingName?: string;
};
export type FrDomainContactExtraDetails = {
registrantType?: string;
registrantVatId?: string;
trademarkNumber?: string;
sirenSiret?: string;
};
export interface TermsOfServiceRecord {
key: string;
code: string;
args?: Record< string, string >;
} | random_line_split | |
editable_table_row.js | Spree.Views.Tables.EditableTableRow = Backbone.View.extend({
events: {
"select2-open": "onEdit",
"focus input": "onEdit",
"click [data-action=save]": "onSave",
"click [data-action=cancel]": "onCancel",
'keyup input': 'onKeypress'
},
onEdit: function(e) {
if (this.$el.hasClass('editing')) {
return;
}
this.$el.addClass('editing');
this.$el.find('input, select').each(function() {
var $input = $(this);
$input.data('original-value', $input.val());
});
},
onCancel: function(e) {
e.preventDefault();
this.$el.removeClass("editing");
this.$el.find('input, select').each(function() {
var $input = $(this);
var originalValue = $input.data('original-value');
$input.val(originalValue).change();
});
},
onSave: function(e) {
e.preventDefault();
var view = this;
Spree.ajax(this.$el.find('.actions [data-action=save]').attr('href'), {
data: this.$el.find('select, input').serialize(),
dataType: 'json',
method: 'put',
success: function(response) {
view.$el.removeClass("editing");
},
error: function(response) {
show_flash('error', response.responseJSON.error);
}
});
},
ENTER_KEY: 13,
ESC_KEY: 27,
onKeypress: function(e) {
var key = e.keyCode || e.which;
switch (key) {
case this.ENTER_KEY:
this.onSave(e); | }
}
}); | break;
case this.ESC_KEY:
this.onCancel(e);
break; | random_line_split |
test_power.py | from __future__ import division
import numpy as np
from numpy.testing import assert_almost_equal
import pytest
from acoustics.power import lw_iso3746
@pytest.mark.parametrize("background_noise, expected", [
(79, 91.153934187),
(83, 90.187405234),
(88, 88.153934187),
])
def test_lw_iso3746(background_noise, expected):
| LpAi = np.array([90, 90, 90, 90])
LpAiB = background_noise * np.ones(4)
S = 10
alpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
surfaces = np.array([10, 10, 10, 10, 10, 10])
calculated = lw_iso3746(LpAi, LpAiB, S, alpha, surfaces)
assert_almost_equal(calculated, expected) | identifier_body | |
test_power.py | from __future__ import division
import numpy as np
from numpy.testing import assert_almost_equal
import pytest
from acoustics.power import lw_iso3746
@pytest.mark.parametrize("background_noise, expected", [
(79, 91.153934187),
(83, 90.187405234),
(88, 88.153934187),
])
def | (background_noise, expected):
LpAi = np.array([90, 90, 90, 90])
LpAiB = background_noise * np.ones(4)
S = 10
alpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
surfaces = np.array([10, 10, 10, 10, 10, 10])
calculated = lw_iso3746(LpAi, LpAiB, S, alpha, surfaces)
assert_almost_equal(calculated, expected)
| test_lw_iso3746 | identifier_name |
test_power.py | from __future__ import division
import numpy as np |
import pytest
from acoustics.power import lw_iso3746
@pytest.mark.parametrize("background_noise, expected", [
(79, 91.153934187),
(83, 90.187405234),
(88, 88.153934187),
])
def test_lw_iso3746(background_noise, expected):
LpAi = np.array([90, 90, 90, 90])
LpAiB = background_noise * np.ones(4)
S = 10
alpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
surfaces = np.array([10, 10, 10, 10, 10, 10])
calculated = lw_iso3746(LpAi, LpAiB, S, alpha, surfaces)
assert_almost_equal(calculated, expected) | from numpy.testing import assert_almost_equal | random_line_split |
efs.py | from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
def efs_setup(template, ops, app_cfn_options, stack_name, stack_setup):
# Variable Declarations
vpc_id=ops.get('vpc_id')
efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name']
efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name']
# Create EFS FIleSystem
efs_fs=FileSystem(
title='{}{}'.format(ops.app_name, stack_name),
FileSystemTags=Tags(Name='{}-{}'.format(ops.app_name, stack_name))
)
template.add_resource(efs_fs)
export_ref(template, '{}{}{}'.format(ops.app_name,stack_name,"Endpoint"), value=Ref(efs_fs), desc="Endpoint for EFS FileSystem")
# EFS FS Security Groups
efs_security_group=SecurityGroup(
title=efs_sg,
GroupDescription='Allow Access',
VpcId=vpc_id,
Tags=Tags(Name=efs_sg)
)
template.add_resource(efs_security_group)
export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Group")
# Create Network ACL for EFS Stack
efs_nacl = AclFactory(
template,
name=efs_acl,
vpc_id=ops.vpc_id,
in_networks=[val for key, val in sorted(ops.app_networks.items())],
in_ports=stack_setup['ports'],
out_ports=ops.out_ports,
out_networks=[val for key, val in sorted(ops.app_networks.items())],
ssh_hosts=ops.get("deploy_hosts"),
)
export_ref(
template,
export_name=efs_acl,
value=Ref(efs_acl),
desc="{}{} stack".format("NetACL for", stack_name)
)
# Create Subnets for Mount Targets
for k, v in ops['tcpstacks']['EFS']['networks'].items():
| efs_subnet=Subnet(
title='{}{}{}{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]),
AvailabilityZone=k,
CidrBlock=v,
VpcId=vpc_id,
Tags=Tags(Name='{}-{}-{}-{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]))
)
template.add_resource(efs_subnet)
assoc_name = '{}{}{}'.format(stack_name,"AclAssoc",k.split("-")[-1])
assoc_nacl_subnet(template, assoc_name, Ref(efs_acl), Ref(efs_subnet))
efs_mount_target=MountTarget(
title='{}{}{}'.format(ops.app_name, "EFSMountTarget", k.split("-")[-1]),
FileSystemId=Ref(efs_fs),
SecurityGroups=[Ref(efs_security_group)],
SubnetId=Ref(efs_subnet)
)
template.add_resource(efs_mount_target) | conditional_block | |
efs.py | from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
def efs_setup(template, ops, app_cfn_options, stack_name, stack_setup):
# Variable Declarations
vpc_id=ops.get('vpc_id')
efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name']
efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name']
# Create EFS FIleSystem
efs_fs=FileSystem(
title='{}{}'.format(ops.app_name, stack_name),
FileSystemTags=Tags(Name='{}-{}'.format(ops.app_name, stack_name))
)
template.add_resource(efs_fs) | # EFS FS Security Groups
efs_security_group=SecurityGroup(
title=efs_sg,
GroupDescription='Allow Access',
VpcId=vpc_id,
Tags=Tags(Name=efs_sg)
)
template.add_resource(efs_security_group)
export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Group")
# Create Network ACL for EFS Stack
efs_nacl = AclFactory(
template,
name=efs_acl,
vpc_id=ops.vpc_id,
in_networks=[val for key, val in sorted(ops.app_networks.items())],
in_ports=stack_setup['ports'],
out_ports=ops.out_ports,
out_networks=[val for key, val in sorted(ops.app_networks.items())],
ssh_hosts=ops.get("deploy_hosts"),
)
export_ref(
template,
export_name=efs_acl,
value=Ref(efs_acl),
desc="{}{} stack".format("NetACL for", stack_name)
)
# Create Subnets for Mount Targets
for k, v in ops['tcpstacks']['EFS']['networks'].items():
efs_subnet=Subnet(
title='{}{}{}{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]),
AvailabilityZone=k,
CidrBlock=v,
VpcId=vpc_id,
Tags=Tags(Name='{}-{}-{}-{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]))
)
template.add_resource(efs_subnet)
assoc_name = '{}{}{}'.format(stack_name,"AclAssoc",k.split("-")[-1])
assoc_nacl_subnet(template, assoc_name, Ref(efs_acl), Ref(efs_subnet))
efs_mount_target=MountTarget(
title='{}{}{}'.format(ops.app_name, "EFSMountTarget", k.split("-")[-1]),
FileSystemId=Ref(efs_fs),
SecurityGroups=[Ref(efs_security_group)],
SubnetId=Ref(efs_subnet)
)
template.add_resource(efs_mount_target) |
export_ref(template, '{}{}{}'.format(ops.app_name,stack_name,"Endpoint"), value=Ref(efs_fs), desc="Endpoint for EFS FileSystem")
| random_line_split |
efs.py | from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
def | (template, ops, app_cfn_options, stack_name, stack_setup):
# Variable Declarations
vpc_id=ops.get('vpc_id')
efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name']
efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name']
# Create EFS FIleSystem
efs_fs=FileSystem(
title='{}{}'.format(ops.app_name, stack_name),
FileSystemTags=Tags(Name='{}-{}'.format(ops.app_name, stack_name))
)
template.add_resource(efs_fs)
export_ref(template, '{}{}{}'.format(ops.app_name,stack_name,"Endpoint"), value=Ref(efs_fs), desc="Endpoint for EFS FileSystem")
# EFS FS Security Groups
efs_security_group=SecurityGroup(
title=efs_sg,
GroupDescription='Allow Access',
VpcId=vpc_id,
Tags=Tags(Name=efs_sg)
)
template.add_resource(efs_security_group)
export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Group")
# Create Network ACL for EFS Stack
efs_nacl = AclFactory(
template,
name=efs_acl,
vpc_id=ops.vpc_id,
in_networks=[val for key, val in sorted(ops.app_networks.items())],
in_ports=stack_setup['ports'],
out_ports=ops.out_ports,
out_networks=[val for key, val in sorted(ops.app_networks.items())],
ssh_hosts=ops.get("deploy_hosts"),
)
export_ref(
template,
export_name=efs_acl,
value=Ref(efs_acl),
desc="{}{} stack".format("NetACL for", stack_name)
)
# Create Subnets for Mount Targets
for k, v in ops['tcpstacks']['EFS']['networks'].items():
efs_subnet=Subnet(
title='{}{}{}{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]),
AvailabilityZone=k,
CidrBlock=v,
VpcId=vpc_id,
Tags=Tags(Name='{}-{}-{}-{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]))
)
template.add_resource(efs_subnet)
assoc_name = '{}{}{}'.format(stack_name,"AclAssoc",k.split("-")[-1])
assoc_nacl_subnet(template, assoc_name, Ref(efs_acl), Ref(efs_subnet))
efs_mount_target=MountTarget(
title='{}{}{}'.format(ops.app_name, "EFSMountTarget", k.split("-")[-1]),
FileSystemId=Ref(efs_fs),
SecurityGroups=[Ref(efs_security_group)],
SubnetId=Ref(efs_subnet)
)
template.add_resource(efs_mount_target)
| efs_setup | identifier_name |
efs.py | from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
def efs_setup(template, ops, app_cfn_options, stack_name, stack_setup):
# Variable Declarations
| vpc_id=ops.get('vpc_id')
efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name']
efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name']
# Create EFS FIleSystem
efs_fs=FileSystem(
title='{}{}'.format(ops.app_name, stack_name),
FileSystemTags=Tags(Name='{}-{}'.format(ops.app_name, stack_name))
)
template.add_resource(efs_fs)
export_ref(template, '{}{}{}'.format(ops.app_name,stack_name,"Endpoint"), value=Ref(efs_fs), desc="Endpoint for EFS FileSystem")
# EFS FS Security Groups
efs_security_group=SecurityGroup(
title=efs_sg,
GroupDescription='Allow Access',
VpcId=vpc_id,
Tags=Tags(Name=efs_sg)
)
template.add_resource(efs_security_group)
export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Group")
# Create Network ACL for EFS Stack
efs_nacl = AclFactory(
template,
name=efs_acl,
vpc_id=ops.vpc_id,
in_networks=[val for key, val in sorted(ops.app_networks.items())],
in_ports=stack_setup['ports'],
out_ports=ops.out_ports,
out_networks=[val for key, val in sorted(ops.app_networks.items())],
ssh_hosts=ops.get("deploy_hosts"),
)
export_ref(
template,
export_name=efs_acl,
value=Ref(efs_acl),
desc="{}{} stack".format("NetACL for", stack_name)
)
# Create Subnets for Mount Targets
for k, v in ops['tcpstacks']['EFS']['networks'].items():
efs_subnet=Subnet(
title='{}{}{}{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]),
AvailabilityZone=k,
CidrBlock=v,
VpcId=vpc_id,
Tags=Tags(Name='{}-{}-{}-{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]))
)
template.add_resource(efs_subnet)
assoc_name = '{}{}{}'.format(stack_name,"AclAssoc",k.split("-")[-1])
assoc_nacl_subnet(template, assoc_name, Ref(efs_acl), Ref(efs_subnet))
efs_mount_target=MountTarget(
title='{}{}{}'.format(ops.app_name, "EFSMountTarget", k.split("-")[-1]),
FileSystemId=Ref(efs_fs),
SecurityGroups=[Ref(efs_security_group)],
SubnetId=Ref(efs_subnet)
)
template.add_resource(efs_mount_target) | identifier_body | |
event.py | """
sentry.models.event
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import warnings
from collections import OrderedDict
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.db.models import (
Model, NodeField, BoundedIntegerField, BoundedPositiveIntegerField,
BaseManager, FlexibleForeignKey, sane_repr
)
from sentry.interfaces.base import get_interface
from sentry.utils.cache import memoize
from sentry.utils.safe import safe_execute
from sentry.utils.strings import truncatechars, strip
class Event(Model):
"""
An individual event.
"""
__core__ = False
group = FlexibleForeignKey('sentry.Group', blank=True, null=True, related_name="event_set")
event_id = models.CharField(max_length=32, null=True, db_column="message_id")
project = FlexibleForeignKey('sentry.Project', null=True)
message = models.TextField()
num_comments = BoundedPositiveIntegerField(default=0, null=True)
platform = models.CharField(max_length=64, null=True)
datetime = models.DateTimeField(default=timezone.now, db_index=True)
time_spent = BoundedIntegerField(null=True)
data = NodeField(blank=True, null=True)
objects = BaseManager()
class Meta:
app_label = 'sentry'
db_table = 'sentry_message'
verbose_name = _('message')
verbose_name_plural = _('messages')
unique_together = (('project', 'event_id'),)
index_together = (('group', 'datetime'),)
__repr__ = sane_repr('project_id', 'group_id')
def error(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
error.short_description = _('error')
def has_two_part_message(self):
message = strip(self.message)
return '\n' in message or len(message) > 100
@property
def message_short(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
@property
def team(self):
return self.project.team
@property
def organization(self):
return self.project.organization
@property
def version(self):
return self.data.get('version', '5')
@memoize
def ip_address(self):
user_data = self.data.get('sentry.interfaces.User')
if user_data:
value = user_data.get('ip_address')
if value:
return value
http_data = self.data.get('sentry.interfaces.Http')
if http_data and 'env' in http_data:
value = http_data['env'].get('REMOTE_ADDR')
if value:
return value
return None
@memoize
def user_ident(self):
"""
The identifier from a user is considered from several interfaces.
In order:
- User.id
- User.email
- User.username
- Http.env.REMOTE_ADDR
"""
user_data = self.data.get('sentry.interfaces.User', self.data.get('user'))
if user_data:
|
ident = self.ip_address
if ident:
return 'ip:%s' % (ident,)
return None
def get_interfaces(self):
result = []
for key, data in self.data.iteritems():
try:
cls = get_interface(key)
except ValueError:
continue
value = safe_execute(cls.to_python, data)
if not value:
continue
result.append((key, value))
return OrderedDict((k, v) for k, v in sorted(result, key=lambda x: x[1].get_score(), reverse=True))
@memoize
def interfaces(self):
return self.get_interfaces()
def get_tags(self, with_internal=True):
try:
return sorted(
(t, v) for t, v in self.data.get('tags') or ()
if with_internal or not t.startswith('sentry:')
)
except ValueError:
# at one point Sentry allowed invalid tag sets such as (foo, bar)
# vs ((tag, foo), (tag, bar))
return []
tags = property(get_tags)
def get_tag(self, key):
for t, v in (self.data.get('tags') or ()):
if t == key:
return v
return None
def as_dict(self):
# We use a OrderedDict to keep elements ordered for a potential JSON serializer
data = OrderedDict()
data['id'] = self.event_id
data['project'] = self.project_id
data['release'] = self.get_tag('sentry:release')
data['platform'] = self.platform
data['culprit'] = self.group.culprit
data['message'] = self.message
data['datetime'] = self.datetime
data['time_spent'] = self.time_spent
data['tags'] = self.get_tags()
for k, v in sorted(self.data.iteritems()):
data[k] = v
return data
@property
def size(self):
data_len = len(self.message)
for value in self.data.itervalues():
data_len += len(repr(value))
return data_len
# XXX(dcramer): compatibility with plugins
def get_level_display(self):
warnings.warn('Event.get_level_display is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.get_level_display()
@property
def level(self):
warnings.warn('Event.level is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.level
@property
def logger(self):
warnings.warn('Event.logger is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('logger')
@property
def site(self):
warnings.warn('Event.site is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('site')
@property
def server_name(self):
warnings.warn('Event.server_name is deprecated. Use Event.tags instead.')
return self.get_tag('server_name')
@property
def culprit(self):
warnings.warn('Event.culprit is deprecated. Use Group.culprit instead.')
return self.group.culprit
@property
def checksum(self):
warnings.warn('Event.checksum is no longer used', DeprecationWarning)
return ''
| ident = user_data.get('id')
if ident:
return 'id:%s' % (ident,)
ident = user_data.get('email')
if ident:
return 'email:%s' % (ident,)
ident = user_data.get('username')
if ident:
return 'username:%s' % (ident,) | conditional_block |
event.py | """
sentry.models.event
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import warnings
from collections import OrderedDict
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.db.models import (
Model, NodeField, BoundedIntegerField, BoundedPositiveIntegerField,
BaseManager, FlexibleForeignKey, sane_repr
)
from sentry.interfaces.base import get_interface
from sentry.utils.cache import memoize
from sentry.utils.safe import safe_execute
from sentry.utils.strings import truncatechars, strip
class Event(Model):
"""
An individual event.
"""
__core__ = False
group = FlexibleForeignKey('sentry.Group', blank=True, null=True, related_name="event_set")
event_id = models.CharField(max_length=32, null=True, db_column="message_id")
project = FlexibleForeignKey('sentry.Project', null=True)
message = models.TextField()
num_comments = BoundedPositiveIntegerField(default=0, null=True)
platform = models.CharField(max_length=64, null=True)
datetime = models.DateTimeField(default=timezone.now, db_index=True)
time_spent = BoundedIntegerField(null=True)
data = NodeField(blank=True, null=True)
objects = BaseManager()
class Meta:
app_label = 'sentry'
db_table = 'sentry_message'
verbose_name = _('message')
verbose_name_plural = _('messages')
unique_together = (('project', 'event_id'),)
index_together = (('group', 'datetime'),)
__repr__ = sane_repr('project_id', 'group_id')
def error(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
error.short_description = _('error')
def has_two_part_message(self):
message = strip(self.message)
return '\n' in message or len(message) > 100
@property
def message_short(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
@property
def team(self):
return self.project.team
@property
def organization(self):
return self.project.organization
@property
def version(self): | @memoize
def ip_address(self):
user_data = self.data.get('sentry.interfaces.User')
if user_data:
value = user_data.get('ip_address')
if value:
return value
http_data = self.data.get('sentry.interfaces.Http')
if http_data and 'env' in http_data:
value = http_data['env'].get('REMOTE_ADDR')
if value:
return value
return None
@memoize
def user_ident(self):
"""
The identifier from a user is considered from several interfaces.
In order:
- User.id
- User.email
- User.username
- Http.env.REMOTE_ADDR
"""
user_data = self.data.get('sentry.interfaces.User', self.data.get('user'))
if user_data:
ident = user_data.get('id')
if ident:
return 'id:%s' % (ident,)
ident = user_data.get('email')
if ident:
return 'email:%s' % (ident,)
ident = user_data.get('username')
if ident:
return 'username:%s' % (ident,)
ident = self.ip_address
if ident:
return 'ip:%s' % (ident,)
return None
def get_interfaces(self):
result = []
for key, data in self.data.iteritems():
try:
cls = get_interface(key)
except ValueError:
continue
value = safe_execute(cls.to_python, data)
if not value:
continue
result.append((key, value))
return OrderedDict((k, v) for k, v in sorted(result, key=lambda x: x[1].get_score(), reverse=True))
@memoize
def interfaces(self):
return self.get_interfaces()
def get_tags(self, with_internal=True):
try:
return sorted(
(t, v) for t, v in self.data.get('tags') or ()
if with_internal or not t.startswith('sentry:')
)
except ValueError:
# at one point Sentry allowed invalid tag sets such as (foo, bar)
# vs ((tag, foo), (tag, bar))
return []
tags = property(get_tags)
def get_tag(self, key):
for t, v in (self.data.get('tags') or ()):
if t == key:
return v
return None
def as_dict(self):
# We use a OrderedDict to keep elements ordered for a potential JSON serializer
data = OrderedDict()
data['id'] = self.event_id
data['project'] = self.project_id
data['release'] = self.get_tag('sentry:release')
data['platform'] = self.platform
data['culprit'] = self.group.culprit
data['message'] = self.message
data['datetime'] = self.datetime
data['time_spent'] = self.time_spent
data['tags'] = self.get_tags()
for k, v in sorted(self.data.iteritems()):
data[k] = v
return data
@property
def size(self):
data_len = len(self.message)
for value in self.data.itervalues():
data_len += len(repr(value))
return data_len
# XXX(dcramer): compatibility with plugins
def get_level_display(self):
warnings.warn('Event.get_level_display is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.get_level_display()
@property
def level(self):
warnings.warn('Event.level is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.level
@property
def logger(self):
warnings.warn('Event.logger is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('logger')
@property
def site(self):
warnings.warn('Event.site is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('site')
@property
def server_name(self):
warnings.warn('Event.server_name is deprecated. Use Event.tags instead.')
return self.get_tag('server_name')
@property
def culprit(self):
warnings.warn('Event.culprit is deprecated. Use Group.culprit instead.')
return self.group.culprit
@property
def checksum(self):
warnings.warn('Event.checksum is no longer used', DeprecationWarning)
return '' | return self.data.get('version', '5')
| random_line_split |
event.py | """
sentry.models.event
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import warnings
from collections import OrderedDict
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.db.models import (
Model, NodeField, BoundedIntegerField, BoundedPositiveIntegerField,
BaseManager, FlexibleForeignKey, sane_repr
)
from sentry.interfaces.base import get_interface
from sentry.utils.cache import memoize
from sentry.utils.safe import safe_execute
from sentry.utils.strings import truncatechars, strip
class Event(Model):
"""
An individual event.
"""
__core__ = False
group = FlexibleForeignKey('sentry.Group', blank=True, null=True, related_name="event_set")
event_id = models.CharField(max_length=32, null=True, db_column="message_id")
project = FlexibleForeignKey('sentry.Project', null=True)
message = models.TextField()
num_comments = BoundedPositiveIntegerField(default=0, null=True)
platform = models.CharField(max_length=64, null=True)
datetime = models.DateTimeField(default=timezone.now, db_index=True)
time_spent = BoundedIntegerField(null=True)
data = NodeField(blank=True, null=True)
objects = BaseManager()
class Meta:
app_label = 'sentry'
db_table = 'sentry_message'
verbose_name = _('message')
verbose_name_plural = _('messages')
unique_together = (('project', 'event_id'),)
index_together = (('group', 'datetime'),)
__repr__ = sane_repr('project_id', 'group_id')
def error(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
error.short_description = _('error')
def has_two_part_message(self):
message = strip(self.message)
return '\n' in message or len(message) > 100
@property
def message_short(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
@property
def team(self):
return self.project.team
@property
def organization(self):
return self.project.organization
@property
def version(self):
return self.data.get('version', '5')
@memoize
def ip_address(self):
user_data = self.data.get('sentry.interfaces.User')
if user_data:
value = user_data.get('ip_address')
if value:
return value
http_data = self.data.get('sentry.interfaces.Http')
if http_data and 'env' in http_data:
value = http_data['env'].get('REMOTE_ADDR')
if value:
return value
return None
@memoize
def user_ident(self):
"""
The identifier from a user is considered from several interfaces.
In order:
- User.id
- User.email
- User.username
- Http.env.REMOTE_ADDR
"""
user_data = self.data.get('sentry.interfaces.User', self.data.get('user'))
if user_data:
ident = user_data.get('id')
if ident:
return 'id:%s' % (ident,)
ident = user_data.get('email')
if ident:
return 'email:%s' % (ident,)
ident = user_data.get('username')
if ident:
return 'username:%s' % (ident,)
ident = self.ip_address
if ident:
return 'ip:%s' % (ident,)
return None
def get_interfaces(self):
result = []
for key, data in self.data.iteritems():
try:
cls = get_interface(key)
except ValueError:
continue
value = safe_execute(cls.to_python, data)
if not value:
continue
result.append((key, value))
return OrderedDict((k, v) for k, v in sorted(result, key=lambda x: x[1].get_score(), reverse=True))
@memoize
def interfaces(self):
return self.get_interfaces()
def get_tags(self, with_internal=True):
try:
return sorted(
(t, v) for t, v in self.data.get('tags') or ()
if with_internal or not t.startswith('sentry:')
)
except ValueError:
# at one point Sentry allowed invalid tag sets such as (foo, bar)
# vs ((tag, foo), (tag, bar))
return []
tags = property(get_tags)
def get_tag(self, key):
for t, v in (self.data.get('tags') or ()):
if t == key:
return v
return None
def as_dict(self):
# We use a OrderedDict to keep elements ordered for a potential JSON serializer
data = OrderedDict()
data['id'] = self.event_id
data['project'] = self.project_id
data['release'] = self.get_tag('sentry:release')
data['platform'] = self.platform
data['culprit'] = self.group.culprit
data['message'] = self.message
data['datetime'] = self.datetime
data['time_spent'] = self.time_spent
data['tags'] = self.get_tags()
for k, v in sorted(self.data.iteritems()):
data[k] = v
return data
@property
def size(self):
data_len = len(self.message)
for value in self.data.itervalues():
data_len += len(repr(value))
return data_len
# XXX(dcramer): compatibility with plugins
def get_level_display(self):
warnings.warn('Event.get_level_display is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.get_level_display()
@property
def level(self):
warnings.warn('Event.level is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.level
@property
def logger(self):
warnings.warn('Event.logger is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('logger')
@property
def site(self):
warnings.warn('Event.site is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('site')
@property
def server_name(self):
warnings.warn('Event.server_name is deprecated. Use Event.tags instead.')
return self.get_tag('server_name')
@property
def culprit(self):
warnings.warn('Event.culprit is deprecated. Use Group.culprit instead.')
return self.group.culprit
@property
def | (self):
warnings.warn('Event.checksum is no longer used', DeprecationWarning)
return ''
| checksum | identifier_name |
event.py | """
sentry.models.event
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import warnings
from collections import OrderedDict
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.db.models import (
Model, NodeField, BoundedIntegerField, BoundedPositiveIntegerField,
BaseManager, FlexibleForeignKey, sane_repr
)
from sentry.interfaces.base import get_interface
from sentry.utils.cache import memoize
from sentry.utils.safe import safe_execute
from sentry.utils.strings import truncatechars, strip
class Event(Model):
| """
An individual event.
"""
__core__ = False
group = FlexibleForeignKey('sentry.Group', blank=True, null=True, related_name="event_set")
event_id = models.CharField(max_length=32, null=True, db_column="message_id")
project = FlexibleForeignKey('sentry.Project', null=True)
message = models.TextField()
num_comments = BoundedPositiveIntegerField(default=0, null=True)
platform = models.CharField(max_length=64, null=True)
datetime = models.DateTimeField(default=timezone.now, db_index=True)
time_spent = BoundedIntegerField(null=True)
data = NodeField(blank=True, null=True)
objects = BaseManager()
class Meta:
app_label = 'sentry'
db_table = 'sentry_message'
verbose_name = _('message')
verbose_name_plural = _('messages')
unique_together = (('project', 'event_id'),)
index_together = (('group', 'datetime'),)
__repr__ = sane_repr('project_id', 'group_id')
def error(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
error.short_description = _('error')
def has_two_part_message(self):
message = strip(self.message)
return '\n' in message or len(message) > 100
@property
def message_short(self):
message = strip(self.message)
if not message:
message = '<unlabeled message>'
else:
message = truncatechars(message.splitlines()[0], 100)
return message
@property
def team(self):
return self.project.team
@property
def organization(self):
return self.project.organization
@property
def version(self):
return self.data.get('version', '5')
@memoize
def ip_address(self):
user_data = self.data.get('sentry.interfaces.User')
if user_data:
value = user_data.get('ip_address')
if value:
return value
http_data = self.data.get('sentry.interfaces.Http')
if http_data and 'env' in http_data:
value = http_data['env'].get('REMOTE_ADDR')
if value:
return value
return None
@memoize
def user_ident(self):
"""
The identifier from a user is considered from several interfaces.
In order:
- User.id
- User.email
- User.username
- Http.env.REMOTE_ADDR
"""
user_data = self.data.get('sentry.interfaces.User', self.data.get('user'))
if user_data:
ident = user_data.get('id')
if ident:
return 'id:%s' % (ident,)
ident = user_data.get('email')
if ident:
return 'email:%s' % (ident,)
ident = user_data.get('username')
if ident:
return 'username:%s' % (ident,)
ident = self.ip_address
if ident:
return 'ip:%s' % (ident,)
return None
def get_interfaces(self):
result = []
for key, data in self.data.iteritems():
try:
cls = get_interface(key)
except ValueError:
continue
value = safe_execute(cls.to_python, data)
if not value:
continue
result.append((key, value))
return OrderedDict((k, v) for k, v in sorted(result, key=lambda x: x[1].get_score(), reverse=True))
@memoize
def interfaces(self):
return self.get_interfaces()
def get_tags(self, with_internal=True):
try:
return sorted(
(t, v) for t, v in self.data.get('tags') or ()
if with_internal or not t.startswith('sentry:')
)
except ValueError:
# at one point Sentry allowed invalid tag sets such as (foo, bar)
# vs ((tag, foo), (tag, bar))
return []
tags = property(get_tags)
def get_tag(self, key):
for t, v in (self.data.get('tags') or ()):
if t == key:
return v
return None
def as_dict(self):
# We use a OrderedDict to keep elements ordered for a potential JSON serializer
data = OrderedDict()
data['id'] = self.event_id
data['project'] = self.project_id
data['release'] = self.get_tag('sentry:release')
data['platform'] = self.platform
data['culprit'] = self.group.culprit
data['message'] = self.message
data['datetime'] = self.datetime
data['time_spent'] = self.time_spent
data['tags'] = self.get_tags()
for k, v in sorted(self.data.iteritems()):
data[k] = v
return data
@property
def size(self):
data_len = len(self.message)
for value in self.data.itervalues():
data_len += len(repr(value))
return data_len
# XXX(dcramer): compatibility with plugins
def get_level_display(self):
warnings.warn('Event.get_level_display is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.get_level_display()
@property
def level(self):
warnings.warn('Event.level is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.group.level
@property
def logger(self):
warnings.warn('Event.logger is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('logger')
@property
def site(self):
warnings.warn('Event.site is deprecated. Use Event.tags instead.',
DeprecationWarning)
return self.get_tag('site')
@property
def server_name(self):
warnings.warn('Event.server_name is deprecated. Use Event.tags instead.')
return self.get_tag('server_name')
@property
def culprit(self):
warnings.warn('Event.culprit is deprecated. Use Group.culprit instead.')
return self.group.culprit
@property
def checksum(self):
warnings.warn('Event.checksum is no longer used', DeprecationWarning)
return '' | identifier_body | |
diagnose.py | import re
import json
from subprocess import call, Popen, PIPE
def init_parser(parser):
parser.add_argument('name', type=str, help='Cluster name.')
parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.")
parser.add_argument('--hail-log', '-l', required=False, type=str, default='/home/hail/hail.log',
help="Path for hail.log file.")
parser.add_argument('--overwrite', required=False, action='store_true',
help="Delete dest directory before adding new files.")
parser.add_argument('--no-diagnose', required=False, action='store_true',
help="Do not run gcloud dataproc clusters diagnose.")
parser.add_argument('--compress', '-z', required=False, action='store_true', help="GZIP all files.")
parser.add_argument('--workers', required=False, nargs='*', help="Specific workers to get log files from.")
parser.add_argument('--take', required=False, type=int, default=None,
help="Only download logs from the first N workers.")
def main(args, pass_through_args): # pylint: disable=unused-argument
print("Diagnosing cluster '{}'...".format(args.name))
is_local = not args.dest.startswith("gs://")
if args.overwrite:
if is_local:
call('rm -r {dir}'.format(dir=args.dest), shell=True)
else:
call('gsutil -m rm -r {dir}'.format(dir=args.dest), shell=True)
master_dest = args.dest.rstrip('/') + "/master/"
worker_dest = args.dest.rstrip('/') + "/workers/"
if is_local:
call('mkdir -p {dir}'.format(dir=master_dest), shell=True)
call('mkdir -p {dir}'.format(dir=worker_dest), shell=True)
desc = json.loads(Popen('gcloud dataproc clusters describe {name} --format json'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate()[0].strip())
config = desc['config']
master = config['masterConfig']['instanceNames'][0]
try:
workers = config['workerConfig']['instanceNames'] + config['secondaryWorkerConfig']['instanceNames']
except KeyError:
workers = config['workerConfig']['instanceNames']
zone = re.search(r'zones/(?P<zone>\S+)$', config['gceClusterConfig']['zoneUri']).group('zone')
if args.workers:
invalid_workers = set(args.workers).difference(set(workers))
assert len(invalid_workers) == 0, "Non-existent workers specified: " + ", ".join(invalid_workers)
workers = args.workers
if args.take:
assert args.take > 0 and args.take <= len(
workers), "Number of workers to take must be in the range of [0, nWorkers]. Found " + args.take + "."
workers = workers[:args.take]
def gcloud_ssh(remote, command):
return 'gcloud compute ssh {remote} --zone {zone} --command "{command}"'.format(remote=remote, zone=zone,
command=command)
def gcloud_copy_files(remote, src, dest):
return 'gcloud compute copy-files {remote}:{src} {dest} --zone {zone}'.format(remote=remote, src=src, dest=dest,
zone=zone)
def gsutil_cp(src, dest):
return 'gsutil -m cp -r {src} {dest}'.format(src=src, dest=dest)
def copy_files_tmp(remote, files, dest, tmp):
|
if not args.no_diagnose:
diagnose_tar_path = re.search(r'Diagnostic results saved in: (?P<tarfile>gs://\S+diagnostic\.tar)',
str(Popen('gcloud dataproc clusters diagnose {name}'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate())).group('tarfile')
call(gsutil_cp(diagnose_tar_path, args.dest), shell=True)
master_log_files = ['/var/log/hive/hive-*',
'/var/log/google-dataproc-agent.0.log',
'/var/log/dataproc-initialization-script-0.log',
'/var/log/hadoop-mapreduce/mapred-mapred-historyserver*',
'/var/log/hadoop-hdfs/*-m.*',
'/var/log/hadoop-yarn/yarn-yarn-resourcemanager-*-m.*',
args.hail_log
]
copy_files_tmp(master, master_log_files, master_dest, '/tmp/' + master + '/')
worker_log_files = ['/var/log/hadoop-hdfs/hadoop-hdfs-datanode-*.*',
'/var/log/dataproc-startup-script.log',
'/var/log/hadoop-yarn/yarn-yarn-nodemanager-*.*']
for worker in workers:
copy_files_tmp(worker, worker_log_files, worker_dest, '/tmp/' + worker + '/')
copy_files_tmp(worker, ['/var/log/hadoop-yarn/userlogs/'], args.dest, '/tmp/hadoop-yarn/')
| init_cmd = ['mkdir -p {tmp}; rm -r {tmp}/*'.format(tmp=tmp)]
copy_tmp_cmds = ['sudo cp -r {file} {tmp}'.format(file=file, tmp=tmp) for file in files]
copy_tmp_cmds.append('sudo chmod -R 777 {tmp}'.format(tmp=tmp))
if args.compress:
copy_tmp_cmds.append('sudo find ' + tmp + ' -type f ! -name \'*.gz\' -exec gzip "{}" \\;')
call(gcloud_ssh(remote, '; '.join(init_cmd + copy_tmp_cmds)), shell=True)
if not is_local:
copy_dest_cmd = gcloud_ssh(remote, 'gsutil -m cp -r {tmp} {dest}'.format(tmp=tmp, dest=dest))
else:
copy_dest_cmd = gcloud_copy_files(remote, tmp, dest)
call(copy_dest_cmd, shell=True) | identifier_body |
diagnose.py | import re
import json |
def init_parser(parser):
parser.add_argument('name', type=str, help='Cluster name.')
parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.")
parser.add_argument('--hail-log', '-l', required=False, type=str, default='/home/hail/hail.log',
help="Path for hail.log file.")
parser.add_argument('--overwrite', required=False, action='store_true',
help="Delete dest directory before adding new files.")
parser.add_argument('--no-diagnose', required=False, action='store_true',
help="Do not run gcloud dataproc clusters diagnose.")
parser.add_argument('--compress', '-z', required=False, action='store_true', help="GZIP all files.")
parser.add_argument('--workers', required=False, nargs='*', help="Specific workers to get log files from.")
parser.add_argument('--take', required=False, type=int, default=None,
help="Only download logs from the first N workers.")
def main(args, pass_through_args): # pylint: disable=unused-argument
print("Diagnosing cluster '{}'...".format(args.name))
is_local = not args.dest.startswith("gs://")
if args.overwrite:
if is_local:
call('rm -r {dir}'.format(dir=args.dest), shell=True)
else:
call('gsutil -m rm -r {dir}'.format(dir=args.dest), shell=True)
master_dest = args.dest.rstrip('/') + "/master/"
worker_dest = args.dest.rstrip('/') + "/workers/"
if is_local:
call('mkdir -p {dir}'.format(dir=master_dest), shell=True)
call('mkdir -p {dir}'.format(dir=worker_dest), shell=True)
desc = json.loads(Popen('gcloud dataproc clusters describe {name} --format json'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate()[0].strip())
config = desc['config']
master = config['masterConfig']['instanceNames'][0]
try:
workers = config['workerConfig']['instanceNames'] + config['secondaryWorkerConfig']['instanceNames']
except KeyError:
workers = config['workerConfig']['instanceNames']
zone = re.search(r'zones/(?P<zone>\S+)$', config['gceClusterConfig']['zoneUri']).group('zone')
if args.workers:
invalid_workers = set(args.workers).difference(set(workers))
assert len(invalid_workers) == 0, "Non-existent workers specified: " + ", ".join(invalid_workers)
workers = args.workers
if args.take:
assert args.take > 0 and args.take <= len(
workers), "Number of workers to take must be in the range of [0, nWorkers]. Found " + args.take + "."
workers = workers[:args.take]
def gcloud_ssh(remote, command):
return 'gcloud compute ssh {remote} --zone {zone} --command "{command}"'.format(remote=remote, zone=zone,
command=command)
def gcloud_copy_files(remote, src, dest):
return 'gcloud compute copy-files {remote}:{src} {dest} --zone {zone}'.format(remote=remote, src=src, dest=dest,
zone=zone)
def gsutil_cp(src, dest):
return 'gsutil -m cp -r {src} {dest}'.format(src=src, dest=dest)
def copy_files_tmp(remote, files, dest, tmp):
init_cmd = ['mkdir -p {tmp}; rm -r {tmp}/*'.format(tmp=tmp)]
copy_tmp_cmds = ['sudo cp -r {file} {tmp}'.format(file=file, tmp=tmp) for file in files]
copy_tmp_cmds.append('sudo chmod -R 777 {tmp}'.format(tmp=tmp))
if args.compress:
copy_tmp_cmds.append('sudo find ' + tmp + ' -type f ! -name \'*.gz\' -exec gzip "{}" \\;')
call(gcloud_ssh(remote, '; '.join(init_cmd + copy_tmp_cmds)), shell=True)
if not is_local:
copy_dest_cmd = gcloud_ssh(remote, 'gsutil -m cp -r {tmp} {dest}'.format(tmp=tmp, dest=dest))
else:
copy_dest_cmd = gcloud_copy_files(remote, tmp, dest)
call(copy_dest_cmd, shell=True)
if not args.no_diagnose:
diagnose_tar_path = re.search(r'Diagnostic results saved in: (?P<tarfile>gs://\S+diagnostic\.tar)',
str(Popen('gcloud dataproc clusters diagnose {name}'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate())).group('tarfile')
call(gsutil_cp(diagnose_tar_path, args.dest), shell=True)
master_log_files = ['/var/log/hive/hive-*',
'/var/log/google-dataproc-agent.0.log',
'/var/log/dataproc-initialization-script-0.log',
'/var/log/hadoop-mapreduce/mapred-mapred-historyserver*',
'/var/log/hadoop-hdfs/*-m.*',
'/var/log/hadoop-yarn/yarn-yarn-resourcemanager-*-m.*',
args.hail_log
]
copy_files_tmp(master, master_log_files, master_dest, '/tmp/' + master + '/')
worker_log_files = ['/var/log/hadoop-hdfs/hadoop-hdfs-datanode-*.*',
'/var/log/dataproc-startup-script.log',
'/var/log/hadoop-yarn/yarn-yarn-nodemanager-*.*']
for worker in workers:
copy_files_tmp(worker, worker_log_files, worker_dest, '/tmp/' + worker + '/')
copy_files_tmp(worker, ['/var/log/hadoop-yarn/userlogs/'], args.dest, '/tmp/hadoop-yarn/') | from subprocess import call, Popen, PIPE
| random_line_split |
diagnose.py | import re
import json
from subprocess import call, Popen, PIPE
def init_parser(parser):
parser.add_argument('name', type=str, help='Cluster name.')
parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.")
parser.add_argument('--hail-log', '-l', required=False, type=str, default='/home/hail/hail.log',
help="Path for hail.log file.")
parser.add_argument('--overwrite', required=False, action='store_true',
help="Delete dest directory before adding new files.")
parser.add_argument('--no-diagnose', required=False, action='store_true',
help="Do not run gcloud dataproc clusters diagnose.")
parser.add_argument('--compress', '-z', required=False, action='store_true', help="GZIP all files.")
parser.add_argument('--workers', required=False, nargs='*', help="Specific workers to get log files from.")
parser.add_argument('--take', required=False, type=int, default=None,
help="Only download logs from the first N workers.")
def | (args, pass_through_args): # pylint: disable=unused-argument
print("Diagnosing cluster '{}'...".format(args.name))
is_local = not args.dest.startswith("gs://")
if args.overwrite:
if is_local:
call('rm -r {dir}'.format(dir=args.dest), shell=True)
else:
call('gsutil -m rm -r {dir}'.format(dir=args.dest), shell=True)
master_dest = args.dest.rstrip('/') + "/master/"
worker_dest = args.dest.rstrip('/') + "/workers/"
if is_local:
call('mkdir -p {dir}'.format(dir=master_dest), shell=True)
call('mkdir -p {dir}'.format(dir=worker_dest), shell=True)
desc = json.loads(Popen('gcloud dataproc clusters describe {name} --format json'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate()[0].strip())
config = desc['config']
master = config['masterConfig']['instanceNames'][0]
try:
workers = config['workerConfig']['instanceNames'] + config['secondaryWorkerConfig']['instanceNames']
except KeyError:
workers = config['workerConfig']['instanceNames']
zone = re.search(r'zones/(?P<zone>\S+)$', config['gceClusterConfig']['zoneUri']).group('zone')
if args.workers:
invalid_workers = set(args.workers).difference(set(workers))
assert len(invalid_workers) == 0, "Non-existent workers specified: " + ", ".join(invalid_workers)
workers = args.workers
if args.take:
assert args.take > 0 and args.take <= len(
workers), "Number of workers to take must be in the range of [0, nWorkers]. Found " + args.take + "."
workers = workers[:args.take]
def gcloud_ssh(remote, command):
return 'gcloud compute ssh {remote} --zone {zone} --command "{command}"'.format(remote=remote, zone=zone,
command=command)
def gcloud_copy_files(remote, src, dest):
return 'gcloud compute copy-files {remote}:{src} {dest} --zone {zone}'.format(remote=remote, src=src, dest=dest,
zone=zone)
def gsutil_cp(src, dest):
return 'gsutil -m cp -r {src} {dest}'.format(src=src, dest=dest)
def copy_files_tmp(remote, files, dest, tmp):
init_cmd = ['mkdir -p {tmp}; rm -r {tmp}/*'.format(tmp=tmp)]
copy_tmp_cmds = ['sudo cp -r {file} {tmp}'.format(file=file, tmp=tmp) for file in files]
copy_tmp_cmds.append('sudo chmod -R 777 {tmp}'.format(tmp=tmp))
if args.compress:
copy_tmp_cmds.append('sudo find ' + tmp + ' -type f ! -name \'*.gz\' -exec gzip "{}" \\;')
call(gcloud_ssh(remote, '; '.join(init_cmd + copy_tmp_cmds)), shell=True)
if not is_local:
copy_dest_cmd = gcloud_ssh(remote, 'gsutil -m cp -r {tmp} {dest}'.format(tmp=tmp, dest=dest))
else:
copy_dest_cmd = gcloud_copy_files(remote, tmp, dest)
call(copy_dest_cmd, shell=True)
if not args.no_diagnose:
diagnose_tar_path = re.search(r'Diagnostic results saved in: (?P<tarfile>gs://\S+diagnostic\.tar)',
str(Popen('gcloud dataproc clusters diagnose {name}'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate())).group('tarfile')
call(gsutil_cp(diagnose_tar_path, args.dest), shell=True)
master_log_files = ['/var/log/hive/hive-*',
'/var/log/google-dataproc-agent.0.log',
'/var/log/dataproc-initialization-script-0.log',
'/var/log/hadoop-mapreduce/mapred-mapred-historyserver*',
'/var/log/hadoop-hdfs/*-m.*',
'/var/log/hadoop-yarn/yarn-yarn-resourcemanager-*-m.*',
args.hail_log
]
copy_files_tmp(master, master_log_files, master_dest, '/tmp/' + master + '/')
worker_log_files = ['/var/log/hadoop-hdfs/hadoop-hdfs-datanode-*.*',
'/var/log/dataproc-startup-script.log',
'/var/log/hadoop-yarn/yarn-yarn-nodemanager-*.*']
for worker in workers:
copy_files_tmp(worker, worker_log_files, worker_dest, '/tmp/' + worker + '/')
copy_files_tmp(worker, ['/var/log/hadoop-yarn/userlogs/'], args.dest, '/tmp/hadoop-yarn/')
| main | identifier_name |
diagnose.py | import re
import json
from subprocess import call, Popen, PIPE
def init_parser(parser):
parser.add_argument('name', type=str, help='Cluster name.')
parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.")
parser.add_argument('--hail-log', '-l', required=False, type=str, default='/home/hail/hail.log',
help="Path for hail.log file.")
parser.add_argument('--overwrite', required=False, action='store_true',
help="Delete dest directory before adding new files.")
parser.add_argument('--no-diagnose', required=False, action='store_true',
help="Do not run gcloud dataproc clusters diagnose.")
parser.add_argument('--compress', '-z', required=False, action='store_true', help="GZIP all files.")
parser.add_argument('--workers', required=False, nargs='*', help="Specific workers to get log files from.")
parser.add_argument('--take', required=False, type=int, default=None,
help="Only download logs from the first N workers.")
def main(args, pass_through_args): # pylint: disable=unused-argument
print("Diagnosing cluster '{}'...".format(args.name))
is_local = not args.dest.startswith("gs://")
if args.overwrite:
if is_local:
call('rm -r {dir}'.format(dir=args.dest), shell=True)
else:
call('gsutil -m rm -r {dir}'.format(dir=args.dest), shell=True)
master_dest = args.dest.rstrip('/') + "/master/"
worker_dest = args.dest.rstrip('/') + "/workers/"
if is_local:
call('mkdir -p {dir}'.format(dir=master_dest), shell=True)
call('mkdir -p {dir}'.format(dir=worker_dest), shell=True)
desc = json.loads(Popen('gcloud dataproc clusters describe {name} --format json'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate()[0].strip())
config = desc['config']
master = config['masterConfig']['instanceNames'][0]
try:
workers = config['workerConfig']['instanceNames'] + config['secondaryWorkerConfig']['instanceNames']
except KeyError:
workers = config['workerConfig']['instanceNames']
zone = re.search(r'zones/(?P<zone>\S+)$', config['gceClusterConfig']['zoneUri']).group('zone')
if args.workers:
invalid_workers = set(args.workers).difference(set(workers))
assert len(invalid_workers) == 0, "Non-existent workers specified: " + ", ".join(invalid_workers)
workers = args.workers
if args.take:
assert args.take > 0 and args.take <= len(
workers), "Number of workers to take must be in the range of [0, nWorkers]. Found " + args.take + "."
workers = workers[:args.take]
def gcloud_ssh(remote, command):
return 'gcloud compute ssh {remote} --zone {zone} --command "{command}"'.format(remote=remote, zone=zone,
command=command)
def gcloud_copy_files(remote, src, dest):
return 'gcloud compute copy-files {remote}:{src} {dest} --zone {zone}'.format(remote=remote, src=src, dest=dest,
zone=zone)
def gsutil_cp(src, dest):
return 'gsutil -m cp -r {src} {dest}'.format(src=src, dest=dest)
def copy_files_tmp(remote, files, dest, tmp):
init_cmd = ['mkdir -p {tmp}; rm -r {tmp}/*'.format(tmp=tmp)]
copy_tmp_cmds = ['sudo cp -r {file} {tmp}'.format(file=file, tmp=tmp) for file in files]
copy_tmp_cmds.append('sudo chmod -R 777 {tmp}'.format(tmp=tmp))
if args.compress:
|
call(gcloud_ssh(remote, '; '.join(init_cmd + copy_tmp_cmds)), shell=True)
if not is_local:
copy_dest_cmd = gcloud_ssh(remote, 'gsutil -m cp -r {tmp} {dest}'.format(tmp=tmp, dest=dest))
else:
copy_dest_cmd = gcloud_copy_files(remote, tmp, dest)
call(copy_dest_cmd, shell=True)
if not args.no_diagnose:
diagnose_tar_path = re.search(r'Diagnostic results saved in: (?P<tarfile>gs://\S+diagnostic\.tar)',
str(Popen('gcloud dataproc clusters diagnose {name}'.format(name=args.name),
shell=True,
stdout=PIPE,
stderr=PIPE).communicate())).group('tarfile')
call(gsutil_cp(diagnose_tar_path, args.dest), shell=True)
master_log_files = ['/var/log/hive/hive-*',
'/var/log/google-dataproc-agent.0.log',
'/var/log/dataproc-initialization-script-0.log',
'/var/log/hadoop-mapreduce/mapred-mapred-historyserver*',
'/var/log/hadoop-hdfs/*-m.*',
'/var/log/hadoop-yarn/yarn-yarn-resourcemanager-*-m.*',
args.hail_log
]
copy_files_tmp(master, master_log_files, master_dest, '/tmp/' + master + '/')
worker_log_files = ['/var/log/hadoop-hdfs/hadoop-hdfs-datanode-*.*',
'/var/log/dataproc-startup-script.log',
'/var/log/hadoop-yarn/yarn-yarn-nodemanager-*.*']
for worker in workers:
copy_files_tmp(worker, worker_log_files, worker_dest, '/tmp/' + worker + '/')
copy_files_tmp(worker, ['/var/log/hadoop-yarn/userlogs/'], args.dest, '/tmp/hadoop-yarn/')
| copy_tmp_cmds.append('sudo find ' + tmp + ' -type f ! -name \'*.gz\' -exec gzip "{}" \\;') | conditional_block |
users.py | """
Page classes to test either the Course Team page or the Library Team page.
"""
from bok_choy.promise import EmptyPromise
from bok_choy.page_object import PageObject
from ...tests.helpers import disable_animations
from . import BASE_URL
def wait_for_ajax_or_reload(browser):
"""
Wait for all ajax requests to finish, OR for the page to reload.
Normal wait_for_ajax() chokes on occasion if the pages reloads,
giving "WebDriverException: Message: u'jQuery is not defined'"
"""
def _is_ajax_finished():
""" Wait for jQuery to finish all AJAX calls, if it is present. """
return browser.execute_script("return typeof(jQuery) == 'undefined' || jQuery.active == 0")
EmptyPromise(_is_ajax_finished, "Finished waiting for ajax requests.").fulfill()
class UsersPage(PageObject):
"""
Base class for either the Course Team page or the Library Team page
"""
def __init__(self, browser, locator):
super(UsersPage, self).__init__(browser)
self.locator = locator
@property
def url(self):
"""
URL to this page - override in subclass
"""
raise NotImplementedError
def is_browser_on_page(self):
"""
Returns True iff the browser has loaded the page.
"""
return self.q(css='body.view-team').present
@property
def users(self):
"""
Return a list of users listed on this page.
"""
return self.q(css='.user-list .user-item').map(
lambda el: UserWrapper(self.browser, el.get_attribute('data-email'))
).results
@property
def has_add_button(self): | """
Is the "New Team Member" button present?
"""
return self.q(css='.create-user-button').present
def click_add_button(self):
"""
Click on the "New Team Member" button
"""
self.q(css='.create-user-button').click()
@property
def new_user_form_visible(self):
""" Is the new user form visible? """
return self.q(css='.form-create.create-user .user-email-input').visible
def set_new_user_email(self, email):
""" Set the value of the "New User Email Address" field. """
self.q(css='.form-create.create-user .user-email-input').fill(email)
def click_submit_new_user_form(self):
""" Submit the "New User" form """
self.q(css='.form-create.create-user .action-primary').click()
wait_for_ajax_or_reload(self.browser)
class LibraryUsersPage(UsersPage):
"""
Library Team page in Studio
"""
@property
def url(self):
"""
URL to the "User Access" page for the given library.
"""
return "{}/library/{}/team/".format(BASE_URL, unicode(self.locator))
class UserWrapper(PageObject):
"""
A PageObject representing a wrapper around a user listed on the course/library team page.
"""
url = None
COMPONENT_BUTTONS = {
'basic_tab': '.editor-tabs li.inner_tab_wrap:nth-child(1) > a',
'advanced_tab': '.editor-tabs li.inner_tab_wrap:nth-child(2) > a',
'save_settings': '.action-save',
}
def __init__(self, browser, email):
super(UserWrapper, self).__init__(browser)
self.email = email
self.selector = '.user-list .user-item[data-email="{}"]'.format(self.email)
def is_browser_on_page(self):
"""
Sanity check that our wrapper element is on the page.
"""
return self.q(css=self.selector).present
def _bounded_selector(self, selector):
"""
Return `selector`, but limited to this particular user entry's context
"""
return '{} {}'.format(self.selector, selector)
@property
def name(self):
""" Get this user's username, as displayed. """
return self.q(css=self._bounded_selector('.user-username')).text[0]
@property
def role_label(self):
""" Get this user's role, as displayed. """
return self.q(css=self._bounded_selector('.flag-role .value')).text[0]
@property
def is_current_user(self):
""" Does the UI indicate that this is the current user? """
return self.q(css=self._bounded_selector('.flag-role .msg-you')).present
@property
def can_promote(self):
""" Can this user be promoted to a more powerful role? """
return self.q(css=self._bounded_selector('.add-admin-role')).present
@property
def promote_button_text(self):
""" What does the promote user button say? """
return self.q(css=self._bounded_selector('.add-admin-role')).text[0]
def click_promote(self):
""" Click on the button to promote this user to the more powerful role """
self.q(css=self._bounded_selector('.add-admin-role')).click()
wait_for_ajax_or_reload(self.browser)
@property
def can_demote(self):
""" Can this user be demoted to a less powerful role? """
return self.q(css=self._bounded_selector('.remove-admin-role')).present
@property
def demote_button_text(self):
""" What does the demote user button say? """
return self.q(css=self._bounded_selector('.remove-admin-role')).text[0]
def click_demote(self):
""" Click on the button to demote this user to the less powerful role """
self.q(css=self._bounded_selector('.remove-admin-role')).click()
wait_for_ajax_or_reload(self.browser)
@property
def can_delete(self):
""" Can this user be deleted? """
return self.q(css=self._bounded_selector('.action-delete:not(.is-disabled) .remove-user')).present
def click_delete(self):
""" Click the button to delete this user. """
disable_animations(self)
self.q(css=self._bounded_selector('.remove-user')).click()
# We can't use confirm_prompt because its wait_for_ajax is flaky when the page is expected to reload.
self.wait_for_element_visibility('.prompt', 'Prompt is visible')
self.wait_for_element_visibility('.prompt .action-primary', 'Confirmation button is visible')
self.q(css='.prompt .action-primary').click()
wait_for_ajax_or_reload(self.browser)
@property
def has_no_change_warning(self):
""" Does this have a warning in place of the promote/demote buttons? """
return self.q(css=self._bounded_selector('.notoggleforyou')).present
@property
def no_change_warning_text(self):
""" Text of the warning seen in place of the promote/demote buttons. """
return self.q(css=self._bounded_selector('.notoggleforyou')).text[0] | random_line_split | |
users.py | """
Page classes to test either the Course Team page or the Library Team page.
"""
from bok_choy.promise import EmptyPromise
from bok_choy.page_object import PageObject
from ...tests.helpers import disable_animations
from . import BASE_URL
def wait_for_ajax_or_reload(browser):
"""
Wait for all ajax requests to finish, OR for the page to reload.
Normal wait_for_ajax() chokes on occasion if the pages reloads,
giving "WebDriverException: Message: u'jQuery is not defined'"
"""
def _is_ajax_finished():
""" Wait for jQuery to finish all AJAX calls, if it is present. """
return browser.execute_script("return typeof(jQuery) == 'undefined' || jQuery.active == 0")
EmptyPromise(_is_ajax_finished, "Finished waiting for ajax requests.").fulfill()
class UsersPage(PageObject):
"""
Base class for either the Course Team page or the Library Team page
"""
def __init__(self, browser, locator):
super(UsersPage, self).__init__(browser)
self.locator = locator
@property
def url(self):
"""
URL to this page - override in subclass
"""
raise NotImplementedError
def is_browser_on_page(self):
"""
Returns True iff the browser has loaded the page.
"""
return self.q(css='body.view-team').present
@property
def users(self):
"""
Return a list of users listed on this page.
"""
return self.q(css='.user-list .user-item').map(
lambda el: UserWrapper(self.browser, el.get_attribute('data-email'))
).results
@property
def has_add_button(self):
"""
Is the "New Team Member" button present?
"""
return self.q(css='.create-user-button').present
def click_add_button(self):
"""
Click on the "New Team Member" button
"""
self.q(css='.create-user-button').click()
@property
def new_user_form_visible(self):
""" Is the new user form visible? """
return self.q(css='.form-create.create-user .user-email-input').visible
def set_new_user_email(self, email):
""" Set the value of the "New User Email Address" field. """
self.q(css='.form-create.create-user .user-email-input').fill(email)
def click_submit_new_user_form(self):
""" Submit the "New User" form """
self.q(css='.form-create.create-user .action-primary').click()
wait_for_ajax_or_reload(self.browser)
class LibraryUsersPage(UsersPage):
"""
Library Team page in Studio
"""
@property
def url(self):
"""
URL to the "User Access" page for the given library.
"""
return "{}/library/{}/team/".format(BASE_URL, unicode(self.locator))
class UserWrapper(PageObject):
"""
A PageObject representing a wrapper around a user listed on the course/library team page.
"""
url = None
COMPONENT_BUTTONS = {
'basic_tab': '.editor-tabs li.inner_tab_wrap:nth-child(1) > a',
'advanced_tab': '.editor-tabs li.inner_tab_wrap:nth-child(2) > a',
'save_settings': '.action-save',
}
def __init__(self, browser, email):
super(UserWrapper, self).__init__(browser)
self.email = email
self.selector = '.user-list .user-item[data-email="{}"]'.format(self.email)
def is_browser_on_page(self):
"""
Sanity check that our wrapper element is on the page.
"""
return self.q(css=self.selector).present
def _bounded_selector(self, selector):
"""
Return `selector`, but limited to this particular user entry's context
"""
return '{} {}'.format(self.selector, selector)
@property
def name(self):
""" Get this user's username, as displayed. """
return self.q(css=self._bounded_selector('.user-username')).text[0]
@property
def | (self):
""" Get this user's role, as displayed. """
return self.q(css=self._bounded_selector('.flag-role .value')).text[0]
@property
def is_current_user(self):
""" Does the UI indicate that this is the current user? """
return self.q(css=self._bounded_selector('.flag-role .msg-you')).present
@property
def can_promote(self):
""" Can this user be promoted to a more powerful role? """
return self.q(css=self._bounded_selector('.add-admin-role')).present
@property
def promote_button_text(self):
""" What does the promote user button say? """
return self.q(css=self._bounded_selector('.add-admin-role')).text[0]
def click_promote(self):
""" Click on the button to promote this user to the more powerful role """
self.q(css=self._bounded_selector('.add-admin-role')).click()
wait_for_ajax_or_reload(self.browser)
@property
def can_demote(self):
""" Can this user be demoted to a less powerful role? """
return self.q(css=self._bounded_selector('.remove-admin-role')).present
@property
def demote_button_text(self):
""" What does the demote user button say? """
return self.q(css=self._bounded_selector('.remove-admin-role')).text[0]
def click_demote(self):
""" Click on the button to demote this user to the less powerful role """
self.q(css=self._bounded_selector('.remove-admin-role')).click()
wait_for_ajax_or_reload(self.browser)
@property
def can_delete(self):
""" Can this user be deleted? """
return self.q(css=self._bounded_selector('.action-delete:not(.is-disabled) .remove-user')).present
def click_delete(self):
""" Click the button to delete this user. """
disable_animations(self)
self.q(css=self._bounded_selector('.remove-user')).click()
# We can't use confirm_prompt because its wait_for_ajax is flaky when the page is expected to reload.
self.wait_for_element_visibility('.prompt', 'Prompt is visible')
self.wait_for_element_visibility('.prompt .action-primary', 'Confirmation button is visible')
self.q(css='.prompt .action-primary').click()
wait_for_ajax_or_reload(self.browser)
@property
def has_no_change_warning(self):
""" Does this have a warning in place of the promote/demote buttons? """
return self.q(css=self._bounded_selector('.notoggleforyou')).present
@property
def no_change_warning_text(self):
""" Text of the warning seen in place of the promote/demote buttons. """
return self.q(css=self._bounded_selector('.notoggleforyou')).text[0]
| role_label | identifier_name |
users.py | """
Page classes to test either the Course Team page or the Library Team page.
"""
from bok_choy.promise import EmptyPromise
from bok_choy.page_object import PageObject
from ...tests.helpers import disable_animations
from . import BASE_URL
def wait_for_ajax_or_reload(browser):
"""
Wait for all ajax requests to finish, OR for the page to reload.
Normal wait_for_ajax() chokes on occasion if the pages reloads,
giving "WebDriverException: Message: u'jQuery is not defined'"
"""
def _is_ajax_finished():
""" Wait for jQuery to finish all AJAX calls, if it is present. """
return browser.execute_script("return typeof(jQuery) == 'undefined' || jQuery.active == 0")
EmptyPromise(_is_ajax_finished, "Finished waiting for ajax requests.").fulfill()
class UsersPage(PageObject):
"""
Base class for either the Course Team page or the Library Team page
"""
def __init__(self, browser, locator):
super(UsersPage, self).__init__(browser)
self.locator = locator
@property
def url(self):
|
def is_browser_on_page(self):
"""
Returns True iff the browser has loaded the page.
"""
return self.q(css='body.view-team').present
@property
def users(self):
"""
Return a list of users listed on this page.
"""
return self.q(css='.user-list .user-item').map(
lambda el: UserWrapper(self.browser, el.get_attribute('data-email'))
).results
@property
def has_add_button(self):
"""
Is the "New Team Member" button present?
"""
return self.q(css='.create-user-button').present
def click_add_button(self):
"""
Click on the "New Team Member" button
"""
self.q(css='.create-user-button').click()
@property
def new_user_form_visible(self):
""" Is the new user form visible? """
return self.q(css='.form-create.create-user .user-email-input').visible
def set_new_user_email(self, email):
""" Set the value of the "New User Email Address" field. """
self.q(css='.form-create.create-user .user-email-input').fill(email)
def click_submit_new_user_form(self):
""" Submit the "New User" form """
self.q(css='.form-create.create-user .action-primary').click()
wait_for_ajax_or_reload(self.browser)
class LibraryUsersPage(UsersPage):
"""
Library Team page in Studio
"""
@property
def url(self):
"""
URL to the "User Access" page for the given library.
"""
return "{}/library/{}/team/".format(BASE_URL, unicode(self.locator))
class UserWrapper(PageObject):
"""
A PageObject representing a wrapper around a user listed on the course/library team page.
"""
url = None
COMPONENT_BUTTONS = {
'basic_tab': '.editor-tabs li.inner_tab_wrap:nth-child(1) > a',
'advanced_tab': '.editor-tabs li.inner_tab_wrap:nth-child(2) > a',
'save_settings': '.action-save',
}
def __init__(self, browser, email):
super(UserWrapper, self).__init__(browser)
self.email = email
self.selector = '.user-list .user-item[data-email="{}"]'.format(self.email)
def is_browser_on_page(self):
"""
Sanity check that our wrapper element is on the page.
"""
return self.q(css=self.selector).present
def _bounded_selector(self, selector):
"""
Return `selector`, but limited to this particular user entry's context
"""
return '{} {}'.format(self.selector, selector)
@property
def name(self):
""" Get this user's username, as displayed. """
return self.q(css=self._bounded_selector('.user-username')).text[0]
@property
def role_label(self):
""" Get this user's role, as displayed. """
return self.q(css=self._bounded_selector('.flag-role .value')).text[0]
@property
def is_current_user(self):
""" Does the UI indicate that this is the current user? """
return self.q(css=self._bounded_selector('.flag-role .msg-you')).present
@property
def can_promote(self):
""" Can this user be promoted to a more powerful role? """
return self.q(css=self._bounded_selector('.add-admin-role')).present
@property
def promote_button_text(self):
""" What does the promote user button say? """
return self.q(css=self._bounded_selector('.add-admin-role')).text[0]
def click_promote(self):
""" Click on the button to promote this user to the more powerful role """
self.q(css=self._bounded_selector('.add-admin-role')).click()
wait_for_ajax_or_reload(self.browser)
@property
def can_demote(self):
""" Can this user be demoted to a less powerful role? """
return self.q(css=self._bounded_selector('.remove-admin-role')).present
@property
def demote_button_text(self):
""" What does the demote user button say? """
return self.q(css=self._bounded_selector('.remove-admin-role')).text[0]
def click_demote(self):
""" Click on the button to demote this user to the less powerful role """
self.q(css=self._bounded_selector('.remove-admin-role')).click()
wait_for_ajax_or_reload(self.browser)
@property
def can_delete(self):
""" Can this user be deleted? """
return self.q(css=self._bounded_selector('.action-delete:not(.is-disabled) .remove-user')).present
def click_delete(self):
""" Click the button to delete this user. """
disable_animations(self)
self.q(css=self._bounded_selector('.remove-user')).click()
# We can't use confirm_prompt because its wait_for_ajax is flaky when the page is expected to reload.
self.wait_for_element_visibility('.prompt', 'Prompt is visible')
self.wait_for_element_visibility('.prompt .action-primary', 'Confirmation button is visible')
self.q(css='.prompt .action-primary').click()
wait_for_ajax_or_reload(self.browser)
@property
def has_no_change_warning(self):
""" Does this have a warning in place of the promote/demote buttons? """
return self.q(css=self._bounded_selector('.notoggleforyou')).present
@property
def no_change_warning_text(self):
""" Text of the warning seen in place of the promote/demote buttons. """
return self.q(css=self._bounded_selector('.notoggleforyou')).text[0]
| """
URL to this page - override in subclass
"""
raise NotImplementedError | identifier_body |
request.rs | #[derive(RustcDecodable, RustcEncodable)] | Ping,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct UserFlagPair {
pub id: usize,
pub flag: String,
pub user: String,
}
impl CTFRequest {
pub fn verify_flag(id: usize, flag: String, user: String) -> Self {
CTFRequest::FlagOffer(UserFlagPair::new(id, flag, user))
}
pub fn view_leaderboard(start: usize, stop: usize) -> Self {
CTFRequest::Leaderboard(start, stop)
}
}
impl UserFlagPair {
pub fn new(id: usize, flag: String, user: String) -> Self {
UserFlagPair {
id: id,
flag: flag,
user: user,
}
}
} | pub enum CTFRequest {
FlagOffer(UserFlagPair),
Leaderboard(usize, usize), | random_line_split |
request.rs | #[derive(RustcDecodable, RustcEncodable)]
pub enum | {
FlagOffer(UserFlagPair),
Leaderboard(usize, usize),
Ping,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct UserFlagPair {
pub id: usize,
pub flag: String,
pub user: String,
}
impl CTFRequest {
pub fn verify_flag(id: usize, flag: String, user: String) -> Self {
CTFRequest::FlagOffer(UserFlagPair::new(id, flag, user))
}
pub fn view_leaderboard(start: usize, stop: usize) -> Self {
CTFRequest::Leaderboard(start, stop)
}
}
impl UserFlagPair {
pub fn new(id: usize, flag: String, user: String) -> Self {
UserFlagPair {
id: id,
flag: flag,
user: user,
}
}
}
| CTFRequest | identifier_name |
stream.rs | use std::io::Read;
use std::fmt::{self, Debug};
use response::{Response, Responder, DEFAULT_CHUNK_SIZE};
use http::Status;
/// Streams a response to a client from an arbitrary `Read`er type.
///
/// The client is sent a "chunked" response, where the chunk size is at most
/// 4KiB. This means that at most 4KiB are stored in memory while the response
/// is being sent. This type should be used when sending responses that are
/// arbitrarily large in size, such as when streaming from a local socket.
pub struct Stream<T: Read>(T, u64);
impl<T: Read> Stream<T> {
/// Create a new stream from the given `reader`.
///
/// # Example
///
/// Stream a response from whatever is in `stdin`. Note: you probably
/// shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::from(io::stdin());
/// ```
pub fn from(reader: T) -> Stream<T> |
/// Create a new stream from the given `reader` and sets the chunk size for
/// each streamed chunk to `chunk_size` bytes.
///
/// # Example
///
/// Stream a response from whatever is in `stdin` with a chunk size of 10
/// bytes. Note: you probably shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::chunked(io::stdin(), 10);
/// ```
pub fn chunked(reader: T, chunk_size: u64) -> Stream<T> {
Stream(reader, chunk_size)
}
}
impl<T: Read + Debug> Debug for Stream<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream({:?})", self.0)
}
}
/// Sends a response to the client using the "Chunked" transfer encoding. The
/// maximum chunk size is 4KiB.
///
/// # Failure
///
/// If reading from the input stream fails at any point during the response, the
/// response is abandoned, and the response ends abruptly. An error is printed
/// to the console with an indication of what went wrong.
impl<'r, T: Read + 'r> Responder<'r> for Stream<T> {
fn respond(self) -> Result<Response<'r>, Status> {
Response::build().chunked_body(self.0, self.1).ok()
}
}
| {
Stream(reader, DEFAULT_CHUNK_SIZE)
} | identifier_body |
stream.rs | use std::io::Read;
use std::fmt::{self, Debug};
use response::{Response, Responder, DEFAULT_CHUNK_SIZE};
use http::Status;
/// Streams a response to a client from an arbitrary `Read`er type.
///
/// The client is sent a "chunked" response, where the chunk size is at most
/// 4KiB. This means that at most 4KiB are stored in memory while the response
/// is being sent. This type should be used when sending responses that are
/// arbitrarily large in size, such as when streaming from a local socket.
pub struct Stream<T: Read>(T, u64);
impl<T: Read> Stream<T> {
/// Create a new stream from the given `reader`.
///
/// # Example
///
/// Stream a response from whatever is in `stdin`. Note: you probably
/// shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::from(io::stdin());
/// ```
pub fn from(reader: T) -> Stream<T> {
Stream(reader, DEFAULT_CHUNK_SIZE)
}
/// Create a new stream from the given `reader` and sets the chunk size for
/// each streamed chunk to `chunk_size` bytes.
///
/// # Example
///
/// Stream a response from whatever is in `stdin` with a chunk size of 10
/// bytes. Note: you probably shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::chunked(io::stdin(), 10);
/// ```
pub fn | (reader: T, chunk_size: u64) -> Stream<T> {
Stream(reader, chunk_size)
}
}
impl<T: Read + Debug> Debug for Stream<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream({:?})", self.0)
}
}
/// Sends a response to the client using the "Chunked" transfer encoding. The
/// maximum chunk size is 4KiB.
///
/// # Failure
///
/// If reading from the input stream fails at any point during the response, the
/// response is abandoned, and the response ends abruptly. An error is printed
/// to the console with an indication of what went wrong.
impl<'r, T: Read + 'r> Responder<'r> for Stream<T> {
fn respond(self) -> Result<Response<'r>, Status> {
Response::build().chunked_body(self.0, self.1).ok()
}
}
| chunked | identifier_name |
stream.rs | use std::io::Read;
use std::fmt::{self, Debug};
use response::{Response, Responder, DEFAULT_CHUNK_SIZE};
use http::Status;
/// Streams a response to a client from an arbitrary `Read`er type.
///
/// The client is sent a "chunked" response, where the chunk size is at most
/// 4KiB. This means that at most 4KiB are stored in memory while the response
/// is being sent. This type should be used when sending responses that are
/// arbitrarily large in size, such as when streaming from a local socket.
pub struct Stream<T: Read>(T, u64);
impl<T: Read> Stream<T> {
/// Create a new stream from the given `reader`.
///
/// # Example
///
/// Stream a response from whatever is in `stdin`. Note: you probably
/// shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::from(io::stdin());
/// ```
pub fn from(reader: T) -> Stream<T> {
Stream(reader, DEFAULT_CHUNK_SIZE)
}
/// Create a new stream from the given `reader` and sets the chunk size for
/// each streamed chunk to `chunk_size` bytes.
///
/// # Example
///
/// Stream a response from whatever is in `stdin` with a chunk size of 10
/// bytes. Note: you probably shouldn't do this.
///
/// ```rust
/// use std::io;
/// use rocket::response::Stream;
///
/// # #[allow(unused_variables)]
/// let response = Stream::chunked(io::stdin(), 10);
/// ```
pub fn chunked(reader: T, chunk_size: u64) -> Stream<T> {
Stream(reader, chunk_size)
}
}
impl<T: Read + Debug> Debug for Stream<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream({:?})", self.0)
}
}
/// Sends a response to the client using the "Chunked" transfer encoding. The
/// maximum chunk size is 4KiB. | /// response is abandoned, and the response ends abruptly. An error is printed
/// to the console with an indication of what went wrong.
impl<'r, T: Read + 'r> Responder<'r> for Stream<T> {
fn respond(self) -> Result<Response<'r>, Status> {
Response::build().chunked_body(self.0, self.1).ok()
}
} | ///
/// # Failure
///
/// If reading from the input stream fails at any point during the response, the | random_line_split |
match-beginning-vert.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
enum Foo {
A,
B,
C,
D,
E,
}
use Foo::*;
| match *foo {
| A => println!("A"),
| B | C if 1 < 2 => println!("BC!"),
| _ => {},
}
}
} | fn main() {
for foo in &[A, B, C, D, E] { | random_line_split |
match-beginning-vert.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
enum | {
A,
B,
C,
D,
E,
}
use Foo::*;
fn main() {
for foo in &[A, B, C, D, E] {
match *foo {
| A => println!("A"),
| B | C if 1 < 2 => println!("BC!"),
| _ => {},
}
}
}
| Foo | identifier_name |
userinfo-edit.js | /**
* Created by zhangjh on 2015/10/27.
*/
(function ($) {
"use strict";
var path = $.basepath();
var newURL = path + "/system/userinfo/new";
var user_infoURL = path + "/system/userinfo/info/";
var editURL = path + "/system/userinfo/edit";
var _0URL = path + "/system/permission/user-tab/0";
var usertypeURL = path + "/system/userinfo/usertype";
var fileUploadURL = path + "/files/upload";
var uploadFileInfos = [];
var isSubmitAction = "N";//是否点击的
var $fileInput = $("#fileLocation");
var $fileListLi = $("#filesList");
$.extend({
saveuserinfo: saveuserinfo
});
var fieldsDesc =
{
name: {
validators: {
notEmpty: {
message: '名称为必填项'
}
}
},
aliases: {
validators: {
notEmpty: {
message: '用户别名为必填项'
}
}
},
password: {
validators: {
notEmpty: {
message: '密码为必填项'
}
}
},
rptUserPwd: {
validators: {
notEmpty: {
message: '密码确认为必填项'
}
}
},
userType: {
validators: {
notEmpty: {
message: '用户类型为必填项'
}
}
},
userEmail: {
validators: {
notEmpty: {
message: '用户邮箱为必填项'
}
}
},
userMobile: {
validators: {
notEmpty: {
message: '用户手机为必填项'
}
}
}
};
var doSaveAction = function () {
var formDataStr = $("#userinfoForm").serialize();
formDataStr = decodeURIComponent(formDataStr);
var natrualkey = $("#natrualkey").val();
var url;
if (natrualkey == '' || natrualkey == 'null') {
url = newURL;
} else {
url = editURL;
}
var userInfo = $.strToJson(formDataStr);
userInfo.fileInfos = uploadFileInfos;
$.sendJsonAjax(url, userInfo, function () {
window.location.href = _0URL;
})
}
function saveuserinfo() {
//执行表单监听
$('#userinfoForm').bootstrapValidator('validate');
}
//启动表单校验监听
$('#userinfoForm').bootstrapValidator({
//live: 'disabled',
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: fieldsDesc
}).on('success.form.bv', function (e) { //表单校验成功,ajax提交数据
$fileInput.fileinput('upload');//批量提交
var hasExtraData = $.isEmptyObject($fileInput.fileinput("getExtraData"));
if (hasExtraData) {
doSaveAction();
}
isSubmitAction = "Y";
});
$(function () {
//用户类型
$.sendRestFulAjax(usertypeURL, null, 'GET', 'json', initSelect);
//initFileLocation(null, null);
$.fileInputAddListenr($fileListLi, $fileInput, uploadFileInfos, doSaveAction, getIsSubmitAction);
})
function getIsSubmitAction() {
return isSubmitAction;
}
function initSelectCallback() {
var natrualkey = $("#natrualkey").val();
if (natrualkey != '') {
$.sendRestFulAjax(user_infoURL + natrualkey, null, 'GET', 'json', initFormFields);
}
}
function initFormFields(_data) {
//初始化赋值
Object.keys(_data).map(function (key) {
//下拉框
$("#" + key).val(_data[key]);
});
$.loadFileInput($fileInput, $fileListLi, _data["fileinfosMap"], fileUploadURL);
}
/**
*
* @param data
*/
var initSelect = function (data) {
$("#userType").empty();
$("<option></option>").val('').text("请选择...").appendTo($("#userType"));
$.each(data, function (key, value) {
$("<option></option>") | });
initSelectCallback();
}
}(jQuery)); | .val(key)
.text(value)
.appendTo($("#userType")); | random_line_split |
userinfo-edit.js | /**
* Created by zhangjh on 2015/10/27.
*/
(function ($) {
"use strict";
var path = $.basepath();
var newURL = path + "/system/userinfo/new";
var user_infoURL = path + "/system/userinfo/info/";
var editURL = path + "/system/userinfo/edit";
var _0URL = path + "/system/permission/user-tab/0";
var usertypeURL = path + "/system/userinfo/usertype";
var fileUploadURL = path + "/files/upload";
var uploadFileInfos = [];
var isSubmitAction = "N";//是否点击的
var $fileInput = $("#fileLocation");
var $fileListLi = $("#filesList");
$.extend({
saveuserinfo: saveuserinfo
});
var fieldsDesc =
{
name: {
validators: {
notEmpty: {
message: '名称为必填项'
}
}
},
aliases: {
validators: {
notEmpty: {
message: '用户别名为必填项'
}
}
},
password: {
validators: {
notEmpty: {
message: '密码为必填项'
}
}
},
rptUserPwd: {
validators: {
notEmpty: {
message: '密码确认为必填项'
}
}
},
userType: {
validators: {
notEmpty: {
message: '用户类型为必填项'
}
}
},
userEmail: {
validators: {
notEmpty: {
message: '用户邮箱为必填项'
}
}
},
userMobile: {
validators: {
notEmpty: {
message: '用户手机为必填项'
}
}
}
};
var doSaveAction = function () {
var formDataStr = $("#userinfoForm").serialize();
formDataStr = decodeURIComponent(formDataStr);
var natrualkey = $("#natrualkey").val();
var url;
if (natrualkey == '' || natrualkey == 'null') {
url = newURL;
} else {
url = editURL;
}
var userInfo = $.strToJson(formDataStr);
userInfo.fileInfos = uploadFileInfos;
$.sendJsonAjax(url, userInfo, function () {
window.location.href = _0URL;
})
}
function saveuserinfo() {
//执行表单监听
$('#userinfoForm').bootstrapValidator('validate');
}
//启动表单校验监听
$('#userinfoForm').bootstrapValidator({
//live: 'disabled',
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: fieldsDesc
}).on('success.form.bv', function (e) { //表单校验成功,ajax提交数据
$fileInput.fileinput('upload');//批量提交
var hasExtraData = $.isEmptyObject($fileInput.fileinput("getExtraData"));
if (hasExtraData) {
doSaveAction();
}
isSubmitAction = "Y";
});
$(function () {
//用户类型
$.sendRestFulAjax(usertypeURL, null, 'GET', 'json', initSelect);
//initFileLocation(null, null);
$.fileInputAddListenr($fileListLi, $fileInput, uploadFileInfos, doSaveAction, getIsSubmitAction);
})
function getIsSubmitAction() {
return isSubmitAction;
}
function initSelectCallback() {
var natrualkey = $("#natrualkey").val();
if (natrualkey != '') {
$.sendRestFulAjax(user_infoURL + natrualkey, null, 'GET', 'json', initFormFields);
}
}
function initFormFields(_data) {
//初始化赋值
Object.keys(_data).map(function (key) {
//下拉框
$("#" + key).val(_data[key]);
});
$.loadFileI | t, $fileListLi, _data["fileinfosMap"], fileUploadURL);
}
/**
*
* @param data
*/
var initSelect = function (data) {
$("#userType").empty();
$("<option></option>").val('').text("请选择...").appendTo($("#userType"));
$.each(data, function (key, value) {
$("<option></option>")
.val(key)
.text(value)
.appendTo($("#userType"));
});
initSelectCallback();
}
}(jQuery)); | nput($fileInpu | identifier_name |
userinfo-edit.js | /**
* Created by zhangjh on 2015/10/27.
*/
(function ($) {
"use strict";
var path = $.basepath();
var newURL = path + "/system/userinfo/new";
var user_infoURL = path + "/system/userinfo/info/";
var editURL = path + "/system/userinfo/edit";
var _0URL = path + "/system/permission/user-tab/0";
var usertypeURL = path + "/system/userinfo/usertype";
var fileUploadURL = path + "/files/upload";
var uploadFileInfos = [];
var isSubmitAction = "N";//是否点击的
var $fileInput = $("#fileLocation");
var $fileListLi = $("#filesList");
$.extend({
saveuserinfo: saveuserinfo
});
var fieldsDesc =
{
name: {
validators: {
notEmpty: {
message: '名称为必填项'
}
}
},
aliases: {
validators: {
notEmpty: {
message: '用户别名为必填项'
}
}
},
password: {
validators: {
notEmpty: {
message: '密码为必填项'
}
}
},
rptUserPwd: {
validators: {
notEmpty: {
message: '密码确认为必填项'
}
}
},
userType: {
validators: {
notEmpty: {
message: '用户类型为必填项'
}
}
},
userEmail: {
validators: {
notEmpty: {
message: '用户邮箱为必填项'
}
}
},
userMobile: {
validators: {
notEmpty: {
message: '用户手机为必填项'
}
}
}
};
var doSaveAction = function () {
var formDataStr = $("#userinfoForm").serialize();
formDataStr = decodeURIComponent(formDataStr);
var natrualkey = $("#natrualkey").val();
var url;
if (natrualkey == '' || natrualkey == 'null') {
url = newURL;
} else {
url = editURL;
}
var userInfo = $.strToJson(formDataStr);
userInfo.fileInfos = uploadFileInfos;
$.sendJsonAjax(url, userInfo, function () {
window.location.href = _0URL;
})
}
function saveuserinfo() {
//执行表单监听
$('#userinfoForm').bootstrapValidator('validate');
}
//启动表单校验监听
$('#userinfoForm').bootstrapValidator({
//live: 'disabled',
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: fieldsDesc
}).on('success.form.bv', function (e) { //表单校验成功,ajax提交数据
$fileInput.fileinput('upload');//批量提交
var hasExtraData = $.isEmptyObject($fileInput.fileinput("getExtraData"));
if (hasExtraData) {
doSaveAction();
}
isSubmitAction = "Y";
});
$(function () {
//用户类型
$.sendRestFulAjax(usertypeURL, null, 'GET', 'json', initSelect);
//initFileLocation(null, null);
$.fileInputAddListenr($fileListLi, $fileInput, uploadFileInfos, doSaveAction, getIsSubmitAction);
})
function getIsSubmitAction() {
return isSubmitAction;
}
function initSelectCallback() {
var natrualkey = $("#natrualkey").val();
if (natrualkey != '') {
$.sendRestFulAjax(user_infoURL + natrualkey, null, 'GET', 'json', initFormFields);
}
}
function initFormFields(_data) {
//初始化赋值
Object.keys(_data).map(function (key) {
//下拉框
$("#" + key).val(_data[key]);
});
$.loadFileInput($fileInput, $file |
$.each(data, function (key, value) {
$("<option></option>")
.val(key)
.text(value)
.appendTo($("#userType"));
});
initSelectCallback();
}
}(jQuery)); | ListLi, _data["fileinfosMap"], fileUploadURL);
}
/**
*
* @param data
*/
var initSelect = function (data) {
$("#userType").empty();
$("<option></option>").val('').text("请选择...").appendTo($("#userType")); | identifier_body |
userinfo-edit.js | /**
* Created by zhangjh on 2015/10/27.
*/
(function ($) {
"use strict";
var path = $.basepath();
var newURL = path + "/system/userinfo/new";
var user_infoURL = path + "/system/userinfo/info/";
var editURL = path + "/system/userinfo/edit";
var _0URL = path + "/system/permission/user-tab/0";
var usertypeURL = path + "/system/userinfo/usertype";
var fileUploadURL = path + "/files/upload";
var uploadFileInfos = [];
var isSubmitAction = "N";//是否点击的
var $fileInput = $("#fileLocation");
var $fileListLi = $("#filesList");
$.extend({
saveuserinfo: saveuserinfo
});
var fieldsDesc =
{
name: {
validators: {
notEmpty: {
message: '名称为必填项'
}
}
},
aliases: {
validators: {
notEmpty: {
message: '用户别名为必填项'
}
}
},
password: {
validators: {
notEmpty: {
message: '密码为必填项'
}
}
},
rptUserPwd: {
validators: {
notEmpty: {
message: '密码确认为必填项'
}
}
},
userType: {
validators: {
notEmpty: {
message: '用户类型为必填项'
}
}
},
userEmail: {
validators: {
notEmpty: {
message: '用户邮箱为必填项'
}
}
},
userMobile: {
validators: {
notEmpty: {
message: '用户手机为必填项'
}
}
}
};
var doSaveAction = function () {
var formDataStr = $("#userinfoForm").serialize();
formDataStr = decodeURIComponent(formDataStr);
var natrualkey = $("#natrualkey").val();
var url;
if (natrualkey == '' || natrualkey == 'null') {
url = newURL;
} else {
url = editURL;
}
var userInfo = $.strToJson(formDataStr);
userInfo.fileInfos = uploadFileInfos;
$.sendJsonAjax(url, userInfo, function () {
window.location.href = _0URL;
})
}
function saveuserinfo() {
//执行表单监听
$('#userinfoForm').bootstrapValidator('validate');
}
//启动表单校验监听
$('#userinfoForm').bootstrapValidator({
//live: 'disabled',
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: fieldsDesc
}).on('success.form.bv', function (e) { //表单校验成功,ajax提交数据
$fileInput.fileinput('upload');//批量提交
var hasExtraData = $.isEmptyObject($fileInput.fileinput("getExtraData"));
if (hasExtraData) {
doSaveAction();
}
isSubmitAction = "Y";
});
$(function () {
//用户类型
$.sendRestFulAjax(usertypeURL, null, 'GET', 'jso | ation(null, null);
$.fileInputAddListenr($fileListLi, $fileInput, uploadFileInfos, doSaveAction, getIsSubmitAction);
})
function getIsSubmitAction() {
return isSubmitAction;
}
function initSelectCallback() {
var natrualkey = $("#natrualkey").val();
if (natrualkey != '') {
$.sendRestFulAjax(user_infoURL + natrualkey, null, 'GET', 'json', initFormFields);
}
}
function initFormFields(_data) {
//初始化赋值
Object.keys(_data).map(function (key) {
//下拉框
$("#" + key).val(_data[key]);
});
$.loadFileInput($fileInput, $fileListLi, _data["fileinfosMap"], fileUploadURL);
}
/**
*
* @param data
*/
var initSelect = function (data) {
$("#userType").empty();
$("<option></option>").val('').text("请选择...").appendTo($("#userType"));
$.each(data, function (key, value) {
$("<option></option>")
.val(key)
.text(value)
.appendTo($("#userType"));
});
initSelectCallback();
}
}(jQuery)); | n', initSelect);
//initFileLoc | conditional_block |
amendments.py | '''
US Amendments - tweets proposed ammendments to us constitution
from: http://www.archives.gov/open/dataset-amendments.html
'''
if __name__ == "__main__":
import sys
sys.path.append("..")
import credentials
from robot_core import Robot
from funcs.ql import QuickList
import os
import time
class | (Robot):
handle = "USAmendments"
twitter_credentials = credentials.twitter_almostamends
minutes= 135
def get_amendment_link(self,row):
"""constructs url page"""
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff
url = "https://www.congress.gov/bill/{0}-congress/{2}-joint-resolution/{1}"
if row["joint_resolution_chamber"] == "House Joint Resolution":
house = "house"
else:
house = "senate"
url = url.format(ordinal(int(row["congress"])),int(row['joint_resolution_number']),house)
return url
def tweet(self):
local_loc = os.path.dirname(__file__)
storage = QuickList().open(os.path.join(local_loc,
"..//schedules//us-nara-amending-america-dataset-raw-2016-02-25.xls"))
storage.shuffle()
storage.data = storage.data[:1]
for r in storage:
if r["year"] and r["title_or_description_from_source"]:
row = r
desc = row["title_or_description_from_source"]
"""
remove generic phrasing
"""
bad_terms=[
"Proposing an amendment to the Constitution of the United States relating to ",
"Proposing an amendment to the Constitution of the United States",
"A joint resolution proposing an amendment to the Constitution of the United States",
" to the Constitution of the United States.",
"A joint resolution proposing",
"A joint resolution proposing an amendment to the Constitution of the United States relative to ",
]
bad_terms.sort(key=lambda x:len(x), reverse=True)
for b in bad_terms:
desc = desc.replace(b,"")
"""
fix formatting
"""
desc = desc.strip()
if desc[0] == desc[0].lower():
desc = desc[0].upper() + desc[1:]
"""
are we able to provide a link to this?
"""
if row["year"] >= 1973 and row['joint_resolution_number']:
link = self.get_amendment_link(row)
allowed_length = 141 - 22
elif row['source_code'] == "A":
#link = "book"
allowed_length = 141
link = None
else:
link = None
allowed_length = 141
text = u"{0} - {1}".format(int(row["year"]),desc)
if len(text) > allowed_length:
long_text = text
if link == None:
#get pastebin version of this and get ready to link it
#link = self._paste_to_pastebin(long_text)
if link: #pastebin might fail
allowed_length = 141 -22
text = text[:allowed_length-3] + "..."
if link:
text += " " + link
return self._tweet(text)
if __name__ == "__main__":
AmendmentBot().populate(20) | AmendmentBot | identifier_name |
amendments.py | '''
US Amendments - tweets proposed ammendments to us constitution
from: http://www.archives.gov/open/dataset-amendments.html
'''
if __name__ == "__main__":
import sys
sys.path.append("..")
| import time
class AmendmentBot(Robot):
handle = "USAmendments"
twitter_credentials = credentials.twitter_almostamends
minutes= 135
def get_amendment_link(self,row):
"""constructs url page"""
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff
url = "https://www.congress.gov/bill/{0}-congress/{2}-joint-resolution/{1}"
if row["joint_resolution_chamber"] == "House Joint Resolution":
house = "house"
else:
house = "senate"
url = url.format(ordinal(int(row["congress"])),int(row['joint_resolution_number']),house)
return url
def tweet(self):
local_loc = os.path.dirname(__file__)
storage = QuickList().open(os.path.join(local_loc,
"..//schedules//us-nara-amending-america-dataset-raw-2016-02-25.xls"))
storage.shuffle()
storage.data = storage.data[:1]
for r in storage:
if r["year"] and r["title_or_description_from_source"]:
row = r
desc = row["title_or_description_from_source"]
"""
remove generic phrasing
"""
bad_terms=[
"Proposing an amendment to the Constitution of the United States relating to ",
"Proposing an amendment to the Constitution of the United States",
"A joint resolution proposing an amendment to the Constitution of the United States",
" to the Constitution of the United States.",
"A joint resolution proposing",
"A joint resolution proposing an amendment to the Constitution of the United States relative to ",
]
bad_terms.sort(key=lambda x:len(x), reverse=True)
for b in bad_terms:
desc = desc.replace(b,"")
"""
fix formatting
"""
desc = desc.strip()
if desc[0] == desc[0].lower():
desc = desc[0].upper() + desc[1:]
"""
are we able to provide a link to this?
"""
if row["year"] >= 1973 and row['joint_resolution_number']:
link = self.get_amendment_link(row)
allowed_length = 141 - 22
elif row['source_code'] == "A":
#link = "book"
allowed_length = 141
link = None
else:
link = None
allowed_length = 141
text = u"{0} - {1}".format(int(row["year"]),desc)
if len(text) > allowed_length:
long_text = text
if link == None:
#get pastebin version of this and get ready to link it
#link = self._paste_to_pastebin(long_text)
if link: #pastebin might fail
allowed_length = 141 -22
text = text[:allowed_length-3] + "..."
if link:
text += " " + link
return self._tweet(text)
if __name__ == "__main__":
AmendmentBot().populate(20) | import credentials
from robot_core import Robot
from funcs.ql import QuickList
import os | random_line_split |
amendments.py | '''
US Amendments - tweets proposed ammendments to us constitution
from: http://www.archives.gov/open/dataset-amendments.html
'''
if __name__ == "__main__":
import sys
sys.path.append("..")
import credentials
from robot_core import Robot
from funcs.ql import QuickList
import os
import time
class AmendmentBot(Robot):
|
if __name__ == "__main__":
AmendmentBot().populate(20) | handle = "USAmendments"
twitter_credentials = credentials.twitter_almostamends
minutes= 135
def get_amendment_link(self,row):
"""constructs url page"""
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff
url = "https://www.congress.gov/bill/{0}-congress/{2}-joint-resolution/{1}"
if row["joint_resolution_chamber"] == "House Joint Resolution":
house = "house"
else:
house = "senate"
url = url.format(ordinal(int(row["congress"])),int(row['joint_resolution_number']),house)
return url
def tweet(self):
local_loc = os.path.dirname(__file__)
storage = QuickList().open(os.path.join(local_loc,
"..//schedules//us-nara-amending-america-dataset-raw-2016-02-25.xls"))
storage.shuffle()
storage.data = storage.data[:1]
for r in storage:
if r["year"] and r["title_or_description_from_source"]:
row = r
desc = row["title_or_description_from_source"]
"""
remove generic phrasing
"""
bad_terms=[
"Proposing an amendment to the Constitution of the United States relating to ",
"Proposing an amendment to the Constitution of the United States",
"A joint resolution proposing an amendment to the Constitution of the United States",
" to the Constitution of the United States.",
"A joint resolution proposing",
"A joint resolution proposing an amendment to the Constitution of the United States relative to ",
]
bad_terms.sort(key=lambda x:len(x), reverse=True)
for b in bad_terms:
desc = desc.replace(b,"")
"""
fix formatting
"""
desc = desc.strip()
if desc[0] == desc[0].lower():
desc = desc[0].upper() + desc[1:]
"""
are we able to provide a link to this?
"""
if row["year"] >= 1973 and row['joint_resolution_number']:
link = self.get_amendment_link(row)
allowed_length = 141 - 22
elif row['source_code'] == "A":
#link = "book"
allowed_length = 141
link = None
else:
link = None
allowed_length = 141
text = u"{0} - {1}".format(int(row["year"]),desc)
if len(text) > allowed_length:
long_text = text
if link == None:
#get pastebin version of this and get ready to link it
#link = self._paste_to_pastebin(long_text)
if link: #pastebin might fail
allowed_length = 141 -22
text = text[:allowed_length-3] + "..."
if link:
text += " " + link
return self._tweet(text) | identifier_body |
amendments.py | '''
US Amendments - tweets proposed ammendments to us constitution
from: http://www.archives.gov/open/dataset-amendments.html
'''
if __name__ == "__main__":
import sys
sys.path.append("..")
import credentials
from robot_core import Robot
from funcs.ql import QuickList
import os
import time
class AmendmentBot(Robot):
handle = "USAmendments"
twitter_credentials = credentials.twitter_almostamends
minutes= 135
def get_amendment_link(self,row):
"""constructs url page"""
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff
url = "https://www.congress.gov/bill/{0}-congress/{2}-joint-resolution/{1}"
if row["joint_resolution_chamber"] == "House Joint Resolution":
house = "house"
else:
house = "senate"
url = url.format(ordinal(int(row["congress"])),int(row['joint_resolution_number']),house)
return url
def tweet(self):
local_loc = os.path.dirname(__file__)
storage = QuickList().open(os.path.join(local_loc,
"..//schedules//us-nara-amending-america-dataset-raw-2016-02-25.xls"))
storage.shuffle()
storage.data = storage.data[:1]
for r in storage:
if r["year"] and r["title_or_description_from_source"]:
row = r
desc = row["title_or_description_from_source"]
"""
remove generic phrasing
"""
bad_terms=[
"Proposing an amendment to the Constitution of the United States relating to ",
"Proposing an amendment to the Constitution of the United States",
"A joint resolution proposing an amendment to the Constitution of the United States",
" to the Constitution of the United States.",
"A joint resolution proposing",
"A joint resolution proposing an amendment to the Constitution of the United States relative to ",
]
bad_terms.sort(key=lambda x:len(x), reverse=True)
for b in bad_terms:
desc = desc.replace(b,"")
"""
fix formatting
"""
desc = desc.strip()
if desc[0] == desc[0].lower():
desc = desc[0].upper() + desc[1:]
"""
are we able to provide a link to this?
"""
if row["year"] >= 1973 and row['joint_resolution_number']:
link = self.get_amendment_link(row)
allowed_length = 141 - 22
elif row['source_code'] == "A":
#link = "book"
allowed_length = 141
link = None
else:
link = None
allowed_length = 141
text = u"{0} - {1}".format(int(row["year"]),desc)
if len(text) > allowed_length:
long_text = text
if link == None:
#get pastebin version of this and get ready to link it
#link = self._paste_to_pastebin(long_text)
|
text = text[:allowed_length-3] + "..."
if link:
text += " " + link
return self._tweet(text)
if __name__ == "__main__":
AmendmentBot().populate(20) | if link: #pastebin might fail
allowed_length = 141 -22 | conditional_block |
SVG.js | /*
* L.SVG renders vector layers with SVG. All SVG-specific code goes here.
*/
L.SVG = L.Renderer.extend({
_initContainer: function () {
this._container = L.SVG.create('svg');
// makes it possible to click through svg root; we'll reset it back in individual paths
this._container.setAttribute('pointer-events', 'none');
},
_update: function () {
if (this._map._animatingZoom && this._bounds) { return; }
L.Renderer.prototype._update.call(this);
var b = this._bounds,
size = b.getSize(),
container = this._container;
L.DomUtil.setPosition(container, b.min);
// set size of svg-container if changed
if (!this._svgSize || !this._svgSize.equals(size)) {
this._svgSize = size;
container.setAttribute('width', size.x);
container.setAttribute('height', size.y);
}
// movement: update container viewBox so that we don't have to change coordinates of individual layers
L.DomUtil.setPosition(container, b.min);
container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
},
// methods below are called by vector layers implementations
_initPath: function (layer) {
var path = layer._path = L.SVG.create('path');
if (layer.options.className) {
L.DomUtil.addClass(path, layer.options.className);
}
if (layer.options.interactive) {
L.DomUtil.addClass(path, 'leaflet-interactive');
}
this._updateStyle(layer);
}, |
_removePath: function (layer) {
L.DomUtil.remove(layer._path);
layer.removeInteractiveTarget(layer._path);
},
_updatePath: function (layer) {
layer._project();
layer._update();
},
_updateStyle: function (layer) {
var path = layer._path,
options = layer.options;
if (!path) { return; }
if (options.stroke) {
path.setAttribute('stroke', options.color);
path.setAttribute('stroke-opacity', options.opacity);
path.setAttribute('stroke-width', options.weight);
path.setAttribute('stroke-linecap', options.lineCap);
path.setAttribute('stroke-linejoin', options.lineJoin);
if (options.dashArray) {
path.setAttribute('stroke-dasharray', options.dashArray);
} else {
path.removeAttribute('stroke-dasharray');
}
if (options.dashOffset) {
path.setAttribute('stroke-dashoffset', options.dashOffset);
} else {
path.removeAttribute('stroke-dashoffset');
}
} else {
path.setAttribute('stroke', 'none');
}
if (options.fill) {
path.setAttribute('fill', options.fillColor || options.color);
path.setAttribute('fill-opacity', options.fillOpacity);
path.setAttribute('fill-rule', options.fillRule || 'evenodd');
} else {
path.setAttribute('fill', 'none');
}
path.setAttribute('pointer-events', options.pointerEvents || (options.interactive ? 'visiblePainted' : 'none'));
},
_updatePoly: function (layer, closed) {
this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed));
},
_updateCircle: function (layer) {
var p = layer._point,
r = layer._radius,
r2 = layer._radiusY || r,
arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
// drawing a circle with two half-arcs
var d = layer._empty() ? 'M0 0' :
'M' + (p.x - r) + ',' + p.y +
arc + (r * 2) + ',0 ' +
arc + (-r * 2) + ',0 ';
this._setPath(layer, d);
},
_setPath: function (layer, path) {
layer._path.setAttribute('d', path);
},
// SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
_bringToFront: function (layer) {
L.DomUtil.toFront(layer._path);
},
_bringToBack: function (layer) {
L.DomUtil.toBack(layer._path);
}
});
L.extend(L.SVG, {
create: function (name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
},
// generates SVG path string for multiple rings, with each ring turning into "M..L..L.." instructions
pointsToPath: function (rings, closed) {
var str = '',
i, j, len, len2, points, p;
for (i = 0, len = rings.length; i < len; i++) {
points = rings[i];
for (j = 0, len2 = points.length; j < len2; j++) {
p = points[j];
str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
}
// closes the ring for polygons; "x" is VML syntax
str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
}
// SVG complains about empty path strings
return str || 'M0 0';
}
});
L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect);
L.svg = function (options) {
return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null;
}; |
_addPath: function (layer) {
this._container.appendChild(layer._path);
layer.addInteractiveTarget(layer._path);
}, | random_line_split |
SVG.js | /*
* L.SVG renders vector layers with SVG. All SVG-specific code goes here.
*/
L.SVG = L.Renderer.extend({
_initContainer: function () {
this._container = L.SVG.create('svg');
// makes it possible to click through svg root; we'll reset it back in individual paths
this._container.setAttribute('pointer-events', 'none');
},
_update: function () {
if (this._map._animatingZoom && this._bounds) { return; }
L.Renderer.prototype._update.call(this);
var b = this._bounds,
size = b.getSize(),
container = this._container;
L.DomUtil.setPosition(container, b.min);
// set size of svg-container if changed
if (!this._svgSize || !this._svgSize.equals(size)) {
this._svgSize = size;
container.setAttribute('width', size.x);
container.setAttribute('height', size.y);
}
// movement: update container viewBox so that we don't have to change coordinates of individual layers
L.DomUtil.setPosition(container, b.min);
container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
},
// methods below are called by vector layers implementations
_initPath: function (layer) {
var path = layer._path = L.SVG.create('path');
if (layer.options.className) {
L.DomUtil.addClass(path, layer.options.className);
}
if (layer.options.interactive) {
L.DomUtil.addClass(path, 'leaflet-interactive');
}
this._updateStyle(layer);
},
_addPath: function (layer) {
this._container.appendChild(layer._path);
layer.addInteractiveTarget(layer._path);
},
_removePath: function (layer) {
L.DomUtil.remove(layer._path);
layer.removeInteractiveTarget(layer._path);
},
_updatePath: function (layer) {
layer._project();
layer._update();
},
_updateStyle: function (layer) {
var path = layer._path,
options = layer.options;
if (!path) { return; }
if (options.stroke) {
path.setAttribute('stroke', options.color);
path.setAttribute('stroke-opacity', options.opacity);
path.setAttribute('stroke-width', options.weight);
path.setAttribute('stroke-linecap', options.lineCap);
path.setAttribute('stroke-linejoin', options.lineJoin);
if (options.dashArray) {
path.setAttribute('stroke-dasharray', options.dashArray);
} else {
path.removeAttribute('stroke-dasharray');
}
if (options.dashOffset) {
path.setAttribute('stroke-dashoffset', options.dashOffset);
} else {
path.removeAttribute('stroke-dashoffset');
}
} else {
path.setAttribute('stroke', 'none');
}
if (options.fill) | else {
path.setAttribute('fill', 'none');
}
path.setAttribute('pointer-events', options.pointerEvents || (options.interactive ? 'visiblePainted' : 'none'));
},
_updatePoly: function (layer, closed) {
this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed));
},
_updateCircle: function (layer) {
var p = layer._point,
r = layer._radius,
r2 = layer._radiusY || r,
arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
// drawing a circle with two half-arcs
var d = layer._empty() ? 'M0 0' :
'M' + (p.x - r) + ',' + p.y +
arc + (r * 2) + ',0 ' +
arc + (-r * 2) + ',0 ';
this._setPath(layer, d);
},
_setPath: function (layer, path) {
layer._path.setAttribute('d', path);
},
// SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
_bringToFront: function (layer) {
L.DomUtil.toFront(layer._path);
},
_bringToBack: function (layer) {
L.DomUtil.toBack(layer._path);
}
});
L.extend(L.SVG, {
create: function (name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
},
// generates SVG path string for multiple rings, with each ring turning into "M..L..L.." instructions
pointsToPath: function (rings, closed) {
var str = '',
i, j, len, len2, points, p;
for (i = 0, len = rings.length; i < len; i++) {
points = rings[i];
for (j = 0, len2 = points.length; j < len2; j++) {
p = points[j];
str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
}
// closes the ring for polygons; "x" is VML syntax
str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
}
// SVG complains about empty path strings
return str || 'M0 0';
}
});
L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect);
L.svg = function (options) {
return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null;
};
| {
path.setAttribute('fill', options.fillColor || options.color);
path.setAttribute('fill-opacity', options.fillOpacity);
path.setAttribute('fill-rule', options.fillRule || 'evenodd');
} | conditional_block |
feature_collection.rs | // Copyright 2015 The GeoRust Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use rustc_serialize::json::{self, Json, ToJson};
use ::{Bbox, Crs, Error, Feature, FromObject, util};
/// Feature Collection Objects
///
/// [GeoJSON Format Specification § 2.3]
/// (http://geojson.org/geojson-spec.html#feature-collection-objects) | pub struct FeatureCollection {
pub bbox: Option<Bbox>,
pub crs: Option<Crs>,
pub features: Vec<Feature>,
}
impl<'a> From<&'a FeatureCollection> for json::Object {
fn from(fc: &'a FeatureCollection) -> json::Object {
let mut map = BTreeMap::new();
map.insert(String::from("type"), "FeatureCollection".to_json());
map.insert(String::from("features"), fc.features.to_json());
if let Some(ref crs) = fc.crs {
map.insert(String::from("crs"), crs.to_json());
}
if let Some(ref bbox) = fc.bbox {
map.insert(String::from("bbox"), bbox.to_json());
}
return map;
}
}
impl FromObject for FeatureCollection {
fn from_object(object: &json::Object) -> Result<Self, Error> {
return Ok(FeatureCollection{
bbox: try!(util::get_bbox(object)),
features: try!(util::get_features(object)),
crs: try!(util::get_crs(object)),
});
}
}
impl ToJson for FeatureCollection {
fn to_json(&self) -> json::Json {
return json::Json::Object(self.into());
}
} | #[derive(Clone, Debug, PartialEq)] | random_line_split |
feature_collection.rs | // Copyright 2015 The GeoRust Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use rustc_serialize::json::{self, Json, ToJson};
use ::{Bbox, Crs, Error, Feature, FromObject, util};
/// Feature Collection Objects
///
/// [GeoJSON Format Specification § 2.3]
/// (http://geojson.org/geojson-spec.html#feature-collection-objects)
#[derive(Clone, Debug, PartialEq)]
pub struct FeatureCollection {
pub bbox: Option<Bbox>,
pub crs: Option<Crs>,
pub features: Vec<Feature>,
}
impl<'a> From<&'a FeatureCollection> for json::Object {
fn from(fc: &'a FeatureCollection) -> json::Object {
let mut map = BTreeMap::new();
map.insert(String::from("type"), "FeatureCollection".to_json());
map.insert(String::from("features"), fc.features.to_json());
if let Some(ref crs) = fc.crs {
map.insert(String::from("crs"), crs.to_json());
}
if let Some(ref bbox) = fc.bbox {
map.insert(String::from("bbox"), bbox.to_json());
}
return map;
}
}
impl FromObject for FeatureCollection {
fn from_object(object: &json::Object) -> Result<Self, Error> {
return Ok(FeatureCollection{
bbox: try!(util::get_bbox(object)),
features: try!(util::get_features(object)),
crs: try!(util::get_crs(object)),
});
}
}
impl ToJson for FeatureCollection {
fn t | &self) -> json::Json {
return json::Json::Object(self.into());
}
}
| o_json( | identifier_name |
feature_collection.rs | // Copyright 2015 The GeoRust Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use rustc_serialize::json::{self, Json, ToJson};
use ::{Bbox, Crs, Error, Feature, FromObject, util};
/// Feature Collection Objects
///
/// [GeoJSON Format Specification § 2.3]
/// (http://geojson.org/geojson-spec.html#feature-collection-objects)
#[derive(Clone, Debug, PartialEq)]
pub struct FeatureCollection {
pub bbox: Option<Bbox>,
pub crs: Option<Crs>,
pub features: Vec<Feature>,
}
impl<'a> From<&'a FeatureCollection> for json::Object {
fn from(fc: &'a FeatureCollection) -> json::Object {
let mut map = BTreeMap::new();
map.insert(String::from("type"), "FeatureCollection".to_json());
map.insert(String::from("features"), fc.features.to_json());
if let Some(ref crs) = fc.crs { |
if let Some(ref bbox) = fc.bbox {
map.insert(String::from("bbox"), bbox.to_json());
}
return map;
}
}
impl FromObject for FeatureCollection {
fn from_object(object: &json::Object) -> Result<Self, Error> {
return Ok(FeatureCollection{
bbox: try!(util::get_bbox(object)),
features: try!(util::get_features(object)),
crs: try!(util::get_crs(object)),
});
}
}
impl ToJson for FeatureCollection {
fn to_json(&self) -> json::Json {
return json::Json::Object(self.into());
}
}
|
map.insert(String::from("crs"), crs.to_json());
}
| conditional_block |
watcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IRawFileChange, toFileChangesEvent } from 'vs/workbench/services/files/node/watcher/common';
import { OutOfProcessWin32FolderWatcher } from 'vs/workbench/services/files/node/watcher/win32/csharpWatcherService';
import { FileChangesEvent } from 'vs/platform/files/common/files';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { normalize } from 'path';
import { rtrim, endsWith } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
export class FileWatcher {
private isDisposed: boolean;
constructor(
private contextService: IWorkspaceContextService,
private ignored: string[],
private onFileChanges: (changes: FileChangesEvent) => void,
private errorLogger: (msg: string) => void,
private verboseLogging: boolean
) |
public startWatching(): () => void {
let basePath: string = normalize(this.contextService.getWorkspace().folders[0].uri.fsPath);
if (basePath && basePath.indexOf('\\\\') === 0 && endsWith(basePath, sep)) {
// for some weird reason, node adds a trailing slash to UNC paths
// we never ever want trailing slashes as our base path unless
// someone opens root ("/").
// See also https://github.com/nodejs/io.js/issues/1765
basePath = rtrim(basePath, sep);
}
const watcher = new OutOfProcessWin32FolderWatcher(
basePath,
this.ignored,
events => this.onRawFileEvents(events),
error => this.onError(error),
this.verboseLogging
);
return () => {
this.isDisposed = true;
watcher.dispose();
};
}
private onRawFileEvents(events: IRawFileChange[]): void {
if (this.isDisposed) {
return;
}
// Emit through event emitter
if (events.length > 0) {
this.onFileChanges(toFileChangesEvent(events));
}
}
private onError(error: string): void {
if (!this.isDisposed) {
this.errorLogger(error);
}
}
} | {
} | identifier_body |
watcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IRawFileChange, toFileChangesEvent } from 'vs/workbench/services/files/node/watcher/common';
import { OutOfProcessWin32FolderWatcher } from 'vs/workbench/services/files/node/watcher/win32/csharpWatcherService';
import { FileChangesEvent } from 'vs/platform/files/common/files';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { normalize } from 'path';
import { rtrim, endsWith } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
export class FileWatcher {
private isDisposed: boolean;
constructor(
private contextService: IWorkspaceContextService,
private ignored: string[],
private onFileChanges: (changes: FileChangesEvent) => void,
private errorLogger: (msg: string) => void,
private verboseLogging: boolean
) {
}
public startWatching(): () => void {
let basePath: string = normalize(this.contextService.getWorkspace().folders[0].uri.fsPath);
if (basePath && basePath.indexOf('\\\\') === 0 && endsWith(basePath, sep)) |
const watcher = new OutOfProcessWin32FolderWatcher(
basePath,
this.ignored,
events => this.onRawFileEvents(events),
error => this.onError(error),
this.verboseLogging
);
return () => {
this.isDisposed = true;
watcher.dispose();
};
}
private onRawFileEvents(events: IRawFileChange[]): void {
if (this.isDisposed) {
return;
}
// Emit through event emitter
if (events.length > 0) {
this.onFileChanges(toFileChangesEvent(events));
}
}
private onError(error: string): void {
if (!this.isDisposed) {
this.errorLogger(error);
}
}
} | {
// for some weird reason, node adds a trailing slash to UNC paths
// we never ever want trailing slashes as our base path unless
// someone opens root ("/").
// See also https://github.com/nodejs/io.js/issues/1765
basePath = rtrim(basePath, sep);
} | conditional_block |
watcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IRawFileChange, toFileChangesEvent } from 'vs/workbench/services/files/node/watcher/common';
import { OutOfProcessWin32FolderWatcher } from 'vs/workbench/services/files/node/watcher/win32/csharpWatcherService';
import { FileChangesEvent } from 'vs/platform/files/common/files';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { normalize } from 'path';
import { rtrim, endsWith } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
export class FileWatcher {
private isDisposed: boolean;
constructor(
private contextService: IWorkspaceContextService,
private ignored: string[],
private onFileChanges: (changes: FileChangesEvent) => void,
private errorLogger: (msg: string) => void,
private verboseLogging: boolean
) {
}
public startWatching(): () => void {
let basePath: string = normalize(this.contextService.getWorkspace().folders[0].uri.fsPath);
if (basePath && basePath.indexOf('\\\\') === 0 && endsWith(basePath, sep)) {
// for some weird reason, node adds a trailing slash to UNC paths
// we never ever want trailing slashes as our base path unless
// someone opens root ("/").
// See also https://github.com/nodejs/io.js/issues/1765
basePath = rtrim(basePath, sep);
}
const watcher = new OutOfProcessWin32FolderWatcher(
basePath,
this.ignored,
events => this.onRawFileEvents(events),
error => this.onError(error),
this.verboseLogging
); | this.isDisposed = true;
watcher.dispose();
};
}
private onRawFileEvents(events: IRawFileChange[]): void {
if (this.isDisposed) {
return;
}
// Emit through event emitter
if (events.length > 0) {
this.onFileChanges(toFileChangesEvent(events));
}
}
private onError(error: string): void {
if (!this.isDisposed) {
this.errorLogger(error);
}
}
} |
return () => { | random_line_split |
watcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IRawFileChange, toFileChangesEvent } from 'vs/workbench/services/files/node/watcher/common';
import { OutOfProcessWin32FolderWatcher } from 'vs/workbench/services/files/node/watcher/win32/csharpWatcherService';
import { FileChangesEvent } from 'vs/platform/files/common/files';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { normalize } from 'path';
import { rtrim, endsWith } from 'vs/base/common/strings';
import { sep } from 'vs/base/common/paths';
export class | {
private isDisposed: boolean;
constructor(
private contextService: IWorkspaceContextService,
private ignored: string[],
private onFileChanges: (changes: FileChangesEvent) => void,
private errorLogger: (msg: string) => void,
private verboseLogging: boolean
) {
}
public startWatching(): () => void {
let basePath: string = normalize(this.contextService.getWorkspace().folders[0].uri.fsPath);
if (basePath && basePath.indexOf('\\\\') === 0 && endsWith(basePath, sep)) {
// for some weird reason, node adds a trailing slash to UNC paths
// we never ever want trailing slashes as our base path unless
// someone opens root ("/").
// See also https://github.com/nodejs/io.js/issues/1765
basePath = rtrim(basePath, sep);
}
const watcher = new OutOfProcessWin32FolderWatcher(
basePath,
this.ignored,
events => this.onRawFileEvents(events),
error => this.onError(error),
this.verboseLogging
);
return () => {
this.isDisposed = true;
watcher.dispose();
};
}
private onRawFileEvents(events: IRawFileChange[]): void {
if (this.isDisposed) {
return;
}
// Emit through event emitter
if (events.length > 0) {
this.onFileChanges(toFileChangesEvent(events));
}
}
private onError(error: string): void {
if (!this.isDisposed) {
this.errorLogger(error);
}
}
} | FileWatcher | identifier_name |
color.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 azure::AzFloat;
use azure::azure::AzColor;
#[inline]
pub fn new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor |
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn black() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
}
#[inline]
pub fn transparent() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
}
#[inline]
pub fn white() -> AzColor {
AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
}
| {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
} | identifier_body |
color.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 azure::AzFloat;
use azure::azure::AzColor;
#[inline]
pub fn new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { | pub fn black() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
}
#[inline]
pub fn transparent() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
}
#[inline]
pub fn white() -> AzColor {
AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
} | AzColor { r: r, g: g, b: b, a: a }
}
#[inline] | random_line_split |
color.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 azure::AzFloat;
use azure::azure::AzColor;
#[inline]
pub fn | (r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> AzColor {
AzColor {
r: (r as AzFloat) / (255.0 as AzFloat),
g: (g as AzFloat) / (255.0 as AzFloat),
b: (b as AzFloat) / (255.0 as AzFloat),
a: 1.0 as AzFloat
}
}
#[inline]
pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor {
AzColor { r: r, g: g, b: b, a: a }
}
#[inline]
pub fn black() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
}
#[inline]
pub fn transparent() -> AzColor {
AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
}
#[inline]
pub fn white() -> AzColor {
AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
}
| new | identifier_name |
error_page_embed.py | from __future__ import absolute_import
from django import forms
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_exempt
from sentry.models import (
EventMapping, Group, ProjectKey, ProjectOption, UserReport
)
from sentry.web.helpers import render_to_response
from sentry.utils import json
from sentry.utils.http import is_valid_origin
from sentry.utils.validators import is_event_id
class UserReportForm(forms.ModelForm):
name = forms.CharField(max_length=128, widget=forms.TextInput(attrs={
'placeholder': 'Jane Doe',
}))
email = forms.EmailField(max_length=75, widget=forms.TextInput(attrs={
'placeholder': 'jane@example.com',
'type': 'email',
}))
comments = forms.CharField(widget=forms.Textarea(attrs={
'placeholder': "I clicked on 'X' and then hit 'Confirm'",
}))
class Meta:
model = UserReport
fields = ('name', 'email', 'comments')
class ErrorPageEmbedView(View):
def _get_project_key(self, request):
try:
dsn = request.GET['dsn']
except KeyError:
return
try:
key = ProjectKey.from_dsn(dsn)
except ProjectKey.DoesNotExist:
return
return key
def _get_origin(self, request):
return request.META.get('HTTP_ORIGIN', request.META.get('HTTP_REFERER'))
def _json_response(self, request, context=None, status=200):
if context:
content = json.dumps(context)
else:
|
response = HttpResponse(content, status=status, content_type='application/json')
response['Access-Control-Allow-Origin'] = request.META.get('HTTP_ORIGIN', '')
response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response['Access-Control-Max-Age'] = '1000'
response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
return response
@csrf_exempt
def dispatch(self, request):
try:
event_id = request.GET['eventId']
except KeyError:
return self._json_response(request, status=400)
if not is_event_id(event_id):
return self._json_response(request, status=400)
key = self._get_project_key(request)
if not key:
return self._json_response(request, status=404)
origin = self._get_origin(request)
if not origin:
return self._json_response(request, status=403)
if not is_valid_origin(origin, key.project):
return HttpResponse(status=403)
if request.method == 'OPTIONS':
return self._json_response(request)
# TODO(dcramer): since we cant use a csrf cookie we should at the very
# least sign the request / add some kind of nonce
initial = {
'name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
# TODO(dcramer): move this to post to the internal API
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
mapping = EventMapping.objects.get(
event_id=report.event_id,
project_id=key.project_id,
)
except EventMapping.DoesNotExist:
# XXX(dcramer): the system should fill this in later
pass
else:
report.group = Group.objects.get(id=mapping.group_id)
try:
with transaction.atomic():
report.save()
except IntegrityError:
# There was a duplicate, so just overwrite the existing
# row with the new one. The only way this ever happens is
# if someone is messing around with the API, or doing
# something wrong with the SDK, but this behavior is
# more reasonable than just hard erroring and is more
# expected.
UserReport.objects.filter(
project=report.project,
event_id=report.event_id,
).update(
name=report.name,
email=report.email,
comments=report.comments,
date_added=timezone.now(),
)
return self._json_response(request)
elif request.method == 'POST':
return self._json_response(request, {
"errors": dict(form.errors),
}, status=400)
show_branding = ProjectOption.objects.get_value(
project=key.project,
key='feedback:branding',
default='1'
) == '1'
template = render_to_string('sentry/error-page-embed.html', {
'form': form,
'show_branding': show_branding,
})
context = {
'endpoint': mark_safe('*/' + json.dumps(request.build_absolute_uri()) + ';/*'),
'template': mark_safe('*/' + json.dumps(template) + ';/*'),
}
return render_to_response('sentry/error-page-embed.js', context, request,
content_type='text/javascript')
| content = '' | conditional_block |
error_page_embed.py | from __future__ import absolute_import
from django import forms
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_exempt
from sentry.models import (
EventMapping, Group, ProjectKey, ProjectOption, UserReport
)
from sentry.web.helpers import render_to_response
from sentry.utils import json
from sentry.utils.http import is_valid_origin
from sentry.utils.validators import is_event_id
class UserReportForm(forms.ModelForm):
name = forms.CharField(max_length=128, widget=forms.TextInput(attrs={
'placeholder': 'Jane Doe',
}))
email = forms.EmailField(max_length=75, widget=forms.TextInput(attrs={
'placeholder': 'jane@example.com',
'type': 'email',
}))
comments = forms.CharField(widget=forms.Textarea(attrs={
'placeholder': "I clicked on 'X' and then hit 'Confirm'",
}))
class Meta:
model = UserReport
fields = ('name', 'email', 'comments') |
class ErrorPageEmbedView(View):
def _get_project_key(self, request):
try:
dsn = request.GET['dsn']
except KeyError:
return
try:
key = ProjectKey.from_dsn(dsn)
except ProjectKey.DoesNotExist:
return
return key
def _get_origin(self, request):
return request.META.get('HTTP_ORIGIN', request.META.get('HTTP_REFERER'))
def _json_response(self, request, context=None, status=200):
if context:
content = json.dumps(context)
else:
content = ''
response = HttpResponse(content, status=status, content_type='application/json')
response['Access-Control-Allow-Origin'] = request.META.get('HTTP_ORIGIN', '')
response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response['Access-Control-Max-Age'] = '1000'
response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
return response
@csrf_exempt
def dispatch(self, request):
try:
event_id = request.GET['eventId']
except KeyError:
return self._json_response(request, status=400)
if not is_event_id(event_id):
return self._json_response(request, status=400)
key = self._get_project_key(request)
if not key:
return self._json_response(request, status=404)
origin = self._get_origin(request)
if not origin:
return self._json_response(request, status=403)
if not is_valid_origin(origin, key.project):
return HttpResponse(status=403)
if request.method == 'OPTIONS':
return self._json_response(request)
# TODO(dcramer): since we cant use a csrf cookie we should at the very
# least sign the request / add some kind of nonce
initial = {
'name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
# TODO(dcramer): move this to post to the internal API
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
mapping = EventMapping.objects.get(
event_id=report.event_id,
project_id=key.project_id,
)
except EventMapping.DoesNotExist:
# XXX(dcramer): the system should fill this in later
pass
else:
report.group = Group.objects.get(id=mapping.group_id)
try:
with transaction.atomic():
report.save()
except IntegrityError:
# There was a duplicate, so just overwrite the existing
# row with the new one. The only way this ever happens is
# if someone is messing around with the API, or doing
# something wrong with the SDK, but this behavior is
# more reasonable than just hard erroring and is more
# expected.
UserReport.objects.filter(
project=report.project,
event_id=report.event_id,
).update(
name=report.name,
email=report.email,
comments=report.comments,
date_added=timezone.now(),
)
return self._json_response(request)
elif request.method == 'POST':
return self._json_response(request, {
"errors": dict(form.errors),
}, status=400)
show_branding = ProjectOption.objects.get_value(
project=key.project,
key='feedback:branding',
default='1'
) == '1'
template = render_to_string('sentry/error-page-embed.html', {
'form': form,
'show_branding': show_branding,
})
context = {
'endpoint': mark_safe('*/' + json.dumps(request.build_absolute_uri()) + ';/*'),
'template': mark_safe('*/' + json.dumps(template) + ';/*'),
}
return render_to_response('sentry/error-page-embed.js', context, request,
content_type='text/javascript') | random_line_split | |
error_page_embed.py | from __future__ import absolute_import
from django import forms
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_exempt
from sentry.models import (
EventMapping, Group, ProjectKey, ProjectOption, UserReport
)
from sentry.web.helpers import render_to_response
from sentry.utils import json
from sentry.utils.http import is_valid_origin
from sentry.utils.validators import is_event_id
class UserReportForm(forms.ModelForm):
name = forms.CharField(max_length=128, widget=forms.TextInput(attrs={
'placeholder': 'Jane Doe',
}))
email = forms.EmailField(max_length=75, widget=forms.TextInput(attrs={
'placeholder': 'jane@example.com',
'type': 'email',
}))
comments = forms.CharField(widget=forms.Textarea(attrs={
'placeholder': "I clicked on 'X' and then hit 'Confirm'",
}))
class Meta:
|
class ErrorPageEmbedView(View):
def _get_project_key(self, request):
try:
dsn = request.GET['dsn']
except KeyError:
return
try:
key = ProjectKey.from_dsn(dsn)
except ProjectKey.DoesNotExist:
return
return key
def _get_origin(self, request):
return request.META.get('HTTP_ORIGIN', request.META.get('HTTP_REFERER'))
def _json_response(self, request, context=None, status=200):
if context:
content = json.dumps(context)
else:
content = ''
response = HttpResponse(content, status=status, content_type='application/json')
response['Access-Control-Allow-Origin'] = request.META.get('HTTP_ORIGIN', '')
response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response['Access-Control-Max-Age'] = '1000'
response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
return response
@csrf_exempt
def dispatch(self, request):
try:
event_id = request.GET['eventId']
except KeyError:
return self._json_response(request, status=400)
if not is_event_id(event_id):
return self._json_response(request, status=400)
key = self._get_project_key(request)
if not key:
return self._json_response(request, status=404)
origin = self._get_origin(request)
if not origin:
return self._json_response(request, status=403)
if not is_valid_origin(origin, key.project):
return HttpResponse(status=403)
if request.method == 'OPTIONS':
return self._json_response(request)
# TODO(dcramer): since we cant use a csrf cookie we should at the very
# least sign the request / add some kind of nonce
initial = {
'name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
# TODO(dcramer): move this to post to the internal API
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
mapping = EventMapping.objects.get(
event_id=report.event_id,
project_id=key.project_id,
)
except EventMapping.DoesNotExist:
# XXX(dcramer): the system should fill this in later
pass
else:
report.group = Group.objects.get(id=mapping.group_id)
try:
with transaction.atomic():
report.save()
except IntegrityError:
# There was a duplicate, so just overwrite the existing
# row with the new one. The only way this ever happens is
# if someone is messing around with the API, or doing
# something wrong with the SDK, but this behavior is
# more reasonable than just hard erroring and is more
# expected.
UserReport.objects.filter(
project=report.project,
event_id=report.event_id,
).update(
name=report.name,
email=report.email,
comments=report.comments,
date_added=timezone.now(),
)
return self._json_response(request)
elif request.method == 'POST':
return self._json_response(request, {
"errors": dict(form.errors),
}, status=400)
show_branding = ProjectOption.objects.get_value(
project=key.project,
key='feedback:branding',
default='1'
) == '1'
template = render_to_string('sentry/error-page-embed.html', {
'form': form,
'show_branding': show_branding,
})
context = {
'endpoint': mark_safe('*/' + json.dumps(request.build_absolute_uri()) + ';/*'),
'template': mark_safe('*/' + json.dumps(template) + ';/*'),
}
return render_to_response('sentry/error-page-embed.js', context, request,
content_type='text/javascript')
| model = UserReport
fields = ('name', 'email', 'comments') | identifier_body |
error_page_embed.py | from __future__ import absolute_import
from django import forms
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_exempt
from sentry.models import (
EventMapping, Group, ProjectKey, ProjectOption, UserReport
)
from sentry.web.helpers import render_to_response
from sentry.utils import json
from sentry.utils.http import is_valid_origin
from sentry.utils.validators import is_event_id
class UserReportForm(forms.ModelForm):
name = forms.CharField(max_length=128, widget=forms.TextInput(attrs={
'placeholder': 'Jane Doe',
}))
email = forms.EmailField(max_length=75, widget=forms.TextInput(attrs={
'placeholder': 'jane@example.com',
'type': 'email',
}))
comments = forms.CharField(widget=forms.Textarea(attrs={
'placeholder': "I clicked on 'X' and then hit 'Confirm'",
}))
class Meta:
model = UserReport
fields = ('name', 'email', 'comments')
class | (View):
def _get_project_key(self, request):
try:
dsn = request.GET['dsn']
except KeyError:
return
try:
key = ProjectKey.from_dsn(dsn)
except ProjectKey.DoesNotExist:
return
return key
def _get_origin(self, request):
return request.META.get('HTTP_ORIGIN', request.META.get('HTTP_REFERER'))
def _json_response(self, request, context=None, status=200):
if context:
content = json.dumps(context)
else:
content = ''
response = HttpResponse(content, status=status, content_type='application/json')
response['Access-Control-Allow-Origin'] = request.META.get('HTTP_ORIGIN', '')
response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response['Access-Control-Max-Age'] = '1000'
response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
return response
@csrf_exempt
def dispatch(self, request):
try:
event_id = request.GET['eventId']
except KeyError:
return self._json_response(request, status=400)
if not is_event_id(event_id):
return self._json_response(request, status=400)
key = self._get_project_key(request)
if not key:
return self._json_response(request, status=404)
origin = self._get_origin(request)
if not origin:
return self._json_response(request, status=403)
if not is_valid_origin(origin, key.project):
return HttpResponse(status=403)
if request.method == 'OPTIONS':
return self._json_response(request)
# TODO(dcramer): since we cant use a csrf cookie we should at the very
# least sign the request / add some kind of nonce
initial = {
'name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
# TODO(dcramer): move this to post to the internal API
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
mapping = EventMapping.objects.get(
event_id=report.event_id,
project_id=key.project_id,
)
except EventMapping.DoesNotExist:
# XXX(dcramer): the system should fill this in later
pass
else:
report.group = Group.objects.get(id=mapping.group_id)
try:
with transaction.atomic():
report.save()
except IntegrityError:
# There was a duplicate, so just overwrite the existing
# row with the new one. The only way this ever happens is
# if someone is messing around with the API, or doing
# something wrong with the SDK, but this behavior is
# more reasonable than just hard erroring and is more
# expected.
UserReport.objects.filter(
project=report.project,
event_id=report.event_id,
).update(
name=report.name,
email=report.email,
comments=report.comments,
date_added=timezone.now(),
)
return self._json_response(request)
elif request.method == 'POST':
return self._json_response(request, {
"errors": dict(form.errors),
}, status=400)
show_branding = ProjectOption.objects.get_value(
project=key.project,
key='feedback:branding',
default='1'
) == '1'
template = render_to_string('sentry/error-page-embed.html', {
'form': form,
'show_branding': show_branding,
})
context = {
'endpoint': mark_safe('*/' + json.dumps(request.build_absolute_uri()) + ';/*'),
'template': mark_safe('*/' + json.dumps(template) + ';/*'),
}
return render_to_response('sentry/error-page-embed.js', context, request,
content_type='text/javascript')
| ErrorPageEmbedView | identifier_name |
factories.py | import uuid
import factory.fuzzy
from django.conf import settings
from .. import models
from utils.factories import FuzzyMoney
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = settings.AUTH_USER_MODEL
username = factory.Sequence('terminator{0}'.format)
email = factory.Sequence('terminator{0}@skynet.com'.format)
password = 'hunter2'
is_superuser = False
is_staff = False
@classmethod
def _create(cls, model_class, *args, **kwargs):
manager = cls._get_manager(model_class)
return manager.create_user(*args, **kwargs)
class AccountFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Account
user = factory.SubFactory(UserFactory)
class CardFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Card
account = factory.SubFactory(AccountFactory)
number = factory.fuzzy.FuzzyInteger(0, (1 << 32) - 1)
class PurchaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Purchase
account = factory.SubFactory(AccountFactory)
amount = factory.fuzzy.FuzzyInteger(0, 1337)
class PurchaseItemFactory(factory.django.DjangoModelFactory):
|
class PurchaseStatusFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.PurchaseStatus
purchase = factory.SubFactory(PurchaseFactory)
| class Meta:
model = models.PurchaseItem
purchase = factory.SubFactory(PurchaseFactory)
product_id = factory.fuzzy.FuzzyAttribute(uuid.uuid4)
qty = 1
amount = FuzzyMoney(0, 1000) | identifier_body |
factories.py | import uuid
import factory.fuzzy
from django.conf import settings | class UserFactory(factory.DjangoModelFactory):
class Meta:
model = settings.AUTH_USER_MODEL
username = factory.Sequence('terminator{0}'.format)
email = factory.Sequence('terminator{0}@skynet.com'.format)
password = 'hunter2'
is_superuser = False
is_staff = False
@classmethod
def _create(cls, model_class, *args, **kwargs):
manager = cls._get_manager(model_class)
return manager.create_user(*args, **kwargs)
class AccountFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Account
user = factory.SubFactory(UserFactory)
class CardFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Card
account = factory.SubFactory(AccountFactory)
number = factory.fuzzy.FuzzyInteger(0, (1 << 32) - 1)
class PurchaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Purchase
account = factory.SubFactory(AccountFactory)
amount = factory.fuzzy.FuzzyInteger(0, 1337)
class PurchaseItemFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.PurchaseItem
purchase = factory.SubFactory(PurchaseFactory)
product_id = factory.fuzzy.FuzzyAttribute(uuid.uuid4)
qty = 1
amount = FuzzyMoney(0, 1000)
class PurchaseStatusFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.PurchaseStatus
purchase = factory.SubFactory(PurchaseFactory) | from .. import models
from utils.factories import FuzzyMoney
| random_line_split |
factories.py | import uuid
import factory.fuzzy
from django.conf import settings
from .. import models
from utils.factories import FuzzyMoney
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = settings.AUTH_USER_MODEL
username = factory.Sequence('terminator{0}'.format)
email = factory.Sequence('terminator{0}@skynet.com'.format)
password = 'hunter2'
is_superuser = False
is_staff = False
@classmethod
def _create(cls, model_class, *args, **kwargs):
manager = cls._get_manager(model_class)
return manager.create_user(*args, **kwargs)
class AccountFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Account
user = factory.SubFactory(UserFactory)
class CardFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Card
account = factory.SubFactory(AccountFactory)
number = factory.fuzzy.FuzzyInteger(0, (1 << 32) - 1)
class PurchaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Purchase
account = factory.SubFactory(AccountFactory)
amount = factory.fuzzy.FuzzyInteger(0, 1337)
class PurchaseItemFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.PurchaseItem
purchase = factory.SubFactory(PurchaseFactory)
product_id = factory.fuzzy.FuzzyAttribute(uuid.uuid4)
qty = 1
amount = FuzzyMoney(0, 1000)
class | (factory.django.DjangoModelFactory):
class Meta:
model = models.PurchaseStatus
purchase = factory.SubFactory(PurchaseFactory)
| PurchaseStatusFactory | identifier_name |
vm.ts | import { createContext, isContext, Script, runInNewContext, runInThisContext, compileFunction } from 'vm';
import { inspect } from 'util';
{
const sandbox = {
animal: 'cat',
count: 2
};
const context = createContext(sandbox, {
name: 'test',
origin: 'file://test.js',
codeGeneration: {
strings: true,
wasm: true,
},
});
console.log(isContext(context));
const script = new Script('count += 1; name = "kitty"');
for (let i = 0; i < 10; ++i) {
script.runInContext(context);
}
console.log(inspect(sandbox));
runInNewContext('count += 1; name = "kitty"', sandbox); |
const script = new Script('globalVar = "set"');
sandboxes.forEach((sandbox) => {
script.runInNewContext(sandbox);
script.runInThisContext();
});
console.log(inspect(sandboxes));
const localVar = 'initial value';
runInThisContext('localVar = "vm";');
console.log(localVar);
}
{
runInThisContext('console.log("hello world"', './my-file.js');
}
{
const fn: Function = compileFunction('console.log("test")', [] as ReadonlyArray<string>, {
parsingContext: createContext(),
contextExtensions: [{
a: 1,
}],
produceCachedData: false,
cachedData: Buffer.from('nope'),
});
} | console.log(inspect(sandbox));
}
{
const sandboxes = [{}, {}, {}]; | random_line_split |
vm.ts | import { createContext, isContext, Script, runInNewContext, runInThisContext, compileFunction } from 'vm';
import { inspect } from 'util';
{
const sandbox = {
animal: 'cat',
count: 2
};
const context = createContext(sandbox, {
name: 'test',
origin: 'file://test.js',
codeGeneration: {
strings: true,
wasm: true,
},
});
console.log(isContext(context));
const script = new Script('count += 1; name = "kitty"');
for (let i = 0; i < 10; ++i) |
console.log(inspect(sandbox));
runInNewContext('count += 1; name = "kitty"', sandbox);
console.log(inspect(sandbox));
}
{
const sandboxes = [{}, {}, {}];
const script = new Script('globalVar = "set"');
sandboxes.forEach((sandbox) => {
script.runInNewContext(sandbox);
script.runInThisContext();
});
console.log(inspect(sandboxes));
const localVar = 'initial value';
runInThisContext('localVar = "vm";');
console.log(localVar);
}
{
runInThisContext('console.log("hello world"', './my-file.js');
}
{
const fn: Function = compileFunction('console.log("test")', [] as ReadonlyArray<string>, {
parsingContext: createContext(),
contextExtensions: [{
a: 1,
}],
produceCachedData: false,
cachedData: Buffer.from('nope'),
});
}
| {
script.runInContext(context);
} | conditional_block |
matchUsers_page_common.js | function requestDialogList(){
$.ajax({
url:"http://xunta.so:3000/v1/chat_list",
type:"POST",
dataType:"jsonp",
jsonp:"callback",
contentType: "application/json; charset=utf-8",
data:{
from_user_id:userId
},
async:false,
success:function(data, textStatus) {
console.log("聊天列表请求成功"+data);
showDialogList(data);
},
error:function(data, textStatus) {
console.log("聊天列表请求错误"+data);
return;
}
});
}
//进入聊天页,别人的uid和我的uid都需要
function enterDialogPage(toUserId,toUserName,toUserImgUrl) {
var pageParam = {
"toUserId" : toUserId,
"toUserName" : | toUserName,//这里是为了测试
"toUserImage" : toUserImgUrl,
"userid" : userId,
"userName" : userName,
"userImage" : userImage,
"server_domain" : domain,
"userAgent":userAgent,
"topicPageSign":"yes"
};
console.log("enterDialogPage toUserId=" + toUserId+"|toUserName="+toUserName);
// openWin(topicid,'dialog_page/dialog_page.html',JSON.stringify(pageParam));
openWin(toUserId,'dialog_page/dialog_page.html',JSON.stringify(pageParam));
} | identifier_body | |
matchUsers_page_common.js | function requestDialogList(){
$.ajax({
url:"http://xunta.so:3000/v1/chat_list",
type:"POST",
dataType:"jsonp",
jsonp:"callback",
contentType: "application/json; charset=utf-8",
data:{
from_user_id:userId
},
async:false,
success:function(data, textStatus) {
console.log("聊天列表请求成功"+data);
showDialogList(data);
},
error:function(data, textStatus) {
console.log("聊天列表请求错误"+data);
return;
}
});
}
//进入聊天页,别人的uid和我的uid都需要
function enterDialogPage(toUserId,toUserName,toUserImgUrl) {
var pageP | serId" : toUserId,
"toUserName" : toUserName,//这里是为了测试
"toUserImage" : toUserImgUrl,
"userid" : userId,
"userName" : userName,
"userImage" : userImage,
"server_domain" : domain,
"userAgent":userAgent,
"topicPageSign":"yes"
};
console.log("enterDialogPage toUserId=" + toUserId+"|toUserName="+toUserName);
// openWin(topicid,'dialog_page/dialog_page.html',JSON.stringify(pageParam));
openWin(toUserId,'dialog_page/dialog_page.html',JSON.stringify(pageParam));
} | aram = {
"toU | identifier_name |
matchUsers_page_common.js | function requestDialogList(){
$.ajax({
url:"http://xunta.so:3000/v1/chat_list",
type:"POST",
dataType:"jsonp",
jsonp:"callback",
contentType: "application/json; charset=utf-8",
data:{
from_user_id:userId
},
async:false,
success:function(data, textStatus) {
console.log("聊天列表请求成功"+data);
showDialogList(data);
},
error:function(data, textStatus) {
console.log("聊天列表请求错误"+data);
return;
}
});
}
//进入聊天页,别人的uid和我的uid都需要
function enterDialogPage(toUserId,toUserName,toUserImgUrl) {
var pageParam = {
"toUserId" : toUserId,
"toUserName" : toUserName,//这里是为了测试
"toUserImage" : toUserImgUrl,
"userid" : userId,
"userName" : userName,
"userImage" : userImage,
"server_domain" : domain, | // openWin(topicid,'dialog_page/dialog_page.html',JSON.stringify(pageParam));
openWin(toUserId,'dialog_page/dialog_page.html',JSON.stringify(pageParam));
} | "userAgent":userAgent,
"topicPageSign":"yes"
};
console.log("enterDialogPage toUserId=" + toUserId+"|toUserName="+toUserName); | random_line_split |
createProgramFromFiles.js | define([
'webgl/createProgram',
'webgl/shader/compileShaderFromFile'
], function(
createProgram,
compileShaderFromFile
) {
/**
* Creates a program from 2 script tags.
*
* @param {!WebGLRenderingContext} gl The WebGL Context.
* @param {string} vertexShaderFileName The file name of the vertex shader.
* @param {string} fragmentShaderFileName The file name of the fragment shader.
* @return {!WebGLProgram} A program
*/
return function createProgramFromScripts(gl, vertexShaderFileName, fragmentShaderFileName, callback) {
var async = !!callback;
if(async) {
compileShaderFromFile(gl, vertexShaderFileName, 'vertex', function(vertexShader) {
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment', function(fragmentShader) {
callback(createProgram(gl, vertexShader, fragmentShader));
});
});
}
else |
};
}); | {
return createProgram(gl,
compileShaderFromFile(gl, vertexShaderFileName, 'vertex'),
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment'));
} | conditional_block |
createProgramFromFiles.js | define([
'webgl/createProgram',
'webgl/shader/compileShaderFromFile'
], function( | *
* @param {!WebGLRenderingContext} gl The WebGL Context.
* @param {string} vertexShaderFileName The file name of the vertex shader.
* @param {string} fragmentShaderFileName The file name of the fragment shader.
* @return {!WebGLProgram} A program
*/
return function createProgramFromScripts(gl, vertexShaderFileName, fragmentShaderFileName, callback) {
var async = !!callback;
if(async) {
compileShaderFromFile(gl, vertexShaderFileName, 'vertex', function(vertexShader) {
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment', function(fragmentShader) {
callback(createProgram(gl, vertexShader, fragmentShader));
});
});
}
else {
return createProgram(gl,
compileShaderFromFile(gl, vertexShaderFileName, 'vertex'),
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment'));
}
};
}); | createProgram,
compileShaderFromFile
) {
/**
* Creates a program from 2 script tags. | random_line_split |
DTD.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Deals with DTD files. Primarily, provides the DTD parser and Python
"compiler".
"""
import sys, os
from pycopia import sourcegen
from pycopia.textutils import identifier, keyword_identifier
import pycopia.XML.POM
from pycopia.XML.POM import (ContentModel, ElementNode, Notation, ValidationError,
normalize_unicode)
from pycopia.XML.POMparse import (XMLAttribute, ANY, PCDATA, EMPTY)
### DTD compiler components ###
def get_dtd_compiler(fo, mixinmodule=None, doctype=None):
import xml
if hasattr(xml, "use_pyxml"): # per Gentoo bug #367729
xml.use_pyxml()
from xml.parsers.xmlproc.dtdparser import DTDParser
generator = sourcegen.get_sourcefile(fo)
dh = DTDConsumerForSourceGeneration(generator, mixinmodule, doctype)
parser = DTDParser()
parser.set_dtd_consumer(dh)
return parser
def get_identifier(uname):
return identifier(normalize_unicode(uname))
class AttributeMap(dict):
def __repr__(self):
s = ["{"]
for t in self.items():
s.append("%r: %s, " % t)
s.append("}")
return "\n ".join(s)
# this DTD parser consumer generates the Python source code from the DTD.
class DTDConsumerForSourceGeneration(object):
def __init__(self, generator, mixins=None, doctype=None):
self.generator = generator
self._code_index = 0
self.elements = {}
self.parameter_entities = {}
self.general_entities = {}
self._forwardattributes = {}
self._allattributes = {}
self.mixins = mixins # should be a module object
self.doctype = doctype
def dtd_start(self):
print "Starting to parse DTD...",
self.generator.add_comment("This file generated by a program. do not edit.")
self.generator.add_import(pycopia.XML.POM)
if self.mixins:
self.generator.add_import(self.mixins)
self.generator.add_blank()
self._code_index = self.generator.get_current_index()
def | (self):
print "done parsing. Writing file."
gen = self.generator
for name, value in self._allattributes.items():
gen.add_code("%s = %r" % (name, value), index=2)
gen.add_instance("GENERAL_ENTITIES", self.general_entities)
gen.add_comment("Cache for dynamic classes for this dtd.")
gen.add_instance("_CLASSCACHE", {})
gen.write()
def new_element_type(self, elem_name, elem_cont):
"Receives the declaration of an element type."
try:
element = self.elements[elem_name]
except KeyError:
self.make_new_element(elem_name, elem_cont)
def make_new_element(self, elem_name, contentmodel):
parents = [ElementNode]
if self.mixins:
mixinname = "%sMixin" % ( get_identifier(elem_name) )
if hasattr(self.mixins, mixinname):
parents.insert(0, getattr(self.mixins, mixinname))
# class name is capitalized to avoid clashes with Python key words.
ch = self.generator.add_class(get_identifier(elem_name), tuple(parents))
ch.add_attribute("_name", elem_name)
ch.add_attribute("CONTENTMODEL", _ContentModelGenerator(contentmodel))
self.elements[elem_name] = ch
# Add any previously seen attributes
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem_name]
except KeyError:
pass
else:
ch.add_attribute("ATTRIBUTES", fwdattribs)
ch.add_attribute("KWATTRIBUTES", fwdkwattribs)
del self._forwardattributes[elem_name]
# identify the root element with a generic name (_Root).
if self.doctype and elem_name.lower() == self.doctype.name.lower():
self.generator.add_code("\n_Root = %s\n" % (get_identifier(elem_name),))
def new_attribute(self, elem, a_name, a_type, a_decl, a_def):
"Receives the declaration of a new attribute."
attr = XMLAttribute(a_name, a_type, a_decl, a_def)
ident = attr.get_identifier()
self._allattributes[ident] = attr
try:
element = self.elements[elem]
except KeyError:
# Got a forward attribute definition (defined before element)
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem]
except KeyError:
fwdattribs = AttributeMap()
fwdkwattribs = AttributeMap()
self._forwardattributes[elem] = (fwdattribs, fwdkwattribs)
fwdattribs[a_name] = ident
keywordname = keyword_identifier(normalize_unicode(a_name))
fwdkwattribs[keywordname] = ident
else:
self._add_element_attlist(element, attr, ident)
def _add_element_attlist(self, element, xmlattribute, ident):
try:
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
except KeyError:
element.add_attribute("ATTRIBUTES", AttributeMap())
element.add_attribute("KWATTRIBUTES", AttributeMap())
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
attrmap[xmlattribute.name] = ident
keywordname = keyword_identifier(normalize_unicode(xmlattribute.name))
kwattrmap[keywordname] = ident
def handle_comment(self, contents):
"Receives the contents of a comment."
self.generator.add_comment(contents)
def new_parameter_entity(self,name,val):
"Receives internal parameter entity declarations."
# these are handled internally by the DTD parser. but.. save it anyway.
self.parameter_entities[name] = val
def new_external_pe(self, name, pubid, sysid):
"Receives external parameter entity declarations."
# these are handled internally by the DTD parser.
def new_general_entity(self, name, val):
"Receives internal general entity declarations."
self.general_entities[normalize_unicode(name)] = val
def new_external_entity(self, ent_name, pub_id, sys_id, ndata):
"""Receives external general entity declarations. 'ndata' is the
empty string if the entity is parsed."""
# XXX do we need to handle this?
print "XXX external entity:"
print ent_name, pub_id, sys_id, ndata
def new_notation(self,name, pubid, sysid):
"Receives notation declarations."
n = Notation(name, pubid, sysid)
self.generator.add_instance(get_identifier(name), n)
def handle_pi(self, target, data):
"Receives the target and data of processing instructions."
# XXX do we need to handle this?
print "XXX unhandled PI:",
print "target=%r; data=%r" % (target, data)
class _ContentModelGenerator(object):
"""_ContentModelGenerator(rawmodel)
The DTD parser generated and final content model are so different that a
different content model generator is used for this object.
"""
def __init__(self, rawmodel=None):
tm_type = type(rawmodel)
if tm_type is str:
if rawmodel == "EMPTY":
self.model = EMPTY
elif rawmodel == "#PCDATA":
self.model = PCDATA
elif rawmodel == "ANY":
self.model = ANY
else:
raise ValidationError, "ContentModelGenerator: unknown special type"
elif tm_type is tuple:
self.model = (ANY,) # rawmodel # XXX
elif tm_type is type(None):
self.model = None
else:
raise RuntimeError, "Unknown content model type: %r" % (rawmodel,)
def __repr__(self):
return "%s.%s(%r)" % (ContentModel.__module__, ContentModel.__name__, self.model)
| dtd_end | identifier_name |
DTD.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Deals with DTD files. Primarily, provides the DTD parser and Python
"compiler".
"""
import sys, os
from pycopia import sourcegen
from pycopia.textutils import identifier, keyword_identifier
import pycopia.XML.POM
from pycopia.XML.POM import (ContentModel, ElementNode, Notation, ValidationError,
normalize_unicode)
from pycopia.XML.POMparse import (XMLAttribute, ANY, PCDATA, EMPTY)
### DTD compiler components ###
def get_dtd_compiler(fo, mixinmodule=None, doctype=None):
import xml
if hasattr(xml, "use_pyxml"): # per Gentoo bug #367729
xml.use_pyxml()
from xml.parsers.xmlproc.dtdparser import DTDParser
generator = sourcegen.get_sourcefile(fo)
dh = DTDConsumerForSourceGeneration(generator, mixinmodule, doctype)
parser = DTDParser()
parser.set_dtd_consumer(dh)
return parser
def get_identifier(uname):
return identifier(normalize_unicode(uname))
class AttributeMap(dict):
def __repr__(self):
s = ["{"]
for t in self.items():
s.append("%r: %s, " % t)
s.append("}")
return "\n ".join(s)
# this DTD parser consumer generates the Python source code from the DTD.
class DTDConsumerForSourceGeneration(object):
def __init__(self, generator, mixins=None, doctype=None):
self.generator = generator
self._code_index = 0
self.elements = {}
self.parameter_entities = {}
self.general_entities = {}
self._forwardattributes = {}
self._allattributes = {}
self.mixins = mixins # should be a module object
self.doctype = doctype
def dtd_start(self):
print "Starting to parse DTD...",
self.generator.add_comment("This file generated by a program. do not edit.")
self.generator.add_import(pycopia.XML.POM)
if self.mixins:
self.generator.add_import(self.mixins)
self.generator.add_blank()
self._code_index = self.generator.get_current_index()
def dtd_end(self):
print "done parsing. Writing file."
gen = self.generator
for name, value in self._allattributes.items():
gen.add_code("%s = %r" % (name, value), index=2)
gen.add_instance("GENERAL_ENTITIES", self.general_entities)
gen.add_comment("Cache for dynamic classes for this dtd.")
gen.add_instance("_CLASSCACHE", {})
gen.write()
def new_element_type(self, elem_name, elem_cont):
"Receives the declaration of an element type."
try:
element = self.elements[elem_name]
except KeyError:
self.make_new_element(elem_name, elem_cont)
def make_new_element(self, elem_name, contentmodel):
parents = [ElementNode]
if self.mixins:
mixinname = "%sMixin" % ( get_identifier(elem_name) )
if hasattr(self.mixins, mixinname):
parents.insert(0, getattr(self.mixins, mixinname))
# class name is capitalized to avoid clashes with Python key words.
ch = self.generator.add_class(get_identifier(elem_name), tuple(parents))
ch.add_attribute("_name", elem_name)
ch.add_attribute("CONTENTMODEL", _ContentModelGenerator(contentmodel))
self.elements[elem_name] = ch
# Add any previously seen attributes
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem_name]
except KeyError:
pass
else:
ch.add_attribute("ATTRIBUTES", fwdattribs)
ch.add_attribute("KWATTRIBUTES", fwdkwattribs)
del self._forwardattributes[elem_name]
# identify the root element with a generic name (_Root).
if self.doctype and elem_name.lower() == self.doctype.name.lower():
self.generator.add_code("\n_Root = %s\n" % (get_identifier(elem_name),))
def new_attribute(self, elem, a_name, a_type, a_decl, a_def):
"Receives the declaration of a new attribute."
attr = XMLAttribute(a_name, a_type, a_decl, a_def)
ident = attr.get_identifier()
self._allattributes[ident] = attr
try:
element = self.elements[elem]
except KeyError:
# Got a forward attribute definition (defined before element)
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem]
except KeyError:
fwdattribs = AttributeMap()
fwdkwattribs = AttributeMap()
self._forwardattributes[elem] = (fwdattribs, fwdkwattribs)
fwdattribs[a_name] = ident
keywordname = keyword_identifier(normalize_unicode(a_name))
fwdkwattribs[keywordname] = ident
else:
self._add_element_attlist(element, attr, ident)
def _add_element_attlist(self, element, xmlattribute, ident):
try:
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
except KeyError:
element.add_attribute("ATTRIBUTES", AttributeMap())
element.add_attribute("KWATTRIBUTES", AttributeMap())
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
attrmap[xmlattribute.name] = ident
keywordname = keyword_identifier(normalize_unicode(xmlattribute.name))
kwattrmap[keywordname] = ident
def handle_comment(self, contents):
"Receives the contents of a comment."
self.generator.add_comment(contents)
def new_parameter_entity(self,name,val):
"Receives internal parameter entity declarations."
# these are handled internally by the DTD parser. but.. save it anyway.
self.parameter_entities[name] = val
| "Receives internal general entity declarations."
self.general_entities[normalize_unicode(name)] = val
def new_external_entity(self, ent_name, pub_id, sys_id, ndata):
"""Receives external general entity declarations. 'ndata' is the
empty string if the entity is parsed."""
# XXX do we need to handle this?
print "XXX external entity:"
print ent_name, pub_id, sys_id, ndata
def new_notation(self,name, pubid, sysid):
"Receives notation declarations."
n = Notation(name, pubid, sysid)
self.generator.add_instance(get_identifier(name), n)
def handle_pi(self, target, data):
"Receives the target and data of processing instructions."
# XXX do we need to handle this?
print "XXX unhandled PI:",
print "target=%r; data=%r" % (target, data)
class _ContentModelGenerator(object):
"""_ContentModelGenerator(rawmodel)
The DTD parser generated and final content model are so different that a
different content model generator is used for this object.
"""
def __init__(self, rawmodel=None):
tm_type = type(rawmodel)
if tm_type is str:
if rawmodel == "EMPTY":
self.model = EMPTY
elif rawmodel == "#PCDATA":
self.model = PCDATA
elif rawmodel == "ANY":
self.model = ANY
else:
raise ValidationError, "ContentModelGenerator: unknown special type"
elif tm_type is tuple:
self.model = (ANY,) # rawmodel # XXX
elif tm_type is type(None):
self.model = None
else:
raise RuntimeError, "Unknown content model type: %r" % (rawmodel,)
def __repr__(self):
return "%s.%s(%r)" % (ContentModel.__module__, ContentModel.__name__, self.model) | def new_external_pe(self, name, pubid, sysid):
"Receives external parameter entity declarations."
# these are handled internally by the DTD parser.
def new_general_entity(self, name, val): | random_line_split |
DTD.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Deals with DTD files. Primarily, provides the DTD parser and Python
"compiler".
"""
import sys, os
from pycopia import sourcegen
from pycopia.textutils import identifier, keyword_identifier
import pycopia.XML.POM
from pycopia.XML.POM import (ContentModel, ElementNode, Notation, ValidationError,
normalize_unicode)
from pycopia.XML.POMparse import (XMLAttribute, ANY, PCDATA, EMPTY)
### DTD compiler components ###
def get_dtd_compiler(fo, mixinmodule=None, doctype=None):
import xml
if hasattr(xml, "use_pyxml"): # per Gentoo bug #367729
xml.use_pyxml()
from xml.parsers.xmlproc.dtdparser import DTDParser
generator = sourcegen.get_sourcefile(fo)
dh = DTDConsumerForSourceGeneration(generator, mixinmodule, doctype)
parser = DTDParser()
parser.set_dtd_consumer(dh)
return parser
def get_identifier(uname):
return identifier(normalize_unicode(uname))
class AttributeMap(dict):
def __repr__(self):
s = ["{"]
for t in self.items():
s.append("%r: %s, " % t)
s.append("}")
return "\n ".join(s)
# this DTD parser consumer generates the Python source code from the DTD.
class DTDConsumerForSourceGeneration(object):
def __init__(self, generator, mixins=None, doctype=None):
self.generator = generator
self._code_index = 0
self.elements = {}
self.parameter_entities = {}
self.general_entities = {}
self._forwardattributes = {}
self._allattributes = {}
self.mixins = mixins # should be a module object
self.doctype = doctype
def dtd_start(self):
print "Starting to parse DTD...",
self.generator.add_comment("This file generated by a program. do not edit.")
self.generator.add_import(pycopia.XML.POM)
if self.mixins:
self.generator.add_import(self.mixins)
self.generator.add_blank()
self._code_index = self.generator.get_current_index()
def dtd_end(self):
print "done parsing. Writing file."
gen = self.generator
for name, value in self._allattributes.items():
gen.add_code("%s = %r" % (name, value), index=2)
gen.add_instance("GENERAL_ENTITIES", self.general_entities)
gen.add_comment("Cache for dynamic classes for this dtd.")
gen.add_instance("_CLASSCACHE", {})
gen.write()
def new_element_type(self, elem_name, elem_cont):
"Receives the declaration of an element type."
try:
element = self.elements[elem_name]
except KeyError:
self.make_new_element(elem_name, elem_cont)
def make_new_element(self, elem_name, contentmodel):
parents = [ElementNode]
if self.mixins:
mixinname = "%sMixin" % ( get_identifier(elem_name) )
if hasattr(self.mixins, mixinname):
|
# class name is capitalized to avoid clashes with Python key words.
ch = self.generator.add_class(get_identifier(elem_name), tuple(parents))
ch.add_attribute("_name", elem_name)
ch.add_attribute("CONTENTMODEL", _ContentModelGenerator(contentmodel))
self.elements[elem_name] = ch
# Add any previously seen attributes
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem_name]
except KeyError:
pass
else:
ch.add_attribute("ATTRIBUTES", fwdattribs)
ch.add_attribute("KWATTRIBUTES", fwdkwattribs)
del self._forwardattributes[elem_name]
# identify the root element with a generic name (_Root).
if self.doctype and elem_name.lower() == self.doctype.name.lower():
self.generator.add_code("\n_Root = %s\n" % (get_identifier(elem_name),))
def new_attribute(self, elem, a_name, a_type, a_decl, a_def):
"Receives the declaration of a new attribute."
attr = XMLAttribute(a_name, a_type, a_decl, a_def)
ident = attr.get_identifier()
self._allattributes[ident] = attr
try:
element = self.elements[elem]
except KeyError:
# Got a forward attribute definition (defined before element)
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem]
except KeyError:
fwdattribs = AttributeMap()
fwdkwattribs = AttributeMap()
self._forwardattributes[elem] = (fwdattribs, fwdkwattribs)
fwdattribs[a_name] = ident
keywordname = keyword_identifier(normalize_unicode(a_name))
fwdkwattribs[keywordname] = ident
else:
self._add_element_attlist(element, attr, ident)
def _add_element_attlist(self, element, xmlattribute, ident):
try:
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
except KeyError:
element.add_attribute("ATTRIBUTES", AttributeMap())
element.add_attribute("KWATTRIBUTES", AttributeMap())
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
attrmap[xmlattribute.name] = ident
keywordname = keyword_identifier(normalize_unicode(xmlattribute.name))
kwattrmap[keywordname] = ident
def handle_comment(self, contents):
"Receives the contents of a comment."
self.generator.add_comment(contents)
def new_parameter_entity(self,name,val):
"Receives internal parameter entity declarations."
# these are handled internally by the DTD parser. but.. save it anyway.
self.parameter_entities[name] = val
def new_external_pe(self, name, pubid, sysid):
"Receives external parameter entity declarations."
# these are handled internally by the DTD parser.
def new_general_entity(self, name, val):
"Receives internal general entity declarations."
self.general_entities[normalize_unicode(name)] = val
def new_external_entity(self, ent_name, pub_id, sys_id, ndata):
"""Receives external general entity declarations. 'ndata' is the
empty string if the entity is parsed."""
# XXX do we need to handle this?
print "XXX external entity:"
print ent_name, pub_id, sys_id, ndata
def new_notation(self,name, pubid, sysid):
"Receives notation declarations."
n = Notation(name, pubid, sysid)
self.generator.add_instance(get_identifier(name), n)
def handle_pi(self, target, data):
"Receives the target and data of processing instructions."
# XXX do we need to handle this?
print "XXX unhandled PI:",
print "target=%r; data=%r" % (target, data)
class _ContentModelGenerator(object):
"""_ContentModelGenerator(rawmodel)
The DTD parser generated and final content model are so different that a
different content model generator is used for this object.
"""
def __init__(self, rawmodel=None):
tm_type = type(rawmodel)
if tm_type is str:
if rawmodel == "EMPTY":
self.model = EMPTY
elif rawmodel == "#PCDATA":
self.model = PCDATA
elif rawmodel == "ANY":
self.model = ANY
else:
raise ValidationError, "ContentModelGenerator: unknown special type"
elif tm_type is tuple:
self.model = (ANY,) # rawmodel # XXX
elif tm_type is type(None):
self.model = None
else:
raise RuntimeError, "Unknown content model type: %r" % (rawmodel,)
def __repr__(self):
return "%s.%s(%r)" % (ContentModel.__module__, ContentModel.__name__, self.model)
| parents.insert(0, getattr(self.mixins, mixinname)) | conditional_block |
DTD.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Deals with DTD files. Primarily, provides the DTD parser and Python
"compiler".
"""
import sys, os
from pycopia import sourcegen
from pycopia.textutils import identifier, keyword_identifier
import pycopia.XML.POM
from pycopia.XML.POM import (ContentModel, ElementNode, Notation, ValidationError,
normalize_unicode)
from pycopia.XML.POMparse import (XMLAttribute, ANY, PCDATA, EMPTY)
### DTD compiler components ###
def get_dtd_compiler(fo, mixinmodule=None, doctype=None):
import xml
if hasattr(xml, "use_pyxml"): # per Gentoo bug #367729
xml.use_pyxml()
from xml.parsers.xmlproc.dtdparser import DTDParser
generator = sourcegen.get_sourcefile(fo)
dh = DTDConsumerForSourceGeneration(generator, mixinmodule, doctype)
parser = DTDParser()
parser.set_dtd_consumer(dh)
return parser
def get_identifier(uname):
return identifier(normalize_unicode(uname))
class AttributeMap(dict):
|
# this DTD parser consumer generates the Python source code from the DTD.
class DTDConsumerForSourceGeneration(object):
def __init__(self, generator, mixins=None, doctype=None):
self.generator = generator
self._code_index = 0
self.elements = {}
self.parameter_entities = {}
self.general_entities = {}
self._forwardattributes = {}
self._allattributes = {}
self.mixins = mixins # should be a module object
self.doctype = doctype
def dtd_start(self):
print "Starting to parse DTD...",
self.generator.add_comment("This file generated by a program. do not edit.")
self.generator.add_import(pycopia.XML.POM)
if self.mixins:
self.generator.add_import(self.mixins)
self.generator.add_blank()
self._code_index = self.generator.get_current_index()
def dtd_end(self):
print "done parsing. Writing file."
gen = self.generator
for name, value in self._allattributes.items():
gen.add_code("%s = %r" % (name, value), index=2)
gen.add_instance("GENERAL_ENTITIES", self.general_entities)
gen.add_comment("Cache for dynamic classes for this dtd.")
gen.add_instance("_CLASSCACHE", {})
gen.write()
def new_element_type(self, elem_name, elem_cont):
"Receives the declaration of an element type."
try:
element = self.elements[elem_name]
except KeyError:
self.make_new_element(elem_name, elem_cont)
def make_new_element(self, elem_name, contentmodel):
parents = [ElementNode]
if self.mixins:
mixinname = "%sMixin" % ( get_identifier(elem_name) )
if hasattr(self.mixins, mixinname):
parents.insert(0, getattr(self.mixins, mixinname))
# class name is capitalized to avoid clashes with Python key words.
ch = self.generator.add_class(get_identifier(elem_name), tuple(parents))
ch.add_attribute("_name", elem_name)
ch.add_attribute("CONTENTMODEL", _ContentModelGenerator(contentmodel))
self.elements[elem_name] = ch
# Add any previously seen attributes
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem_name]
except KeyError:
pass
else:
ch.add_attribute("ATTRIBUTES", fwdattribs)
ch.add_attribute("KWATTRIBUTES", fwdkwattribs)
del self._forwardattributes[elem_name]
# identify the root element with a generic name (_Root).
if self.doctype and elem_name.lower() == self.doctype.name.lower():
self.generator.add_code("\n_Root = %s\n" % (get_identifier(elem_name),))
def new_attribute(self, elem, a_name, a_type, a_decl, a_def):
"Receives the declaration of a new attribute."
attr = XMLAttribute(a_name, a_type, a_decl, a_def)
ident = attr.get_identifier()
self._allattributes[ident] = attr
try:
element = self.elements[elem]
except KeyError:
# Got a forward attribute definition (defined before element)
try:
fwdattribs, fwdkwattribs = self._forwardattributes[elem]
except KeyError:
fwdattribs = AttributeMap()
fwdkwattribs = AttributeMap()
self._forwardattributes[elem] = (fwdattribs, fwdkwattribs)
fwdattribs[a_name] = ident
keywordname = keyword_identifier(normalize_unicode(a_name))
fwdkwattribs[keywordname] = ident
else:
self._add_element_attlist(element, attr, ident)
def _add_element_attlist(self, element, xmlattribute, ident):
try:
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
except KeyError:
element.add_attribute("ATTRIBUTES", AttributeMap())
element.add_attribute("KWATTRIBUTES", AttributeMap())
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
attrmap[xmlattribute.name] = ident
keywordname = keyword_identifier(normalize_unicode(xmlattribute.name))
kwattrmap[keywordname] = ident
def handle_comment(self, contents):
"Receives the contents of a comment."
self.generator.add_comment(contents)
def new_parameter_entity(self,name,val):
"Receives internal parameter entity declarations."
# these are handled internally by the DTD parser. but.. save it anyway.
self.parameter_entities[name] = val
def new_external_pe(self, name, pubid, sysid):
"Receives external parameter entity declarations."
# these are handled internally by the DTD parser.
def new_general_entity(self, name, val):
"Receives internal general entity declarations."
self.general_entities[normalize_unicode(name)] = val
def new_external_entity(self, ent_name, pub_id, sys_id, ndata):
"""Receives external general entity declarations. 'ndata' is the
empty string if the entity is parsed."""
# XXX do we need to handle this?
print "XXX external entity:"
print ent_name, pub_id, sys_id, ndata
def new_notation(self,name, pubid, sysid):
"Receives notation declarations."
n = Notation(name, pubid, sysid)
self.generator.add_instance(get_identifier(name), n)
def handle_pi(self, target, data):
"Receives the target and data of processing instructions."
# XXX do we need to handle this?
print "XXX unhandled PI:",
print "target=%r; data=%r" % (target, data)
class _ContentModelGenerator(object):
"""_ContentModelGenerator(rawmodel)
The DTD parser generated and final content model are so different that a
different content model generator is used for this object.
"""
def __init__(self, rawmodel=None):
tm_type = type(rawmodel)
if tm_type is str:
if rawmodel == "EMPTY":
self.model = EMPTY
elif rawmodel == "#PCDATA":
self.model = PCDATA
elif rawmodel == "ANY":
self.model = ANY
else:
raise ValidationError, "ContentModelGenerator: unknown special type"
elif tm_type is tuple:
self.model = (ANY,) # rawmodel # XXX
elif tm_type is type(None):
self.model = None
else:
raise RuntimeError, "Unknown content model type: %r" % (rawmodel,)
def __repr__(self):
return "%s.%s(%r)" % (ContentModel.__module__, ContentModel.__name__, self.model)
| def __repr__(self):
s = ["{"]
for t in self.items():
s.append("%r: %s, " % t)
s.append("}")
return "\n ".join(s) | identifier_body |
jquery.maxsubmit.js | /**
* Copyright 2013-2014 Academe Computing Ltd
* Released under the MIT license
* Author: Jason Judge <jason@academe.co.uk>
* Version: 1.2.1
*/
/**
* jquery.maxsubmit.js
*
* Checks how many parameters a form is going to submit, and
* gives the user a chance to cancel if it exceeds a set number.
* PHP5.3+ has limits set by default on the number of POST parameters
* that will be accepted. Parameters beyond that number, usually 1000,
* will be silently discarded. This can have nasty side-effects in some
* applications, such as editiong shop products with many variations
* against a product, which can result in well over 1000 submitted
* parameters (looking at you WooCommerce). This aims to provide some
* level of protection.
*
*/
(function($) {
/**
* Set a trigger on a form to pop up a warning if the fields to be submitted
* exceed a specified maximum.
* Usage: $('form#selector').maxSubmit({options});
*/
$.fn.maxSubmit = function(options) {
// this.each() is the wrapper for each form.
return this.each(function() {
var settings = $.extend({
// The maximum number of parameters the form will be allowed to submit
// before the user is issued a confirm (OK/Cancel) dialogue.
max_count: 1000,
// The message given to the user to confirm they want to submit anyway.
// Can use {max_count} as a placeholder for the permitted maximum
// and {form_count} for the counted form items.
max_exceeded_message:
'This form has too many fields for the server to accept.\n'
+ ' Data may be lost if you submit. Are you sure you want to go ahead?',
// The function that will display the confirm message.
// Replace this with something fancy such as jquery.ui if you wish.
confirm_display: function(form_count) {
if (typeof(form_count) === 'undefined') form_count = '';
return confirm(
settings
.max_exceeded_message
.replace("{max_count}", settings.max_count)
.replace("{form_count}", form_count)
);
}
}, options);
// Form elements will be passed in, so we need to trigger on
// an attempt to submit that form.
// First check we do have a form.
if ($(this).is("form")) {
$(this).on('submit', function(e) {
// We have a form, so count up the form items that will be
// submitted to the server.
// For now, add one for the submit button.
var form_count = $(this).maxSubmitCount() + 1;
if (form_count > settings.max_count) {
// If the user cancels, then abort the form submit.
if (!settings.confirm_display(form_count)) return false;
}
// Allow the submit to go ahead.
return true;
});
}
// Support chaining.
return this;
});
};
/**
* Count the number of fields that will be posted in a form.
* If return_elements is true, then an array of elements will be returned
* instead of the count. This is handy for testing.
* TODO: elements without names will not be submitted.
* Another approach may be to get all input fields at once using $("form :input")
* then knock out the ones that we don't want. That would keep the same order as the
* items would be submitted.
*/
$.fn.maxSubmitCount = function(return_elements) {
// Text fields and submit buttons will all post one parameter.
// Find the textareas.
// These will count as one post parameter each.
var fields = $('textarea:enabled[name]', this).toArray();
// Find the basic textual input fields (text, email, number, date and similar).
// These will count as one post parameter each.
// We deal with checkboxes, radio buttons sparately.
// Checkboxes will post only if checked, so exclude any that are not checked.
// There may be multiple form submit buttons, but only one will be posted with the
// form, assuming the form has been submitted by the user with a button.
// An image submit will post two fields - an x and y coordinate.
fields = fields.concat(
$('input:enabled[name]', this)
// Data items that are handled later.
.not("[type='checkbox']:not(:checked)")
.not("[type='radio']")
.not("[type='file']")
.not("[type='reset']")
// Submit form items.
.not("[type='submit']")
.not("[type='button']")
.not("[type='image']")
.toArray()
);
// Single-select lists will always post one value.
fields = fields.concat(
$('select:enabled[name]', this)
.not('[multiple]')
.toArray()
);
// Multi-select lists will post one parameter for each selected option.
// The parent select is $(this).parent() with its name being $(this).parent().attr('name')
$('select[multiple]:enabled[name] option:selected', this).each(function() {
// We collect all the options that have been selected.
fields = fields.concat(this);
});
// Each radio button group will post one parameter.
// We assume all checked radio buttons will be posted.
fields = fields.concat(
$('input:enabled:radio:checked', this)
.toArray()
);
// TODO: provide an option to return an array of objects containing the form field names,
// types and values, in a form that can be compared to what is actually posted.
if (typeof(return_elements) === 'undefined') return_elements = false;
if (return_elements === true) | else {
// Just return the number of elements matched.
return fields.length;
}
};
}(jQuery));
| {
// Return the full list of elements for analysis.
return fields;
} | conditional_block |
jquery.maxsubmit.js | /**
* Copyright 2013-2014 Academe Computing Ltd
* Released under the MIT license
* Author: Jason Judge <jason@academe.co.uk>
* Version: 1.2.1
*/
/**
* jquery.maxsubmit.js
*
* Checks how many parameters a form is going to submit, and
* gives the user a chance to cancel if it exceeds a set number.
* PHP5.3+ has limits set by default on the number of POST parameters
* that will be accepted. Parameters beyond that number, usually 1000,
* will be silently discarded. This can have nasty side-effects in some
* applications, such as editiong shop products with many variations
* against a product, which can result in well over 1000 submitted
* parameters (looking at you WooCommerce). This aims to provide some
* level of protection.
*
*/
(function($) {
/**
* Set a trigger on a form to pop up a warning if the fields to be submitted
* exceed a specified maximum.
* Usage: $('form#selector').maxSubmit({options});
*/
$.fn.maxSubmit = function(options) {
// this.each() is the wrapper for each form.
return this.each(function() {
var settings = $.extend({
// The maximum number of parameters the form will be allowed to submit
// before the user is issued a confirm (OK/Cancel) dialogue.
max_count: 1000,
// The message given to the user to confirm they want to submit anyway.
// Can use {max_count} as a placeholder for the permitted maximum
// and {form_count} for the counted form items.
max_exceeded_message:
'This form has too many fields for the server to accept.\n'
+ ' Data may be lost if you submit. Are you sure you want to go ahead?',
// The function that will display the confirm message.
// Replace this with something fancy such as jquery.ui if you wish.
confirm_display: function(form_count) {
if (typeof(form_count) === 'undefined') form_count = '';
| return confirm(
settings
.max_exceeded_message
.replace("{max_count}", settings.max_count)
.replace("{form_count}", form_count)
);
}
}, options);
// Form elements will be passed in, so we need to trigger on
// an attempt to submit that form.
// First check we do have a form.
if ($(this).is("form")) {
$(this).on('submit', function(e) {
// We have a form, so count up the form items that will be
// submitted to the server.
// For now, add one for the submit button.
var form_count = $(this).maxSubmitCount() + 1;
if (form_count > settings.max_count) {
// If the user cancels, then abort the form submit.
if (!settings.confirm_display(form_count)) return false;
}
// Allow the submit to go ahead.
return true;
});
}
// Support chaining.
return this;
});
};
/**
* Count the number of fields that will be posted in a form.
* If return_elements is true, then an array of elements will be returned
* instead of the count. This is handy for testing.
* TODO: elements without names will not be submitted.
* Another approach may be to get all input fields at once using $("form :input")
* then knock out the ones that we don't want. That would keep the same order as the
* items would be submitted.
*/
$.fn.maxSubmitCount = function(return_elements) {
// Text fields and submit buttons will all post one parameter.
// Find the textareas.
// These will count as one post parameter each.
var fields = $('textarea:enabled[name]', this).toArray();
// Find the basic textual input fields (text, email, number, date and similar).
// These will count as one post parameter each.
// We deal with checkboxes, radio buttons sparately.
// Checkboxes will post only if checked, so exclude any that are not checked.
// There may be multiple form submit buttons, but only one will be posted with the
// form, assuming the form has been submitted by the user with a button.
// An image submit will post two fields - an x and y coordinate.
fields = fields.concat(
$('input:enabled[name]', this)
// Data items that are handled later.
.not("[type='checkbox']:not(:checked)")
.not("[type='radio']")
.not("[type='file']")
.not("[type='reset']")
// Submit form items.
.not("[type='submit']")
.not("[type='button']")
.not("[type='image']")
.toArray()
);
// Single-select lists will always post one value.
fields = fields.concat(
$('select:enabled[name]', this)
.not('[multiple]')
.toArray()
);
// Multi-select lists will post one parameter for each selected option.
// The parent select is $(this).parent() with its name being $(this).parent().attr('name')
$('select[multiple]:enabled[name] option:selected', this).each(function() {
// We collect all the options that have been selected.
fields = fields.concat(this);
});
// Each radio button group will post one parameter.
// We assume all checked radio buttons will be posted.
fields = fields.concat(
$('input:enabled:radio:checked', this)
.toArray()
);
// TODO: provide an option to return an array of objects containing the form field names,
// types and values, in a form that can be compared to what is actually posted.
if (typeof(return_elements) === 'undefined') return_elements = false;
if (return_elements === true) {
// Return the full list of elements for analysis.
return fields;
} else {
// Just return the number of elements matched.
return fields.length;
}
};
}(jQuery)); | random_line_split | |
testgridff2.py |
from Sire.IO import *
from Sire.MM import *
from Sire.System import *
from Sire.Mol import *
from Sire.Maths import *
from Sire.FF import *
from Sire.Move import *
from Sire.Units import *
from Sire.Vol import *
from Sire.Qt import *
import os
coul_cutoff = 20 * angstrom
lj_cutoff = 10 * angstrom
amber = Amber()
(molecules, space) = amber.readCrdTop("test/io/waterbox.crd", "test/io/waterbox.top")
system = System()
swapwaters = MoleculeGroup("swapwaters")
waters = MoleculeGroup("waters")
molnums = molecules.molNums();
for molnum in molnums:
water = molecules[molnum].molecule()
if water.residue().number() == ResNum(2025):
center_water = water
swapwaters.add(center_water)
center_point = center_water.evaluate().center()
for molnum in molnums:
if molnum != center_water.number():
water = molecules[molnum].molecule()
if Vector.distance(center_point, water.evaluate().center()) < 7.5:
water = water.residue().edit().setProperty("PDB-residue-name", "SWP").commit()
swapwaters.add(water)
else:
|
system.add(swapwaters)
system.add(waters)
gridff = GridFF("gridff")
gridff.setCombiningRules("arithmetic")
print("Combining rules are %s" % gridff.combiningRules())
gridff.setBuffer(2 * angstrom)
gridff.setGridSpacing( 0.5 * angstrom )
gridff.setLJCutoff(lj_cutoff)
gridff.setCoulombCutoff(coul_cutoff)
gridff.setShiftElectrostatics(True)
#gridff.setUseAtomisticCutoff(True)
#gridff.setUseReactionField(True)
cljgridff = CLJGrid()
cljgridff.setCLJFunction( CLJShiftFunction(coul_cutoff,lj_cutoff) )
cljgridff.setFixedAtoms( CLJAtoms(waters.molecules()) )
cljatoms = CLJAtoms(swapwaters.molecules())
cljgridff.setGridDimensions( cljatoms, 0.5 * angstrom, 2 * angstrom )
print("Grid box equals %s" % cljgridff.grid())
cljboxes = CLJBoxes(cljatoms)
(cnrg, ljnrg) = cljgridff.calculate(cljboxes)
print("CLJGridFF: %s %s %s" % (cnrg+ljnrg, cnrg, ljnrg))
cljgridff.setUseGrid(False)
(cnrg, ljnrg) = cljgridff.calculate(cljboxes)
print("CLJGridFF: %s %s %s" % (cnrg+ljnrg, cnrg, ljnrg))
gridff.add(swapwaters, MGIdx(0))
gridff.add(waters, MGIdx(1))
gridff.setSpace( Cartesian() )
gridff2 = GridFF2("gridff2")
gridff2.setCombiningRules("arithmetic")
gridff2.setBuffer(2*angstrom)
gridff2.setGridSpacing( 0.5 * angstrom )
gridff2.setLJCutoff(lj_cutoff)
gridff2.setCoulombCutoff(coul_cutoff)
gridff2.setShiftElectrostatics(True)
#gridff2.setUseAtomisticCutoff(True)
#gridff2.setUseReactionField(True)
gridff2.add( swapwaters, MGIdx(0) )
gridff2.addFixedAtoms(waters.molecules())
gridff2.setSpace( Cartesian() )
testff = TestFF()
testff.add( swapwaters.molecules() )
testff.addFixedAtoms(waters.molecules())
testff.setCutoff(coul_cutoff, lj_cutoff)
cljff = InterGroupCLJFF("cljff")
cljff.setSwitchingFunction( HarmonicSwitchingFunction(coul_cutoff,coul_cutoff,lj_cutoff,lj_cutoff) )
cljff.add(swapwaters, MGIdx(0))
cljff.add(waters, MGIdx(1))
cljff.setShiftElectrostatics(True)
#cljff.setUseAtomisticCutoff(True)
#cljff.setUseReactionField(True)
cljff.setSpace( Cartesian() )
cljff2 = InterCLJFF("cljff2")
cljff2.setSwitchingFunction( HarmonicSwitchingFunction(coul_cutoff,coul_cutoff,lj_cutoff,lj_cutoff) )
cljff2.add(waters)
cljff2.setShiftElectrostatics(True)
cljff2.setSpace( Cartesian() )
print(gridff.energies())
print(gridff2.energies())
print("\nEnergies")
print(gridff.energies())
print(gridff2.energies())
t = QTime()
t.start()
nrgs = cljff.energies()
ms = t.elapsed()
print(cljff.energies())
print("Took %d ms" % ms)
testff.calculateEnergy()
t.start()
nrgs = cljff2.energies()
ms = t.elapsed()
print("\nExact compare")
print(cljff2.energies())
print("Took %d ms" % ms)
| waters.add(water) | conditional_block |
testgridff2.py | from Sire.IO import *
from Sire.MM import *
from Sire.System import *
from Sire.Mol import *
from Sire.Maths import *
from Sire.FF import *
from Sire.Move import *
from Sire.Units import *
from Sire.Vol import *
from Sire.Qt import *
import os
coul_cutoff = 20 * angstrom
lj_cutoff = 10 * angstrom
amber = Amber()
(molecules, space) = amber.readCrdTop("test/io/waterbox.crd", "test/io/waterbox.top")
system = System()
swapwaters = MoleculeGroup("swapwaters")
waters = MoleculeGroup("waters")
molnums = molecules.molNums();
for molnum in molnums:
water = molecules[molnum].molecule()
if water.residue().number() == ResNum(2025):
center_water = water
swapwaters.add(center_water)
center_point = center_water.evaluate().center()
for molnum in molnums:
if molnum != center_water.number():
water = molecules[molnum].molecule()
if Vector.distance(center_point, water.evaluate().center()) < 7.5:
water = water.residue().edit().setProperty("PDB-residue-name", "SWP").commit()
swapwaters.add(water)
else:
waters.add(water)
system.add(swapwaters)
system.add(waters)
gridff = GridFF("gridff")
gridff.setCombiningRules("arithmetic")
print("Combining rules are %s" % gridff.combiningRules())
gridff.setBuffer(2 * angstrom)
gridff.setGridSpacing( 0.5 * angstrom )
gridff.setLJCutoff(lj_cutoff)
gridff.setCoulombCutoff(coul_cutoff)
gridff.setShiftElectrostatics(True)
#gridff.setUseAtomisticCutoff(True)
#gridff.setUseReactionField(True)
cljgridff = CLJGrid()
cljgridff.setCLJFunction( CLJShiftFunction(coul_cutoff,lj_cutoff) )
cljgridff.setFixedAtoms( CLJAtoms(waters.molecules()) )
cljatoms = CLJAtoms(swapwaters.molecules())
cljgridff.setGridDimensions( cljatoms, 0.5 * angstrom, 2 * angstrom )
print("Grid box equals %s" % cljgridff.grid())
cljboxes = CLJBoxes(cljatoms)
(cnrg, ljnrg) = cljgridff.calculate(cljboxes)
print("CLJGridFF: %s %s %s" % (cnrg+ljnrg, cnrg, ljnrg))
cljgridff.setUseGrid(False)
(cnrg, ljnrg) = cljgridff.calculate(cljboxes)
print("CLJGridFF: %s %s %s" % (cnrg+ljnrg, cnrg, ljnrg))
gridff.add(swapwaters, MGIdx(0))
gridff.add(waters, MGIdx(1))
gridff.setSpace( Cartesian() )
gridff2 = GridFF2("gridff2")
gridff2.setCombiningRules("arithmetic") | gridff2.setGridSpacing( 0.5 * angstrom )
gridff2.setLJCutoff(lj_cutoff)
gridff2.setCoulombCutoff(coul_cutoff)
gridff2.setShiftElectrostatics(True)
#gridff2.setUseAtomisticCutoff(True)
#gridff2.setUseReactionField(True)
gridff2.add( swapwaters, MGIdx(0) )
gridff2.addFixedAtoms(waters.molecules())
gridff2.setSpace( Cartesian() )
testff = TestFF()
testff.add( swapwaters.molecules() )
testff.addFixedAtoms(waters.molecules())
testff.setCutoff(coul_cutoff, lj_cutoff)
cljff = InterGroupCLJFF("cljff")
cljff.setSwitchingFunction( HarmonicSwitchingFunction(coul_cutoff,coul_cutoff,lj_cutoff,lj_cutoff) )
cljff.add(swapwaters, MGIdx(0))
cljff.add(waters, MGIdx(1))
cljff.setShiftElectrostatics(True)
#cljff.setUseAtomisticCutoff(True)
#cljff.setUseReactionField(True)
cljff.setSpace( Cartesian() )
cljff2 = InterCLJFF("cljff2")
cljff2.setSwitchingFunction( HarmonicSwitchingFunction(coul_cutoff,coul_cutoff,lj_cutoff,lj_cutoff) )
cljff2.add(waters)
cljff2.setShiftElectrostatics(True)
cljff2.setSpace( Cartesian() )
print(gridff.energies())
print(gridff2.energies())
print("\nEnergies")
print(gridff.energies())
print(gridff2.energies())
t = QTime()
t.start()
nrgs = cljff.energies()
ms = t.elapsed()
print(cljff.energies())
print("Took %d ms" % ms)
testff.calculateEnergy()
t.start()
nrgs = cljff2.energies()
ms = t.elapsed()
print("\nExact compare")
print(cljff2.energies())
print("Took %d ms" % ms) | gridff2.setBuffer(2*angstrom) | random_line_split |
print-command.js | 'use strict';
const chalk = require('chalk');
const EOL = require('os').EOL;
module.exports = function(initialMargin, shouldDescriptionBeGrey) {
initialMargin = initialMargin || '';
let output = '';
let options = this.anonymousOptions;
// <anonymous-option-1> ...
if (options.length) {
output += ` ${chalk.yellow(
options
.map(option => {
// blueprints we insert brackets, commands already have them
if (option.indexOf('<') === 0) {
return option;
} else {
return `<${option}>`;
}
})
.join(' ')
)}`;
}
options = this.availableOptions;
// <options...>
if (options.length) {
output += ` ${chalk.cyan('<options...>')}`;
}
// Description
let description = this.description;
if (description) {
if (shouldDescriptionBeGrey) {
description = chalk.grey(description);
}
output += `${EOL + initialMargin} ${description}`;
}
// aliases: a b c
if (this.aliases && this.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(`aliases: ${this.aliases.filter(a => a).join(', ')}`)}`;
}
// --available-option (Required) (Default: value)
// ...
options.forEach(option => {
output += `${EOL + initialMargin} ${chalk.cyan(`--${option.name}`)}`;
if (option.values) {
output += chalk.cyan(`=${option.values.join('|')}`);
}
if (option.type) {
let types = Array.isArray(option.type) ? option.type.map(formatType).join(', ') : formatType(option.type);
output += ` ${chalk.cyan(`(${types})`)}`;
}
if (option.required) {
output += ` ${chalk.cyan('(Required)')}`;
}
if (option.default !== undefined) {
output += ` ${chalk.cyan(`(Default: ${formatValue(option.default)})`)}`;
}
if (option.description) {
output += ` ${option.description}`;
}
if (option.aliases && option.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(
`aliases: ${option.aliases
.map(a => {
if (typeof a === 'string') {
return (a.length > 4 ? '--' : '-') + a + (option.type === Boolean ? '' : ' <value>');
} else {
let key = Object.keys(a)[0];
return `${(key.length > 4 ? '--' : '-') + key} (--${option.name}=${formatValue(a[key])})`;
}
})
.join(', ')}`
)}`;
}
});
return output;
};
function formatType(type) {
return typeof type === 'string' ? formatValue(type) : type.name;
}
function | (val) {
return val === '' ? '""' : val;
}
| formatValue | identifier_name |
print-command.js | 'use strict';
const chalk = require('chalk');
const EOL = require('os').EOL;
module.exports = function(initialMargin, shouldDescriptionBeGrey) {
initialMargin = initialMargin || '';
let output = '';
let options = this.anonymousOptions;
// <anonymous-option-1> ...
if (options.length) {
output += ` ${chalk.yellow(
options
.map(option => {
// blueprints we insert brackets, commands already have them
if (option.indexOf('<') === 0) {
return option;
} else {
return `<${option}>`;
}
})
.join(' ')
)}`;
}
options = this.availableOptions;
// <options...>
if (options.length) {
output += ` ${chalk.cyan('<options...>')}`;
}
// Description
let description = this.description;
if (description) {
if (shouldDescriptionBeGrey) {
description = chalk.grey(description);
}
output += `${EOL + initialMargin} ${description}`;
}
// aliases: a b c
if (this.aliases && this.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(`aliases: ${this.aliases.filter(a => a).join(', ')}`)}`;
}
// --available-option (Required) (Default: value)
// ...
options.forEach(option => {
output += `${EOL + initialMargin} ${chalk.cyan(`--${option.name}`)}`;
if (option.values) {
output += chalk.cyan(`=${option.values.join('|')}`);
}
if (option.type) {
let types = Array.isArray(option.type) ? option.type.map(formatType).join(', ') : formatType(option.type);
output += ` ${chalk.cyan(`(${types})`)}`;
}
if (option.required) {
output += ` ${chalk.cyan('(Required)')}`;
}
if (option.default !== undefined) {
output += ` ${chalk.cyan(`(Default: ${formatValue(option.default)})`)}`;
}
if (option.description) {
output += ` ${option.description}`;
}
if (option.aliases && option.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(
`aliases: ${option.aliases
.map(a => {
if (typeof a === 'string') {
return (a.length > 4 ? '--' : '-') + a + (option.type === Boolean ? '' : ' <value>');
} else {
let key = Object.keys(a)[0];
return `${(key.length > 4 ? '--' : '-') + key} (--${option.name}=${formatValue(a[key])})`;
}
})
.join(', ')}`
)}`;
}
});
return output;
};
function formatType(type) |
function formatValue(val) {
return val === '' ? '""' : val;
}
| {
return typeof type === 'string' ? formatValue(type) : type.name;
} | identifier_body |
print-command.js | 'use strict';
const chalk = require('chalk');
const EOL = require('os').EOL;
module.exports = function(initialMargin, shouldDescriptionBeGrey) {
initialMargin = initialMargin || '';
let output = '';
let options = this.anonymousOptions;
// <anonymous-option-1> ...
if (options.length) {
output += ` ${chalk.yellow(
options
.map(option => {
// blueprints we insert brackets, commands already have them
if (option.indexOf('<') === 0) {
return option;
} else {
return `<${option}>`;
}
})
.join(' ')
)}`;
}
options = this.availableOptions;
// <options...>
if (options.length) {
output += ` ${chalk.cyan('<options...>')}`;
}
// Description
let description = this.description;
if (description) {
if (shouldDescriptionBeGrey) {
description = chalk.grey(description);
}
output += `${EOL + initialMargin} ${description}`;
}
// aliases: a b c
if (this.aliases && this.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(`aliases: ${this.aliases.filter(a => a).join(', ')}`)}`;
}
// --available-option (Required) (Default: value)
// ...
options.forEach(option => {
output += `${EOL + initialMargin} ${chalk.cyan(`--${option.name}`)}`;
if (option.values) {
output += chalk.cyan(`=${option.values.join('|')}`);
}
if (option.type) {
let types = Array.isArray(option.type) ? option.type.map(formatType).join(', ') : formatType(option.type);
output += ` ${chalk.cyan(`(${types})`)}`;
}
if (option.required) {
output += ` ${chalk.cyan('(Required)')}`;
}
if (option.default !== undefined) {
output += ` ${chalk.cyan(`(Default: ${formatValue(option.default)})`)}`;
}
if (option.description) {
output += ` ${option.description}`;
}
if (option.aliases && option.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(
`aliases: ${option.aliases
.map(a => {
if (typeof a === 'string') {
return (a.length > 4 ? '--' : '-') + a + (option.type === Boolean ? '' : ' <value>');
} else {
let key = Object.keys(a)[0];
return `${(key.length > 4 ? '--' : '-') + key} (--${option.name}=${formatValue(a[key])})`;
}
})
.join(', ')}`
)}`; | });
return output;
};
function formatType(type) {
return typeof type === 'string' ? formatValue(type) : type.name;
}
function formatValue(val) {
return val === '' ? '""' : val;
} | } | random_line_split |
print-command.js | 'use strict';
const chalk = require('chalk');
const EOL = require('os').EOL;
module.exports = function(initialMargin, shouldDescriptionBeGrey) {
initialMargin = initialMargin || '';
let output = '';
let options = this.anonymousOptions;
// <anonymous-option-1> ...
if (options.length) {
output += ` ${chalk.yellow(
options
.map(option => {
// blueprints we insert brackets, commands already have them
if (option.indexOf('<') === 0) {
return option;
} else {
return `<${option}>`;
}
})
.join(' ')
)}`;
}
options = this.availableOptions;
// <options...>
if (options.length) {
output += ` ${chalk.cyan('<options...>')}`;
}
// Description
let description = this.description;
if (description) {
if (shouldDescriptionBeGrey) {
description = chalk.grey(description);
}
output += `${EOL + initialMargin} ${description}`;
}
// aliases: a b c
if (this.aliases && this.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(`aliases: ${this.aliases.filter(a => a).join(', ')}`)}`;
}
// --available-option (Required) (Default: value)
// ...
options.forEach(option => {
output += `${EOL + initialMargin} ${chalk.cyan(`--${option.name}`)}`;
if (option.values) {
output += chalk.cyan(`=${option.values.join('|')}`);
}
if (option.type) {
let types = Array.isArray(option.type) ? option.type.map(formatType).join(', ') : formatType(option.type);
output += ` ${chalk.cyan(`(${types})`)}`;
}
if (option.required) {
output += ` ${chalk.cyan('(Required)')}`;
}
if (option.default !== undefined) |
if (option.description) {
output += ` ${option.description}`;
}
if (option.aliases && option.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(
`aliases: ${option.aliases
.map(a => {
if (typeof a === 'string') {
return (a.length > 4 ? '--' : '-') + a + (option.type === Boolean ? '' : ' <value>');
} else {
let key = Object.keys(a)[0];
return `${(key.length > 4 ? '--' : '-') + key} (--${option.name}=${formatValue(a[key])})`;
}
})
.join(', ')}`
)}`;
}
});
return output;
};
function formatType(type) {
return typeof type === 'string' ? formatValue(type) : type.name;
}
function formatValue(val) {
return val === '' ? '""' : val;
}
| {
output += ` ${chalk.cyan(`(Default: ${formatValue(option.default)})`)}`;
} | conditional_block |
managers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
import time
from collections import OrderedDict
from contextlib import contextmanager
import six
from django.utils.functional import cached_property
from .client import get_es_client
logger = logging.getLogger('elasticindex')
class ElasticQuerySet(object):
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.body = body or {"query": {"match_all": {}}}
self.kwargs = kwargs or {}
self.latest_total_count = None
self.latest_raw_result = None
self.query_finished = False
def __len__(self):
return len(self.result_list)
def __iter__(self):
return iter(self.result_list)
def __bool__(self):
return bool(self.result_list)
def __getitem__(self, k):
"""
Retrieves an item or slice from the set of results.
"""
if not isinstance(k, (slice,) + six.integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0)) or
(isinstance(k, slice) and (k.start is None or k.start >= 0) and
(k.stop is None or k.stop >= 0))), \
"Negative indexing is not supported."
if self.query_finished:
return self.result_list[k]
if isinstance(k, slice):
qs = self
offset = 0
if k.start is not None:
offset = int(k.start)
qs = qs.offset(offset)
if k.stop is not None:
limit = int(k.stop) - offset
qs = qs.limit(limit)
return list(qs)[::k.step] if k.step else qs
qs = self.limit(1).offset(k)
return list(qs)[0]
def _clone(self):
"""
:rtype: ElasticQuerySet
"""
qs = self.__class__(
self.model_cls, copy.deepcopy(self.body),
**copy.deepcopy(self.kwargs))
return qs
@cached_property
def result_list(self):
self.query_finished = True
return list(self.get_result())
def get_result(self):
"""
elasticsearch の search をそのまま実行
:rtype: generator
"""
with self.log_query():
result = self.es_client.search(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=self.body, **self.kwargs)
self.latest_total_count = result['hits']['total'] | yield self.model_cls(hit)
@cached_property
def es_client(self):
"""
:rtype: Elasticsearch
"""
return get_es_client()
def get_by_id(self, id):
"""
Elasticsearch のIDで1件取得
:param id:
:return:
"""
result = self.es_client.get(
self.model_cls.INDEX, id, doc_type=self.model_cls.DOC_TYPE)
self.latest_raw_result = result
if not result['found']:
raise self.model_cls.DoesNotExist(id)
return self.model_cls(result)
def delete_by_id(self, id, **kwargs):
"""
Elasticsearch のIDで1件削除
:param id: elasticsearch document id
"""
result = self.es_client.delete(
self.model_cls.INDEX, self.model_cls.DOC_TYPE, id, **kwargs)
self.latest_raw_result = result
return result
def all(self):
"""
:rtype: ElasticQuerySet
"""
return self._clone()
def limit(self, limit):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if limit is None:
if 'size' in o.body:
del o.body['size']
else:
o.body['size'] = limit
return o
def offset(self, offset):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if offset is None:
if 'from' in o.body:
del o.body['from']
else:
o.body['from'] = offset
return o
def query(self, filter_query_dict):
"""
:param filter_query_dict:
- {"match": {"product_id": 192}}
- {"match_all": {}} # default
- {"multi_match": {
"query": query_word,
"fields": [
"upc", "title^3", "description", "authors",
"publishers", "tags", "keywords"]
}}
- {"bool": {
"must": [
{"match": {"is_used": True}},
{"range": {"stock": {"gt": 0}}}
]}}
:rtype: ElasticQuerySet
"""
o = self._clone()
o.body['query'] = filter_query_dict
return o
def set_body(self, body_dict):
"""
replace query body
"""
o = self._clone()
o.body = body_dict
return o
def get(self, filter_query_dict):
"""
1件取得
複数件あってもエラーは出さず、黙って1件だけ返す
"""
qs = self.query(filter_query_dict).limit(1)
if not qs:
raise self.model_cls.DoesNotExist(filter_query_dict)
return qs[0]
def count(self):
"""
件数取得
"""
if self.query_finished:
return len(self.result_list)
body = self.body.copy()
if 'sort' in body:
del body['sort']
with self.log_query(label='count', body=body):
result = self.es_client.count(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=body, **self.kwargs
)
self.latest_raw_result = result
return result['count']
def order_by(self, order_query_list):
"""
sort パラメータをつける
:type order_query_list: list, dict, string
- "mz_score"
- {"mz_score": "desc"}
"""
o = self._clone()
o.body['sort'] = order_query_list
return o
@property
def log_query(self):
"""
クエリをロギングするコンテクストマネージャ
elasticsearch や elasticsearch.trace のロガーを
DEBUG レベルで設定するともっと詳しく出る (結果が全部出る)
"""
@contextmanager
def _context(label='', body=None):
start_time = time.time()
yield
elapsed_time = time.time() - start_time
logger.debug('{}time:{}ms, body:{}'.format(
'{}: '.format(label) if label else '',
int(elapsed_time * 100), body or self.body))
return _context
def bulk(self, body):
return self.es_client.bulk(
body, index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE)
class ElasticDocumentManager(object):
"""
class ElasticDocumentManager(ElasticQuerySet)
でもいいんだけど、インスタンス変数が汚れる可能性があるので
クラスプロパティっぽい感じで、アクセスされるたびに新しいクエリセットを作ることにした
"""
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.kwargs = kwargs
def __get__(self, cls, owner):
return ElasticQuerySet(self.model_cls)
class ElasticIndexManager(object):
def __init__(self, model_cls):
self.model_cls = model_cls
@cached_property
def mappings_properties(self):
return OrderedDict(
[
(f_name, f.mapping)
for f_name, f
in self.model_cls._cached_fields().items()
])
@cached_property
def mappings(self):
"""
インデックスの mappings の指定にそのまま使える dict
"""
return {
self.model_cls.DOC_TYPE: {
"properties": self.mappings_properties
}
}
def delete(self):
"""
インデックスを削除
:return:
"""
es = get_es_client()
es.indices.delete(self.model_cls.INDEX, ignore=[404, ])
@cached_property
def create_body_params(self):
body = {"mappings": self.mappings}
index_setting = getattr(self.model_cls, 'INDEX_SETTINGS', None)
if index_setting:
body["settings"] = index_setting
return body
def create(self):
"""
インデックスを作成
:return:
"""
es = get_es_client()
es.indices.create(
self.model_cls.INDEX, self.create_body_params)
def exists(self):
"""
インデックスが存在するか
"""
es = get_es_client()
return es.indices.exists(self.model_cls.INDEX)
class ElasticDocumentMeta(type):
def __new__(mcs, name, bases, attrs):
c = super(ElasticDocumentMeta, mcs).__new__(
mcs, name, bases, attrs)
c.objects = ElasticDocumentManager(c)
c.index = ElasticIndexManager(c)
return c | self.latest_raw_result = result
for hit in result['hits']['hits']: | random_line_split |
managers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
import time
from collections import OrderedDict
from contextlib import contextmanager
import six
from django.utils.functional import cached_property
from .client import get_es_client
logger = logging.getLogger('elasticindex')
class ElasticQuerySet(object):
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.body = body or {"query": {"match_all": {}}}
self.kwargs = kwargs or {}
self.latest_total_count = None
self.latest_raw_result = None
self.query_finished = False
def __len__(self):
return len(self.result_list)
def __iter__(self):
return iter(self.result_list)
def __bool__(self):
return bool(self.result_list)
def __getitem__(self, k):
"""
Retrieves an item or slice from the set of results.
"""
if not isinstance(k, (slice,) + six.integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0)) or
(isinstance(k, slice) and (k.start is None or k.start >= 0) and
(k.stop is None or k.stop >= 0))), \
"Negative indexing is not supported."
if self.query_finished:
return self.result_list[k]
if isinstance(k, slice):
qs = self
offset = 0
if k.start is not None:
offset = int(k.start)
qs = qs.offset(offset)
if k.stop is not None:
limit = int(k.stop) - offset
qs = qs.limit(limit)
return list(qs)[::k.step] if k.step else qs
qs = self.limit(1).offset(k)
return list(qs)[0]
def _clone(self):
"""
:rtype: ElasticQuerySet
"""
qs = self.__class__(
self.model_cls, copy.deepcopy(self.body),
**copy.deepcopy(self.kwargs))
return qs
@cached_property
def result_list(self):
self.query_finished = True
return list(self.get_result())
def get_result(self):
"""
elasticsearch の search をそのまま実行
:rtype: generator
"""
with self.log_query():
result = self.es_client.search(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=self.body, **self.kwargs)
self.latest_total_count = result['hits']['total']
self.latest_raw_result = result
for hit in result['hits']['hits']:
yield self.model_cls(hit)
@cached_property
def es_client(self):
"""
:rtype: Elasticsearch
"""
return get_es_client()
def get_by_id(self, id):
"""
Elasticsearch のIDで1件取得
:param id:
:return:
"""
result = self.es_client.get(
self.model_cls.INDEX, id, doc_type=self.model_cls.DOC_TYPE)
self.latest_raw_result = result
if not result['found']:
raise self.model_cls.DoesNotExist(id)
return self.model_cls(result)
def delete_by_id(self, id, **kwargs):
"""
Elasticsearch のIDで1件削除
:param id: elasticsearch document id
"""
result = self.es_client.delete(
self.model_cls.INDEX, self.model_cls.DOC_TYPE, id, **kwargs)
self.latest_raw_result = result
return result
def all(self):
"""
:rtype: ElasticQuerySet
"""
return self._clone()
def limit(self, limit):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if limit is None:
if 'size' in o.body:
del o.body['size']
else:
o.body['size'] = limit
return o
def offset(self, offset):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if offset is None:
if 'from' in o.body:
del o.body['from']
else:
o.body['from'] = offset
return o
def query(self, filter_query_dict):
"""
:param filter_query_dict:
- {"match": {"product_id": 192}}
- {"match_all": {}} # default
- {"multi_match": {
"query": query_word,
"fields": [
"upc", "title^3", "description", "authors",
"publishers", "tags", "keywords"]
}}
- {"bool": {
"must": [
{"match": {"is_used": True}},
{"range": {"stock": {"gt": 0}}}
]}}
:rtype: ElasticQuerySet
"""
o = self._clone()
o.body['query'] = filter_query_dict
return o
def set_body(self, body_dict):
"""
replace query body
"""
o = self._clone()
o.body = body_dict
return o
def get(self, filter_query_dict):
"""
1件取得
複数件あってもエラーは出さず、黙って1件だけ返す
"""
qs = self.query(filter_query_dict).limit(1)
if not qs:
raise self.model_cls.DoesNotExist(filter_query_dict)
return qs[0]
def count(self):
"""
件数取得
"""
if self.query_finished:
return len(self.result_list)
body = self.body.copy()
if 'sort' in body:
del body['sort']
with self.log_query(label='count', body=body):
result = self.es_client.count(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=body, **self.kwargs
)
self.latest_raw_result = result
return result['count']
def order_by(self, order_query_list):
"""
sort パラメータをつける
:type order_query_list: list, dict, string
- "mz_score"
- {"mz_score": "desc"}
"""
o = self._clone()
o.body['sort'] = order_query_list
return o
@property
def log_query(self):
"""
クエリをロギングするコンテクストマネージャ
elasticsearch や elasticsearch.trace のロガーを
DEBUG レベルで設定するともっと詳しく出る (結果が全部出る)
"""
@contextmanager
def _context(label='', body=None):
start_time = time.time()
yield
elapsed_time = time.time() - start_time
logger.debug('{}time:{}ms, body:{}'.format(
'{}: '.format(label) if label else '',
int(elapsed_time * 100), body or self.body))
return _context
def bulk(self, body):
return self.es_client.bulk(
body, index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE)
class ElasticDocumentManager(object):
"""
class ElasticDocum | anager(ElasticQuerySet)
でもいいんだけど、インスタンス変数が汚れる可能性があるので
クラスプロパティっぽい感じで、アクセスされるたびに新しいクエリセットを作ることにした
"""
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.kwargs = kwargs
def __get__(self, cls, owner):
return ElasticQuerySet(self.model_cls)
class ElasticIndexManager(object):
def __init__(self, model_cls):
self.model_cls = model_cls
@cached_property
def mappings_properties(self):
return OrderedDict(
[
(f_name, f.mapping)
for f_name, f
in self.model_cls._cached_fields().items()
])
@cached_property
def mappings(self):
"""
インデックスの mappings の指定にそのまま使える dict
"""
return {
self.model_cls.DOC_TYPE: {
"properties": self.mappings_properties
}
}
def delete(self):
"""
インデックスを削除
:return:
"""
es = get_es_client()
es.indices.delete(self.model_cls.INDEX, ignore=[404, ])
@cached_property
def create_body_params(self):
body = {"mappings": self.mappings}
index_setting = getattr(self.model_cls, 'INDEX_SETTINGS', None)
if index_setting:
body["settings"] = index_setting
return body
def create(self):
"""
インデックスを作成
:return:
"""
es = get_es_client()
es.indices.create(
self.model_cls.INDEX, self.create_body_params)
def exists(self):
"""
インデックスが存在するか
"""
es = get_es_client()
return es.indices.exists(self.model_cls.INDEX)
class ElasticDocumentMeta(type):
def __new__(mcs, name, bases, attrs):
c = super(ElasticDocumentMeta, mcs).__new__(
mcs, name, bases, attrs)
c.objects = ElasticDocumentManager(c)
c.index = ElasticIndexManager(c)
return c
| entM | identifier_name |
managers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
import time
from collections import OrderedDict
from contextlib import contextmanager
import six
from django.utils.functional import cached_property
from .client import get_es_client
logger = logging.getLogger('elasticindex')
class ElasticQuerySet(object):
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.body = body or {"query": {"match_all": {}}}
self.kwargs = kwargs or {}
self.latest_total_count = None
self.latest_raw_result = None
self.query_finished = False
def __len__(self):
return len(self.result_list)
def __iter__(self):
return iter(self.result_list)
def __bool__(self):
return bool(self.result_list)
def __getitem__(self, k):
"""
Retrieves an item or slice from the set of results.
"""
if not isinstance(k, (slice,) + six.integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0)) or
(isinstance(k, slice) and (k.start is None or k.start >= 0) and
(k.stop is None or k.stop >= 0))), \
"Negative indexing is not supported."
if self.query_finished:
return self.result_list[k]
if isinstance(k, slice):
qs = self
offset = 0
if k.start is not None:
offset = int(k.start)
qs = qs.offset(offset)
if k.stop is not None:
limit = int(k.stop) - offset
qs = qs.limit(limit)
return list(qs)[::k.step] if k.step else qs
qs = self.limit(1).offset(k)
return list(qs)[0]
def _clone(self):
"""
:rtype: ElasticQuerySet
"""
qs = self.__class__(
self.model_cls, copy.deepcopy(self.body),
**copy.deepcopy(self.kwargs))
return qs
@cached_property
def result_list(self):
self.query_finished = True
return list(self.get_result())
def get_result(self):
"""
elasticsearch の search をそのまま実行
:rtype: generator
"""
with self.log_query():
result = self.es_client.search(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=self.body, **self.kwargs)
self.latest_total_count = result['hits']['total']
self.latest_raw_result = result
for hit in result['hits']['hits']:
yield self.model_cls(hit)
@cached_property
def es_client(self):
"""
:rtype: Elasticsearch
"""
return get_es_client()
def get_by_id(self, id):
"""
Elasticsearch のIDで1件取得
:param id:
:return:
"""
result = self.es_client.get(
self.model_cls.INDEX, id, doc_type=self.model_cls.DOC_TYPE)
self.latest_raw_result = result
if not result['found']:
raise self.model_cls.DoesNotExist(id)
return self.model_cls(result)
def delete_by_id(self, id, **kwargs):
"""
Elasticsearch のIDで1件削除
:param id: elasticsearch document id
"""
result = self.es_client.delete(
self.model_cls.INDEX, self.model_cls.DOC_TYPE, id, **kwargs)
self.latest_raw_result = result
return result
def all(self):
"""
:rtype: ElasticQuerySet
"""
return self._clone()
def limit(self, limit):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if limit is None:
if 'size' in o.body:
del o.body['size']
else:
o.body['size'] = limit
return o
def offset(self, offset):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if offset is None:
if 'from' in o.body:
| rom'] = offset
return o
def query(self, filter_query_dict):
"""
:param filter_query_dict:
- {"match": {"product_id": 192}}
- {"match_all": {}} # default
- {"multi_match": {
"query": query_word,
"fields": [
"upc", "title^3", "description", "authors",
"publishers", "tags", "keywords"]
}}
- {"bool": {
"must": [
{"match": {"is_used": True}},
{"range": {"stock": {"gt": 0}}}
]}}
:rtype: ElasticQuerySet
"""
o = self._clone()
o.body['query'] = filter_query_dict
return o
def set_body(self, body_dict):
"""
replace query body
"""
o = self._clone()
o.body = body_dict
return o
def get(self, filter_query_dict):
"""
1件取得
複数件あってもエラーは出さず、黙って1件だけ返す
"""
qs = self.query(filter_query_dict).limit(1)
if not qs:
raise self.model_cls.DoesNotExist(filter_query_dict)
return qs[0]
def count(self):
"""
件数取得
"""
if self.query_finished:
return len(self.result_list)
body = self.body.copy()
if 'sort' in body:
del body['sort']
with self.log_query(label='count', body=body):
result = self.es_client.count(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=body, **self.kwargs
)
self.latest_raw_result = result
return result['count']
def order_by(self, order_query_list):
"""
sort パラメータをつける
:type order_query_list: list, dict, string
- "mz_score"
- {"mz_score": "desc"}
"""
o = self._clone()
o.body['sort'] = order_query_list
return o
@property
def log_query(self):
"""
クエリをロギングするコンテクストマネージャ
elasticsearch や elasticsearch.trace のロガーを
DEBUG レベルで設定するともっと詳しく出る (結果が全部出る)
"""
@contextmanager
def _context(label='', body=None):
start_time = time.time()
yield
elapsed_time = time.time() - start_time
logger.debug('{}time:{}ms, body:{}'.format(
'{}: '.format(label) if label else '',
int(elapsed_time * 100), body or self.body))
return _context
def bulk(self, body):
return self.es_client.bulk(
body, index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE)
class ElasticDocumentManager(object):
"""
class ElasticDocumentManager(ElasticQuerySet)
でもいいんだけど、インスタンス変数が汚れる可能性があるので
クラスプロパティっぽい感じで、アクセスされるたびに新しいクエリセットを作ることにした
"""
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.kwargs = kwargs
def __get__(self, cls, owner):
return ElasticQuerySet(self.model_cls)
class ElasticIndexManager(object):
def __init__(self, model_cls):
self.model_cls = model_cls
@cached_property
def mappings_properties(self):
return OrderedDict(
[
(f_name, f.mapping)
for f_name, f
in self.model_cls._cached_fields().items()
])
@cached_property
def mappings(self):
"""
インデックスの mappings の指定にそのまま使える dict
"""
return {
self.model_cls.DOC_TYPE: {
"properties": self.mappings_properties
}
}
def delete(self):
"""
インデックスを削除
:return:
"""
es = get_es_client()
es.indices.delete(self.model_cls.INDEX, ignore=[404, ])
@cached_property
def create_body_params(self):
body = {"mappings": self.mappings}
index_setting = getattr(self.model_cls, 'INDEX_SETTINGS', None)
if index_setting:
body["settings"] = index_setting
return body
def create(self):
"""
インデックスを作成
:return:
"""
es = get_es_client()
es.indices.create(
self.model_cls.INDEX, self.create_body_params)
def exists(self):
"""
インデックスが存在するか
"""
es = get_es_client()
return es.indices.exists(self.model_cls.INDEX)
class ElasticDocumentMeta(type):
def __new__(mcs, name, bases, attrs):
c = super(ElasticDocumentMeta, mcs).__new__(
mcs, name, bases, attrs)
c.objects = ElasticDocumentManager(c)
c.index = ElasticIndexManager(c)
return c
| del o.body['from']
else:
o.body['f | conditional_block |
managers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
import time
from collections import OrderedDict
from contextlib import contextmanager
import six
from django.utils.functional import cached_property
from .client import get_es_client
logger = logging.getLogger('elasticindex')
class ElasticQuerySet(object):
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.body = body or {"query": {"match_all": {}}}
self.kwargs = kwargs or {}
self.latest_total_count = None
self.latest_raw_result = None
self.query_finished = False
def __len__(self):
return len(self.result_list)
def __iter__(self):
return iter(self.result_list)
def __bool__(self):
|
def __getitem__(self, k):
"""
Retrieves an item or slice from the set of results.
"""
if not isinstance(k, (slice,) + six.integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0)) or
(isinstance(k, slice) and (k.start is None or k.start >= 0) and
(k.stop is None or k.stop >= 0))), \
"Negative indexing is not supported."
if self.query_finished:
return self.result_list[k]
if isinstance(k, slice):
qs = self
offset = 0
if k.start is not None:
offset = int(k.start)
qs = qs.offset(offset)
if k.stop is not None:
limit = int(k.stop) - offset
qs = qs.limit(limit)
return list(qs)[::k.step] if k.step else qs
qs = self.limit(1).offset(k)
return list(qs)[0]
def _clone(self):
"""
:rtype: ElasticQuerySet
"""
qs = self.__class__(
self.model_cls, copy.deepcopy(self.body),
**copy.deepcopy(self.kwargs))
return qs
@cached_property
def result_list(self):
self.query_finished = True
return list(self.get_result())
def get_result(self):
"""
elasticsearch の search をそのまま実行
:rtype: generator
"""
with self.log_query():
result = self.es_client.search(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=self.body, **self.kwargs)
self.latest_total_count = result['hits']['total']
self.latest_raw_result = result
for hit in result['hits']['hits']:
yield self.model_cls(hit)
@cached_property
def es_client(self):
"""
:rtype: Elasticsearch
"""
return get_es_client()
def get_by_id(self, id):
"""
Elasticsearch のIDで1件取得
:param id:
:return:
"""
result = self.es_client.get(
self.model_cls.INDEX, id, doc_type=self.model_cls.DOC_TYPE)
self.latest_raw_result = result
if not result['found']:
raise self.model_cls.DoesNotExist(id)
return self.model_cls(result)
def delete_by_id(self, id, **kwargs):
"""
Elasticsearch のIDで1件削除
:param id: elasticsearch document id
"""
result = self.es_client.delete(
self.model_cls.INDEX, self.model_cls.DOC_TYPE, id, **kwargs)
self.latest_raw_result = result
return result
def all(self):
"""
:rtype: ElasticQuerySet
"""
return self._clone()
def limit(self, limit):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if limit is None:
if 'size' in o.body:
del o.body['size']
else:
o.body['size'] = limit
return o
def offset(self, offset):
"""
:rtype: ElasticQuerySet
"""
o = self._clone()
if offset is None:
if 'from' in o.body:
del o.body['from']
else:
o.body['from'] = offset
return o
def query(self, filter_query_dict):
"""
:param filter_query_dict:
- {"match": {"product_id": 192}}
- {"match_all": {}} # default
- {"multi_match": {
"query": query_word,
"fields": [
"upc", "title^3", "description", "authors",
"publishers", "tags", "keywords"]
}}
- {"bool": {
"must": [
{"match": {"is_used": True}},
{"range": {"stock": {"gt": 0}}}
]}}
:rtype: ElasticQuerySet
"""
o = self._clone()
o.body['query'] = filter_query_dict
return o
def set_body(self, body_dict):
"""
replace query body
"""
o = self._clone()
o.body = body_dict
return o
def get(self, filter_query_dict):
"""
1件取得
複数件あってもエラーは出さず、黙って1件だけ返す
"""
qs = self.query(filter_query_dict).limit(1)
if not qs:
raise self.model_cls.DoesNotExist(filter_query_dict)
return qs[0]
def count(self):
"""
件数取得
"""
if self.query_finished:
return len(self.result_list)
body = self.body.copy()
if 'sort' in body:
del body['sort']
with self.log_query(label='count', body=body):
result = self.es_client.count(
index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE,
body=body, **self.kwargs
)
self.latest_raw_result = result
return result['count']
def order_by(self, order_query_list):
"""
sort パラメータをつける
:type order_query_list: list, dict, string
- "mz_score"
- {"mz_score": "desc"}
"""
o = self._clone()
o.body['sort'] = order_query_list
return o
@property
def log_query(self):
"""
クエリをロギングするコンテクストマネージャ
elasticsearch や elasticsearch.trace のロガーを
DEBUG レベルで設定するともっと詳しく出る (結果が全部出る)
"""
@contextmanager
def _context(label='', body=None):
start_time = time.time()
yield
elapsed_time = time.time() - start_time
logger.debug('{}time:{}ms, body:{}'.format(
'{}: '.format(label) if label else '',
int(elapsed_time * 100), body or self.body))
return _context
def bulk(self, body):
return self.es_client.bulk(
body, index=self.model_cls.INDEX,
doc_type=self.model_cls.DOC_TYPE)
class ElasticDocumentManager(object):
"""
class ElasticDocumentManager(ElasticQuerySet)
でもいいんだけど、インスタンス変数が汚れる可能性があるので
クラスプロパティっぽい感じで、アクセスされるたびに新しいクエリセットを作ることにした
"""
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.kwargs = kwargs
def __get__(self, cls, owner):
return ElasticQuerySet(self.model_cls)
class ElasticIndexManager(object):
def __init__(self, model_cls):
self.model_cls = model_cls
@cached_property
def mappings_properties(self):
return OrderedDict(
[
(f_name, f.mapping)
for f_name, f
in self.model_cls._cached_fields().items()
])
@cached_property
def mappings(self):
"""
インデックスの mappings の指定にそのまま使える dict
"""
return {
self.model_cls.DOC_TYPE: {
"properties": self.mappings_properties
}
}
def delete(self):
"""
インデックスを削除
:return:
"""
es = get_es_client()
es.indices.delete(self.model_cls.INDEX, ignore=[404, ])
@cached_property
def create_body_params(self):
body = {"mappings": self.mappings}
index_setting = getattr(self.model_cls, 'INDEX_SETTINGS', None)
if index_setting:
body["settings"] = index_setting
return body
def create(self):
"""
インデックスを作成
:return:
"""
es = get_es_client()
es.indices.create(
self.model_cls.INDEX, self.create_body_params)
def exists(self):
"""
インデックスが存在するか
"""
es = get_es_client()
return es.indices.exists(self.model_cls.INDEX)
class ElasticDocumentMeta(type):
def __new__(mcs, name, bases, attrs):
c = super(ElasticDocumentMeta, mcs).__new__(
mcs, name, bases, attrs)
c.objects = ElasticDocumentManager(c)
c.index = ElasticIndexManager(c)
return c
| return bool(self.result_list) | identifier_body |
__init__.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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.
from designate.api.v2 import patches # flake8: noqa
import pecan.deploy
from oslo.config import cfg
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def factory(global_config, **local_conf):
if not cfg.CONF['service:api'].enable_api_v2:
|
conf = {
'app': {
'root': 'designate.api.v2.controllers.root.RootController',
'modules': ['designate.api.v2']
}
}
app = pecan.deploy.deploy(conf)
return app
| def disabled_app(environ, start_response):
status = '404 Not Found'
start_response(status, [])
return []
return disabled_app | conditional_block |
__init__.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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.
from designate.api.v2 import patches # flake8: noqa
import pecan.deploy
from oslo.config import cfg
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def factory(global_config, **local_conf):
| if not cfg.CONF['service:api'].enable_api_v2:
def disabled_app(environ, start_response):
status = '404 Not Found'
start_response(status, [])
return []
return disabled_app
conf = {
'app': {
'root': 'designate.api.v2.controllers.root.RootController',
'modules': ['designate.api.v2']
}
}
app = pecan.deploy.deploy(conf)
return app | identifier_body | |
__init__.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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 | from oslo.config import cfg
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def factory(global_config, **local_conf):
if not cfg.CONF['service:api'].enable_api_v2:
def disabled_app(environ, start_response):
status = '404 Not Found'
start_response(status, [])
return []
return disabled_app
conf = {
'app': {
'root': 'designate.api.v2.controllers.root.RootController',
'modules': ['designate.api.v2']
}
}
app = pecan.deploy.deploy(conf)
return app | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from designate.api.v2 import patches # flake8: noqa
import pecan.deploy | random_line_split |
__init__.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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.
from designate.api.v2 import patches # flake8: noqa
import pecan.deploy
from oslo.config import cfg
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def | (global_config, **local_conf):
if not cfg.CONF['service:api'].enable_api_v2:
def disabled_app(environ, start_response):
status = '404 Not Found'
start_response(status, [])
return []
return disabled_app
conf = {
'app': {
'root': 'designate.api.v2.controllers.root.RootController',
'modules': ['designate.api.v2']
}
}
app = pecan.deploy.deploy(conf)
return app
| factory | identifier_name |
__init__.py | """Multidict implementation.
HTTP Headers and URL query string require specific data structure:
multidict. It behaves mostly like a dict but it can have
several values for the same key.
"""
import os
__all__ = ('MultiDictProxy', 'CIMultiDictProxy',
'MultiDict', 'CIMultiDict', 'upstr', 'istr')
__version__ = '2.1.5'
if bool(os.environ.get('MULTIDICT_NO_EXTENSIONS')):
from ._multidict_py import (MultiDictProxy,
CIMultiDictProxy,
MultiDict,
CIMultiDict,
upstr, istr)
else:
try:
from ._multidict import (MultiDictProxy,
CIMultiDictProxy, | CIMultiDictProxy,
MultiDict,
CIMultiDict,
upstr, istr) | MultiDict,
CIMultiDict,
upstr, istr)
except ImportError: # pragma: no cover
from ._multidict_py import (MultiDictProxy, | random_line_split |
__init__.py | """Multidict implementation.
HTTP Headers and URL query string require specific data structure:
multidict. It behaves mostly like a dict but it can have
several values for the same key.
"""
import os
__all__ = ('MultiDictProxy', 'CIMultiDictProxy',
'MultiDict', 'CIMultiDict', 'upstr', 'istr')
__version__ = '2.1.5'
if bool(os.environ.get('MULTIDICT_NO_EXTENSIONS')):
from ._multidict_py import (MultiDictProxy,
CIMultiDictProxy,
MultiDict,
CIMultiDict,
upstr, istr)
else:
| try:
from ._multidict import (MultiDictProxy,
CIMultiDictProxy,
MultiDict,
CIMultiDict,
upstr, istr)
except ImportError: # pragma: no cover
from ._multidict_py import (MultiDictProxy,
CIMultiDictProxy,
MultiDict,
CIMultiDict,
upstr, istr) | conditional_block | |
entity.js | var entity = function() {
this.width = 0;
this.height = 0;
this.scale = 1;
this.x = 0;
this.y = 0;
this.image = null;
this.imageWidth = 0;
this.imageHeight = 0;
};
entity.prototype = entity;
entity.prototype.init = function(width, height, scale) {
this.width = width;
this.height = height;
this.scale = scale;
this.x = 0;
this.y = 0;
}
entity.prototype.draw = function(ctx) {
alert("this is base entity");
}
entity.prototype.setImage = function(img, imgWidth, imgHeight) {
this.image = img;
this.imageWidth = imgWidth;
this.imageHeight = imgHeight;
}
entity.prototype.setPos = function(x,y) { | }
entity.prototype.moveRight = function(shift) {
this.x += shift;
}
entity.prototype.moveLeft = function(shift) {
this.x -= shift;
}
entity.prototype.moveUp = function(shift) {
this.y -= shift;
}
entity.prototype.moveDown = function(shift) {
this.y += shift;
} | this.x = x;
this.y = y; | random_line_split |
security_dataset_tests.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit tests for Superset"""
import json
import prison
import pytest
from flask import escape
from superset import app
from superset.models import core as models
from tests.integration_tests.dashboards.base_case import DashboardTestCase
from tests.integration_tests.dashboards.consts import *
from tests.integration_tests.dashboards.dashboard_test_utils import *
from tests.integration_tests.dashboards.superset_factory_util import *
from tests.integration_tests.fixtures.energy_dashboard import (
load_energy_table_with_slice,
)
class TestDashboardDatasetSecurity(DashboardTestCase):
@pytest.fixture
def load_dashboard(self):
with app.app_context():
table = (
db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
)
# get a slice from the allowed table
slice = db.session.query(Slice).filter_by(slice_name="Energy Sankey").one()
self.grant_public_access_to_table(table)
pytest.hidden_dash_slug = f"hidden_dash_{random_slug()}"
pytest.published_dash_slug = f"published_dash_{random_slug()}"
# Create a published and hidden dashboard and add them to the database
published_dash = Dashboard()
published_dash.dashboard_title = "Published Dashboard"
published_dash.slug = pytest.published_dash_slug
published_dash.slices = [slice]
published_dash.published = True
hidden_dash = Dashboard()
hidden_dash.dashboard_title = "Hidden Dashboard"
hidden_dash.slug = pytest.hidden_dash_slug
hidden_dash.slices = [slice]
hidden_dash.published = False
db.session.merge(published_dash)
db.session.merge(hidden_dash)
yield db.session.commit()
self.revoke_public_access_to_table(table)
db.session.delete(published_dash)
db.session.delete(hidden_dash)
db.session.commit()
def test_dashboard_access__admin_can_access_all(self):
# arrange
self.login(username=ADMIN_USERNAME)
dashboard_title_by_url = {
dash.url: dash.dashboard_title for dash in get_all_dashboards()
}
# act
responses_by_url = {
url: self.client.get(url) for url in dashboard_title_by_url.keys()
}
# assert
for dashboard_url, get_dashboard_response in responses_by_url.items():
|
def test_get_dashboards__users_are_dashboards_owners(self):
# arrange
username = "gamma"
user = security_manager.find_user(username)
my_owned_dashboard = create_dashboard_to_db(
dashboard_title="My Dashboard", published=False, owners=[user],
)
not_my_owned_dashboard = create_dashboard_to_db(
dashboard_title="Not My Dashboard", published=False,
)
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(my_owned_dashboard.url, get_dashboards_response)
self.assertNotIn(not_my_owned_dashboard.url, get_dashboards_response)
def test_get_dashboards__owners_can_view_empty_dashboard(self):
# arrange
dash = create_dashboard_to_db("Empty Dashboard", slug="empty_dashboard")
dashboard_url = dash.url
gamma_user = security_manager.find_user("gamma")
self.login(gamma_user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(dashboard_url, get_dashboards_response)
def test_get_dashboards__users_can_view_favorites_dashboards(self):
# arrange
user = security_manager.find_user("gamma")
fav_dash_slug = f"my_favorite_dash_{random_slug()}"
regular_dash_slug = f"regular_dash_{random_slug()}"
favorite_dash = Dashboard()
favorite_dash.dashboard_title = "My Favorite Dashboard"
favorite_dash.slug = fav_dash_slug
regular_dash = Dashboard()
regular_dash.dashboard_title = "A Plain Ol Dashboard"
regular_dash.slug = regular_dash_slug
db.session.merge(favorite_dash)
db.session.merge(regular_dash)
db.session.commit()
dash = db.session.query(Dashboard).filter_by(slug=fav_dash_slug).first()
favorites = models.FavStar()
favorites.obj_id = dash.id
favorites.class_name = "Dashboard"
favorites.user_id = user.id
db.session.merge(favorites)
db.session.commit()
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(f"/superset/dashboard/{fav_dash_slug}/", get_dashboards_response)
def test_get_dashboards__user_can_not_view_unpublished_dash(self):
# arrange
admin_user = security_manager.find_user(ADMIN_USERNAME)
gamma_user = security_manager.find_user(GAMMA_USERNAME)
admin_and_draft_dashboard = create_dashboard_to_db(
dashboard_title="admin_owned_unpublished_dash", owners=[admin_user]
)
self.login(gamma_user.username)
# act - list dashboards as a gamma user
get_dashboards_response_as_gamma = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(
admin_and_draft_dashboard.url, get_dashboards_response_as_gamma
)
@pytest.mark.usefixtures("load_energy_table_with_slice", "load_dashboard")
def test_get_dashboards__users_can_view_permitted_dashboard(self):
# arrange
username = random_str()
new_role = f"role_{random_str()}"
self.create_user_with_roles(username, [new_role], should_create_roles=True)
accessed_table = get_sql_table_by_name("energy_usage")
self.grant_role_access_to_table(accessed_table, new_role)
# get a slice from the allowed table
slice_to_add_to_dashboards = get_slice_by_name("Energy Sankey")
# Create a published and hidden dashboard and add them to the database
first_dash = create_dashboard_to_db(
dashboard_title="Published Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
second_dash = create_dashboard_to_db(
dashboard_title="Hidden Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
try:
self.login(username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(second_dash.url, get_dashboards_response)
self.assertIn(first_dash.url, get_dashboards_response)
finally:
self.revoke_public_access_to_table(accessed_table)
def test_get_dashboards_api_no_data_access(self):
"""
Dashboard API: Test get dashboards no data access
"""
admin = self.get_user("admin")
title = f"title{random_str()}"
create_dashboard_to_db(title, "slug1", owners=[admin])
self.login(username="gamma")
arguments = {
"filters": [{"col": "dashboard_title", "opr": "sw", "value": title[0:8]}]
}
uri = DASHBOARDS_API_URL_WITH_QUERY_FORMAT.format(prison.dumps(arguments))
rv = self.client.get(uri)
self.assert200(rv)
data = json.loads(rv.data.decode("utf-8"))
self.assertEqual(0, data["count"])
| self.assert200(get_dashboard_response) | conditional_block |
security_dataset_tests.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit tests for Superset"""
import json
import prison
import pytest
from flask import escape
from superset import app
from superset.models import core as models
from tests.integration_tests.dashboards.base_case import DashboardTestCase
from tests.integration_tests.dashboards.consts import *
from tests.integration_tests.dashboards.dashboard_test_utils import *
from tests.integration_tests.dashboards.superset_factory_util import *
from tests.integration_tests.fixtures.energy_dashboard import (
load_energy_table_with_slice, | @pytest.fixture
def load_dashboard(self):
with app.app_context():
table = (
db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
)
# get a slice from the allowed table
slice = db.session.query(Slice).filter_by(slice_name="Energy Sankey").one()
self.grant_public_access_to_table(table)
pytest.hidden_dash_slug = f"hidden_dash_{random_slug()}"
pytest.published_dash_slug = f"published_dash_{random_slug()}"
# Create a published and hidden dashboard and add them to the database
published_dash = Dashboard()
published_dash.dashboard_title = "Published Dashboard"
published_dash.slug = pytest.published_dash_slug
published_dash.slices = [slice]
published_dash.published = True
hidden_dash = Dashboard()
hidden_dash.dashboard_title = "Hidden Dashboard"
hidden_dash.slug = pytest.hidden_dash_slug
hidden_dash.slices = [slice]
hidden_dash.published = False
db.session.merge(published_dash)
db.session.merge(hidden_dash)
yield db.session.commit()
self.revoke_public_access_to_table(table)
db.session.delete(published_dash)
db.session.delete(hidden_dash)
db.session.commit()
def test_dashboard_access__admin_can_access_all(self):
# arrange
self.login(username=ADMIN_USERNAME)
dashboard_title_by_url = {
dash.url: dash.dashboard_title for dash in get_all_dashboards()
}
# act
responses_by_url = {
url: self.client.get(url) for url in dashboard_title_by_url.keys()
}
# assert
for dashboard_url, get_dashboard_response in responses_by_url.items():
self.assert200(get_dashboard_response)
def test_get_dashboards__users_are_dashboards_owners(self):
# arrange
username = "gamma"
user = security_manager.find_user(username)
my_owned_dashboard = create_dashboard_to_db(
dashboard_title="My Dashboard", published=False, owners=[user],
)
not_my_owned_dashboard = create_dashboard_to_db(
dashboard_title="Not My Dashboard", published=False,
)
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(my_owned_dashboard.url, get_dashboards_response)
self.assertNotIn(not_my_owned_dashboard.url, get_dashboards_response)
def test_get_dashboards__owners_can_view_empty_dashboard(self):
# arrange
dash = create_dashboard_to_db("Empty Dashboard", slug="empty_dashboard")
dashboard_url = dash.url
gamma_user = security_manager.find_user("gamma")
self.login(gamma_user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(dashboard_url, get_dashboards_response)
def test_get_dashboards__users_can_view_favorites_dashboards(self):
# arrange
user = security_manager.find_user("gamma")
fav_dash_slug = f"my_favorite_dash_{random_slug()}"
regular_dash_slug = f"regular_dash_{random_slug()}"
favorite_dash = Dashboard()
favorite_dash.dashboard_title = "My Favorite Dashboard"
favorite_dash.slug = fav_dash_slug
regular_dash = Dashboard()
regular_dash.dashboard_title = "A Plain Ol Dashboard"
regular_dash.slug = regular_dash_slug
db.session.merge(favorite_dash)
db.session.merge(regular_dash)
db.session.commit()
dash = db.session.query(Dashboard).filter_by(slug=fav_dash_slug).first()
favorites = models.FavStar()
favorites.obj_id = dash.id
favorites.class_name = "Dashboard"
favorites.user_id = user.id
db.session.merge(favorites)
db.session.commit()
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(f"/superset/dashboard/{fav_dash_slug}/", get_dashboards_response)
def test_get_dashboards__user_can_not_view_unpublished_dash(self):
# arrange
admin_user = security_manager.find_user(ADMIN_USERNAME)
gamma_user = security_manager.find_user(GAMMA_USERNAME)
admin_and_draft_dashboard = create_dashboard_to_db(
dashboard_title="admin_owned_unpublished_dash", owners=[admin_user]
)
self.login(gamma_user.username)
# act - list dashboards as a gamma user
get_dashboards_response_as_gamma = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(
admin_and_draft_dashboard.url, get_dashboards_response_as_gamma
)
@pytest.mark.usefixtures("load_energy_table_with_slice", "load_dashboard")
def test_get_dashboards__users_can_view_permitted_dashboard(self):
# arrange
username = random_str()
new_role = f"role_{random_str()}"
self.create_user_with_roles(username, [new_role], should_create_roles=True)
accessed_table = get_sql_table_by_name("energy_usage")
self.grant_role_access_to_table(accessed_table, new_role)
# get a slice from the allowed table
slice_to_add_to_dashboards = get_slice_by_name("Energy Sankey")
# Create a published and hidden dashboard and add them to the database
first_dash = create_dashboard_to_db(
dashboard_title="Published Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
second_dash = create_dashboard_to_db(
dashboard_title="Hidden Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
try:
self.login(username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(second_dash.url, get_dashboards_response)
self.assertIn(first_dash.url, get_dashboards_response)
finally:
self.revoke_public_access_to_table(accessed_table)
def test_get_dashboards_api_no_data_access(self):
"""
Dashboard API: Test get dashboards no data access
"""
admin = self.get_user("admin")
title = f"title{random_str()}"
create_dashboard_to_db(title, "slug1", owners=[admin])
self.login(username="gamma")
arguments = {
"filters": [{"col": "dashboard_title", "opr": "sw", "value": title[0:8]}]
}
uri = DASHBOARDS_API_URL_WITH_QUERY_FORMAT.format(prison.dumps(arguments))
rv = self.client.get(uri)
self.assert200(rv)
data = json.loads(rv.data.decode("utf-8"))
self.assertEqual(0, data["count"]) | )
class TestDashboardDatasetSecurity(DashboardTestCase): | random_line_split |
security_dataset_tests.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit tests for Superset"""
import json
import prison
import pytest
from flask import escape
from superset import app
from superset.models import core as models
from tests.integration_tests.dashboards.base_case import DashboardTestCase
from tests.integration_tests.dashboards.consts import *
from tests.integration_tests.dashboards.dashboard_test_utils import *
from tests.integration_tests.dashboards.superset_factory_util import *
from tests.integration_tests.fixtures.energy_dashboard import (
load_energy_table_with_slice,
)
class TestDashboardDatasetSecurity(DashboardTestCase):
@pytest.fixture
def load_dashboard(self):
with app.app_context():
table = (
db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
)
# get a slice from the allowed table
slice = db.session.query(Slice).filter_by(slice_name="Energy Sankey").one()
self.grant_public_access_to_table(table)
pytest.hidden_dash_slug = f"hidden_dash_{random_slug()}"
pytest.published_dash_slug = f"published_dash_{random_slug()}"
# Create a published and hidden dashboard and add them to the database
published_dash = Dashboard()
published_dash.dashboard_title = "Published Dashboard"
published_dash.slug = pytest.published_dash_slug
published_dash.slices = [slice]
published_dash.published = True
hidden_dash = Dashboard()
hidden_dash.dashboard_title = "Hidden Dashboard"
hidden_dash.slug = pytest.hidden_dash_slug
hidden_dash.slices = [slice]
hidden_dash.published = False
db.session.merge(published_dash)
db.session.merge(hidden_dash)
yield db.session.commit()
self.revoke_public_access_to_table(table)
db.session.delete(published_dash)
db.session.delete(hidden_dash)
db.session.commit()
def test_dashboard_access__admin_can_access_all(self):
# arrange
self.login(username=ADMIN_USERNAME)
dashboard_title_by_url = {
dash.url: dash.dashboard_title for dash in get_all_dashboards()
}
# act
responses_by_url = {
url: self.client.get(url) for url in dashboard_title_by_url.keys()
}
# assert
for dashboard_url, get_dashboard_response in responses_by_url.items():
self.assert200(get_dashboard_response)
def test_get_dashboards__users_are_dashboards_owners(self):
# arrange
username = "gamma"
user = security_manager.find_user(username)
my_owned_dashboard = create_dashboard_to_db(
dashboard_title="My Dashboard", published=False, owners=[user],
)
not_my_owned_dashboard = create_dashboard_to_db(
dashboard_title="Not My Dashboard", published=False,
)
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(my_owned_dashboard.url, get_dashboards_response)
self.assertNotIn(not_my_owned_dashboard.url, get_dashboards_response)
def test_get_dashboards__owners_can_view_empty_dashboard(self):
# arrange
dash = create_dashboard_to_db("Empty Dashboard", slug="empty_dashboard")
dashboard_url = dash.url
gamma_user = security_manager.find_user("gamma")
self.login(gamma_user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(dashboard_url, get_dashboards_response)
def | (self):
# arrange
user = security_manager.find_user("gamma")
fav_dash_slug = f"my_favorite_dash_{random_slug()}"
regular_dash_slug = f"regular_dash_{random_slug()}"
favorite_dash = Dashboard()
favorite_dash.dashboard_title = "My Favorite Dashboard"
favorite_dash.slug = fav_dash_slug
regular_dash = Dashboard()
regular_dash.dashboard_title = "A Plain Ol Dashboard"
regular_dash.slug = regular_dash_slug
db.session.merge(favorite_dash)
db.session.merge(regular_dash)
db.session.commit()
dash = db.session.query(Dashboard).filter_by(slug=fav_dash_slug).first()
favorites = models.FavStar()
favorites.obj_id = dash.id
favorites.class_name = "Dashboard"
favorites.user_id = user.id
db.session.merge(favorites)
db.session.commit()
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(f"/superset/dashboard/{fav_dash_slug}/", get_dashboards_response)
def test_get_dashboards__user_can_not_view_unpublished_dash(self):
# arrange
admin_user = security_manager.find_user(ADMIN_USERNAME)
gamma_user = security_manager.find_user(GAMMA_USERNAME)
admin_and_draft_dashboard = create_dashboard_to_db(
dashboard_title="admin_owned_unpublished_dash", owners=[admin_user]
)
self.login(gamma_user.username)
# act - list dashboards as a gamma user
get_dashboards_response_as_gamma = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(
admin_and_draft_dashboard.url, get_dashboards_response_as_gamma
)
@pytest.mark.usefixtures("load_energy_table_with_slice", "load_dashboard")
def test_get_dashboards__users_can_view_permitted_dashboard(self):
# arrange
username = random_str()
new_role = f"role_{random_str()}"
self.create_user_with_roles(username, [new_role], should_create_roles=True)
accessed_table = get_sql_table_by_name("energy_usage")
self.grant_role_access_to_table(accessed_table, new_role)
# get a slice from the allowed table
slice_to_add_to_dashboards = get_slice_by_name("Energy Sankey")
# Create a published and hidden dashboard and add them to the database
first_dash = create_dashboard_to_db(
dashboard_title="Published Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
second_dash = create_dashboard_to_db(
dashboard_title="Hidden Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
try:
self.login(username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(second_dash.url, get_dashboards_response)
self.assertIn(first_dash.url, get_dashboards_response)
finally:
self.revoke_public_access_to_table(accessed_table)
def test_get_dashboards_api_no_data_access(self):
"""
Dashboard API: Test get dashboards no data access
"""
admin = self.get_user("admin")
title = f"title{random_str()}"
create_dashboard_to_db(title, "slug1", owners=[admin])
self.login(username="gamma")
arguments = {
"filters": [{"col": "dashboard_title", "opr": "sw", "value": title[0:8]}]
}
uri = DASHBOARDS_API_URL_WITH_QUERY_FORMAT.format(prison.dumps(arguments))
rv = self.client.get(uri)
self.assert200(rv)
data = json.loads(rv.data.decode("utf-8"))
self.assertEqual(0, data["count"])
| test_get_dashboards__users_can_view_favorites_dashboards | identifier_name |
security_dataset_tests.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit tests for Superset"""
import json
import prison
import pytest
from flask import escape
from superset import app
from superset.models import core as models
from tests.integration_tests.dashboards.base_case import DashboardTestCase
from tests.integration_tests.dashboards.consts import *
from tests.integration_tests.dashboards.dashboard_test_utils import *
from tests.integration_tests.dashboards.superset_factory_util import *
from tests.integration_tests.fixtures.energy_dashboard import (
load_energy_table_with_slice,
)
class TestDashboardDatasetSecurity(DashboardTestCase):
| @pytest.fixture
def load_dashboard(self):
with app.app_context():
table = (
db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
)
# get a slice from the allowed table
slice = db.session.query(Slice).filter_by(slice_name="Energy Sankey").one()
self.grant_public_access_to_table(table)
pytest.hidden_dash_slug = f"hidden_dash_{random_slug()}"
pytest.published_dash_slug = f"published_dash_{random_slug()}"
# Create a published and hidden dashboard and add them to the database
published_dash = Dashboard()
published_dash.dashboard_title = "Published Dashboard"
published_dash.slug = pytest.published_dash_slug
published_dash.slices = [slice]
published_dash.published = True
hidden_dash = Dashboard()
hidden_dash.dashboard_title = "Hidden Dashboard"
hidden_dash.slug = pytest.hidden_dash_slug
hidden_dash.slices = [slice]
hidden_dash.published = False
db.session.merge(published_dash)
db.session.merge(hidden_dash)
yield db.session.commit()
self.revoke_public_access_to_table(table)
db.session.delete(published_dash)
db.session.delete(hidden_dash)
db.session.commit()
def test_dashboard_access__admin_can_access_all(self):
# arrange
self.login(username=ADMIN_USERNAME)
dashboard_title_by_url = {
dash.url: dash.dashboard_title for dash in get_all_dashboards()
}
# act
responses_by_url = {
url: self.client.get(url) for url in dashboard_title_by_url.keys()
}
# assert
for dashboard_url, get_dashboard_response in responses_by_url.items():
self.assert200(get_dashboard_response)
def test_get_dashboards__users_are_dashboards_owners(self):
# arrange
username = "gamma"
user = security_manager.find_user(username)
my_owned_dashboard = create_dashboard_to_db(
dashboard_title="My Dashboard", published=False, owners=[user],
)
not_my_owned_dashboard = create_dashboard_to_db(
dashboard_title="Not My Dashboard", published=False,
)
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(my_owned_dashboard.url, get_dashboards_response)
self.assertNotIn(not_my_owned_dashboard.url, get_dashboards_response)
def test_get_dashboards__owners_can_view_empty_dashboard(self):
# arrange
dash = create_dashboard_to_db("Empty Dashboard", slug="empty_dashboard")
dashboard_url = dash.url
gamma_user = security_manager.find_user("gamma")
self.login(gamma_user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(dashboard_url, get_dashboards_response)
def test_get_dashboards__users_can_view_favorites_dashboards(self):
# arrange
user = security_manager.find_user("gamma")
fav_dash_slug = f"my_favorite_dash_{random_slug()}"
regular_dash_slug = f"regular_dash_{random_slug()}"
favorite_dash = Dashboard()
favorite_dash.dashboard_title = "My Favorite Dashboard"
favorite_dash.slug = fav_dash_slug
regular_dash = Dashboard()
regular_dash.dashboard_title = "A Plain Ol Dashboard"
regular_dash.slug = regular_dash_slug
db.session.merge(favorite_dash)
db.session.merge(regular_dash)
db.session.commit()
dash = db.session.query(Dashboard).filter_by(slug=fav_dash_slug).first()
favorites = models.FavStar()
favorites.obj_id = dash.id
favorites.class_name = "Dashboard"
favorites.user_id = user.id
db.session.merge(favorites)
db.session.commit()
self.login(user.username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(f"/superset/dashboard/{fav_dash_slug}/", get_dashboards_response)
def test_get_dashboards__user_can_not_view_unpublished_dash(self):
# arrange
admin_user = security_manager.find_user(ADMIN_USERNAME)
gamma_user = security_manager.find_user(GAMMA_USERNAME)
admin_and_draft_dashboard = create_dashboard_to_db(
dashboard_title="admin_owned_unpublished_dash", owners=[admin_user]
)
self.login(gamma_user.username)
# act - list dashboards as a gamma user
get_dashboards_response_as_gamma = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertNotIn(
admin_and_draft_dashboard.url, get_dashboards_response_as_gamma
)
@pytest.mark.usefixtures("load_energy_table_with_slice", "load_dashboard")
def test_get_dashboards__users_can_view_permitted_dashboard(self):
# arrange
username = random_str()
new_role = f"role_{random_str()}"
self.create_user_with_roles(username, [new_role], should_create_roles=True)
accessed_table = get_sql_table_by_name("energy_usage")
self.grant_role_access_to_table(accessed_table, new_role)
# get a slice from the allowed table
slice_to_add_to_dashboards = get_slice_by_name("Energy Sankey")
# Create a published and hidden dashboard and add them to the database
first_dash = create_dashboard_to_db(
dashboard_title="Published Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
second_dash = create_dashboard_to_db(
dashboard_title="Hidden Dashboard",
published=True,
slices=[slice_to_add_to_dashboards],
)
try:
self.login(username)
# act
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL)
# assert
self.assertIn(second_dash.url, get_dashboards_response)
self.assertIn(first_dash.url, get_dashboards_response)
finally:
self.revoke_public_access_to_table(accessed_table)
def test_get_dashboards_api_no_data_access(self):
"""
Dashboard API: Test get dashboards no data access
"""
admin = self.get_user("admin")
title = f"title{random_str()}"
create_dashboard_to_db(title, "slug1", owners=[admin])
self.login(username="gamma")
arguments = {
"filters": [{"col": "dashboard_title", "opr": "sw", "value": title[0:8]}]
}
uri = DASHBOARDS_API_URL_WITH_QUERY_FORMAT.format(prison.dumps(arguments))
rv = self.client.get(uri)
self.assert200(rv)
data = json.loads(rv.data.decode("utf-8"))
self.assertEqual(0, data["count"]) | identifier_body | |
passport.js | /**
* Passport configuration
*
* This is the configuration for your Passport.js setup and where you
* define the authentication strategies you want your application to employ.
*
* I have tested the service with all of the providers listed below - if you
* come across a provider that for some reason doesn't work, feel free to open
* an issue on GitHub.
*
* Also, authentication scopes can be set through the `scope` property.
*
* For more information on the available providers, check out:
* http://passportjs.org/guide/providers/
*/
module.exports.passport = {
local: {
strategy: require('passport-local').Strategy
},
bearer: {
strategy: require('passport-http-bearer').Strategy
}
/*twitter: {
name: 'Twitter',
protocol: 'oauth',
strategy: require('passport-twitter').Strategy,
options: {
consumerKey: 'your-consumer-key',
consumerSecret: 'your-consumer-secret'
} | },
github: {
name: 'GitHub',
protocol: 'oauth2',
strategy: require('passport-github').Strategy,
options: {
clientID: 'your-client-id',
clientSecret: 'your-client-secret'
}
},
facebook: {
name: 'Facebook',
protocol: 'oauth2',
strategy: require('passport-facebook').Strategy,
options: {
clientID: 'your-client-id',
clientSecret: 'your-client-secret',
scope: ['email']
}
},
google: {
name: 'Google',
protocol: 'oauth2',
strategy: require('passport-google-oauth').OAuth2Strategy,
options: {
clientID: 'your-client-id',
clientSecret: 'your-client-secret'
}
},
cas: {
name: 'CAS',
protocol: 'cas',
strategy: require('passport-cas').Strategy,
options: {
ssoBaseURL: 'http://your-cas-url',
serverBaseURL: 'http://localhost:1337',
serviceURL: 'http://localhost:1337/auth/cas/callback'
}
}*/
}; | random_line_split | |
inappbrowser.ts | import { Plugin, CordovaInstance } from './plugin';
import { Observable } from 'rxjs/Observable';
declare var cordova: any;
export interface InAppBrowserEvent extends Event {
/** the eventname, either loadstart, loadstop, loaderror, or exit. */
type: string;
/** the URL that was loaded. */
url: string;
/** the error code, only in the case of loaderror. */
code: number;
/** the error message, only in the case of loaderror. */
message: string;
}
/**
* @name InAppBrowser
* @description Launches in app Browser
* @usage
* ```typescript
* import {InAppBrowser} from 'ionic-native';
*
*
* ...
*
*
* let browser = new InAppBrowser('https://ionic.io', '_system');
* browser.executeScript(...);
* browser.insertCSS(...);
* browser.close();
* ```
*/
@Plugin({
pluginName: 'InAppBrowser',
plugin: 'cordova-plugin-inappbrowser',
pluginRef: 'cordova.InAppBrowser',
repo: 'https://github.com/apache/cordova-plugin-inappbrowser'
})
export class InAppBrowser {
static open(url: string, target?: string, options?: string): void {
console.warn('Native: Your current usage of the InAppBrowser plugin is deprecated as of ionic-native@1.3.8. Please check the Ionic Native docs for the latest usage details.');
}
private _objectInstance: any;
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
* @param target The target in which to load the URL, an optional parameter that defaults to _self.
* @param options Options for the InAppBrowser. Optional, defaulting to: location=yes.
* The options string must not contain any blank space, and each feature's
* name/value pairs must be separated by a comma. Feature names are case insensitive.
*/
constructor(url: string, target?: string, options?: string) {
try {
this._objectInstance = cordova.InAppBrowser.open(url, target, options);
} catch (e) {
window.open(url);
console.warn('Native: InAppBrowser is not installed or you are running on a browser. Falling back to window.open, all instance methods will NOT work.');
}
}
/**
* Displays an InAppBrowser window that was opened hidden. Calling this has no effect | */
@CordovaInstance({sync: true})
show(): void { }
/**
* Closes the InAppBrowser window.
*/
@CordovaInstance({sync: true})
close(): void { }
/**
* Injects JavaScript code into the InAppBrowser window.
* @param script Details of the script to run, specifying either a file or code key.
*/
@CordovaInstance()
executeScript(script: {file?: string, code?: string}): Promise<any> {return; }
/**
* Injects CSS into the InAppBrowser window.
* @param css Details of the script to run, specifying either a file or code key.
*/
@CordovaInstance()
insertCss(css: {file?: string, code?: string}): Promise<any> {return; }
/**
* A method that allows you to listen to events happening in the browser.
* @param event Event name
* @returns {Observable<any>} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe.
*/
on(event: string): Observable<InAppBrowserEvent> {
return new Observable<InAppBrowserEvent>((observer) => {
this._objectInstance.addEventListener(event, observer.next.bind(observer));
return () => this._objectInstance.removeEventListener(event, observer.next.bind(observer));
});
}
} | * if the InAppBrowser was already visible. | random_line_split |
inappbrowser.ts | import { Plugin, CordovaInstance } from './plugin';
import { Observable } from 'rxjs/Observable';
declare var cordova: any;
export interface InAppBrowserEvent extends Event {
/** the eventname, either loadstart, loadstop, loaderror, or exit. */
type: string;
/** the URL that was loaded. */
url: string;
/** the error code, only in the case of loaderror. */
code: number;
/** the error message, only in the case of loaderror. */
message: string;
}
/**
* @name InAppBrowser
* @description Launches in app Browser
* @usage
* ```typescript
* import {InAppBrowser} from 'ionic-native';
*
*
* ...
*
*
* let browser = new InAppBrowser('https://ionic.io', '_system');
* browser.executeScript(...);
* browser.insertCSS(...);
* browser.close();
* ```
*/
@Plugin({
pluginName: 'InAppBrowser',
plugin: 'cordova-plugin-inappbrowser',
pluginRef: 'cordova.InAppBrowser',
repo: 'https://github.com/apache/cordova-plugin-inappbrowser'
})
export class InAppBrowser {
static open(url: string, target?: string, options?: string): void {
console.warn('Native: Your current usage of the InAppBrowser plugin is deprecated as of ionic-native@1.3.8. Please check the Ionic Native docs for the latest usage details.');
}
private _objectInstance: any;
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
* @param target The target in which to load the URL, an optional parameter that defaults to _self.
* @param options Options for the InAppBrowser. Optional, defaulting to: location=yes.
* The options string must not contain any blank space, and each feature's
* name/value pairs must be separated by a comma. Feature names are case insensitive.
*/
constructor(url: string, target?: string, options?: string) {
try {
this._objectInstance = cordova.InAppBrowser.open(url, target, options);
} catch (e) {
window.open(url);
console.warn('Native: InAppBrowser is not installed or you are running on a browser. Falling back to window.open, all instance methods will NOT work.');
}
}
/**
* Displays an InAppBrowser window that was opened hidden. Calling this has no effect
* if the InAppBrowser was already visible.
*/
@CordovaInstance({sync: true})
show(): void { }
/**
* Closes the InAppBrowser window.
*/
@CordovaInstance({sync: true})
close(): void { }
/**
* Injects JavaScript code into the InAppBrowser window.
* @param script Details of the script to run, specifying either a file or code key.
*/
@CordovaInstance()
executeScript(script: {file?: string, code?: string}): Promise<any> |
/**
* Injects CSS into the InAppBrowser window.
* @param css Details of the script to run, specifying either a file or code key.
*/
@CordovaInstance()
insertCss(css: {file?: string, code?: string}): Promise<any> {return; }
/**
* A method that allows you to listen to events happening in the browser.
* @param event Event name
* @returns {Observable<any>} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe.
*/
on(event: string): Observable<InAppBrowserEvent> {
return new Observable<InAppBrowserEvent>((observer) => {
this._objectInstance.addEventListener(event, observer.next.bind(observer));
return () => this._objectInstance.removeEventListener(event, observer.next.bind(observer));
});
}
}
| {return; } | identifier_body |
inappbrowser.ts | import { Plugin, CordovaInstance } from './plugin';
import { Observable } from 'rxjs/Observable';
declare var cordova: any;
export interface InAppBrowserEvent extends Event {
/** the eventname, either loadstart, loadstop, loaderror, or exit. */
type: string;
/** the URL that was loaded. */
url: string;
/** the error code, only in the case of loaderror. */
code: number;
/** the error message, only in the case of loaderror. */
message: string;
}
/**
* @name InAppBrowser
* @description Launches in app Browser
* @usage
* ```typescript
* import {InAppBrowser} from 'ionic-native';
*
*
* ...
*
*
* let browser = new InAppBrowser('https://ionic.io', '_system');
* browser.executeScript(...);
* browser.insertCSS(...);
* browser.close();
* ```
*/
@Plugin({
pluginName: 'InAppBrowser',
plugin: 'cordova-plugin-inappbrowser',
pluginRef: 'cordova.InAppBrowser',
repo: 'https://github.com/apache/cordova-plugin-inappbrowser'
})
export class InAppBrowser {
static open(url: string, target?: string, options?: string): void {
console.warn('Native: Your current usage of the InAppBrowser plugin is deprecated as of ionic-native@1.3.8. Please check the Ionic Native docs for the latest usage details.');
}
private _objectInstance: any;
/**
* Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
* @param url The URL to load.
* @param target The target in which to load the URL, an optional parameter that defaults to _self.
* @param options Options for the InAppBrowser. Optional, defaulting to: location=yes.
* The options string must not contain any blank space, and each feature's
* name/value pairs must be separated by a comma. Feature names are case insensitive.
*/
constructor(url: string, target?: string, options?: string) {
try {
this._objectInstance = cordova.InAppBrowser.open(url, target, options);
} catch (e) {
window.open(url);
console.warn('Native: InAppBrowser is not installed or you are running on a browser. Falling back to window.open, all instance methods will NOT work.');
}
}
/**
* Displays an InAppBrowser window that was opened hidden. Calling this has no effect
* if the InAppBrowser was already visible.
*/
@CordovaInstance({sync: true})
show(): void { }
/**
* Closes the InAppBrowser window.
*/
@CordovaInstance({sync: true})
close(): void { }
/**
* Injects JavaScript code into the InAppBrowser window.
* @param script Details of the script to run, specifying either a file or code key.
*/
@CordovaInstance()
executeScript(script: {file?: string, code?: string}): Promise<any> {return; }
/**
* Injects CSS into the InAppBrowser window.
* @param css Details of the script to run, specifying either a file or code key.
*/
@CordovaInstance()
| (css: {file?: string, code?: string}): Promise<any> {return; }
/**
* A method that allows you to listen to events happening in the browser.
* @param event Event name
* @returns {Observable<any>} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe.
*/
on(event: string): Observable<InAppBrowserEvent> {
return new Observable<InAppBrowserEvent>((observer) => {
this._objectInstance.addEventListener(event, observer.next.bind(observer));
return () => this._objectInstance.removeEventListener(event, observer.next.bind(observer));
});
}
}
| insertCss | identifier_name |
index.js | /**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; | map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function parse(html) {
if ('string' != typeof html) throw new TypeError('String expected');
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
} | random_line_split | |
index.js |
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function | (html) {
if ('string' != typeof html) throw new TypeError('String expected');
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
| parse | identifier_name |
index.js |
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function parse(html) | {
if ('string' != typeof html) throw new TypeError('String expected');
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
} | identifier_body | |
city.rs | use iron::prelude::*;
use hyper::status::StatusCode;
use super::request_body;
use ::proto::response::*;
use ::proto::schema::NewCity;
use ::db::schema::*;
use ::db::*;
pub fn | (_: &mut Request) -> IronResult<Response> {
let query = City::select_builder().build();
let conn = get_db_connection();
info!("request GET /city");
let rows = conn.query(&query, &[]).unwrap();
let cities = rows.into_iter()
.map(City::from)
.collect::<Vec<City>>();
Ok(cities.as_response())
}
pub fn put_city(req: &mut Request) -> IronResult<Response> {
let new_city: NewCity = request_body(req)?;
info!("request PUT /city {{ {:?} }}", new_city);
let conn = get_db_connection();
let query = City::insert_query();
conn.execute(&query, &[&new_city.Name]).unwrap();
Ok(Response::with(StatusCode::Ok))
} | get_cities | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.