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
index.ts
import Module from 'ringcentral-integration/lib/di/decorators/module'; import RcUIModule from '../../lib/RcUIModule'; @Module({ name: 'ConnectivityBadgeUI', deps: ['Locale', 'ConnectivityManager'], }) export default class ConnectivityBadgeUI extends RcUIModule { _locale: any; _connectivityManager: any; constructor({ locale, connectivityManager, ...options })
getUIProps() { return { currentLocale: this._locale.currentLocale, mode: (this._connectivityManager.ready && this._connectivityManager.mode) || null, webphoneConnecting: this._connectivityManager.ready && this._connectivityManager.webphoneConnecting, hasLimitedStatusError: this._connectivityManager.ready && this._connectivityManager.hasLimitedStatusError, }; } getUIFunctions() { const connectivityManager = this._connectivityManager; return { onClick() { if (connectivityManager.isWebphoneUnavailableMode) { connectivityManager.checkWebphoneAndConnect(); } else if (connectivityManager.hasLimitedStatusError) { connectivityManager.checkStatus(); } else { connectivityManager.showConnectivityAlert(); } }, showBadgeAlert() { connectivityManager.showConnectivityAlert(); }, }; } }
{ super({ ...options, }); this._locale = locale; this._connectivityManager = connectivityManager; }
identifier_body
index.ts
import Module from 'ringcentral-integration/lib/di/decorators/module'; import RcUIModule from '../../lib/RcUIModule'; @Module({ name: 'ConnectivityBadgeUI', deps: ['Locale', 'ConnectivityManager'], }) export default class ConnectivityBadgeUI extends RcUIModule { _locale: any; _connectivityManager: any; constructor({ locale, connectivityManager, ...options }) { super({ ...options, }); this._locale = locale; this._connectivityManager = connectivityManager; } getUIProps() { return { currentLocale: this._locale.currentLocale, mode: (this._connectivityManager.ready && this._connectivityManager.mode) || null, webphoneConnecting: this._connectivityManager.ready && this._connectivityManager.webphoneConnecting, hasLimitedStatusError: this._connectivityManager.ready && this._connectivityManager.hasLimitedStatusError, }; } getUIFunctions() { const connectivityManager = this._connectivityManager; return { onClick() { if (connectivityManager.isWebphoneUnavailableMode) { connectivityManager.checkWebphoneAndConnect(); } else if (connectivityManager.hasLimitedStatusError) { connectivityManager.checkStatus(); } else
}, showBadgeAlert() { connectivityManager.showConnectivityAlert(); }, }; } }
{ connectivityManager.showConnectivityAlert(); }
conditional_block
overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test overloaded indexing combined with autoderef. #![allow(unknown_features)] #![feature(box_syntax)] use std::ops::{Index, IndexMut}; struct Foo { x: int, y: int, } impl Index<int> for Foo { type Output = int; fn index(&self, z: &int) -> &int { if *z == 0 { &self.x } else { &self.y }
impl IndexMut<int> for Foo { fn index_mut(&mut self, z: &int) -> &mut int { if *z == 0 { &mut self.x } else { &mut self.y } } } trait Int { fn get(self) -> int; fn get_from_ref(&self) -> int; fn inc(&mut self); } impl Int for int { fn get(self) -> int { self } fn get_from_ref(&self) -> int { *self } fn inc(&mut self) { *self += 1; } } fn main() { let mut f: Box<_> = box Foo { x: 1, y: 2, }; assert_eq!(f[1], 2); f[0] = 3; assert_eq!(f[0], 3); // Test explicit IndexMut where `f` must be autoderef: { let p = &mut f[1]; *p = 4; } // Test explicit Index where `f` must be autoderef: { let p = &f[1]; assert_eq!(*p, 4); } // Test calling methods with `&mut self`, `self, and `&self` receivers: f[1].inc(); assert_eq!(f[1].get(), 5); assert_eq!(f[1].get_from_ref(), 5); }
} }
random_line_split
overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test overloaded indexing combined with autoderef. #![allow(unknown_features)] #![feature(box_syntax)] use std::ops::{Index, IndexMut}; struct Foo { x: int, y: int, } impl Index<int> for Foo { type Output = int; fn index(&self, z: &int) -> &int { if *z == 0
else { &self.y } } } impl IndexMut<int> for Foo { fn index_mut(&mut self, z: &int) -> &mut int { if *z == 0 { &mut self.x } else { &mut self.y } } } trait Int { fn get(self) -> int; fn get_from_ref(&self) -> int; fn inc(&mut self); } impl Int for int { fn get(self) -> int { self } fn get_from_ref(&self) -> int { *self } fn inc(&mut self) { *self += 1; } } fn main() { let mut f: Box<_> = box Foo { x: 1, y: 2, }; assert_eq!(f[1], 2); f[0] = 3; assert_eq!(f[0], 3); // Test explicit IndexMut where `f` must be autoderef: { let p = &mut f[1]; *p = 4; } // Test explicit Index where `f` must be autoderef: { let p = &f[1]; assert_eq!(*p, 4); } // Test calling methods with `&mut self`, `self, and `&self` receivers: f[1].inc(); assert_eq!(f[1].get(), 5); assert_eq!(f[1].get_from_ref(), 5); }
{ &self.x }
conditional_block
overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test overloaded indexing combined with autoderef. #![allow(unknown_features)] #![feature(box_syntax)] use std::ops::{Index, IndexMut}; struct Foo { x: int, y: int, } impl Index<int> for Foo { type Output = int; fn
(&self, z: &int) -> &int { if *z == 0 { &self.x } else { &self.y } } } impl IndexMut<int> for Foo { fn index_mut(&mut self, z: &int) -> &mut int { if *z == 0 { &mut self.x } else { &mut self.y } } } trait Int { fn get(self) -> int; fn get_from_ref(&self) -> int; fn inc(&mut self); } impl Int for int { fn get(self) -> int { self } fn get_from_ref(&self) -> int { *self } fn inc(&mut self) { *self += 1; } } fn main() { let mut f: Box<_> = box Foo { x: 1, y: 2, }; assert_eq!(f[1], 2); f[0] = 3; assert_eq!(f[0], 3); // Test explicit IndexMut where `f` must be autoderef: { let p = &mut f[1]; *p = 4; } // Test explicit Index where `f` must be autoderef: { let p = &f[1]; assert_eq!(*p, 4); } // Test calling methods with `&mut self`, `self, and `&self` receivers: f[1].inc(); assert_eq!(f[1].get(), 5); assert_eq!(f[1].get_from_ref(), 5); }
index
identifier_name
overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test overloaded indexing combined with autoderef. #![allow(unknown_features)] #![feature(box_syntax)] use std::ops::{Index, IndexMut}; struct Foo { x: int, y: int, } impl Index<int> for Foo { type Output = int; fn index(&self, z: &int) -> &int
} impl IndexMut<int> for Foo { fn index_mut(&mut self, z: &int) -> &mut int { if *z == 0 { &mut self.x } else { &mut self.y } } } trait Int { fn get(self) -> int; fn get_from_ref(&self) -> int; fn inc(&mut self); } impl Int for int { fn get(self) -> int { self } fn get_from_ref(&self) -> int { *self } fn inc(&mut self) { *self += 1; } } fn main() { let mut f: Box<_> = box Foo { x: 1, y: 2, }; assert_eq!(f[1], 2); f[0] = 3; assert_eq!(f[0], 3); // Test explicit IndexMut where `f` must be autoderef: { let p = &mut f[1]; *p = 4; } // Test explicit Index where `f` must be autoderef: { let p = &f[1]; assert_eq!(*p, 4); } // Test calling methods with `&mut self`, `self, and `&self` receivers: f[1].inc(); assert_eq!(f[1].get(), 5); assert_eq!(f[1].get_from_ref(), 5); }
{ if *z == 0 { &self.x } else { &self.y } }
identifier_body
Zombie.spec.ts
import { Zombie } from './'; describe('Zombie', () => { it('should set UUIDLeast', () => { let zombie = new Zombie(); zombie.Tag.UUIDLeast = 'Test'; expect(zombie.Command).to.be('{UUIDLeast:"Test"}'); }); it('should set AttackTime', () => { let zombie = new Zombie(); zombie.Tag.AttackTime = 50; zombie.Tag.UUIDLeast = 'Test'; expect(zombie.Command).to.be('{AttackTime:50,UUIDLeast:"Test"}'); }); it('should set CanBreakDoors', () => { let zombie = new Zombie(); zombie.Tag.CanBreakDoors = true; expect(zombie.Command).to.be('{CanBreakDoors:true}'); }); it('should add a Passenger', () => { let zombie1 = new Zombie(); zombie1.Tag.AttackTime = 5; zombie1.Tag.UUIDMost = '25'; let zombie2 = new Zombie();
});
zombie2.Tag.AddPassenger(zombie1); expect(zombie2.Command).to.be('{Passengers:[{AttackTime:5,UUIDMost:"25",id:"minecraft:zombie"}]}'); });
random_line_split
nested_macro_privacy.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(decl_macro)] macro n($foo:ident, $S:ident, $i:ident, $m:ident) { mod $foo { #[derive(Default)] pub struct $S { $i: u32 } pub macro $m($e:expr) { $e.$i } } } n!(foo, S, i, m); fn
() { use foo::{S, m}; S::default().i; //~ ERROR field `i` of struct `foo::S` is private m!(S::default()); // ok }
main
identifier_name
nested_macro_privacy.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(decl_macro)] macro n($foo:ident, $S:ident, $i:ident, $m:ident) { mod $foo { #[derive(Default)] pub struct $S { $i: u32 } pub macro $m($e:expr) { $e.$i } } } n!(foo, S, i, m); fn main()
{ use foo::{S, m}; S::default().i; //~ ERROR field `i` of struct `foo::S` is private m!(S::default()); // ok }
identifier_body
nested_macro_privacy.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(decl_macro)]
pub macro $m($e:expr) { $e.$i } } } n!(foo, S, i, m); fn main() { use foo::{S, m}; S::default().i; //~ ERROR field `i` of struct `foo::S` is private m!(S::default()); // ok }
macro n($foo:ident, $S:ident, $i:ident, $m:ident) { mod $foo { #[derive(Default)] pub struct $S { $i: u32 }
random_line_split
fashion_mnist_cnn.py
'''Trains a simple convnet on the Fashion MNIST dataset. Gets to % test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). ''' from __future__ import print_function import keras from keras.datasets import fashion_mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1])
# the data, shuffled and split between train and test sets
random_line_split
fashion_mnist_cnn.py
'''Trains a simple convnet on the Fashion MNIST dataset. Gets to % test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). ''' from __future__ import print_function import keras from keras.datasets import fashion_mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() if K.image_data_format() == 'channels_first':
else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1])
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols)
conditional_block
schema.py
# encoding: utf-8 # # # 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/. # from __future__ import absolute_import, division, unicode_literals from jx_base.queries import get_property_name from jx_sqlite.utils import GUID, untyped_column from mo_dots import concat_field, relative_field, set_default, startswith_field from mo_json import EXISTS, OBJECT, STRUCT from mo_logs import Log class Schema(object): """ A Schema MAPS ALL COLUMNS IN SNOWFLAKE FROM THE PERSPECTIVE OF A SINGLE TABLE (a nested_path) """ def __init__(self, nested_path, snowflake): if nested_path[-1] != '.': Log.error("Expecting full nested path") self.path = concat_field(snowflake.fact_name, nested_path[0]) self.nested_path = nested_path self.snowflake = snowflake # def add(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.columns.append(column) # # for np in self.nested_path: # rel_name = column.names[np] # container = self.namespace.setdefault(rel_name, set()) # hidden = [ # c # for c in container # if len(c.nested_path[0]) < len(np) # ] # for h in hidden: # container.remove(h) # # container.add(column) # # container = self.namespace.setdefault(column.es_column, set()) # container.add(column) # def remove(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.namespace[column_name] = [c for c in self.namespace[column_name] if c != column] def __getitem__(self, item): output = self.snowflake.namespace.columns.find(self.path, item) return output # def __copy__(self): # output = Schema(self.nested_path) # for k, v in self.namespace.items(): # output.namespace[k] = copy(v) # return output def get_column_name(self, column): """ RETURN THE COLUMN NAME, FROM THE PERSPECTIVE OF THIS SCHEMA :param column: :return: NAME OF column """ relative_name = relative_field(column.name, self.nested_path[0]) return get_property_name(relative_name) @property def namespace(self): return self.snowflake.namespace def keys(self): """ :return: ALL COLUMN NAMES """ return set(c.name for c in self.columns) @property def columns(self): return self.snowflake.namespace.columns.find(self.snowflake.fact_name) def column(self, prefix): full_name = untyped_column(concat_field(self.nested_path, prefix)) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k, t in [untyped_column(c.name)] if k == full_name and k != GUID if c.jx_type not in [OBJECT, EXISTS] ) def leaves(self, prefix): full_name = concat_field(self.nested_path, prefix) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k in [c.name] if startswith_field(k, full_name) and k != GUID or k == full_name if c.jx_type not in [OBJECT, EXISTS] ) def map_to_sql(self, var=""): """ RETURN A MAP FROM THE RELATIVE AND ABSOLUTE NAME SPACE TO COLUMNS """ origin = self.nested_path[0] if startswith_field(var, origin) and origin != var: var = relative_field(var, origin) fact_dict = {} origin_dict = {} for k, cs in self.namespace.items():
return set_default(origin_dict, fact_dict)
for c in cs: if c.jx_type in STRUCT: continue if startswith_field(get_property_name(k), var): origin_dict.setdefault(c.names[origin], []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(c.name, []).append(c) elif origin == var: origin_dict.setdefault(concat_field(var, c.names[origin]), []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(concat_field(var, c.name), []).append(c)
conditional_block
schema.py
# encoding: utf-8 # # # 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/. # from __future__ import absolute_import, division, unicode_literals from jx_base.queries import get_property_name from jx_sqlite.utils import GUID, untyped_column from mo_dots import concat_field, relative_field, set_default, startswith_field from mo_json import EXISTS, OBJECT, STRUCT from mo_logs import Log class Schema(object): """ A Schema MAPS ALL COLUMNS IN SNOWFLAKE FROM THE PERSPECTIVE OF A SINGLE TABLE (a nested_path) """ def __init__(self, nested_path, snowflake):
# def add(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.columns.append(column) # # for np in self.nested_path: # rel_name = column.names[np] # container = self.namespace.setdefault(rel_name, set()) # hidden = [ # c # for c in container # if len(c.nested_path[0]) < len(np) # ] # for h in hidden: # container.remove(h) # # container.add(column) # # container = self.namespace.setdefault(column.es_column, set()) # container.add(column) # def remove(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.namespace[column_name] = [c for c in self.namespace[column_name] if c != column] def __getitem__(self, item): output = self.snowflake.namespace.columns.find(self.path, item) return output # def __copy__(self): # output = Schema(self.nested_path) # for k, v in self.namespace.items(): # output.namespace[k] = copy(v) # return output def get_column_name(self, column): """ RETURN THE COLUMN NAME, FROM THE PERSPECTIVE OF THIS SCHEMA :param column: :return: NAME OF column """ relative_name = relative_field(column.name, self.nested_path[0]) return get_property_name(relative_name) @property def namespace(self): return self.snowflake.namespace def keys(self): """ :return: ALL COLUMN NAMES """ return set(c.name for c in self.columns) @property def columns(self): return self.snowflake.namespace.columns.find(self.snowflake.fact_name) def column(self, prefix): full_name = untyped_column(concat_field(self.nested_path, prefix)) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k, t in [untyped_column(c.name)] if k == full_name and k != GUID if c.jx_type not in [OBJECT, EXISTS] ) def leaves(self, prefix): full_name = concat_field(self.nested_path, prefix) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k in [c.name] if startswith_field(k, full_name) and k != GUID or k == full_name if c.jx_type not in [OBJECT, EXISTS] ) def map_to_sql(self, var=""): """ RETURN A MAP FROM THE RELATIVE AND ABSOLUTE NAME SPACE TO COLUMNS """ origin = self.nested_path[0] if startswith_field(var, origin) and origin != var: var = relative_field(var, origin) fact_dict = {} origin_dict = {} for k, cs in self.namespace.items(): for c in cs: if c.jx_type in STRUCT: continue if startswith_field(get_property_name(k), var): origin_dict.setdefault(c.names[origin], []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(c.name, []).append(c) elif origin == var: origin_dict.setdefault(concat_field(var, c.names[origin]), []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(concat_field(var, c.name), []).append(c) return set_default(origin_dict, fact_dict)
if nested_path[-1] != '.': Log.error("Expecting full nested path") self.path = concat_field(snowflake.fact_name, nested_path[0]) self.nested_path = nested_path self.snowflake = snowflake
identifier_body
schema.py
# encoding: utf-8 # # # 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/. # from __future__ import absolute_import, division, unicode_literals from jx_base.queries import get_property_name from jx_sqlite.utils import GUID, untyped_column from mo_dots import concat_field, relative_field, set_default, startswith_field from mo_json import EXISTS, OBJECT, STRUCT from mo_logs import Log class Schema(object): """ A Schema MAPS ALL COLUMNS IN SNOWFLAKE FROM THE PERSPECTIVE OF A SINGLE TABLE (a nested_path) """ def __init__(self, nested_path, snowflake): if nested_path[-1] != '.': Log.error("Expecting full nested path") self.path = concat_field(snowflake.fact_name, nested_path[0]) self.nested_path = nested_path self.snowflake = snowflake # def add(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.columns.append(column) # # for np in self.nested_path: # rel_name = column.names[np] # container = self.namespace.setdefault(rel_name, set()) # hidden = [ # c # for c in container # if len(c.nested_path[0]) < len(np) # ] # for h in hidden: # container.remove(h) # # container.add(column) # # container = self.namespace.setdefault(column.es_column, set()) # container.add(column) # def remove(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.namespace[column_name] = [c for c in self.namespace[column_name] if c != column] def __getitem__(self, item): output = self.snowflake.namespace.columns.find(self.path, item) return output # def __copy__(self): # output = Schema(self.nested_path) # for k, v in self.namespace.items(): # output.namespace[k] = copy(v) # return output def get_column_name(self, column): """ RETURN THE COLUMN NAME, FROM THE PERSPECTIVE OF THIS SCHEMA :param column: :return: NAME OF column """ relative_name = relative_field(column.name, self.nested_path[0]) return get_property_name(relative_name) @property def namespace(self): return self.snowflake.namespace def keys(self): """ :return: ALL COLUMN NAMES """ return set(c.name for c in self.columns) @property def columns(self): return self.snowflake.namespace.columns.find(self.snowflake.fact_name) def column(self, prefix): full_name = untyped_column(concat_field(self.nested_path, prefix)) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k, t in [untyped_column(c.name)] if k == full_name and k != GUID if c.jx_type not in [OBJECT, EXISTS] ) def leaves(self, prefix): full_name = concat_field(self.nested_path, prefix) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k in [c.name] if startswith_field(k, full_name) and k != GUID or k == full_name if c.jx_type not in [OBJECT, EXISTS] ) def
(self, var=""): """ RETURN A MAP FROM THE RELATIVE AND ABSOLUTE NAME SPACE TO COLUMNS """ origin = self.nested_path[0] if startswith_field(var, origin) and origin != var: var = relative_field(var, origin) fact_dict = {} origin_dict = {} for k, cs in self.namespace.items(): for c in cs: if c.jx_type in STRUCT: continue if startswith_field(get_property_name(k), var): origin_dict.setdefault(c.names[origin], []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(c.name, []).append(c) elif origin == var: origin_dict.setdefault(concat_field(var, c.names[origin]), []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(concat_field(var, c.name), []).append(c) return set_default(origin_dict, fact_dict)
map_to_sql
identifier_name
schema.py
# encoding: utf-8 # # # 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/. # from __future__ import absolute_import, division, unicode_literals from jx_base.queries import get_property_name from jx_sqlite.utils import GUID, untyped_column from mo_dots import concat_field, relative_field, set_default, startswith_field from mo_json import EXISTS, OBJECT, STRUCT from mo_logs import Log class Schema(object): """ A Schema MAPS ALL COLUMNS IN SNOWFLAKE FROM THE PERSPECTIVE OF A SINGLE TABLE (a nested_path) """ def __init__(self, nested_path, snowflake): if nested_path[-1] != '.': Log.error("Expecting full nested path") self.path = concat_field(snowflake.fact_name, nested_path[0]) self.nested_path = nested_path self.snowflake = snowflake # def add(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.columns.append(column) # # for np in self.nested_path: # rel_name = column.names[np] # container = self.namespace.setdefault(rel_name, set()) # hidden = [ # c # for c in container # if len(c.nested_path[0]) < len(np) # ] # for h in hidden: # container.remove(h) # # container.add(column) # # container = self.namespace.setdefault(column.es_column, set()) # container.add(column) # def remove(self, column_name, column): # if column_name != column.names[self.nested_path[0]]: # Log.error("Logic error") # # self.namespace[column_name] = [c for c in self.namespace[column_name] if c != column]
output = self.snowflake.namespace.columns.find(self.path, item) return output # def __copy__(self): # output = Schema(self.nested_path) # for k, v in self.namespace.items(): # output.namespace[k] = copy(v) # return output def get_column_name(self, column): """ RETURN THE COLUMN NAME, FROM THE PERSPECTIVE OF THIS SCHEMA :param column: :return: NAME OF column """ relative_name = relative_field(column.name, self.nested_path[0]) return get_property_name(relative_name) @property def namespace(self): return self.snowflake.namespace def keys(self): """ :return: ALL COLUMN NAMES """ return set(c.name for c in self.columns) @property def columns(self): return self.snowflake.namespace.columns.find(self.snowflake.fact_name) def column(self, prefix): full_name = untyped_column(concat_field(self.nested_path, prefix)) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k, t in [untyped_column(c.name)] if k == full_name and k != GUID if c.jx_type not in [OBJECT, EXISTS] ) def leaves(self, prefix): full_name = concat_field(self.nested_path, prefix) return set( c for c in self.snowflake.namespace.columns.find(self.snowflake.fact_name) for k in [c.name] if startswith_field(k, full_name) and k != GUID or k == full_name if c.jx_type not in [OBJECT, EXISTS] ) def map_to_sql(self, var=""): """ RETURN A MAP FROM THE RELATIVE AND ABSOLUTE NAME SPACE TO COLUMNS """ origin = self.nested_path[0] if startswith_field(var, origin) and origin != var: var = relative_field(var, origin) fact_dict = {} origin_dict = {} for k, cs in self.namespace.items(): for c in cs: if c.jx_type in STRUCT: continue if startswith_field(get_property_name(k), var): origin_dict.setdefault(c.names[origin], []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(c.name, []).append(c) elif origin == var: origin_dict.setdefault(concat_field(var, c.names[origin]), []).append(c) if origin != c.nested_path[0]: fact_dict.setdefault(concat_field(var, c.name), []).append(c) return set_default(origin_dict, fact_dict)
def __getitem__(self, item):
random_line_split
templeenter.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function enter(pi)
{ pi.warp(270000100, "out00"); return true; }
identifier_body
templeenter.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function
(pi) { pi.warp(270000100, "out00"); return true; }
enter
identifier_name
templeenter.js
/*
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function enter(pi) { pi.warp(270000100, "out00"); return true; }
This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de>
random_line_split
util.py
from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _get_zh_word2vec_ff(num_units, vec_type, projection, cdtb): prefix = 'zh_gigaword3' if cdtb: file_name = '/data/word_embeddings/%s-%s%s-cdtb_vocab.txt' \ % (prefix, vec_type, num_units) else: file_name = '/data/word_embeddings/%s-%s%s.txt' \ % (prefix, vec_type, num_units) word2vec = df.EmbeddingFeaturizer(file_name) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _sparse_featurize_relation_list(relation_list, ff_list, alphabet=None): if alphabet is None: alphabet = {} grow_alphabet = True else: grow_alphabet = False feature_vectors = [] print 'Applying feature functions...' for relation in relation_list: feature_vector_indices = [] for ff in ff_list: feature_vector = ff(relation) for f in feature_vector: if grow_alphabet and f not in alphabet: alphabet[f] = len(alphabet) if f in alphabet: feature_vector_indices.append(alphabet[f]) feature_vectors.append(feature_vector_indices) print 'Creating feature sparse matrix...' feature_matrix = sp.sparse.lil_matrix((len(relation_list), len(alphabet))) for i, fv in enumerate(feature_vectors): feature_matrix[i, fv] = 1 return feature_matrix.tocsr(), alphabet def sparse_featurize(relation_list_list, ff_list): print 'Featurizing...' data_list = [] alphabet = None for relation_list in relation_list_list: data, alphabet = _sparse_featurize_relation_list(relation_list, ff_list, alphabet) data_list.append(data) return (data_list, alphabet) def convert_seconds_to_hours(num_seconds): m, s = divmod(num_seconds, 60) h, m = divmod(m, 60) return (h, m, s) def compute_mi(feature_matrix, label_vector): """Compute mutual information of each feature """ num_labels = np.max(label_vector) + 1 num_features = feature_matrix.shape[1] num_rows = feature_matrix.shape[0] total = num_rows + num_labels c_y = np.zeros(num_labels) for l in label_vector: c_y[l] += 1.0 c_y += 1.0 c_x_y = np.zeros((num_features, num_labels)) c_x = np.zeros(num_features) for i in range(num_rows): c_x_y[:, label_vector[i]] += feature_matrix[i, :] c_x += feature_matrix[i, :] c_x_y += 1.0 c_x += 1.0 c_x_c_y = np.outer(c_x, c_y) c_not_x_c_y = np.outer((total - c_x), c_y) c_not_x_y = c_y - c_x_y inner = c_x_y / total * np.log(c_x_y * total / c_x_c_y) + \ c_not_x_y / total * np.log(c_not_x_y * total / c_not_x_c_y) mi_x = inner.sum(1) return mi_x def prune_feature_matrices(feature_matrices, mi, num_features): sorted_indices = mi.argsort()[-num_features:] return [x[:, sorted_indices] for x in feature_matrices] class BrownDictionary(object): def __init__(self): self.word_to_brown_mapping = {} self.num_clusters = 0 brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt' self._load_brown_clusters('resources/%s' % brown_cluster_file_name) def _load_brown_clusters(self, path): try: lexicon_file = open(path) except: print 'fail to load brown cluster data' cluster_set = set() for line in lexicon_file: cluster_assn, word, _ = line.split('\t') if cluster_assn not in cluster_set: cluster_set.add(cluster_assn) self.word_to_brown_mapping[word] = len(cluster_set) - 1 self.num_clusters = len(cluster_set) def _get_brown_cluster_bag(self, tokens):
def get_brown_sparse_matrices_relations(self, relations): X1 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) X2 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) for i, relation in enumerate(relations): bag1 = self._get_brown_cluster_bag(relation.arg_tokens(1)) for cluster in bag1: X1[i, cluster] = 1.0 bag2 = self._get_brown_cluster_bag(relation.arg_tokens(2)) for cluster in bag2: X2[i, cluster] = 1.0 return (X1, X2) def get_brown_matrices_data(self, relation_list_list, use_sparse): """Extract sparse For each directory, returns (X1, X2, Y) X1 and X2 are sparse matrices from arg1 and arg2 respectively. Y is an integer vector of type int32 """ data = [] alphabet = None # load the data for relation_list in relation_list_list: # turn them into a data matrix print 'Making matrices' X1, X2 = self.get_brown_sparse_matrices_relations(relation_list) if not use_sparse: X1 = X1.toarray() X2 = X2.toarray() Y, alphabet = level2_labels(relation_list, alphabet) data.append((X1, X2, Y)) return (data, alphabet) def label_vectorize(relation_list_list, lf): alphabet = {} for i, valid_label in enumerate(lf.valid_labels()): alphabet[valid_label] = i label_vectors = [] for relation_list in relation_list_list: label_vector = [alphabet[lf.label(x)] for x in relation_list] label_vectors.append(np.array(label_vector, np.int64)) return label_vectors, alphabet def compute_baseline_acc(label_vector): label_counter = Counter() for label in label_vector: label_counter[label] += 1.0 _, freq = label_counter.most_common(1)[0] return round(freq / len(label_vector), 4) def convert_level2_labels(relations): # TODO: this is not enough because we have to exclude some tinay classes new_relation_list = [] for relation in relations: split_sense = relation.senses[0].split('.') if len(split_sense) >= 2: relation.relation_dict['Sense']= ['.'.join(split_sense[0:2])] new_relation_list.append(relation) return new_relation_list def level2_labels(relations, alphabet=None): if alphabet is None: alphabet = {} label_set = set() for relation in relations: label_set.add(relation.senses[0]) print label_set sorted_label = sorted(list(label_set)) for i, label in enumerate(sorted_label): alphabet[label] = i label_vector = [] for relation in relations: if relation.senses[0] not in alphabet: alphabet[relation.senses[0]] = len(alphabet) label_vector.append(alphabet[relation.senses[0]]) return np.array(label_vector, np.int64), alphabet def get_wbm(num_units): if num_units == 50: dict_file = '/data/word_embeddings/wsj-skipgram50.npy' vocab_file = '/data/word_embeddings/wsj-skipgram50_vocab.txt' elif num_units == 100: dict_file = '/data/word_embeddings/wsj-skipgram100.npy' vocab_file = '/data/word_embeddings/wsj-skipgram100_vocab.txt' elif num_units == 300: #dict_file = '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300.npy' dict_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300-wsj_vocab.npy' vocab_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors.negative300-wsj_vocab-vocab.txt' else: # this will crash the next step and te's too lazy to make it throw an exception. dict_file = None vocab_file = None wbm = WordEmbeddingDict(dict_file, vocab_file) return wbm def get_zh_wbm(num_units): dict_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab.npy' % num_units vocab_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab-vocab.txt' % num_units return WordEmbeddingDict(dict_file, vocab_file) def set_logger(file_name, dry_mode=False): if not dry_mode: sys.stdout = open('%s.log' % file_name, 'w', 1) json_file = open('%s.json' % file_name, 'w', 1) return json_file import base_label_functions as l from nets.learning import DataTriplet from data_reader import extract_implicit_relations from lstm import prep_serrated_matrix_relations def get_data_srm(dir_list, wbm, max_length=75): sense_lf = l.SecondLevelLabel() relation_list_list = [extract_implicit_relations(dir, sense_lf) for dir in dir_list] data_list = [] for relation_list in relation_list_list: data = prep_serrated_matrix_relations(relation_list, wbm, max_length) data_list.append(data) label_vectors, label_alphabet = \ label_vectorize(relation_list_list, sense_lf) data_triplet = DataTriplet( data_list, [[x] for x in label_vectors], [label_alphabet]) return data_triplet def make_givens_srm(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 mask1 X2 mask2] X1 and X2 are TxNxd serrated matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][:,start_idx:end_idx, :] givens[input_vec[1]] = T_training_data[1][:,start_idx:end_idx] # second arg embedding and mask givens[input_vec[2]] = T_training_data[2][:,start_idx:end_idx, :] givens[input_vec[3]] = T_training_data[3][:,start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] def make_givens(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 X2] X1 and X2 are Nxd matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][start_idx:end_idx] givens[input_vec[1]] = T_training_data[1][start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] if __name__ == '__main__': fm = np.array([ [1, 0, 1], [1, 0, 0], [0, 0, 0], [0, 1, 1], [0, 1, 0], [0, 0, 0]]) lv = np.array([0,0,0,1,1,1]) compute_mi(fm, lv)
bag = set() for token in tokens: if token in self.word_to_brown_mapping: cluster_assn = self.word_to_brown_mapping[token] if cluster_assn not in bag: bag.add(cluster_assn) return bag
identifier_body
util.py
from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _get_zh_word2vec_ff(num_units, vec_type, projection, cdtb): prefix = 'zh_gigaword3' if cdtb: file_name = '/data/word_embeddings/%s-%s%s-cdtb_vocab.txt' \ % (prefix, vec_type, num_units) else: file_name = '/data/word_embeddings/%s-%s%s.txt' \ % (prefix, vec_type, num_units) word2vec = df.EmbeddingFeaturizer(file_name) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _sparse_featurize_relation_list(relation_list, ff_list, alphabet=None): if alphabet is None: alphabet = {} grow_alphabet = True else: grow_alphabet = False feature_vectors = [] print 'Applying feature functions...' for relation in relation_list: feature_vector_indices = [] for ff in ff_list: feature_vector = ff(relation) for f in feature_vector: if grow_alphabet and f not in alphabet: alphabet[f] = len(alphabet) if f in alphabet: feature_vector_indices.append(alphabet[f]) feature_vectors.append(feature_vector_indices) print 'Creating feature sparse matrix...' feature_matrix = sp.sparse.lil_matrix((len(relation_list), len(alphabet))) for i, fv in enumerate(feature_vectors): feature_matrix[i, fv] = 1 return feature_matrix.tocsr(), alphabet def sparse_featurize(relation_list_list, ff_list): print 'Featurizing...' data_list = [] alphabet = None for relation_list in relation_list_list: data, alphabet = _sparse_featurize_relation_list(relation_list, ff_list, alphabet) data_list.append(data) return (data_list, alphabet) def convert_seconds_to_hours(num_seconds): m, s = divmod(num_seconds, 60) h, m = divmod(m, 60) return (h, m, s) def compute_mi(feature_matrix, label_vector): """Compute mutual information of each feature """ num_labels = np.max(label_vector) + 1 num_features = feature_matrix.shape[1] num_rows = feature_matrix.shape[0] total = num_rows + num_labels c_y = np.zeros(num_labels) for l in label_vector: c_y[l] += 1.0 c_y += 1.0 c_x_y = np.zeros((num_features, num_labels)) c_x = np.zeros(num_features) for i in range(num_rows): c_x_y[:, label_vector[i]] += feature_matrix[i, :] c_x += feature_matrix[i, :] c_x_y += 1.0 c_x += 1.0 c_x_c_y = np.outer(c_x, c_y) c_not_x_c_y = np.outer((total - c_x), c_y) c_not_x_y = c_y - c_x_y inner = c_x_y / total * np.log(c_x_y * total / c_x_c_y) + \ c_not_x_y / total * np.log(c_not_x_y * total / c_not_x_c_y) mi_x = inner.sum(1) return mi_x def prune_feature_matrices(feature_matrices, mi, num_features): sorted_indices = mi.argsort()[-num_features:] return [x[:, sorted_indices] for x in feature_matrices] class BrownDictionary(object): def __init__(self): self.word_to_brown_mapping = {} self.num_clusters = 0 brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt' self._load_brown_clusters('resources/%s' % brown_cluster_file_name) def _load_brown_clusters(self, path): try: lexicon_file = open(path) except: print 'fail to load brown cluster data' cluster_set = set() for line in lexicon_file: cluster_assn, word, _ = line.split('\t') if cluster_assn not in cluster_set: cluster_set.add(cluster_assn) self.word_to_brown_mapping[word] = len(cluster_set) - 1 self.num_clusters = len(cluster_set) def _get_brown_cluster_bag(self, tokens): bag = set() for token in tokens: if token in self.word_to_brown_mapping: cluster_assn = self.word_to_brown_mapping[token] if cluster_assn not in bag: bag.add(cluster_assn) return bag def get_brown_sparse_matrices_relations(self, relations): X1 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) X2 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) for i, relation in enumerate(relations): bag1 = self._get_brown_cluster_bag(relation.arg_tokens(1)) for cluster in bag1: X1[i, cluster] = 1.0 bag2 = self._get_brown_cluster_bag(relation.arg_tokens(2)) for cluster in bag2: X2[i, cluster] = 1.0 return (X1, X2) def get_brown_matrices_data(self, relation_list_list, use_sparse): """Extract sparse For each directory, returns (X1, X2, Y) X1 and X2 are sparse matrices from arg1 and arg2 respectively. Y is an integer vector of type int32 """ data = [] alphabet = None # load the data for relation_list in relation_list_list: # turn them into a data matrix print 'Making matrices' X1, X2 = self.get_brown_sparse_matrices_relations(relation_list) if not use_sparse: X1 = X1.toarray() X2 = X2.toarray() Y, alphabet = level2_labels(relation_list, alphabet) data.append((X1, X2, Y)) return (data, alphabet) def label_vectorize(relation_list_list, lf): alphabet = {} for i, valid_label in enumerate(lf.valid_labels()): alphabet[valid_label] = i label_vectors = [] for relation_list in relation_list_list: label_vector = [alphabet[lf.label(x)] for x in relation_list] label_vectors.append(np.array(label_vector, np.int64)) return label_vectors, alphabet def compute_baseline_acc(label_vector): label_counter = Counter() for label in label_vector: label_counter[label] += 1.0 _, freq = label_counter.most_common(1)[0] return round(freq / len(label_vector), 4) def convert_level2_labels(relations): # TODO: this is not enough because we have to exclude some tinay classes new_relation_list = [] for relation in relations: split_sense = relation.senses[0].split('.') if len(split_sense) >= 2: relation.relation_dict['Sense']= ['.'.join(split_sense[0:2])] new_relation_list.append(relation) return new_relation_list def level2_labels(relations, alphabet=None): if alphabet is None: alphabet = {} label_set = set() for relation in relations:
print label_set sorted_label = sorted(list(label_set)) for i, label in enumerate(sorted_label): alphabet[label] = i label_vector = [] for relation in relations: if relation.senses[0] not in alphabet: alphabet[relation.senses[0]] = len(alphabet) label_vector.append(alphabet[relation.senses[0]]) return np.array(label_vector, np.int64), alphabet def get_wbm(num_units): if num_units == 50: dict_file = '/data/word_embeddings/wsj-skipgram50.npy' vocab_file = '/data/word_embeddings/wsj-skipgram50_vocab.txt' elif num_units == 100: dict_file = '/data/word_embeddings/wsj-skipgram100.npy' vocab_file = '/data/word_embeddings/wsj-skipgram100_vocab.txt' elif num_units == 300: #dict_file = '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300.npy' dict_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300-wsj_vocab.npy' vocab_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors.negative300-wsj_vocab-vocab.txt' else: # this will crash the next step and te's too lazy to make it throw an exception. dict_file = None vocab_file = None wbm = WordEmbeddingDict(dict_file, vocab_file) return wbm def get_zh_wbm(num_units): dict_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab.npy' % num_units vocab_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab-vocab.txt' % num_units return WordEmbeddingDict(dict_file, vocab_file) def set_logger(file_name, dry_mode=False): if not dry_mode: sys.stdout = open('%s.log' % file_name, 'w', 1) json_file = open('%s.json' % file_name, 'w', 1) return json_file import base_label_functions as l from nets.learning import DataTriplet from data_reader import extract_implicit_relations from lstm import prep_serrated_matrix_relations def get_data_srm(dir_list, wbm, max_length=75): sense_lf = l.SecondLevelLabel() relation_list_list = [extract_implicit_relations(dir, sense_lf) for dir in dir_list] data_list = [] for relation_list in relation_list_list: data = prep_serrated_matrix_relations(relation_list, wbm, max_length) data_list.append(data) label_vectors, label_alphabet = \ label_vectorize(relation_list_list, sense_lf) data_triplet = DataTriplet( data_list, [[x] for x in label_vectors], [label_alphabet]) return data_triplet def make_givens_srm(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 mask1 X2 mask2] X1 and X2 are TxNxd serrated matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][:,start_idx:end_idx, :] givens[input_vec[1]] = T_training_data[1][:,start_idx:end_idx] # second arg embedding and mask givens[input_vec[2]] = T_training_data[2][:,start_idx:end_idx, :] givens[input_vec[3]] = T_training_data[3][:,start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] def make_givens(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 X2] X1 and X2 are Nxd matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][start_idx:end_idx] givens[input_vec[1]] = T_training_data[1][start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] if __name__ == '__main__': fm = np.array([ [1, 0, 1], [1, 0, 0], [0, 0, 0], [0, 1, 1], [0, 1, 0], [0, 0, 0]]) lv = np.array([0,0,0,1,1,1]) compute_mi(fm, lv)
label_set.add(relation.senses[0])
conditional_block
util.py
from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _get_zh_word2vec_ff(num_units, vec_type, projection, cdtb): prefix = 'zh_gigaword3' if cdtb: file_name = '/data/word_embeddings/%s-%s%s-cdtb_vocab.txt' \ % (prefix, vec_type, num_units) else: file_name = '/data/word_embeddings/%s-%s%s.txt' \ % (prefix, vec_type, num_units) word2vec = df.EmbeddingFeaturizer(file_name) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _sparse_featurize_relation_list(relation_list, ff_list, alphabet=None): if alphabet is None: alphabet = {} grow_alphabet = True else: grow_alphabet = False feature_vectors = [] print 'Applying feature functions...' for relation in relation_list: feature_vector_indices = [] for ff in ff_list: feature_vector = ff(relation) for f in feature_vector: if grow_alphabet and f not in alphabet: alphabet[f] = len(alphabet) if f in alphabet: feature_vector_indices.append(alphabet[f]) feature_vectors.append(feature_vector_indices) print 'Creating feature sparse matrix...' feature_matrix = sp.sparse.lil_matrix((len(relation_list), len(alphabet))) for i, fv in enumerate(feature_vectors): feature_matrix[i, fv] = 1 return feature_matrix.tocsr(), alphabet def sparse_featurize(relation_list_list, ff_list): print 'Featurizing...' data_list = [] alphabet = None for relation_list in relation_list_list: data, alphabet = _sparse_featurize_relation_list(relation_list, ff_list, alphabet) data_list.append(data) return (data_list, alphabet) def convert_seconds_to_hours(num_seconds): m, s = divmod(num_seconds, 60) h, m = divmod(m, 60) return (h, m, s) def compute_mi(feature_matrix, label_vector): """Compute mutual information of each feature """ num_labels = np.max(label_vector) + 1 num_features = feature_matrix.shape[1] num_rows = feature_matrix.shape[0] total = num_rows + num_labels c_y = np.zeros(num_labels) for l in label_vector: c_y[l] += 1.0 c_y += 1.0 c_x_y = np.zeros((num_features, num_labels)) c_x = np.zeros(num_features) for i in range(num_rows): c_x_y[:, label_vector[i]] += feature_matrix[i, :] c_x += feature_matrix[i, :] c_x_y += 1.0 c_x += 1.0 c_x_c_y = np.outer(c_x, c_y) c_not_x_c_y = np.outer((total - c_x), c_y) c_not_x_y = c_y - c_x_y inner = c_x_y / total * np.log(c_x_y * total / c_x_c_y) + \ c_not_x_y / total * np.log(c_not_x_y * total / c_not_x_c_y) mi_x = inner.sum(1) return mi_x def prune_feature_matrices(feature_matrices, mi, num_features): sorted_indices = mi.argsort()[-num_features:] return [x[:, sorted_indices] for x in feature_matrices] class BrownDictionary(object): def __init__(self): self.word_to_brown_mapping = {} self.num_clusters = 0 brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt' self._load_brown_clusters('resources/%s' % brown_cluster_file_name) def _load_brown_clusters(self, path): try: lexicon_file = open(path) except: print 'fail to load brown cluster data' cluster_set = set() for line in lexicon_file: cluster_assn, word, _ = line.split('\t') if cluster_assn not in cluster_set: cluster_set.add(cluster_assn) self.word_to_brown_mapping[word] = len(cluster_set) - 1 self.num_clusters = len(cluster_set) def _get_brown_cluster_bag(self, tokens): bag = set() for token in tokens: if token in self.word_to_brown_mapping: cluster_assn = self.word_to_brown_mapping[token] if cluster_assn not in bag: bag.add(cluster_assn) return bag def get_brown_sparse_matrices_relations(self, relations): X1 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) X2 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) for i, relation in enumerate(relations): bag1 = self._get_brown_cluster_bag(relation.arg_tokens(1)) for cluster in bag1: X1[i, cluster] = 1.0 bag2 = self._get_brown_cluster_bag(relation.arg_tokens(2)) for cluster in bag2: X2[i, cluster] = 1.0 return (X1, X2) def get_brown_matrices_data(self, relation_list_list, use_sparse): """Extract sparse For each directory, returns (X1, X2, Y) X1 and X2 are sparse matrices from arg1 and arg2 respectively. Y is an integer vector of type int32 """ data = [] alphabet = None # load the data for relation_list in relation_list_list: # turn them into a data matrix print 'Making matrices' X1, X2 = self.get_brown_sparse_matrices_relations(relation_list) if not use_sparse: X1 = X1.toarray() X2 = X2.toarray() Y, alphabet = level2_labels(relation_list, alphabet) data.append((X1, X2, Y)) return (data, alphabet) def label_vectorize(relation_list_list, lf): alphabet = {} for i, valid_label in enumerate(lf.valid_labels()): alphabet[valid_label] = i label_vectors = [] for relation_list in relation_list_list: label_vector = [alphabet[lf.label(x)] for x in relation_list] label_vectors.append(np.array(label_vector, np.int64)) return label_vectors, alphabet def compute_baseline_acc(label_vector): label_counter = Counter() for label in label_vector: label_counter[label] += 1.0 _, freq = label_counter.most_common(1)[0] return round(freq / len(label_vector), 4) def convert_level2_labels(relations): # TODO: this is not enough because we have to exclude some tinay classes new_relation_list = [] for relation in relations: split_sense = relation.senses[0].split('.') if len(split_sense) >= 2: relation.relation_dict['Sense']= ['.'.join(split_sense[0:2])] new_relation_list.append(relation) return new_relation_list def level2_labels(relations, alphabet=None): if alphabet is None: alphabet = {} label_set = set() for relation in relations: label_set.add(relation.senses[0]) print label_set sorted_label = sorted(list(label_set)) for i, label in enumerate(sorted_label): alphabet[label] = i label_vector = [] for relation in relations: if relation.senses[0] not in alphabet: alphabet[relation.senses[0]] = len(alphabet) label_vector.append(alphabet[relation.senses[0]]) return np.array(label_vector, np.int64), alphabet def get_wbm(num_units): if num_units == 50: dict_file = '/data/word_embeddings/wsj-skipgram50.npy' vocab_file = '/data/word_embeddings/wsj-skipgram50_vocab.txt' elif num_units == 100: dict_file = '/data/word_embeddings/wsj-skipgram100.npy' vocab_file = '/data/word_embeddings/wsj-skipgram100_vocab.txt' elif num_units == 300: #dict_file = '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300.npy' dict_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300-wsj_vocab.npy' vocab_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors.negative300-wsj_vocab-vocab.txt' else: # this will crash the next step and te's too lazy to make it throw an exception. dict_file = None vocab_file = None wbm = WordEmbeddingDict(dict_file, vocab_file) return wbm def get_zh_wbm(num_units): dict_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab.npy' % num_units vocab_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab-vocab.txt' % num_units return WordEmbeddingDict(dict_file, vocab_file) def set_logger(file_name, dry_mode=False): if not dry_mode: sys.stdout = open('%s.log' % file_name, 'w', 1) json_file = open('%s.json' % file_name, 'w', 1) return json_file import base_label_functions as l from nets.learning import DataTriplet from data_reader import extract_implicit_relations from lstm import prep_serrated_matrix_relations def get_data_srm(dir_list, wbm, max_length=75): sense_lf = l.SecondLevelLabel() relation_list_list = [extract_implicit_relations(dir, sense_lf) for dir in dir_list] data_list = [] for relation_list in relation_list_list: data = prep_serrated_matrix_relations(relation_list, wbm, max_length) data_list.append(data) label_vectors, label_alphabet = \ label_vectorize(relation_list_list, sense_lf) data_triplet = DataTriplet( data_list, [[x] for x in label_vectors], [label_alphabet]) return data_triplet def make_givens_srm(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 mask1 X2 mask2] X1 and X2 are TxNxd serrated matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][:,start_idx:end_idx, :] givens[input_vec[1]] = T_training_data[1][:,start_idx:end_idx] # second arg embedding and mask givens[input_vec[2]] = T_training_data[2][:,start_idx:end_idx, :] givens[input_vec[3]] = T_training_data[3][:,start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] def make_givens(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 X2] X1 and X2 are Nxd matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][start_idx:end_idx] givens[input_vec[1]] = T_training_data[1][start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx]
[0, 1, 0], [0, 0, 0]]) lv = np.array([0,0,0,1,1,1]) compute_mi(fm, lv)
if __name__ == '__main__': fm = np.array([ [1, 0, 1], [1, 0, 0], [0, 0, 0], [0, 1, 1],
random_line_split
util.py
from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _get_zh_word2vec_ff(num_units, vec_type, projection, cdtb): prefix = 'zh_gigaword3' if cdtb: file_name = '/data/word_embeddings/%s-%s%s-cdtb_vocab.txt' \ % (prefix, vec_type, num_units) else: file_name = '/data/word_embeddings/%s-%s%s.txt' \ % (prefix, vec_type, num_units) word2vec = df.EmbeddingFeaturizer(file_name) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _sparse_featurize_relation_list(relation_list, ff_list, alphabet=None): if alphabet is None: alphabet = {} grow_alphabet = True else: grow_alphabet = False feature_vectors = [] print 'Applying feature functions...' for relation in relation_list: feature_vector_indices = [] for ff in ff_list: feature_vector = ff(relation) for f in feature_vector: if grow_alphabet and f not in alphabet: alphabet[f] = len(alphabet) if f in alphabet: feature_vector_indices.append(alphabet[f]) feature_vectors.append(feature_vector_indices) print 'Creating feature sparse matrix...' feature_matrix = sp.sparse.lil_matrix((len(relation_list), len(alphabet))) for i, fv in enumerate(feature_vectors): feature_matrix[i, fv] = 1 return feature_matrix.tocsr(), alphabet def sparse_featurize(relation_list_list, ff_list): print 'Featurizing...' data_list = [] alphabet = None for relation_list in relation_list_list: data, alphabet = _sparse_featurize_relation_list(relation_list, ff_list, alphabet) data_list.append(data) return (data_list, alphabet) def convert_seconds_to_hours(num_seconds): m, s = divmod(num_seconds, 60) h, m = divmod(m, 60) return (h, m, s) def compute_mi(feature_matrix, label_vector): """Compute mutual information of each feature """ num_labels = np.max(label_vector) + 1 num_features = feature_matrix.shape[1] num_rows = feature_matrix.shape[0] total = num_rows + num_labels c_y = np.zeros(num_labels) for l in label_vector: c_y[l] += 1.0 c_y += 1.0 c_x_y = np.zeros((num_features, num_labels)) c_x = np.zeros(num_features) for i in range(num_rows): c_x_y[:, label_vector[i]] += feature_matrix[i, :] c_x += feature_matrix[i, :] c_x_y += 1.0 c_x += 1.0 c_x_c_y = np.outer(c_x, c_y) c_not_x_c_y = np.outer((total - c_x), c_y) c_not_x_y = c_y - c_x_y inner = c_x_y / total * np.log(c_x_y * total / c_x_c_y) + \ c_not_x_y / total * np.log(c_not_x_y * total / c_not_x_c_y) mi_x = inner.sum(1) return mi_x def prune_feature_matrices(feature_matrices, mi, num_features): sorted_indices = mi.argsort()[-num_features:] return [x[:, sorted_indices] for x in feature_matrices] class BrownDictionary(object): def __init__(self): self.word_to_brown_mapping = {} self.num_clusters = 0 brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt' self._load_brown_clusters('resources/%s' % brown_cluster_file_name) def _load_brown_clusters(self, path): try: lexicon_file = open(path) except: print 'fail to load brown cluster data' cluster_set = set() for line in lexicon_file: cluster_assn, word, _ = line.split('\t') if cluster_assn not in cluster_set: cluster_set.add(cluster_assn) self.word_to_brown_mapping[word] = len(cluster_set) - 1 self.num_clusters = len(cluster_set) def _get_brown_cluster_bag(self, tokens): bag = set() for token in tokens: if token in self.word_to_brown_mapping: cluster_assn = self.word_to_brown_mapping[token] if cluster_assn not in bag: bag.add(cluster_assn) return bag def get_brown_sparse_matrices_relations(self, relations): X1 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) X2 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) for i, relation in enumerate(relations): bag1 = self._get_brown_cluster_bag(relation.arg_tokens(1)) for cluster in bag1: X1[i, cluster] = 1.0 bag2 = self._get_brown_cluster_bag(relation.arg_tokens(2)) for cluster in bag2: X2[i, cluster] = 1.0 return (X1, X2) def get_brown_matrices_data(self, relation_list_list, use_sparse): """Extract sparse For each directory, returns (X1, X2, Y) X1 and X2 are sparse matrices from arg1 and arg2 respectively. Y is an integer vector of type int32 """ data = [] alphabet = None # load the data for relation_list in relation_list_list: # turn them into a data matrix print 'Making matrices' X1, X2 = self.get_brown_sparse_matrices_relations(relation_list) if not use_sparse: X1 = X1.toarray() X2 = X2.toarray() Y, alphabet = level2_labels(relation_list, alphabet) data.append((X1, X2, Y)) return (data, alphabet) def label_vectorize(relation_list_list, lf): alphabet = {} for i, valid_label in enumerate(lf.valid_labels()): alphabet[valid_label] = i label_vectors = [] for relation_list in relation_list_list: label_vector = [alphabet[lf.label(x)] for x in relation_list] label_vectors.append(np.array(label_vector, np.int64)) return label_vectors, alphabet def compute_baseline_acc(label_vector): label_counter = Counter() for label in label_vector: label_counter[label] += 1.0 _, freq = label_counter.most_common(1)[0] return round(freq / len(label_vector), 4) def convert_level2_labels(relations): # TODO: this is not enough because we have to exclude some tinay classes new_relation_list = [] for relation in relations: split_sense = relation.senses[0].split('.') if len(split_sense) >= 2: relation.relation_dict['Sense']= ['.'.join(split_sense[0:2])] new_relation_list.append(relation) return new_relation_list def level2_labels(relations, alphabet=None): if alphabet is None: alphabet = {} label_set = set() for relation in relations: label_set.add(relation.senses[0]) print label_set sorted_label = sorted(list(label_set)) for i, label in enumerate(sorted_label): alphabet[label] = i label_vector = [] for relation in relations: if relation.senses[0] not in alphabet: alphabet[relation.senses[0]] = len(alphabet) label_vector.append(alphabet[relation.senses[0]]) return np.array(label_vector, np.int64), alphabet def get_wbm(num_units): if num_units == 50: dict_file = '/data/word_embeddings/wsj-skipgram50.npy' vocab_file = '/data/word_embeddings/wsj-skipgram50_vocab.txt' elif num_units == 100: dict_file = '/data/word_embeddings/wsj-skipgram100.npy' vocab_file = '/data/word_embeddings/wsj-skipgram100_vocab.txt' elif num_units == 300: #dict_file = '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300.npy' dict_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300-wsj_vocab.npy' vocab_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors.negative300-wsj_vocab-vocab.txt' else: # this will crash the next step and te's too lazy to make it throw an exception. dict_file = None vocab_file = None wbm = WordEmbeddingDict(dict_file, vocab_file) return wbm def get_zh_wbm(num_units): dict_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab.npy' % num_units vocab_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab-vocab.txt' % num_units return WordEmbeddingDict(dict_file, vocab_file) def set_logger(file_name, dry_mode=False): if not dry_mode: sys.stdout = open('%s.log' % file_name, 'w', 1) json_file = open('%s.json' % file_name, 'w', 1) return json_file import base_label_functions as l from nets.learning import DataTriplet from data_reader import extract_implicit_relations from lstm import prep_serrated_matrix_relations def get_data_srm(dir_list, wbm, max_length=75): sense_lf = l.SecondLevelLabel() relation_list_list = [extract_implicit_relations(dir, sense_lf) for dir in dir_list] data_list = [] for relation_list in relation_list_list: data = prep_serrated_matrix_relations(relation_list, wbm, max_length) data_list.append(data) label_vectors, label_alphabet = \ label_vectorize(relation_list_list, sense_lf) data_triplet = DataTriplet( data_list, [[x] for x in label_vectors], [label_alphabet]) return data_triplet def make_givens_srm(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 mask1 X2 mask2] X1 and X2 are TxNxd serrated matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][:,start_idx:end_idx, :] givens[input_vec[1]] = T_training_data[1][:,start_idx:end_idx] # second arg embedding and mask givens[input_vec[2]] = T_training_data[2][:,start_idx:end_idx, :] givens[input_vec[3]] = T_training_data[3][:,start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] def
(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 X2] X1 and X2 are Nxd matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][start_idx:end_idx] givens[input_vec[1]] = T_training_data[1][start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] if __name__ == '__main__': fm = np.array([ [1, 0, 1], [1, 0, 0], [0, 0, 0], [0, 1, 1], [0, 1, 0], [0, 0, 0]]) lv = np.array([0,0,0,1,1,1]) compute_mi(fm, lv)
make_givens
identifier_name
transport-server-test.js
// Copyright (c) 2016 the rocket-skates AUTHORS. All rights reserved. // 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 strict'; const assert = require('chai').assert; const request = require('supertest'); const https = require('https'); const MockClient = require('./tools/mock-client'); const promisify = require('./tools/promisify'); const cachedCrypto = require('./tools/cached-crypto'); const TransportServer = require('../lib/server/transport-server'); const port = 4300; const rateLimit = 5; const nonceRE = /^[a-zA-Z0-9-_]+$/;
const mockClient = new MockClient(); describe('transport-level server', () => { let transport; let server; beforeEach(done => { cachedCrypto.tlsConfig .then(tlsConfig => { transport = new TransportServer({rateLimit: rateLimit}); server = https.createServer(tlsConfig, transport.app); server.listen(port, done); }); }); afterEach(done => { server.close(done); }); it('responds to a valid POST request', (done) => { let nonce = transport.nonces.get(); let payload = {'fnord': 42}; let gotPOST = false; let result = {'bar': 2}; transport.app.post('/foo', (req, res) => { gotPOST = true; try { assert.deepEqual(req.payload, payload); } catch (e) { res.status(418); } res.json(result); }); mockClient.makeJWS(nonce, 'https://127.0.0.1/foo', payload) .then(jws => promisify(request(server).post('/foo').send(jws))) .then(res => { assert.equal(res.status, 200); assert.property(res.headers, 'replay-nonce'); assert.ok(res.headers['replay-nonce'].match(nonceRE)); assert.isTrue(gotPOST); assert.deepEqual(res.body, result); done(); }) .catch(done); }); it('refuses a non-HTTPS request', (done) => { transport = new TransportServer(); let httpServer = transport.app.listen(8080, () => { request(httpServer) .get('/') .expect(500, done); }); }); it('applies a rate limit', (done) => { transport.rateLimit.queue.push(new Date('2016-01-01')); for (let i = 0; i < rateLimit; ++i) { transport.rateLimit.update(); } promisify(request(server).post('/unknown')) .then(res => { assert.equal(res.status, 403); assert.propertyVal(res.headers, 'retry-after', '1'); done(); }) .catch(done); }); it('rejects a POST with a bad nonce', (done) => { mockClient.makeJWS('asdf', 'https://127.0.0.1/foo?bar=baz', {}) .then(jws => { request(server) .post('/foo?bar=baz') .send(jws) .expect(400, done); }); }); it('rejects a POST with a bad url', (done) => { let nonce = transport.nonces.get(); mockClient.makeJWS(nonce, 'https://example.com/stuff', {}) .then(jws => { request(server) .post('/foo?bar=baz') .send(jws) .expect(400, done); }); }); it('provides a nonce for GET requests', (done) => { request(server) .get('/') .expect(404) .expect('replay-nonce', nonceRE, done); }); it('provides a nonce for HEAD requests', (done) => { request(server) .head('/') .expect(404) .expect('replay-nonce', nonceRE) .end(done); }); });
random_line_split
transport-server-test.js
// Copyright (c) 2016 the rocket-skates AUTHORS. All rights reserved. // 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 strict'; const assert = require('chai').assert; const request = require('supertest'); const https = require('https'); const MockClient = require('./tools/mock-client'); const promisify = require('./tools/promisify'); const cachedCrypto = require('./tools/cached-crypto'); const TransportServer = require('../lib/server/transport-server'); const port = 4300; const rateLimit = 5; const nonceRE = /^[a-zA-Z0-9-_]+$/; const mockClient = new MockClient(); describe('transport-level server', () => { let transport; let server; beforeEach(done => { cachedCrypto.tlsConfig .then(tlsConfig => { transport = new TransportServer({rateLimit: rateLimit}); server = https.createServer(tlsConfig, transport.app); server.listen(port, done); }); }); afterEach(done => { server.close(done); }); it('responds to a valid POST request', (done) => { let nonce = transport.nonces.get(); let payload = {'fnord': 42}; let gotPOST = false; let result = {'bar': 2}; transport.app.post('/foo', (req, res) => { gotPOST = true; try { assert.deepEqual(req.payload, payload); } catch (e) { res.status(418); } res.json(result); }); mockClient.makeJWS(nonce, 'https://127.0.0.1/foo', payload) .then(jws => promisify(request(server).post('/foo').send(jws))) .then(res => { assert.equal(res.status, 200); assert.property(res.headers, 'replay-nonce'); assert.ok(res.headers['replay-nonce'].match(nonceRE)); assert.isTrue(gotPOST); assert.deepEqual(res.body, result); done(); }) .catch(done); }); it('refuses a non-HTTPS request', (done) => { transport = new TransportServer(); let httpServer = transport.app.listen(8080, () => { request(httpServer) .get('/') .expect(500, done); }); }); it('applies a rate limit', (done) => { transport.rateLimit.queue.push(new Date('2016-01-01')); for (let i = 0; i < rateLimit; ++i)
promisify(request(server).post('/unknown')) .then(res => { assert.equal(res.status, 403); assert.propertyVal(res.headers, 'retry-after', '1'); done(); }) .catch(done); }); it('rejects a POST with a bad nonce', (done) => { mockClient.makeJWS('asdf', 'https://127.0.0.1/foo?bar=baz', {}) .then(jws => { request(server) .post('/foo?bar=baz') .send(jws) .expect(400, done); }); }); it('rejects a POST with a bad url', (done) => { let nonce = transport.nonces.get(); mockClient.makeJWS(nonce, 'https://example.com/stuff', {}) .then(jws => { request(server) .post('/foo?bar=baz') .send(jws) .expect(400, done); }); }); it('provides a nonce for GET requests', (done) => { request(server) .get('/') .expect(404) .expect('replay-nonce', nonceRE, done); }); it('provides a nonce for HEAD requests', (done) => { request(server) .head('/') .expect(404) .expect('replay-nonce', nonceRE) .end(done); }); });
{ transport.rateLimit.update(); }
conditional_block
test_config_reader.py
########################################################################## #This file is part of WTFramework. # # WTFramework is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # WTFramework is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with WTFramework. If not, see <http://www.gnu.org/licenses/>. ########################################################################## from wtframework.wtf.config import ConfigReader, ConfigFileReadError import unittest class TestConfigReader(unittest.TestCase): def test_get_returns_string_config_value(self): ''' Test config value returned is expected value ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("string_test") self.assertEqual(value, "some value", "Value did not match expected.") def test_get_with_default_value(self): "Test the get method returns value if available or the the default." config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("some value", config.get("string_test", "default value")) self.assertEqual("default value", config.get("i_dont_exist", "default value")) def test_get_handles_namespaced_keys(self): ''' Test ConfigReader works with namespaced keys like, path.to.element ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("bill-to.given") self.assertEqual(value, "Chris", "Value did not match expected.") def test_get_handles_yaml_arrays(self): ''' Test ConfigReader works with YAML arrays. ''' config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("dogs", config.get("list_test")[0]) self.assertEqual("cats", config.get("list_test")[1]) self.assertEqual("badgers", config.get("list_test")[2]) def test_get_with_cascaded_config_files(self):
def test_get_with_missing_key_and_no_default(self): "An error should be thrown if the key is missing and no default provided." config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertRaises(KeyError, config.get, "setting_that_doesnt_exist") def test_specifying_bad_config_file(self): "Test error is thrown when invalid config file is specified." self.assertRaises(ConfigFileReadError, ConfigReader, "tests/TestConfig1,NOSUCHFILE") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
''' Test Config reader loaded up with multiple configs loads the config preferences in order. ''' config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertEqual("hello", config.get("setting_from_config1")) # this will take the config from config2, which has precedence. self.assertEqual("beautiful", config.get("overwrite_setting")) # this will take the setting form config2. self.assertEqual("hi", config.get("setting_from_config2"))
identifier_body
test_config_reader.py
########################################################################## #This file is part of WTFramework. # # WTFramework is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # WTFramework is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with WTFramework. If not, see <http://www.gnu.org/licenses/>. ########################################################################## from wtframework.wtf.config import ConfigReader, ConfigFileReadError import unittest class TestConfigReader(unittest.TestCase): def test_get_returns_string_config_value(self): ''' Test config value returned is expected value ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("string_test") self.assertEqual(value, "some value", "Value did not match expected.") def test_get_with_default_value(self): "Test the get method returns value if available or the the default." config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("some value", config.get("string_test", "default value")) self.assertEqual("default value", config.get("i_dont_exist", "default value")) def test_get_handles_namespaced_keys(self): ''' Test ConfigReader works with namespaced keys like, path.to.element ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("bill-to.given") self.assertEqual(value, "Chris", "Value did not match expected.") def test_get_handles_yaml_arrays(self): ''' Test ConfigReader works with YAML arrays. ''' config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("dogs", config.get("list_test")[0]) self.assertEqual("cats", config.get("list_test")[1]) self.assertEqual("badgers", config.get("list_test")[2]) def test_get_with_cascaded_config_files(self): ''' Test Config reader loaded up with multiple configs loads the config preferences in order. ''' config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertEqual("hello", config.get("setting_from_config1")) # this will take the config from config2, which has precedence. self.assertEqual("beautiful", config.get("overwrite_setting")) # this will take the setting form config2. self.assertEqual("hi", config.get("setting_from_config2")) def test_get_with_missing_key_and_no_default(self): "An error should be thrown if the key is missing and no default provided." config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertRaises(KeyError, config.get, "setting_that_doesnt_exist") def test_specifying_bad_config_file(self): "Test error is thrown when invalid config file is specified." self.assertRaises(ConfigFileReadError, ConfigReader, "tests/TestConfig1,NOSUCHFILE") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName']
unittest.main()
conditional_block
test_config_reader.py
########################################################################## #This file is part of WTFramework. # # WTFramework is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # WTFramework is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with WTFramework. If not, see <http://www.gnu.org/licenses/>. ########################################################################## from wtframework.wtf.config import ConfigReader, ConfigFileReadError import unittest class TestConfigReader(unittest.TestCase): def test_get_returns_string_config_value(self): ''' Test config value returned is expected value ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("string_test") self.assertEqual(value, "some value", "Value did not match expected.") def test_get_with_default_value(self): "Test the get method returns value if available or the the default." config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("some value", config.get("string_test", "default value")) self.assertEqual("default value", config.get("i_dont_exist", "default value")) def test_get_handles_namespaced_keys(self): ''' Test ConfigReader works with namespaced keys like, path.to.element ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("bill-to.given") self.assertEqual(value, "Chris", "Value did not match expected.") def test_get_handles_yaml_arrays(self): ''' Test ConfigReader works with YAML arrays. ''' config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("dogs", config.get("list_test")[0]) self.assertEqual("cats", config.get("list_test")[1]) self.assertEqual("badgers", config.get("list_test")[2]) def test_get_with_cascaded_config_files(self): ''' Test Config reader loaded up with multiple configs loads the config preferences in order. ''' config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertEqual("hello", config.get("setting_from_config1")) # this will take the config from config2, which has precedence. self.assertEqual("beautiful", config.get("overwrite_setting")) # this will take the setting form config2. self.assertEqual("hi", config.get("setting_from_config2")) def
(self): "An error should be thrown if the key is missing and no default provided." config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertRaises(KeyError, config.get, "setting_that_doesnt_exist") def test_specifying_bad_config_file(self): "Test error is thrown when invalid config file is specified." self.assertRaises(ConfigFileReadError, ConfigReader, "tests/TestConfig1,NOSUCHFILE") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
test_get_with_missing_key_and_no_default
identifier_name
test_config_reader.py
########################################################################## #This file is part of WTFramework. # # WTFramework is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # WTFramework is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with WTFramework. If not, see <http://www.gnu.org/licenses/>. ########################################################################## from wtframework.wtf.config import ConfigReader, ConfigFileReadError import unittest class TestConfigReader(unittest.TestCase): def test_get_returns_string_config_value(self): ''' Test config value returned is expected value ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("string_test") self.assertEqual(value, "some value", "Value did not match expected.") def test_get_with_default_value(self): "Test the get method returns value if available or the the default." config = ConfigReader("tests/TestConfigReaderData")
self.assertEqual("some value", config.get("string_test", "default value")) self.assertEqual("default value", config.get("i_dont_exist", "default value")) def test_get_handles_namespaced_keys(self): ''' Test ConfigReader works with namespaced keys like, path.to.element ''' config = ConfigReader("tests/TestConfigReaderData") value = config.get("bill-to.given") self.assertEqual(value, "Chris", "Value did not match expected.") def test_get_handles_yaml_arrays(self): ''' Test ConfigReader works with YAML arrays. ''' config = ConfigReader("tests/TestConfigReaderData") self.assertEqual("dogs", config.get("list_test")[0]) self.assertEqual("cats", config.get("list_test")[1]) self.assertEqual("badgers", config.get("list_test")[2]) def test_get_with_cascaded_config_files(self): ''' Test Config reader loaded up with multiple configs loads the config preferences in order. ''' config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertEqual("hello", config.get("setting_from_config1")) # this will take the config from config2, which has precedence. self.assertEqual("beautiful", config.get("overwrite_setting")) # this will take the setting form config2. self.assertEqual("hi", config.get("setting_from_config2")) def test_get_with_missing_key_and_no_default(self): "An error should be thrown if the key is missing and no default provided." config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertRaises(KeyError, config.get, "setting_that_doesnt_exist") def test_specifying_bad_config_file(self): "Test error is thrown when invalid config file is specified." self.assertRaises(ConfigFileReadError, ConfigReader, "tests/TestConfig1,NOSUCHFILE") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
random_line_split
cli.js
#!/usr/bin/env node 'use strict'; var meow = require('meow'); var clc = require('cli-color'); var terminalWallet = require('./'); var cli = meow({ help: [ 'Usage', ' wallet debit <value> <purchase details> [-c <category>][-d <date in yyyy-mm-dd format>]', ' wallet credit <value> <source details> [-c <category>][-d <date in yyyy-mm-dd format>]', ' wallet stats', ' wallet export', ' wallet clear', '', 'Example', " wallet debit 10 'Breakfast, Coffee at Canteen' -c 'Food'", '', ' ✔ Expense written to file!', '', " wallet credit 2000 'Salary for July 2015' -c 'Salary'", '', ' ✔ Expense written to file!', '', ' wallet stats',
'', ' Total Credit : 13920', ' Total Debit : 590', ' Balance : 13330', ' Stashed : 0', '', '', ' wallet export', '', ' ✔ Your file can be found at', ' /home/siddharth/.local/share/wallet/exported/export-2015-07-06.csv', '', ' wallet clear', '', ' ✔ Account closed. Expense details have been exported to :-', ' /home/siddharth/.local/share/wallet/closed/closed-2015-07-06.csv', ' Prepared a clean slate, for the next accounting period.', '', ' wallet-open # or just wo', ' This will open the wallet csv file in a less session, in a', ' in a reverse chronographic order, which is convenient for viewing', ' latest transactions', '', ' wallet file_path', ' Shows the file path of the wallet expenses file. Can be used to', ' see it in your editor of choice. Editing it is not advised', '', 'Options', " -c Category ; Default: '' ; Optional", " -d yyyy-mm-dd ; Default: Today's date; Optional" ].join('\n') }); try { terminalWallet(cli.input, cli.flags); } catch (err) { console.log(clc.red(err.message)); process.exit(1); }
random_line_split
test_product_variation.py
# -*- coding: utf-8 -*- from django.forms import formset_factory import pytest from shoop.admin.modules.products.views.variation.simple_variation_forms import SimpleVariationChildForm, SimpleVariationChildFormSet from shoop.admin.modules.products.views.variation.variable_variation_forms import VariableVariationChildrenForm from shoop.core.models.product_variation import ProductVariationVariable, ProductVariationVariableValue from shoop.testing.factories import create_product from shoop_tests.utils import printable_gibberish from shoop_tests.utils.forms import get_form_data @pytest.mark.django_db
# No links yet formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 0 # No children yet # Save a link data = dict(get_form_data(formset, True), **{"form-0-child": child.pk}) formset = FormSet(parent_product=parent, data=data) formset.save() assert parent.variation_children.filter(pk=child.pk).exists() # Got link'd! # Remove the link formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 1 # Got the child here data = dict(get_form_data(formset, True), **{"form-0-DELETE": "1"}) formset = FormSet(parent_product=parent, data=data) formset.save() assert not parent.variation_children.exists() # Got unlinked @pytest.mark.django_db def test_variable_variation_form(): var1 = printable_gibberish() var2 = printable_gibberish() parent = create_product(printable_gibberish()) for a in range(4): for b in range(3): child = create_product(printable_gibberish()) child.link_to_parent(parent, variables={var1: a, var2: b}) assert parent.variation_children.count() == 4 * 3 form = VariableVariationChildrenForm(parent_product=parent) assert len(form.fields) == 12 # TODO: Improve this test?
def test_simple_children_formset(): FormSet = formset_factory(SimpleVariationChildForm, SimpleVariationChildFormSet, extra=5, can_delete=True) parent = create_product(printable_gibberish()) child = create_product(printable_gibberish())
random_line_split
test_product_variation.py
# -*- coding: utf-8 -*- from django.forms import formset_factory import pytest from shoop.admin.modules.products.views.variation.simple_variation_forms import SimpleVariationChildForm, SimpleVariationChildFormSet from shoop.admin.modules.products.views.variation.variable_variation_forms import VariableVariationChildrenForm from shoop.core.models.product_variation import ProductVariationVariable, ProductVariationVariableValue from shoop.testing.factories import create_product from shoop_tests.utils import printable_gibberish from shoop_tests.utils.forms import get_form_data @pytest.mark.django_db def test_simple_children_formset(): FormSet = formset_factory(SimpleVariationChildForm, SimpleVariationChildFormSet, extra=5, can_delete=True) parent = create_product(printable_gibberish()) child = create_product(printable_gibberish()) # No links yet formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 0 # No children yet # Save a link data = dict(get_form_data(formset, True), **{"form-0-child": child.pk}) formset = FormSet(parent_product=parent, data=data) formset.save() assert parent.variation_children.filter(pk=child.pk).exists() # Got link'd! # Remove the link formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 1 # Got the child here data = dict(get_form_data(formset, True), **{"form-0-DELETE": "1"}) formset = FormSet(parent_product=parent, data=data) formset.save() assert not parent.variation_children.exists() # Got unlinked @pytest.mark.django_db def test_variable_variation_form(): var1 = printable_gibberish() var2 = printable_gibberish() parent = create_product(printable_gibberish()) for a in range(4):
assert parent.variation_children.count() == 4 * 3 form = VariableVariationChildrenForm(parent_product=parent) assert len(form.fields) == 12 # TODO: Improve this test?
for b in range(3): child = create_product(printable_gibberish()) child.link_to_parent(parent, variables={var1: a, var2: b})
conditional_block
test_product_variation.py
# -*- coding: utf-8 -*- from django.forms import formset_factory import pytest from shoop.admin.modules.products.views.variation.simple_variation_forms import SimpleVariationChildForm, SimpleVariationChildFormSet from shoop.admin.modules.products.views.variation.variable_variation_forms import VariableVariationChildrenForm from shoop.core.models.product_variation import ProductVariationVariable, ProductVariationVariableValue from shoop.testing.factories import create_product from shoop_tests.utils import printable_gibberish from shoop_tests.utils.forms import get_form_data @pytest.mark.django_db def test_simple_children_formset(): FormSet = formset_factory(SimpleVariationChildForm, SimpleVariationChildFormSet, extra=5, can_delete=True) parent = create_product(printable_gibberish()) child = create_product(printable_gibberish()) # No links yet formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 0 # No children yet # Save a link data = dict(get_form_data(formset, True), **{"form-0-child": child.pk}) formset = FormSet(parent_product=parent, data=data) formset.save() assert parent.variation_children.filter(pk=child.pk).exists() # Got link'd! # Remove the link formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 1 # Got the child here data = dict(get_form_data(formset, True), **{"form-0-DELETE": "1"}) formset = FormSet(parent_product=parent, data=data) formset.save() assert not parent.variation_children.exists() # Got unlinked @pytest.mark.django_db def
(): var1 = printable_gibberish() var2 = printable_gibberish() parent = create_product(printable_gibberish()) for a in range(4): for b in range(3): child = create_product(printable_gibberish()) child.link_to_parent(parent, variables={var1: a, var2: b}) assert parent.variation_children.count() == 4 * 3 form = VariableVariationChildrenForm(parent_product=parent) assert len(form.fields) == 12 # TODO: Improve this test?
test_variable_variation_form
identifier_name
test_product_variation.py
# -*- coding: utf-8 -*- from django.forms import formset_factory import pytest from shoop.admin.modules.products.views.variation.simple_variation_forms import SimpleVariationChildForm, SimpleVariationChildFormSet from shoop.admin.modules.products.views.variation.variable_variation_forms import VariableVariationChildrenForm from shoop.core.models.product_variation import ProductVariationVariable, ProductVariationVariableValue from shoop.testing.factories import create_product from shoop_tests.utils import printable_gibberish from shoop_tests.utils.forms import get_form_data @pytest.mark.django_db def test_simple_children_formset():
@pytest.mark.django_db def test_variable_variation_form(): var1 = printable_gibberish() var2 = printable_gibberish() parent = create_product(printable_gibberish()) for a in range(4): for b in range(3): child = create_product(printable_gibberish()) child.link_to_parent(parent, variables={var1: a, var2: b}) assert parent.variation_children.count() == 4 * 3 form = VariableVariationChildrenForm(parent_product=parent) assert len(form.fields) == 12 # TODO: Improve this test?
FormSet = formset_factory(SimpleVariationChildForm, SimpleVariationChildFormSet, extra=5, can_delete=True) parent = create_product(printable_gibberish()) child = create_product(printable_gibberish()) # No links yet formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 0 # No children yet # Save a link data = dict(get_form_data(formset, True), **{"form-0-child": child.pk}) formset = FormSet(parent_product=parent, data=data) formset.save() assert parent.variation_children.filter(pk=child.pk).exists() # Got link'd! # Remove the link formset = FormSet(parent_product=parent) assert formset.initial_form_count() == 1 # Got the child here data = dict(get_form_data(formset, True), **{"form-0-DELETE": "1"}) formset = FormSet(parent_product=parent, data=data) formset.save() assert not parent.variation_children.exists() # Got unlinked
identifier_body
a6.rs
fn main() { // Ciclos while, for, Enumerate let mut x = 5; let mut completado = false; // La variable mutable completado es de tipo booleano, es decir que solo tiene dos valores: false o true. println!("Ciclo while"); while !completado { // El ciclo while termina cuando la sentencia se cumpla en este caso cuando completado sea diferente a false, es decir verdadero. x += x; println!("{}", x); if x == 160 { completado = true; }; };
for i in 0..6 { // Este ciclo empiza por el primer número y termina uno antes del indicado, para este caso empieza en 0 y termina en 5 println!("{}", i); }; println!("Ciclo for con enumerate()"); for (i,j) in (5..11).enumerate() { // enumerate cuenta las veces que se iterao se hace el ciclo, es importante respetar los parentensis. println!("i = {} y j = {}", i, j); // i imprime el número de iteración y j el rango en el que se esta iterando. }; }
// El ciclo for de rust luce mas parecido al de ruby. println!("Ciclo for");
random_line_split
a6.rs
fn main() { // Ciclos while, for, Enumerate let mut x = 5; let mut completado = false; // La variable mutable completado es de tipo booleano, es decir que solo tiene dos valores: false o true. println!("Ciclo while"); while !completado { // El ciclo while termina cuando la sentencia se cumpla en este caso cuando completado sea diferente a false, es decir verdadero. x += x; println!("{}", x); if x == 160
; }; // El ciclo for de rust luce mas parecido al de ruby. println!("Ciclo for"); for i in 0..6 { // Este ciclo empiza por el primer número y termina uno antes del indicado, para este caso empieza en 0 y termina en 5 println!("{}", i); }; println!("Ciclo for con enumerate()"); for (i,j) in (5..11).enumerate() { // enumerate cuenta las veces que se iterao se hace el ciclo, es importante respetar los parentensis. println!("i = {} y j = {}", i, j); // i imprime el número de iteración y j el rango en el que se esta iterando. }; }
{ completado = true; }
conditional_block
a6.rs
fn main()
{ // Ciclos while, for, Enumerate let mut x = 5; let mut completado = false; // La variable mutable completado es de tipo booleano, es decir que solo tiene dos valores: false o true. println!("Ciclo while"); while !completado { // El ciclo while termina cuando la sentencia se cumpla en este caso cuando completado sea diferente a false, es decir verdadero. x += x; println!("{}", x); if x == 160 { completado = true; }; }; // El ciclo for de rust luce mas parecido al de ruby. println!("Ciclo for"); for i in 0..6 { // Este ciclo empiza por el primer número y termina uno antes del indicado, para este caso empieza en 0 y termina en 5 println!("{}", i); }; println!("Ciclo for con enumerate()"); for (i,j) in (5..11).enumerate() { // enumerate cuenta las veces que se iterao se hace el ciclo, es importante respetar los parentensis. println!("i = {} y j = {}", i, j); // i imprime el número de iteración y j el rango en el que se esta iterando. }; }
identifier_body
a6.rs
fn
() { // Ciclos while, for, Enumerate let mut x = 5; let mut completado = false; // La variable mutable completado es de tipo booleano, es decir que solo tiene dos valores: false o true. println!("Ciclo while"); while !completado { // El ciclo while termina cuando la sentencia se cumpla en este caso cuando completado sea diferente a false, es decir verdadero. x += x; println!("{}", x); if x == 160 { completado = true; }; }; // El ciclo for de rust luce mas parecido al de ruby. println!("Ciclo for"); for i in 0..6 { // Este ciclo empiza por el primer número y termina uno antes del indicado, para este caso empieza en 0 y termina en 5 println!("{}", i); }; println!("Ciclo for con enumerate()"); for (i,j) in (5..11).enumerate() { // enumerate cuenta las veces que se iterao se hace el ciclo, es importante respetar los parentensis. println!("i = {} y j = {}", i, j); // i imprime el número de iteración y j el rango en el que se esta iterando. }; }
main
identifier_name
Point.js
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD * license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Handler.js * @requires OpenLayers/Geometry/Point.js */ /** * Class: OpenLayers.Handler.Point * Handler to draw a point on the map. Point is displayed on mouse down, * moves on mouse move, and is finished on mouse up. The handler triggers * callbacks for 'done', 'cancel', and 'modify'. The modify callback is * called with each change in the sketch and will receive the latest point * drawn. Create a new instance with the <OpenLayers.Handler.Point> * constructor. * * Inherits from: * - <OpenLayers.Handler> */ OpenLayers.Handler.Point = OpenLayers.Class(OpenLayers.Handler, { /** * Property: point * {<OpenLayers.Feature.Vector>} The currently drawn point */ point: null, /** * Property: layer * {<OpenLayers.Layer.Vector>} The temporary drawing layer */ layer: null, /** * APIProperty: multi * {Boolean} Cast features to multi-part geometries before passing to the * layer. Default is false. */ multi: false, /** * Property: drawing * {Boolean} A point is being drawn */ drawing: false, /** * Property: mouseDown * {Boolean} The mouse is down */ mouseDown: false, /** * Property: lastDown * {<OpenLayers.Pixel>} Location of the last mouse down */ lastDown: null, /** * Property: lastUp * {<OpenLayers.Pixel>} */ lastUp: null, /** * APIProperty: persist * {Boolean} Leave the feature rendered until destroyFeature is called. * Default is false. If set to true, the feature remains rendered until * destroyFeature is called, typically by deactivating the handler or * starting another drawing. */ persist: false, /** * Property: layerOptions * {Object} Any optional properties to be set on the sketch layer. */ layerOptions: null, /** * Constructor: OpenLayers.Handler.Point * Create a new point handler. * * Parameters: * control - {<OpenLayers.Control>} The control that owns this handler * callbacks - {Object} An object with a properties whose values are * functions. Various callbacks described below. * options - {Object} An optional object with properties to be set on the * handler * * Named callbacks: * create - Called when a sketch is first created. Callback called with * the creation point geometry and sketch feature. * modify - Called with each move of a vertex with the vertex (point) * geometry and the sketch feature. * done - Called when the point drawing is finished. The callback will * recieve a single argument, the point geometry. * cancel - Called when the handler is deactivated while drawing. The * cancel callback will receive a geometry. */ initialize: function(control, callbacks, options) { if(!(options && options.layerOptions && options.layerOptions.styleMap)) { this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {}); }
* APIMethod: activate * turn on the handler */ activate: function() { if(!OpenLayers.Handler.prototype.activate.apply(this, arguments)) { return false; } // create temporary vector layer for rendering geometry sketch // TBD: this could be moved to initialize/destroy - setting visibility here var options = OpenLayers.Util.extend({ displayInLayerSwitcher: false, // indicate that the temp vector layer will never be out of range // without this, resolution properties must be specified at the // map-level for this temporary layer to init its resolutions // correctly calculateInRange: OpenLayers.Function.True }, this.layerOptions); this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options); this.map.addLayer(this.layer); return true; }, /** * Method: createFeature * Add temporary features * * Parameters: * pixel - {<OpenLayers.Pixel>} A pixel location on the map. */ createFeature: function(pixel) { var lonlat = this.map.getLonLatFromPixel(pixel); this.point = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat) ); this.callback("create", [this.point.geometry, this.point]); this.point.geometry.clearBounds(); this.layer.addFeatures([this.point], {silent: true}); }, /** * APIMethod: deactivate * turn off the handler */ deactivate: function() { if(!OpenLayers.Handler.prototype.deactivate.apply(this, arguments)) { return false; } // call the cancel callback if mid-drawing if(this.drawing) { this.cancel(); } this.destroyFeature(); // If a layer's map property is set to null, it means that that layer // isn't added to the map. Since we ourself added the layer to the map // in activate(), we can assume that if this.layer.map is null it means // that the layer has been destroyed (as a result of map.destroy() for // example. if (this.layer.map != null) { this.layer.destroy(false); } this.layer = null; return true; }, /** * Method: destroyFeature * Destroy the temporary geometries */ destroyFeature: function() { if(this.layer) { this.layer.destroyFeatures(); } this.point = null; }, /** * Method: finalize * Finish the geometry and call the "done" callback. * * Parameters: * cancel - {Boolean} Call cancel instead of done callback. Default is * false. */ finalize: function(cancel) { var key = cancel ? "cancel" : "done"; this.drawing = false; this.mouseDown = false; this.lastDown = null; this.lastUp = null; this.callback(key, [this.geometryClone()]); if(cancel || !this.persist) { this.destroyFeature(); } }, /** * APIMethod: cancel * Finish the geometry and call the "cancel" callback. */ cancel: function() { this.finalize(true); }, /** * Method: click * Handle clicks. Clicks are stopped from propagating to other listeners * on map.events or other dom elements. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ click: function(evt) { OpenLayers.Event.stop(evt); return false; }, /** * Method: dblclick * Handle double-clicks. Double-clicks are stopped from propagating to other * listeners on map.events or other dom elements. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ dblclick: function(evt) { OpenLayers.Event.stop(evt); return false; }, /** * Method: modifyFeature * Modify the existing geometry given a pixel location. * * Parameters: * pixel - {<OpenLayers.Pixel>} A pixel location on the map. */ modifyFeature: function(pixel) { var lonlat = this.map.getLonLatFromPixel(pixel); this.point.geometry.x = lonlat.lon; this.point.geometry.y = lonlat.lat; this.callback("modify", [this.point.geometry, this.point]); this.point.geometry.clearBounds(); this.drawFeature(); }, /** * Method: drawFeature * Render features on the temporary layer. */ drawFeature: function() { this.layer.drawFeature(this.point, this.style); }, /** * Method: getGeometry * Return the sketch geometry. If <multi> is true, this will return * a multi-part geometry. * * Returns: * {<OpenLayers.Geometry.Point>} */ getGeometry: function() { var geometry = this.point && this.point.geometry; if(geometry && this.multi) { geometry = new OpenLayers.Geometry.MultiPoint([geometry]); } return geometry; }, /** * Method: geometryClone * Return a clone of the relevant geometry. * * Returns: * {<OpenLayers.Geometry>} */ geometryClone: function() { var geom = this.getGeometry(); return geom && geom.clone(); }, /** * Method: mousedown * Handle mouse down. Adjust the geometry and redraw. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mousedown: function(evt) { // check keyboard modifiers if(!this.checkModifiers(evt)) { return true; } // ignore double-clicks if(this.lastDown && this.lastDown.equals(evt.xy)) { return true; } this.drawing = true; if(this.lastDown == null) { if(this.persist) { this.destroyFeature(); } this.createFeature(evt.xy); } else { this.modifyFeature(evt.xy); } this.lastDown = evt.xy; return false; }, /** * Method: mousemove * Handle mouse move. Adjust the geometry and redraw. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mousemove: function (evt) { if(this.drawing) { this.modifyFeature(evt.xy); } return true; }, /** * Method: mouseup * Handle mouse up. Send the latest point in the geometry to the control. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mouseup: function (evt) { if(this.drawing) { this.finalize(); return false; } else { return true; } }, CLASS_NAME: "OpenLayers.Handler.Point" });
OpenLayers.Handler.prototype.initialize.apply(this, arguments); }, /**
random_line_split
Point.js
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD * license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Handler.js * @requires OpenLayers/Geometry/Point.js */ /** * Class: OpenLayers.Handler.Point * Handler to draw a point on the map. Point is displayed on mouse down, * moves on mouse move, and is finished on mouse up. The handler triggers * callbacks for 'done', 'cancel', and 'modify'. The modify callback is * called with each change in the sketch and will receive the latest point * drawn. Create a new instance with the <OpenLayers.Handler.Point> * constructor. * * Inherits from: * - <OpenLayers.Handler> */ OpenLayers.Handler.Point = OpenLayers.Class(OpenLayers.Handler, { /** * Property: point * {<OpenLayers.Feature.Vector>} The currently drawn point */ point: null, /** * Property: layer * {<OpenLayers.Layer.Vector>} The temporary drawing layer */ layer: null, /** * APIProperty: multi * {Boolean} Cast features to multi-part geometries before passing to the * layer. Default is false. */ multi: false, /** * Property: drawing * {Boolean} A point is being drawn */ drawing: false, /** * Property: mouseDown * {Boolean} The mouse is down */ mouseDown: false, /** * Property: lastDown * {<OpenLayers.Pixel>} Location of the last mouse down */ lastDown: null, /** * Property: lastUp * {<OpenLayers.Pixel>} */ lastUp: null, /** * APIProperty: persist * {Boolean} Leave the feature rendered until destroyFeature is called. * Default is false. If set to true, the feature remains rendered until * destroyFeature is called, typically by deactivating the handler or * starting another drawing. */ persist: false, /** * Property: layerOptions * {Object} Any optional properties to be set on the sketch layer. */ layerOptions: null, /** * Constructor: OpenLayers.Handler.Point * Create a new point handler. * * Parameters: * control - {<OpenLayers.Control>} The control that owns this handler * callbacks - {Object} An object with a properties whose values are * functions. Various callbacks described below. * options - {Object} An optional object with properties to be set on the * handler * * Named callbacks: * create - Called when a sketch is first created. Callback called with * the creation point geometry and sketch feature. * modify - Called with each move of a vertex with the vertex (point) * geometry and the sketch feature. * done - Called when the point drawing is finished. The callback will * recieve a single argument, the point geometry. * cancel - Called when the handler is deactivated while drawing. The * cancel callback will receive a geometry. */ initialize: function(control, callbacks, options) { if(!(options && options.layerOptions && options.layerOptions.styleMap)) { this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {}); } OpenLayers.Handler.prototype.initialize.apply(this, arguments); }, /** * APIMethod: activate * turn on the handler */ activate: function() { if(!OpenLayers.Handler.prototype.activate.apply(this, arguments)) { return false; } // create temporary vector layer for rendering geometry sketch // TBD: this could be moved to initialize/destroy - setting visibility here var options = OpenLayers.Util.extend({ displayInLayerSwitcher: false, // indicate that the temp vector layer will never be out of range // without this, resolution properties must be specified at the // map-level for this temporary layer to init its resolutions // correctly calculateInRange: OpenLayers.Function.True }, this.layerOptions); this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options); this.map.addLayer(this.layer); return true; }, /** * Method: createFeature * Add temporary features * * Parameters: * pixel - {<OpenLayers.Pixel>} A pixel location on the map. */ createFeature: function(pixel) { var lonlat = this.map.getLonLatFromPixel(pixel); this.point = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat) ); this.callback("create", [this.point.geometry, this.point]); this.point.geometry.clearBounds(); this.layer.addFeatures([this.point], {silent: true}); }, /** * APIMethod: deactivate * turn off the handler */ deactivate: function() { if(!OpenLayers.Handler.prototype.deactivate.apply(this, arguments)) { return false; } // call the cancel callback if mid-drawing if(this.drawing) { this.cancel(); } this.destroyFeature(); // If a layer's map property is set to null, it means that that layer // isn't added to the map. Since we ourself added the layer to the map // in activate(), we can assume that if this.layer.map is null it means // that the layer has been destroyed (as a result of map.destroy() for // example. if (this.layer.map != null) { this.layer.destroy(false); } this.layer = null; return true; }, /** * Method: destroyFeature * Destroy the temporary geometries */ destroyFeature: function() { if(this.layer) { this.layer.destroyFeatures(); } this.point = null; }, /** * Method: finalize * Finish the geometry and call the "done" callback. * * Parameters: * cancel - {Boolean} Call cancel instead of done callback. Default is * false. */ finalize: function(cancel) { var key = cancel ? "cancel" : "done"; this.drawing = false; this.mouseDown = false; this.lastDown = null; this.lastUp = null; this.callback(key, [this.geometryClone()]); if(cancel || !this.persist) { this.destroyFeature(); } }, /** * APIMethod: cancel * Finish the geometry and call the "cancel" callback. */ cancel: function() { this.finalize(true); }, /** * Method: click * Handle clicks. Clicks are stopped from propagating to other listeners * on map.events or other dom elements. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ click: function(evt) { OpenLayers.Event.stop(evt); return false; }, /** * Method: dblclick * Handle double-clicks. Double-clicks are stopped from propagating to other * listeners on map.events or other dom elements. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ dblclick: function(evt) { OpenLayers.Event.stop(evt); return false; }, /** * Method: modifyFeature * Modify the existing geometry given a pixel location. * * Parameters: * pixel - {<OpenLayers.Pixel>} A pixel location on the map. */ modifyFeature: function(pixel) { var lonlat = this.map.getLonLatFromPixel(pixel); this.point.geometry.x = lonlat.lon; this.point.geometry.y = lonlat.lat; this.callback("modify", [this.point.geometry, this.point]); this.point.geometry.clearBounds(); this.drawFeature(); }, /** * Method: drawFeature * Render features on the temporary layer. */ drawFeature: function() { this.layer.drawFeature(this.point, this.style); }, /** * Method: getGeometry * Return the sketch geometry. If <multi> is true, this will return * a multi-part geometry. * * Returns: * {<OpenLayers.Geometry.Point>} */ getGeometry: function() { var geometry = this.point && this.point.geometry; if(geometry && this.multi) { geometry = new OpenLayers.Geometry.MultiPoint([geometry]); } return geometry; }, /** * Method: geometryClone * Return a clone of the relevant geometry. * * Returns: * {<OpenLayers.Geometry>} */ geometryClone: function() { var geom = this.getGeometry(); return geom && geom.clone(); }, /** * Method: mousedown * Handle mouse down. Adjust the geometry and redraw. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mousedown: function(evt) { // check keyboard modifiers if(!this.checkModifiers(evt)) { return true; } // ignore double-clicks if(this.lastDown && this.lastDown.equals(evt.xy)) { return true; } this.drawing = true; if(this.lastDown == null)
else { this.modifyFeature(evt.xy); } this.lastDown = evt.xy; return false; }, /** * Method: mousemove * Handle mouse move. Adjust the geometry and redraw. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mousemove: function (evt) { if(this.drawing) { this.modifyFeature(evt.xy); } return true; }, /** * Method: mouseup * Handle mouse up. Send the latest point in the geometry to the control. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mouseup: function (evt) { if(this.drawing) { this.finalize(); return false; } else { return true; } }, CLASS_NAME: "OpenLayers.Handler.Point" });
{ if(this.persist) { this.destroyFeature(); } this.createFeature(evt.xy); }
conditional_block
user-detail.component.ts
import { Component, Input } from '@angular/core'; // Import User class import { User } from './user'; @Component({ moduleId: module.id, selector: 'user-detail', templateUrl: 'user-detail.component.html' }) export class UserDetailComponent { // Properties ------------- // In our UserDetailComponent, the "user" property receives // the data from the user selected ("userSelected" property in parent's component, AppComponent) // So this property is an INPUT property, beceuse receives data, so we need to use the @Input decorator // Without it, the binding used in the app.component.html template wouldn't work: <user-detail [user]="selectedUser"></user-detail> @Input() user: User; isSaveable: boolean = true; // Indicates if the component is saveable isUnchanged: boolean = true; // Indicates if the component is unchanged isSpecial: boolean = true; // Indicates if the component is special // For testing purpose: we want to test the ngClass directive isUserCredentials: boolean = false; // Methods() -------------- // setCssClasses(): manage the setup of several CSS classes // to component elements (HTML template) according to the // corresponding properties setCssClasses() { let cssClasses = { isSaveable: this.isSaveable, isUnchanged: this.isUnchanged, isSpecial: this.isSpecial
}; return cssClasses; } // setCssInlineStyles(): manage the setup of several CSS inline styles // to component elements (HTML template) according to the // corresponding properties // The keys of the object (cssInlineStyles) are the CSS properties; // the values bind the component properties and the possible values for the CSS property setCssInlineStyles() { let cssInlineStyles = { 'font-style': this.isSaveable ? 'italic' : 'normal', // italic 'font-weight': !this.isUnchanged ? 'bold' : 'normal', // normal 'font-size': this.isSpecial ? '24px' : '8px' // 24px }; return cssInlineStyles; } }
random_line_split
user-detail.component.ts
import { Component, Input } from '@angular/core'; // Import User class import { User } from './user'; @Component({ moduleId: module.id, selector: 'user-detail', templateUrl: 'user-detail.component.html' }) export class UserDetailComponent { // Properties ------------- // In our UserDetailComponent, the "user" property receives // the data from the user selected ("userSelected" property in parent's component, AppComponent) // So this property is an INPUT property, beceuse receives data, so we need to use the @Input decorator // Without it, the binding used in the app.component.html template wouldn't work: <user-detail [user]="selectedUser"></user-detail> @Input() user: User; isSaveable: boolean = true; // Indicates if the component is saveable isUnchanged: boolean = true; // Indicates if the component is unchanged isSpecial: boolean = true; // Indicates if the component is special // For testing purpose: we want to test the ngClass directive isUserCredentials: boolean = false; // Methods() -------------- // setCssClasses(): manage the setup of several CSS classes // to component elements (HTML template) according to the // corresponding properties setCssClasses()
// setCssInlineStyles(): manage the setup of several CSS inline styles // to component elements (HTML template) according to the // corresponding properties // The keys of the object (cssInlineStyles) are the CSS properties; // the values bind the component properties and the possible values for the CSS property setCssInlineStyles() { let cssInlineStyles = { 'font-style': this.isSaveable ? 'italic' : 'normal', // italic 'font-weight': !this.isUnchanged ? 'bold' : 'normal', // normal 'font-size': this.isSpecial ? '24px' : '8px' // 24px }; return cssInlineStyles; } }
{ let cssClasses = { isSaveable: this.isSaveable, isUnchanged: this.isUnchanged, isSpecial: this.isSpecial }; return cssClasses; }
identifier_body
user-detail.component.ts
import { Component, Input } from '@angular/core'; // Import User class import { User } from './user'; @Component({ moduleId: module.id, selector: 'user-detail', templateUrl: 'user-detail.component.html' }) export class UserDetailComponent { // Properties ------------- // In our UserDetailComponent, the "user" property receives // the data from the user selected ("userSelected" property in parent's component, AppComponent) // So this property is an INPUT property, beceuse receives data, so we need to use the @Input decorator // Without it, the binding used in the app.component.html template wouldn't work: <user-detail [user]="selectedUser"></user-detail> @Input() user: User; isSaveable: boolean = true; // Indicates if the component is saveable isUnchanged: boolean = true; // Indicates if the component is unchanged isSpecial: boolean = true; // Indicates if the component is special // For testing purpose: we want to test the ngClass directive isUserCredentials: boolean = false; // Methods() -------------- // setCssClasses(): manage the setup of several CSS classes // to component elements (HTML template) according to the // corresponding properties setCssClasses() { let cssClasses = { isSaveable: this.isSaveable, isUnchanged: this.isUnchanged, isSpecial: this.isSpecial }; return cssClasses; } // setCssInlineStyles(): manage the setup of several CSS inline styles // to component elements (HTML template) according to the // corresponding properties // The keys of the object (cssInlineStyles) are the CSS properties; // the values bind the component properties and the possible values for the CSS property
() { let cssInlineStyles = { 'font-style': this.isSaveable ? 'italic' : 'normal', // italic 'font-weight': !this.isUnchanged ? 'bold' : 'normal', // normal 'font-size': this.isSpecial ? '24px' : '8px' // 24px }; return cssInlineStyles; } }
setCssInlineStyles
identifier_name
lib.rs
extern crate csv; extern crate failure; extern crate flate2; extern crate tar; extern crate unicode_casefold; extern crate unicode_segmentation; pub use failure::Error; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io; use std::io::prelude::*; use std::result; use unicode_casefold::{Locale, UnicodeCaseFold, Variant}; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = result::Result<T, Error>; const MODEL_SIZE_LIMIT: usize = 10000; /// Used to build a "language model" describing a human language, where the /// input data is assumed to come from subtitle files. pub struct ModelBuilder { grapheme_counts: HashMap<String, u64>, pair_counts: HashMap<String, u64>, word_counts: HashMap<String, u64>, } impl ModelBuilder { /// Create a new `ModelBuilder`. pub fn new() -> ModelBuilder { ModelBuilder { grapheme_counts: HashMap::new(), pair_counts: HashMap::new(), word_counts: HashMap::new(), } } /// Add a subtitle line to the `ModelBuilder`. pub fn add_line(&mut self, line: &str) { let grapheme_buffer = line.graphemes(true).collect::<Vec<_>>(); for &grapheme in &grapheme_buffer { if grapheme != " " { incr_map(&mut self.grapheme_counts, grapheme.to_owned()); } } if !grapheme_buffer.is_empty() { incr_map(&mut self.pair_counts, format!("\n{}", grapheme_buffer[0])); incr_map(&mut self.pair_counts, format!("{}\n", grapheme_buffer[grapheme_buffer.len() - 1])); } for pair in grapheme_buffer.windows(2) { incr_map(&mut self.pair_counts, format!("{}{}", pair[0], pair[1])); } for word in line.unicode_words() { // TODO: Handle Turkic "i". let word = word.case_fold_with(Variant::Full, Locale::NonTurkic).collect(); incr_map(&mut self.word_counts, word); } } /// Write our current grapheme frequencies to `out`. pub fn grapheme_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.grapheme_counts, out) } /// Write our current pair frequencies to `out`. pub fn pair_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.pair_counts, out) } /// Write our current word frequencies to `out`. pub fn word_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.word_counts, out) } /// Write the frequencies in `counts` to `out`, labelling them with /// `label`. fn frequencies<W: Write>(&self, counts: &HashMap<String, u64>, out: W) -> Result<()> { // Count the total number of graphemes we've seen. let mut total: f64 = 0.0; for &count in counts.values() { total += count as f64; } // Sort our results into a stable order and replace counts with // probabilities. let mut rows = counts.iter().collect::<Vec<_>>(); rows.sort_by(|&(k1, c1), &(k2, c2)| match c1.cmp(c2).reverse() { Ordering::Equal => k1.cmp(k2), other => other, }); // Write output to a CSV. let mut wtr = csv::Writer::from_writer(out); for (key, &count) in rows.into_iter().take(MODEL_SIZE_LIMIT) { wtr.encode((key, count as f64 / total))?; } Ok(()) } /// Write out our language model to `out`. This is actually a gzipped /// tar file containing multiple CSV files: /// /// - `graphemes.csv`: Frequencies of single grapheme clusters. /// - `pairs.csv`: Frequencies of grapheme pairs. /// - `words.csv`: Frequencies of case-folded words. /// /// All models will be truncted if they exceed a certain limit. pub fn write_model<W: Write>(&self, out: W) -> Result<()> { let gzip = flate2::write::GzEncoder::new(out, flate2::Compression::best()); let mut tar = tar::Builder::new(gzip); self.append_model_part(&mut tar, "graphemes.csv", &self.grapheme_counts)?; self.append_model_part(&mut tar, "pairs.csv", &self.pair_counts)?; self.append_model_part(&mut tar, "words.csv", &self.word_counts)?; tar.into_inner()?.finish()?; Ok(()) } /// Append a file to our model. fn append_model_part<W: Write>(&self, builder: &mut tar::Builder<W>, path: &str, counts: &HashMap<String, u64>) -> Result<()> { let mut csv = vec![]; self.frequencies(counts, &mut csv)?; let mut header = tar::Header::new_old(); header.set_path(path)?; // TODO: Can this fail with a cast error? header.set_size(csv.len() as u64); header.set_mode(0o600); header.set_cksum(); builder.append(&header, io::Cursor::new(&csv))?; Ok(()) } } /// Increment a key in a map. fn incr_map(map: &mut HashMap<String, u64>, key: String) { match map.entry(key.to_owned()) { Entry::Occupied(mut occupied) =>
Entry::Vacant(vacant) => { vacant.insert(1); } } } #[test] fn grapheme_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Hello world"); let mut csv = vec![]; builder.grapheme_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ l,0.3 o,0.2 H,0.1 d,0.1 e,0.1 r,0.1 w,0.1 "); } #[test] fn pair_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Help"); let mut csv = vec![]; builder.pair_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ \"\nH\",0.2 He,0.2 el,0.2 lp,0.2 \"p\n\",0.2 "); } #[test] fn word_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut csv = vec![]; builder.word_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ potato,0.5 one,0.25 two,0.25 "); } #[test] fn write_model() { let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut model = vec![]; builder.write_model(&mut model).unwrap(); assert!(model.len() > 0); }
{ *occupied.get_mut() += 1; }
conditional_block
lib.rs
extern crate csv; extern crate failure; extern crate flate2; extern crate tar; extern crate unicode_casefold; extern crate unicode_segmentation; pub use failure::Error; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io; use std::io::prelude::*; use std::result; use unicode_casefold::{Locale, UnicodeCaseFold, Variant}; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = result::Result<T, Error>; const MODEL_SIZE_LIMIT: usize = 10000; /// Used to build a "language model" describing a human language, where the /// input data is assumed to come from subtitle files. pub struct ModelBuilder { grapheme_counts: HashMap<String, u64>, pair_counts: HashMap<String, u64>, word_counts: HashMap<String, u64>, } impl ModelBuilder { /// Create a new `ModelBuilder`. pub fn new() -> ModelBuilder { ModelBuilder { grapheme_counts: HashMap::new(), pair_counts: HashMap::new(), word_counts: HashMap::new(), } } /// Add a subtitle line to the `ModelBuilder`. pub fn add_line(&mut self, line: &str) { let grapheme_buffer = line.graphemes(true).collect::<Vec<_>>(); for &grapheme in &grapheme_buffer { if grapheme != " " { incr_map(&mut self.grapheme_counts, grapheme.to_owned()); } } if !grapheme_buffer.is_empty() { incr_map(&mut self.pair_counts, format!("\n{}", grapheme_buffer[0])); incr_map(&mut self.pair_counts, format!("{}\n", grapheme_buffer[grapheme_buffer.len() - 1])); } for pair in grapheme_buffer.windows(2) { incr_map(&mut self.pair_counts, format!("{}{}", pair[0], pair[1])); } for word in line.unicode_words() { // TODO: Handle Turkic "i". let word = word.case_fold_with(Variant::Full, Locale::NonTurkic).collect(); incr_map(&mut self.word_counts, word); } } /// Write our current grapheme frequencies to `out`. pub fn grapheme_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.grapheme_counts, out) } /// Write our current pair frequencies to `out`. pub fn pair_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.pair_counts, out) } /// Write our current word frequencies to `out`. pub fn word_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.word_counts, out) } /// Write the frequencies in `counts` to `out`, labelling them with /// `label`. fn frequencies<W: Write>(&self, counts: &HashMap<String, u64>, out: W) -> Result<()> { // Count the total number of graphemes we've seen. let mut total: f64 = 0.0; for &count in counts.values() { total += count as f64; } // Sort our results into a stable order and replace counts with // probabilities. let mut rows = counts.iter().collect::<Vec<_>>(); rows.sort_by(|&(k1, c1), &(k2, c2)| match c1.cmp(c2).reverse() { Ordering::Equal => k1.cmp(k2), other => other, }); // Write output to a CSV. let mut wtr = csv::Writer::from_writer(out); for (key, &count) in rows.into_iter().take(MODEL_SIZE_LIMIT) { wtr.encode((key, count as f64 / total))?; } Ok(()) } /// Write out our language model to `out`. This is actually a gzipped /// tar file containing multiple CSV files: /// /// - `graphemes.csv`: Frequencies of single grapheme clusters. /// - `pairs.csv`: Frequencies of grapheme pairs. /// - `words.csv`: Frequencies of case-folded words. /// /// All models will be truncted if they exceed a certain limit. pub fn write_model<W: Write>(&self, out: W) -> Result<()> { let gzip = flate2::write::GzEncoder::new(out, flate2::Compression::best()); let mut tar = tar::Builder::new(gzip); self.append_model_part(&mut tar, "graphemes.csv", &self.grapheme_counts)?; self.append_model_part(&mut tar, "pairs.csv", &self.pair_counts)?; self.append_model_part(&mut tar, "words.csv", &self.word_counts)?; tar.into_inner()?.finish()?; Ok(()) } /// Append a file to our model. fn append_model_part<W: Write>(&self, builder: &mut tar::Builder<W>, path: &str, counts: &HashMap<String, u64>) -> Result<()> { let mut csv = vec![]; self.frequencies(counts, &mut csv)?; let mut header = tar::Header::new_old(); header.set_path(path)?; // TODO: Can this fail with a cast error? header.set_size(csv.len() as u64); header.set_mode(0o600); header.set_cksum(); builder.append(&header, io::Cursor::new(&csv))?; Ok(()) } } /// Increment a key in a map. fn incr_map(map: &mut HashMap<String, u64>, key: String)
#[test] fn grapheme_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Hello world"); let mut csv = vec![]; builder.grapheme_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ l,0.3 o,0.2 H,0.1 d,0.1 e,0.1 r,0.1 w,0.1 "); } #[test] fn pair_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Help"); let mut csv = vec![]; builder.pair_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ \"\nH\",0.2 He,0.2 el,0.2 lp,0.2 \"p\n\",0.2 "); } #[test] fn word_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut csv = vec![]; builder.word_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ potato,0.5 one,0.25 two,0.25 "); } #[test] fn write_model() { let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut model = vec![]; builder.write_model(&mut model).unwrap(); assert!(model.len() > 0); }
{ match map.entry(key.to_owned()) { Entry::Occupied(mut occupied) => { *occupied.get_mut() += 1; } Entry::Vacant(vacant) => { vacant.insert(1); } } }
identifier_body
lib.rs
extern crate csv; extern crate failure; extern crate flate2; extern crate tar; extern crate unicode_casefold; extern crate unicode_segmentation; pub use failure::Error; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io; use std::io::prelude::*; use std::result; use unicode_casefold::{Locale, UnicodeCaseFold, Variant}; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = result::Result<T, Error>; const MODEL_SIZE_LIMIT: usize = 10000; /// Used to build a "language model" describing a human language, where the /// input data is assumed to come from subtitle files. pub struct ModelBuilder { grapheme_counts: HashMap<String, u64>, pair_counts: HashMap<String, u64>, word_counts: HashMap<String, u64>, } impl ModelBuilder { /// Create a new `ModelBuilder`. pub fn new() -> ModelBuilder { ModelBuilder { grapheme_counts: HashMap::new(), pair_counts: HashMap::new(), word_counts: HashMap::new(), } } /// Add a subtitle line to the `ModelBuilder`. pub fn add_line(&mut self, line: &str) { let grapheme_buffer = line.graphemes(true).collect::<Vec<_>>(); for &grapheme in &grapheme_buffer { if grapheme != " " { incr_map(&mut self.grapheme_counts, grapheme.to_owned()); } } if !grapheme_buffer.is_empty() { incr_map(&mut self.pair_counts, format!("\n{}", grapheme_buffer[0])); incr_map(&mut self.pair_counts, format!("{}\n", grapheme_buffer[grapheme_buffer.len() - 1])); } for pair in grapheme_buffer.windows(2) { incr_map(&mut self.pair_counts, format!("{}{}", pair[0], pair[1])); } for word in line.unicode_words() { // TODO: Handle Turkic "i". let word = word.case_fold_with(Variant::Full, Locale::NonTurkic).collect(); incr_map(&mut self.word_counts, word); } } /// Write our current grapheme frequencies to `out`. pub fn grapheme_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.grapheme_counts, out) } /// Write our current pair frequencies to `out`. pub fn pair_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.pair_counts, out) } /// Write our current word frequencies to `out`. pub fn word_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.word_counts, out) } /// Write the frequencies in `counts` to `out`, labelling them with /// `label`. fn frequencies<W: Write>(&self, counts: &HashMap<String, u64>, out: W) -> Result<()> { // Count the total number of graphemes we've seen. let mut total: f64 = 0.0; for &count in counts.values() { total += count as f64; } // Sort our results into a stable order and replace counts with // probabilities. let mut rows = counts.iter().collect::<Vec<_>>(); rows.sort_by(|&(k1, c1), &(k2, c2)| match c1.cmp(c2).reverse() { Ordering::Equal => k1.cmp(k2), other => other, }); // Write output to a CSV. let mut wtr = csv::Writer::from_writer(out); for (key, &count) in rows.into_iter().take(MODEL_SIZE_LIMIT) { wtr.encode((key, count as f64 / total))?; } Ok(()) } /// Write out our language model to `out`. This is actually a gzipped /// tar file containing multiple CSV files: /// /// - `graphemes.csv`: Frequencies of single grapheme clusters. /// - `pairs.csv`: Frequencies of grapheme pairs. /// - `words.csv`: Frequencies of case-folded words. /// /// All models will be truncted if they exceed a certain limit. pub fn write_model<W: Write>(&self, out: W) -> Result<()> { let gzip = flate2::write::GzEncoder::new(out, flate2::Compression::best()); let mut tar = tar::Builder::new(gzip); self.append_model_part(&mut tar, "graphemes.csv", &self.grapheme_counts)?; self.append_model_part(&mut tar, "pairs.csv", &self.pair_counts)?; self.append_model_part(&mut tar, "words.csv", &self.word_counts)?; tar.into_inner()?.finish()?; Ok(()) } /// Append a file to our model. fn append_model_part<W: Write>(&self, builder: &mut tar::Builder<W>, path: &str, counts: &HashMap<String, u64>) -> Result<()> { let mut csv = vec![]; self.frequencies(counts, &mut csv)?; let mut header = tar::Header::new_old(); header.set_path(path)?; // TODO: Can this fail with a cast error? header.set_size(csv.len() as u64); header.set_mode(0o600); header.set_cksum(); builder.append(&header, io::Cursor::new(&csv))?; Ok(()) } } /// Increment a key in a map. fn incr_map(map: &mut HashMap<String, u64>, key: String) { match map.entry(key.to_owned()) { Entry::Occupied(mut occupied) => { *occupied.get_mut() += 1; } Entry::Vacant(vacant) => { vacant.insert(1); } } } #[test] fn grapheme_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Hello world"); let mut csv = vec![]; builder.grapheme_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ l,0.3 o,0.2 H,0.1 d,0.1 e,0.1 r,0.1 w,0.1 ");
let mut builder = ModelBuilder::new(); builder.add_line("Help"); let mut csv = vec![]; builder.pair_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ \"\nH\",0.2 He,0.2 el,0.2 lp,0.2 \"p\n\",0.2 "); } #[test] fn word_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut csv = vec![]; builder.word_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ potato,0.5 one,0.25 two,0.25 "); } #[test] fn write_model() { let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut model = vec![]; builder.write_model(&mut model).unwrap(); assert!(model.len() > 0); }
} #[test] fn pair_frequency() { use std::str;
random_line_split
lib.rs
extern crate csv; extern crate failure; extern crate flate2; extern crate tar; extern crate unicode_casefold; extern crate unicode_segmentation; pub use failure::Error; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io; use std::io::prelude::*; use std::result; use unicode_casefold::{Locale, UnicodeCaseFold, Variant}; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = result::Result<T, Error>; const MODEL_SIZE_LIMIT: usize = 10000; /// Used to build a "language model" describing a human language, where the /// input data is assumed to come from subtitle files. pub struct ModelBuilder { grapheme_counts: HashMap<String, u64>, pair_counts: HashMap<String, u64>, word_counts: HashMap<String, u64>, } impl ModelBuilder { /// Create a new `ModelBuilder`. pub fn
() -> ModelBuilder { ModelBuilder { grapheme_counts: HashMap::new(), pair_counts: HashMap::new(), word_counts: HashMap::new(), } } /// Add a subtitle line to the `ModelBuilder`. pub fn add_line(&mut self, line: &str) { let grapheme_buffer = line.graphemes(true).collect::<Vec<_>>(); for &grapheme in &grapheme_buffer { if grapheme != " " { incr_map(&mut self.grapheme_counts, grapheme.to_owned()); } } if !grapheme_buffer.is_empty() { incr_map(&mut self.pair_counts, format!("\n{}", grapheme_buffer[0])); incr_map(&mut self.pair_counts, format!("{}\n", grapheme_buffer[grapheme_buffer.len() - 1])); } for pair in grapheme_buffer.windows(2) { incr_map(&mut self.pair_counts, format!("{}{}", pair[0], pair[1])); } for word in line.unicode_words() { // TODO: Handle Turkic "i". let word = word.case_fold_with(Variant::Full, Locale::NonTurkic).collect(); incr_map(&mut self.word_counts, word); } } /// Write our current grapheme frequencies to `out`. pub fn grapheme_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.grapheme_counts, out) } /// Write our current pair frequencies to `out`. pub fn pair_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.pair_counts, out) } /// Write our current word frequencies to `out`. pub fn word_frequencies<W: Write>(&self, out: W) -> Result<()> { self.frequencies(&self.word_counts, out) } /// Write the frequencies in `counts` to `out`, labelling them with /// `label`. fn frequencies<W: Write>(&self, counts: &HashMap<String, u64>, out: W) -> Result<()> { // Count the total number of graphemes we've seen. let mut total: f64 = 0.0; for &count in counts.values() { total += count as f64; } // Sort our results into a stable order and replace counts with // probabilities. let mut rows = counts.iter().collect::<Vec<_>>(); rows.sort_by(|&(k1, c1), &(k2, c2)| match c1.cmp(c2).reverse() { Ordering::Equal => k1.cmp(k2), other => other, }); // Write output to a CSV. let mut wtr = csv::Writer::from_writer(out); for (key, &count) in rows.into_iter().take(MODEL_SIZE_LIMIT) { wtr.encode((key, count as f64 / total))?; } Ok(()) } /// Write out our language model to `out`. This is actually a gzipped /// tar file containing multiple CSV files: /// /// - `graphemes.csv`: Frequencies of single grapheme clusters. /// - `pairs.csv`: Frequencies of grapheme pairs. /// - `words.csv`: Frequencies of case-folded words. /// /// All models will be truncted if they exceed a certain limit. pub fn write_model<W: Write>(&self, out: W) -> Result<()> { let gzip = flate2::write::GzEncoder::new(out, flate2::Compression::best()); let mut tar = tar::Builder::new(gzip); self.append_model_part(&mut tar, "graphemes.csv", &self.grapheme_counts)?; self.append_model_part(&mut tar, "pairs.csv", &self.pair_counts)?; self.append_model_part(&mut tar, "words.csv", &self.word_counts)?; tar.into_inner()?.finish()?; Ok(()) } /// Append a file to our model. fn append_model_part<W: Write>(&self, builder: &mut tar::Builder<W>, path: &str, counts: &HashMap<String, u64>) -> Result<()> { let mut csv = vec![]; self.frequencies(counts, &mut csv)?; let mut header = tar::Header::new_old(); header.set_path(path)?; // TODO: Can this fail with a cast error? header.set_size(csv.len() as u64); header.set_mode(0o600); header.set_cksum(); builder.append(&header, io::Cursor::new(&csv))?; Ok(()) } } /// Increment a key in a map. fn incr_map(map: &mut HashMap<String, u64>, key: String) { match map.entry(key.to_owned()) { Entry::Occupied(mut occupied) => { *occupied.get_mut() += 1; } Entry::Vacant(vacant) => { vacant.insert(1); } } } #[test] fn grapheme_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Hello world"); let mut csv = vec![]; builder.grapheme_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ l,0.3 o,0.2 H,0.1 d,0.1 e,0.1 r,0.1 w,0.1 "); } #[test] fn pair_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("Help"); let mut csv = vec![]; builder.pair_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ \"\nH\",0.2 He,0.2 el,0.2 lp,0.2 \"p\n\",0.2 "); } #[test] fn word_frequency() { use std::str; let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut csv = vec![]; builder.word_frequencies(&mut csv).unwrap(); assert_eq!(str::from_utf8(&csv).unwrap(), "\ potato,0.5 one,0.25 two,0.25 "); } #[test] fn write_model() { let mut builder = ModelBuilder::new(); builder.add_line("One potato, two potato!"); let mut model = vec![]; builder.write_model(&mut model).unwrap(); assert!(model.len() > 0); }
new
identifier_name
status.ts
/* -------------------------------------------------------------------------------------------- * Copyright (c) Ioannis Kappas. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. * ------------------------------------------------------------------------------------------ */ "use strict"; import { StatusBarAlignment, StatusBarItem, window } from "vscode"; import { Timer } from './timer'; export class PhpcsStatus { private statusBarItem: StatusBarItem; private documents: string[] = []; private processing: number = 0; private spinnerIndex = 0; private spinnerSequence: string[] = ["|", "/", "-", "\\"]; private timer: Timer; public startProcessing(uri: string) { this.documents.push(uri); this.processing += 1; this.getTimer().start(); this.getStatusBarItem().show(); } public endProcessing(uri: string) { this.processing -= 1; let index = this.documents.indexOf(uri); if (index !== undefined) { this.documents.slice(index, 1); } if (this.processing === 0) { this.getTimer().stop(); this.getStatusBarItem().hide(); this.updateStatusText(); } } private updateStatusText(): void
private getNextSpinnerChar(): string { let spinnerChar = this.spinnerSequence[this.spinnerIndex]; this.spinnerIndex += 1; if (this.spinnerIndex > this.spinnerSequence.length - 1) { this.spinnerIndex = 0; } return spinnerChar; } private getTimer(): Timer { if (!this.timer) { this.timer = new Timer(() => { this.updateStatusText(); }); this.timer.interval = 100; } return this.timer; } private getStatusBarItem(): StatusBarItem { // Create as needed if (!this.statusBarItem) { this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left); } return this.statusBarItem; } dispose() { if (this.statusBarItem) { this.statusBarItem.dispose(); } if (this.timer) { this.timer.dispose(); } } }
{ let statusBar = this.getStatusBarItem(); let count = this.processing; if (count > 0) { let spinner = this.getNextSpinnerChar(); statusBar.text = count === 1 ? `$(eye) phpcs is linting 1 document ... ${spinner}` : `$(eye) phpcs is linting ${count} documents ... ${spinner}`; } else { statusBar.text = ""; } }
identifier_body
status.ts
/* -------------------------------------------------------------------------------------------- * Copyright (c) Ioannis Kappas. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. * ------------------------------------------------------------------------------------------ */ "use strict"; import { StatusBarAlignment, StatusBarItem, window } from "vscode"; import { Timer } from './timer'; export class PhpcsStatus { private statusBarItem: StatusBarItem; private documents: string[] = []; private processing: number = 0; private spinnerIndex = 0; private spinnerSequence: string[] = ["|", "/", "-", "\\"]; private timer: Timer; public startProcessing(uri: string) { this.documents.push(uri); this.processing += 1; this.getTimer().start(); this.getStatusBarItem().show(); } public endProcessing(uri: string) { this.processing -= 1; let index = this.documents.indexOf(uri); if (index !== undefined) { this.documents.slice(index, 1); } if (this.processing === 0) { this.getTimer().stop(); this.getStatusBarItem().hide(); this.updateStatusText(); } } private updateStatusText(): void { let statusBar = this.getStatusBarItem(); let count = this.processing; if (count > 0) { let spinner = this.getNextSpinnerChar(); statusBar.text = count === 1 ? `$(eye) phpcs is linting 1 document ... ${spinner}` : `$(eye) phpcs is linting ${count} documents ... ${spinner}`; } else { statusBar.text = ""; } } private getNextSpinnerChar(): string { let spinnerChar = this.spinnerSequence[this.spinnerIndex]; this.spinnerIndex += 1; if (this.spinnerIndex > this.spinnerSequence.length - 1) { this.spinnerIndex = 0; } return spinnerChar; } private getTimer(): Timer { if (!this.timer) { this.timer = new Timer(() => { this.updateStatusText(); }); this.timer.interval = 100; } return this.timer; } private
(): StatusBarItem { // Create as needed if (!this.statusBarItem) { this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left); } return this.statusBarItem; } dispose() { if (this.statusBarItem) { this.statusBarItem.dispose(); } if (this.timer) { this.timer.dispose(); } } }
getStatusBarItem
identifier_name
status.ts
/* -------------------------------------------------------------------------------------------- * Copyright (c) Ioannis Kappas. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. * ------------------------------------------------------------------------------------------ */ "use strict"; import { StatusBarAlignment, StatusBarItem, window } from "vscode"; import { Timer } from './timer'; export class PhpcsStatus { private statusBarItem: StatusBarItem; private documents: string[] = []; private processing: number = 0; private spinnerIndex = 0; private spinnerSequence: string[] = ["|", "/", "-", "\\"]; private timer: Timer; public startProcessing(uri: string) { this.documents.push(uri); this.processing += 1; this.getTimer().start(); this.getStatusBarItem().show(); } public endProcessing(uri: string) { this.processing -= 1; let index = this.documents.indexOf(uri); if (index !== undefined) { this.documents.slice(index, 1); } if (this.processing === 0) { this.getTimer().stop(); this.getStatusBarItem().hide(); this.updateStatusText(); } } private updateStatusText(): void { let statusBar = this.getStatusBarItem(); let count = this.processing; if (count > 0) { let spinner = this.getNextSpinnerChar(); statusBar.text = count === 1 ? `$(eye) phpcs is linting 1 document ... ${spinner}` : `$(eye) phpcs is linting ${count} documents ... ${spinner}`; } else { statusBar.text = ""; } } private getNextSpinnerChar(): string { let spinnerChar = this.spinnerSequence[this.spinnerIndex]; this.spinnerIndex += 1; if (this.spinnerIndex > this.spinnerSequence.length - 1) { this.spinnerIndex = 0; } return spinnerChar; } private getTimer(): Timer { if (!this.timer) { this.timer = new Timer(() => { this.updateStatusText(); }); this.timer.interval = 100; } return this.timer; } private getStatusBarItem(): StatusBarItem { // Create as needed if (!this.statusBarItem)
return this.statusBarItem; } dispose() { if (this.statusBarItem) { this.statusBarItem.dispose(); } if (this.timer) { this.timer.dispose(); } } }
{ this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left); }
conditional_block
status.ts
/* -------------------------------------------------------------------------------------------- * Copyright (c) Ioannis Kappas. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. * ------------------------------------------------------------------------------------------ */ "use strict"; import { StatusBarAlignment, StatusBarItem, window } from "vscode"; import { Timer } from './timer'; export class PhpcsStatus { private statusBarItem: StatusBarItem; private documents: string[] = []; private processing: number = 0; private spinnerIndex = 0; private spinnerSequence: string[] = ["|", "/", "-", "\\"]; private timer: Timer; public startProcessing(uri: string) { this.documents.push(uri); this.processing += 1; this.getTimer().start(); this.getStatusBarItem().show(); } public endProcessing(uri: string) { this.processing -= 1; let index = this.documents.indexOf(uri); if (index !== undefined) { this.documents.slice(index, 1); } if (this.processing === 0) { this.getTimer().stop(); this.getStatusBarItem().hide(); this.updateStatusText(); } } private updateStatusText(): void { let statusBar = this.getStatusBarItem(); let count = this.processing; if (count > 0) { let spinner = this.getNextSpinnerChar(); statusBar.text = count === 1 ? `$(eye) phpcs is linting 1 document ... ${spinner}` : `$(eye) phpcs is linting ${count} documents ... ${spinner}`; } else { statusBar.text = ""; } } private getNextSpinnerChar(): string { let spinnerChar = this.spinnerSequence[this.spinnerIndex]; this.spinnerIndex += 1; if (this.spinnerIndex > this.spinnerSequence.length - 1) { this.spinnerIndex = 0; } return spinnerChar; } private getTimer(): Timer { if (!this.timer) { this.timer = new Timer(() => { this.updateStatusText(); }); this.timer.interval = 100;
private getStatusBarItem(): StatusBarItem { // Create as needed if (!this.statusBarItem) { this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left); } return this.statusBarItem; } dispose() { if (this.statusBarItem) { this.statusBarItem.dispose(); } if (this.timer) { this.timer.dispose(); } } }
} return this.timer; }
random_line_split
sendemail.py
# coding=utf-8 # Copyright (C) 2014 Stefano Guglielmetti # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import smtplib, os, sys from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders #From address, to address, subject and message body from_address = 'EMAIL_FROM_ADDRESS' to_address = ['EMAIL_TO_ADDRESS'] email_subject = 'Alert!!! Zombies!!! Ahead!!!' email_body = 'An intruder has been detected and needs to be eliminated!' # Credentials (if needed) username = 'YOUR_EMAIL_USERNAME' password = 'YOUR_EMAIL_PASSWORD' # The actual mail send server = 'smtp.gmail.com:587' def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.starttls() smtp.login(username,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name
random_line_split
sendemail.py
# coding=utf-8 # Copyright (C) 2014 Stefano Guglielmetti # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import smtplib, os, sys from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders #From address, to address, subject and message body from_address = 'EMAIL_FROM_ADDRESS' to_address = ['EMAIL_TO_ADDRESS'] email_subject = 'Alert!!! Zombies!!! Ahead!!!' email_body = 'An intruder has been detected and needs to be eliminated!' # Credentials (if needed) username = 'YOUR_EMAIL_USERNAME' password = 'YOUR_EMAIL_PASSWORD' # The actual mail send server = 'smtp.gmail.com:587' def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files:
smtp = smtplib.SMTP(server) smtp.starttls() smtp.login(username,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name
part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part)
conditional_block
sendemail.py
# coding=utf-8 # Copyright (C) 2014 Stefano Guglielmetti # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import smtplib, os, sys from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders #From address, to address, subject and message body from_address = 'EMAIL_FROM_ADDRESS' to_address = ['EMAIL_TO_ADDRESS'] email_subject = 'Alert!!! Zombies!!! Ahead!!!' email_body = 'An intruder has been detected and needs to be eliminated!' # Credentials (if needed) username = 'YOUR_EMAIL_USERNAME' password = 'YOUR_EMAIL_PASSWORD' # The actual mail send server = 'smtp.gmail.com:587' def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name
assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.starttls() smtp.login(username,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
identifier_body
sendemail.py
# coding=utf-8 # Copyright (C) 2014 Stefano Guglielmetti # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import smtplib, os, sys from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders #From address, to address, subject and message body from_address = 'EMAIL_FROM_ADDRESS' to_address = ['EMAIL_TO_ADDRESS'] email_subject = 'Alert!!! Zombies!!! Ahead!!!' email_body = 'An intruder has been detected and needs to be eliminated!' # Credentials (if needed) username = 'YOUR_EMAIL_USERNAME' password = 'YOUR_EMAIL_PASSWORD' # The actual mail send server = 'smtp.gmail.com:587' def
(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.starttls() smtp.login(username,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name
send_mail
identifier_name
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser( 'This is a custom version of the zc.buildout %prog script. It is ' 'intended to meet a temporary need if you encounter problems with ' 'the zc.buildout 1.5 release.') parser.add_option("-v", "--version", dest="version", default='1.4.4', help='Use a specific zc.buildout version. *This ' 'bootstrap script defaults to ' '1.4.4, unlike usual buildpout bootstrap scripts.*') parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c):
else: def quote (c): return c ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' env = dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(tmpeggs)] if 'bootstrap-testing-find-links' in os.environ: cmd.extend(['-f', os.environ['bootstrap-testing-find-links']]) cmd.append('zc.buildout' + VERSION) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) assert exitcode == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c
identifier_body
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser( 'This is a custom version of the zc.buildout %prog script. It is ' 'intended to meet a temporary need if you encounter problems with ' 'the zc.buildout 1.5 release.') parser.add_option("-v", "--version", dest="version", default='1.4.4', help='Use a specific zc.buildout version. *This ' 'bootstrap script defaults to ' '1.4.4, unlike usual buildpout bootstrap scripts.*') parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else:
if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' env = dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(tmpeggs)] if 'bootstrap-testing-find-links' in os.environ: cmd.extend(['-f', os.environ['bootstrap-testing-find-links']]) cmd.append('zc.buildout' + VERSION) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) assert exitcode == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
random_line_split
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser( 'This is a custom version of the zc.buildout %prog script. It is ' 'intended to meet a temporary need if you encounter problems with ' 'the zc.buildout 1.5 release.') parser.add_option("-v", "--version", dest="version", default='1.4.4', help='Use a specific zc.buildout version. *This ' 'bootstrap script defaults to ' '1.4.4, unlike usual buildpout bootstrap scripts.*') parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def
(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' env = dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(tmpeggs)] if 'bootstrap-testing-find-links' in os.environ: cmd.extend(['-f', os.environ['bootstrap-testing-find-links']]) cmd.append('zc.buildout' + VERSION) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) assert exitcode == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
quote
identifier_name
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser( 'This is a custom version of the zc.buildout %prog script. It is ' 'intended to meet a temporary need if you encounter problems with ' 'the zc.buildout 1.5 release.') parser.add_option("-v", "--version", dest="version", default='1.4.4', help='Use a specific zc.buildout version. *This ' 'bootstrap script defaults to ' '1.4.4, unlike usual buildpout bootstrap scripts.*') parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else:
if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' env = dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(tmpeggs)] if 'bootstrap-testing-find-links' in os.environ: cmd.extend(['-f', os.environ['bootstrap-testing-find-links']]) cmd.append('zc.buildout' + VERSION) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) assert exitcode == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
import pkg_resources
conditional_block
serlo_i18n.js
/** * Dont edit this file!
define(function () { "use strict"; var i18n = {}; i18n.de = { "Visit %s overview" : "Zur %s Übersicht", "An error occured, please reload." : "Es gab einen unerwarteten Fehler. Bitte laden Sie die Seite neu.", "Order successfully saved" : "Reihenfolge erfolgreich gespeichert", "Your browser doesnt support the following technologies: %s <br>Please update your browser!" : "Ihr Browser unterstützt die folgenden Technologien nicht: %s <br>Bitte installieren Sie eine neuere Version Ihres Browsers!", "Close" : "Schließen", "When asynchronously trying to load a ressource, I came across an error: %s" : "Beim Laden einer Ressource gab es leider folgenden Fehler: %s", "You are using an outdated web browser. Please consider an update!" : "Sie benutzen eine veraltete Browser Version. Bitte installieren Sie einen aktuelleren Browser.", "No results found." : "Keine Ergebnisse gefunden.", "No results found for \"%s\"." : "Keine Ergebnisse für \"%s\" gefunden.", "Illegal injection found" : "", "Could not load injection" : "", "You\'re almost done!" : "Du hast es fast geschafft!", "Show overview" : "Übersicht anzeigen", "Show %d contents for \"%s\"" : "", "Abort": "Abbrechen" }; i18n.en = { "An error occured, please reload." : "", "Close" : "", "Visit %s overview" : "", "Order successfully saved" : "", "Your browser doesnt support the following technologies: %s <br>Please update your browser!" : "", "When asynchronously trying to load a ressource, I came across an error: %s" : "", "You are using an outdated web browser. Please consider an update!" : "", "No results found." : "", "No results found for \"%s\"." : "", "Illegal injection found" : "", "Could not load injection" : "", "You\'re almost done!" : "", "Show overview" : "", "Show %d contents for \"%s\"" : "", "Abort": "" }; return i18n; });
* This module generates itself from lang.js files! * Instead edit the language files in /lang/ **/ /*global define*/
random_line_split
CirclePlay.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component {
() { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-circle-play`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'circle-play'); return <svg version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000000" strokeWidth="2" d="M12,22 C17.5228475,22 22,17.5228475 22,12 C22,6.4771525 17.5228475,2 12,2 C6.4771525,2 2,6.4771525 2,12 C2,17.5228475 6.4771525,22 12,22 Z M9.5,15.5 L15.5,12 L9.5,8.5 L9.5,15.5 Z M10.5,13.5 L12.5,12 L10.5,10.5 L10.5,13.5 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'CirclePlay'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
render
identifier_name
CirclePlay.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl';
render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-circle-play`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'circle-play'); return <svg version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000000" strokeWidth="2" d="M12,22 C17.5228475,22 22,17.5228475 22,12 C22,6.4771525 17.5228475,2 12,2 C6.4771525,2 2,6.4771525 2,12 C2,17.5228475 6.4771525,22 12,22 Z M9.5,15.5 L15.5,12 L9.5,8.5 L9.5,15.5 Z M10.5,13.5 L12.5,12 L10.5,10.5 L10.5,13.5 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'CirclePlay'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component {
random_line_split
CirclePlay.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render ()
}; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'CirclePlay'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
{ const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-circle-play`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'circle-play'); return <svg version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000000" strokeWidth="2" d="M12,22 C17.5228475,22 22,17.5228475 22,12 C22,6.4771525 17.5228475,2 12,2 C6.4771525,2 2,6.4771525 2,12 C2,17.5228475 6.4771525,22 12,22 Z M9.5,15.5 L15.5,12 L9.5,8.5 L9.5,15.5 Z M10.5,13.5 L12.5,12 L10.5,10.5 L10.5,13.5 Z"/></svg>; }
identifier_body
xlate.js
var translations = { 'es': { 'One moment while we<br>log you in': 'Espera un momento mientras<br>iniciamos tu sesión', 'You are now connected to the network': 'Ahora estás conectado a la red', 'Account signups/purchases are disabled in preview mode': 'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.', 'Notice': 'Aviso', 'Day': 'Día', 'Days': 'Días', 'Hour': 'Hora', 'Hours': 'Horas', 'Minutes': 'Minutos', 'Continue': 'Continuar', 'Thank You for Trying TWC WiFi': 'Gracias por probar TWC WiFi', 'Please purchase a TWC Access Pass to continue using WiFi': 'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi', 'Your TWC Access Pass has expired. Please select a new Access Pass Now.': 'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.', 'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.': 'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.', 'Your Password': 'Tu contraseña', 'Proceed to Login': 'Proceder con el inicio de sesión', 'Payment portal is not available at this moment': '', 'Redirecting to Payment portal...': '', 'Could not log you into the network': 'No se pudo iniciar sesión en la red' } } function translate(text, language) { if (
language == 'en') return text; if (!translations[language]) return text; if (!translations[language][text]) return text; return translations[language][text] || text; }
identifier_body
xlate.js
var translations = { 'es': { 'One moment while we<br>log you in': 'Espera un momento mientras<br>iniciamos tu sesión', 'You are now connected to the network': 'Ahora estás conectado a la red', 'Account signups/purchases are disabled in preview mode': 'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.', 'Notice': 'Aviso', 'Day': 'Día', 'Days': 'Días', 'Hour': 'Hora', 'Hours': 'Horas', 'Minutes': 'Minutos', 'Continue': 'Continuar', 'Thank You for Trying TWC WiFi': 'Gracias por probar TWC WiFi', 'Please purchase a TWC Access Pass to continue using WiFi': 'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi', 'Your TWC Access Pass has expired. Please select a new Access Pass Now.': 'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.', 'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.': 'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.', 'Your Password': 'Tu contraseña', 'Proceed to Login': 'Proceder con el inicio de sesión',
'', 'Redirecting to Payment portal...': '', 'Could not log you into the network': 'No se pudo iniciar sesión en la red' } } function translate(text, language) { if (language == 'en') return text; if (!translations[language]) return text; if (!translations[language][text]) return text; return translations[language][text] || text; }
'Payment portal is not available at this moment':
random_line_split
xlate.js
var translations = { 'es': { 'One moment while we<br>log you in': 'Espera un momento mientras<br>iniciamos tu sesión', 'You are now connected to the network': 'Ahora estás conectado a la red', 'Account signups/purchases are disabled in preview mode': 'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.', 'Notice': 'Aviso', 'Day': 'Día', 'Days': 'Días', 'Hour': 'Hora', 'Hours': 'Horas', 'Minutes': 'Minutos', 'Continue': 'Continuar', 'Thank You for Trying TWC WiFi': 'Gracias por probar TWC WiFi', 'Please purchase a TWC Access Pass to continue using WiFi': 'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi', 'Your TWC Access Pass has expired. Please select a new Access Pass Now.': 'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.', 'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.': 'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.', 'Your Password': 'Tu contraseña', 'Proceed to Login': 'Proceder con el inicio de sesión', 'Payment portal is not available at this moment': '', 'Redirecting to Payment portal...': '', 'Could not log you into the network': 'No se pudo iniciar sesión en la red' } } function translate(
guage) { if (language == 'en') return text; if (!translations[language]) return text; if (!translations[language][text]) return text; return translations[language][text] || text; }
text, lan
identifier_name
test_xl_cell_to_rowcol_abs.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # import unittest from ...utility import xl_cell_to_rowcol_abs class TestUtility(unittest.TestCase): """ Test xl_cell_to_rowcol_abs() utility function. """ def
(self): """Test xl_cell_to_rowcol_abs()""" tests = [ # row, col, A1 string (0, 0, 'A1'), (0, 1, 'B1'), (0, 2, 'C1'), (0, 9, 'J1'), (1, 0, 'A2'), (2, 0, 'A3'), (9, 0, 'A10'), (1, 24, 'Y2'), (7, 25, 'Z8'), (9, 26, 'AA10'), (1, 254, 'IU2'), (1, 255, 'IV2'), (1, 256, 'IW2'), (0, 16383, 'XFD1'), (1048576, 16384, 'XFE1048577'), ] for row, col, string in tests: exp = (row, col, 0, 0) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp) def test_xl_cell_to_rowcol_abs_abs(self): """Test xl_cell_to_rowcol_abs() with absolute references""" tests = [ # row, col, row_abs, col_abs, A1 string (0, 0, 0, 0, 'A1'), (0, 0, 1, 0, 'A$1'), (0, 0, 0, 1, '$A1'), (0, 0, 1, 1, '$A$1'), ] for row, col, row_abs, col_abs, string in tests: exp = (row, col, row_abs, col_abs) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp)
test_xl_cell_to_rowcol_abs
identifier_name
test_xl_cell_to_rowcol_abs.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # import unittest from ...utility import xl_cell_to_rowcol_abs
""" def test_xl_cell_to_rowcol_abs(self): """Test xl_cell_to_rowcol_abs()""" tests = [ # row, col, A1 string (0, 0, 'A1'), (0, 1, 'B1'), (0, 2, 'C1'), (0, 9, 'J1'), (1, 0, 'A2'), (2, 0, 'A3'), (9, 0, 'A10'), (1, 24, 'Y2'), (7, 25, 'Z8'), (9, 26, 'AA10'), (1, 254, 'IU2'), (1, 255, 'IV2'), (1, 256, 'IW2'), (0, 16383, 'XFD1'), (1048576, 16384, 'XFE1048577'), ] for row, col, string in tests: exp = (row, col, 0, 0) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp) def test_xl_cell_to_rowcol_abs_abs(self): """Test xl_cell_to_rowcol_abs() with absolute references""" tests = [ # row, col, row_abs, col_abs, A1 string (0, 0, 0, 0, 'A1'), (0, 0, 1, 0, 'A$1'), (0, 0, 0, 1, '$A1'), (0, 0, 1, 1, '$A$1'), ] for row, col, row_abs, col_abs, string in tests: exp = (row, col, row_abs, col_abs) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp)
class TestUtility(unittest.TestCase): """ Test xl_cell_to_rowcol_abs() utility function.
random_line_split
test_xl_cell_to_rowcol_abs.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # import unittest from ...utility import xl_cell_to_rowcol_abs class TestUtility(unittest.TestCase): """ Test xl_cell_to_rowcol_abs() utility function. """ def test_xl_cell_to_rowcol_abs(self):
def test_xl_cell_to_rowcol_abs_abs(self): """Test xl_cell_to_rowcol_abs() with absolute references""" tests = [ # row, col, row_abs, col_abs, A1 string (0, 0, 0, 0, 'A1'), (0, 0, 1, 0, 'A$1'), (0, 0, 0, 1, '$A1'), (0, 0, 1, 1, '$A$1'), ] for row, col, row_abs, col_abs, string in tests: exp = (row, col, row_abs, col_abs) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp)
"""Test xl_cell_to_rowcol_abs()""" tests = [ # row, col, A1 string (0, 0, 'A1'), (0, 1, 'B1'), (0, 2, 'C1'), (0, 9, 'J1'), (1, 0, 'A2'), (2, 0, 'A3'), (9, 0, 'A10'), (1, 24, 'Y2'), (7, 25, 'Z8'), (9, 26, 'AA10'), (1, 254, 'IU2'), (1, 255, 'IV2'), (1, 256, 'IW2'), (0, 16383, 'XFD1'), (1048576, 16384, 'XFE1048577'), ] for row, col, string in tests: exp = (row, col, 0, 0) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp)
identifier_body
test_xl_cell_to_rowcol_abs.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # import unittest from ...utility import xl_cell_to_rowcol_abs class TestUtility(unittest.TestCase): """ Test xl_cell_to_rowcol_abs() utility function. """ def test_xl_cell_to_rowcol_abs(self): """Test xl_cell_to_rowcol_abs()""" tests = [ # row, col, A1 string (0, 0, 'A1'), (0, 1, 'B1'), (0, 2, 'C1'), (0, 9, 'J1'), (1, 0, 'A2'), (2, 0, 'A3'), (9, 0, 'A10'), (1, 24, 'Y2'), (7, 25, 'Z8'), (9, 26, 'AA10'), (1, 254, 'IU2'), (1, 255, 'IV2'), (1, 256, 'IW2'), (0, 16383, 'XFD1'), (1048576, 16384, 'XFE1048577'), ] for row, col, string in tests:
def test_xl_cell_to_rowcol_abs_abs(self): """Test xl_cell_to_rowcol_abs() with absolute references""" tests = [ # row, col, row_abs, col_abs, A1 string (0, 0, 0, 0, 'A1'), (0, 0, 1, 0, 'A$1'), (0, 0, 0, 1, '$A1'), (0, 0, 1, 1, '$A$1'), ] for row, col, row_abs, col_abs, string in tests: exp = (row, col, row_abs, col_abs) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp)
exp = (row, col, 0, 0) got = xl_cell_to_rowcol_abs(string) self.assertEqual(got, exp)
conditional_block
t001_basic.py
#!/usr/bin/env python from runtest import TestBase class TestCase(TestBase): def
(self): TestBase.__init__(self, 'abc', """ # DURATION TID FUNCTION 62.202 us [28141] | __cxa_atexit(); [28141] | main() { [28141] | a() { [28141] | b() { [28141] | c() { 0.753 us [28141] | getpid(); 1.430 us [28141] | } /* c */ 1.915 us [28141] | } /* b */ 2.405 us [28141] | } /* a */ 3.005 us [28141] | } /* main */ """)
__init__
identifier_name
t001_basic.py
#!/usr/bin/env python from runtest import TestBase class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'abc', """ # DURATION TID FUNCTION 62.202 us [28141] | __cxa_atexit(); [28141] | main() { [28141] | a() {
[28141] | b() { [28141] | c() { 0.753 us [28141] | getpid(); 1.430 us [28141] | } /* c */ 1.915 us [28141] | } /* b */ 2.405 us [28141] | } /* a */ 3.005 us [28141] | } /* main */ """)
random_line_split
t001_basic.py
#!/usr/bin/env python from runtest import TestBase class TestCase(TestBase): def __init__(self):
TestBase.__init__(self, 'abc', """ # DURATION TID FUNCTION 62.202 us [28141] | __cxa_atexit(); [28141] | main() { [28141] | a() { [28141] | b() { [28141] | c() { 0.753 us [28141] | getpid(); 1.430 us [28141] | } /* c */ 1.915 us [28141] | } /* b */ 2.405 us [28141] | } /* a */ 3.005 us [28141] | } /* main */ """)
identifier_body
OtherCollectionEntity.jest.tsx
import { CollectionHubFixture } from "v2/Apps/__tests__/Fixtures/Collections" import { useTracking } from "v2/System/Analytics/useTracking" import { mount } from "enzyme" import React from "react" import { OtherCollectionEntity } from "../OtherCollectionEntity" import { OwnerType } from "@artsy/cohesion" import { AnalyticsContext } from "v2/System/Analytics/AnalyticsContext" import { Image } from "@artsy/palette" import { RouterLink } from "v2/System/Router/RouterLink" jest.mock("v2/System/Analytics/useTracking") jest.mock("found", () => ({ Link: ({ children, ...props }) => <div {...props}>{children}</div>, RouterContext: jest.requireActual("found").RouterContext, })) describe.skip("OtherCollectionEntity", () => { let props const trackEvent = jest.fn() beforeEach(() => { props = { member: CollectionHubFixture.linkedCollections[0].members[0], itemNumber: 1, } ;(useTracking as jest.Mock).mockImplementation(() => { return {
const getWrapper = (passedProps = props) => { return mount( <AnalyticsContext.Provider value={{ contextPageOwnerId: "1234", contextPageOwnerSlug: "slug", contextPageOwnerType: OwnerType.collection, }} > <OtherCollectionEntity {...passedProps} /> </AnalyticsContext.Provider> ) } it("Renders collection's meta data", () => { const component = getWrapper() expect(component.text()).toMatch("Artist Posters") expect(component.find(Image).length).toBe(1) const thumbnailImage = component.find(Image).at(0).getElement().props expect(thumbnailImage.src).toContain( "posters_thumbnail.png&width=60&height=60&quality=80&convert_to=jpg" ) const link = component.find(RouterLink).at(0).getElement().props expect(link.to).toContain("artist-poster") }) it("Returns entity with just text when there is no image", () => { props.member = CollectionHubFixture.linkedCollections[0].members[1] const component = getWrapper() expect(component.find(Image).length).toBe(0) }) describe("Tracking", () => { it("Tracks collection click", () => { const component = getWrapper() component.at(0).simulate("click") expect(trackEvent).toBeCalledWith({ action: "clickedCollectionGroup", context_module: "otherCollectionsRail", context_page_owner_type: "collection", context_page_owner_id: "1234", context_page_owner_slug: "slug", destination_page_owner_id: "123456", destination_page_owner_slug: "artist-posters", destination_page_owner_type: "collection", horizontal_slide_position: 1, type: "thumbnail", }) }) }) })
trackEvent, } }) })
random_line_split
make-stat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Mar 24 11:17:25 2014 @author: kshmirko """ import pandas as pds import numpy as np def seasons(x): month = x.month ret = None if month in [12,1,2]: ret = "Winter" elif month in [3,4,5]: ret = "Spring" elif month in [6,7,8]: ret = "Summer" else:
return ret Lon0 = 131.9 Lat0 = 43.1 Radius = 4.0 DB = 'DS-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3StatFileName_fig = 'O3-%5.1f-%4.1f-%3.1f.eps'%(Lon0, Lat0, Radius) O3StatFileName_h5 = 'O3-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3 = pds.read_hdf(DB,'O3') O3_Err = pds.read_hdf(DB,'O3Err') TH = pds.read_hdf(DB,'TH') #вычисляем статистику по сезонам относительно земли O3seasons = O3.groupby(seasons).mean().T / 1.0e12 O3seasons_s = O3.groupby(seasons).std().T / 1.0e12 O3seasons_Err = O3_Err.groupby(seasons).mean().T / 100.00 THseasons = TH.groupby(seasons).agg([np.mean, np.std]).T X = np.linspace(0.5, 70, 140) StatO3 = pds.DataFrame(index=X) for iseason in ['Winter','Spring','Summer','Fall']: StatO3[iseason+'_m'] = O3seasons[iseason] StatO3[iseason+'_e'] = O3seasons_Err[iseason] StatO3[iseason+'_s'] = O3seasons_s[iseason] store = pds.HDFStore(O3StatFileName_h5,'w') store.put('Statistics',StatO3) store.close() import pylab as plt plt.figure(1) plt.clf() ax = plt.subplot(2,2,1) ax.plot(X, O3seasons['Winter']) ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Winter') Ht0 = THseasons['Winter'][0]['mean'] Ht0e= THseasons['Winter'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Winter'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) # 2-nd plot ax = plt.subplot(2,2,2) ax.plot(X, O3seasons['Spring'],'g') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_title('Spring') Ht0 = THseasons['Spring'][0]['mean'] Ht0e= THseasons['Spring'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Spring'],'r.--') ax.spines['right'].set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #3-rd plot ax = plt.subplot(2,2,3) ax.plot(X, O3seasons['Summer'],'y') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.grid() ax.set_xlabel('Altitude, km') ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Summer') Ht0 = THseasons['Summer'][0]['mean'] Ht0e= THseasons['Summer'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Summer'],'r.--') ax.spines['right'].set_color('red') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #4-th plot ax = plt.subplot(2,2,4) ax.plot(X, O3seasons['Fall'],'k') ax.set_xlim((0,40)) ax.set_ylim((0,6)) Ht0 = THseasons['Fall'][0]['mean'] Ht0e= THseasons['Fall'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax.set_xlabel('Altitude, km') ax.set_title('Fall') ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Fall'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) plt.savefig(O3StatFileName_fig)
ret = "Fall"
conditional_block
make-stat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Mar 24 11:17:25 2014 @author: kshmirko """ import pandas as pds import numpy as np def seasons(x):
Lon0 = 131.9 Lat0 = 43.1 Radius = 4.0 DB = 'DS-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3StatFileName_fig = 'O3-%5.1f-%4.1f-%3.1f.eps'%(Lon0, Lat0, Radius) O3StatFileName_h5 = 'O3-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3 = pds.read_hdf(DB,'O3') O3_Err = pds.read_hdf(DB,'O3Err') TH = pds.read_hdf(DB,'TH') #вычисляем статистику по сезонам относительно земли O3seasons = O3.groupby(seasons).mean().T / 1.0e12 O3seasons_s = O3.groupby(seasons).std().T / 1.0e12 O3seasons_Err = O3_Err.groupby(seasons).mean().T / 100.00 THseasons = TH.groupby(seasons).agg([np.mean, np.std]).T X = np.linspace(0.5, 70, 140) StatO3 = pds.DataFrame(index=X) for iseason in ['Winter','Spring','Summer','Fall']: StatO3[iseason+'_m'] = O3seasons[iseason] StatO3[iseason+'_e'] = O3seasons_Err[iseason] StatO3[iseason+'_s'] = O3seasons_s[iseason] store = pds.HDFStore(O3StatFileName_h5,'w') store.put('Statistics',StatO3) store.close() import pylab as plt plt.figure(1) plt.clf() ax = plt.subplot(2,2,1) ax.plot(X, O3seasons['Winter']) ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Winter') Ht0 = THseasons['Winter'][0]['mean'] Ht0e= THseasons['Winter'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Winter'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) # 2-nd plot ax = plt.subplot(2,2,2) ax.plot(X, O3seasons['Spring'],'g') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_title('Spring') Ht0 = THseasons['Spring'][0]['mean'] Ht0e= THseasons['Spring'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Spring'],'r.--') ax.spines['right'].set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #3-rd plot ax = plt.subplot(2,2,3) ax.plot(X, O3seasons['Summer'],'y') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.grid() ax.set_xlabel('Altitude, km') ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Summer') Ht0 = THseasons['Summer'][0]['mean'] Ht0e= THseasons['Summer'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Summer'],'r.--') ax.spines['right'].set_color('red') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #4-th plot ax = plt.subplot(2,2,4) ax.plot(X, O3seasons['Fall'],'k') ax.set_xlim((0,40)) ax.set_ylim((0,6)) Ht0 = THseasons['Fall'][0]['mean'] Ht0e= THseasons['Fall'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax.set_xlabel('Altitude, km') ax.set_title('Fall') ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Fall'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) plt.savefig(O3StatFileName_fig)
month = x.month ret = None if month in [12,1,2]: ret = "Winter" elif month in [3,4,5]: ret = "Spring" elif month in [6,7,8]: ret = "Summer" else: ret = "Fall" return ret
identifier_body
make-stat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Mar 24 11:17:25 2014 @author: kshmirko """ import pandas as pds import numpy as np def
(x): month = x.month ret = None if month in [12,1,2]: ret = "Winter" elif month in [3,4,5]: ret = "Spring" elif month in [6,7,8]: ret = "Summer" else: ret = "Fall" return ret Lon0 = 131.9 Lat0 = 43.1 Radius = 4.0 DB = 'DS-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3StatFileName_fig = 'O3-%5.1f-%4.1f-%3.1f.eps'%(Lon0, Lat0, Radius) O3StatFileName_h5 = 'O3-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3 = pds.read_hdf(DB,'O3') O3_Err = pds.read_hdf(DB,'O3Err') TH = pds.read_hdf(DB,'TH') #вычисляем статистику по сезонам относительно земли O3seasons = O3.groupby(seasons).mean().T / 1.0e12 O3seasons_s = O3.groupby(seasons).std().T / 1.0e12 O3seasons_Err = O3_Err.groupby(seasons).mean().T / 100.00 THseasons = TH.groupby(seasons).agg([np.mean, np.std]).T X = np.linspace(0.5, 70, 140) StatO3 = pds.DataFrame(index=X) for iseason in ['Winter','Spring','Summer','Fall']: StatO3[iseason+'_m'] = O3seasons[iseason] StatO3[iseason+'_e'] = O3seasons_Err[iseason] StatO3[iseason+'_s'] = O3seasons_s[iseason] store = pds.HDFStore(O3StatFileName_h5,'w') store.put('Statistics',StatO3) store.close() import pylab as plt plt.figure(1) plt.clf() ax = plt.subplot(2,2,1) ax.plot(X, O3seasons['Winter']) ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Winter') Ht0 = THseasons['Winter'][0]['mean'] Ht0e= THseasons['Winter'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Winter'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) # 2-nd plot ax = plt.subplot(2,2,2) ax.plot(X, O3seasons['Spring'],'g') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_title('Spring') Ht0 = THseasons['Spring'][0]['mean'] Ht0e= THseasons['Spring'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Spring'],'r.--') ax.spines['right'].set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #3-rd plot ax = plt.subplot(2,2,3) ax.plot(X, O3seasons['Summer'],'y') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.grid() ax.set_xlabel('Altitude, km') ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Summer') Ht0 = THseasons['Summer'][0]['mean'] Ht0e= THseasons['Summer'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Summer'],'r.--') ax.spines['right'].set_color('red') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #4-th plot ax = plt.subplot(2,2,4) ax.plot(X, O3seasons['Fall'],'k') ax.set_xlim((0,40)) ax.set_ylim((0,6)) Ht0 = THseasons['Fall'][0]['mean'] Ht0e= THseasons['Fall'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax.set_xlabel('Altitude, km') ax.set_title('Fall') ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Fall'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) plt.savefig(O3StatFileName_fig)
seasons
identifier_name
make-stat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Mar 24 11:17:25 2014 @author: kshmirko """ import pandas as pds import numpy as np def seasons(x): month = x.month ret = None if month in [12,1,2]: ret = "Winter" elif month in [3,4,5]: ret = "Spring" elif month in [6,7,8]: ret = "Summer" else: ret = "Fall" return ret Lon0 = 131.9 Lat0 = 43.1 Radius = 4.0 DB = 'DS-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3StatFileName_fig = 'O3-%5.1f-%4.1f-%3.1f.eps'%(Lon0, Lat0, Radius) O3StatFileName_h5 = 'O3-%5.1f-%4.1f-%3.1f.h5'%(Lon0, Lat0, Radius) O3 = pds.read_hdf(DB,'O3') O3_Err = pds.read_hdf(DB,'O3Err') TH = pds.read_hdf(DB,'TH') #вычисляем статистику по сезонам относительно земли O3seasons = O3.groupby(seasons).mean().T / 1.0e12 O3seasons_s = O3.groupby(seasons).std().T / 1.0e12 O3seasons_Err = O3_Err.groupby(seasons).mean().T / 100.00 THseasons = TH.groupby(seasons).agg([np.mean, np.std]).T X = np.linspace(0.5, 70, 140) StatO3 = pds.DataFrame(index=X) for iseason in ['Winter','Spring','Summer','Fall']: StatO3[iseason+'_m'] = O3seasons[iseason] StatO3[iseason+'_e'] = O3seasons_Err[iseason] StatO3[iseason+'_s'] = O3seasons_s[iseason] store = pds.HDFStore(O3StatFileName_h5,'w') store.put('Statistics',StatO3) store.close() import pylab as plt plt.figure(1) plt.clf() ax = plt.subplot(2,2,1) ax.plot(X, O3seasons['Winter']) ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Winter') Ht0 = THseasons['Winter'][0]['mean'] Ht0e= THseasons['Winter'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Winter'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) # 2-nd plot ax = plt.subplot(2,2,2) ax.plot(X, O3seasons['Spring'],'g') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.set_title('Spring') Ht0 = THseasons['Spring'][0]['mean'] Ht0e= THseasons['Spring'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Spring'],'r.--') ax.spines['right'].set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #3-rd plot ax = plt.subplot(2,2,3) ax.plot(X, O3seasons['Summer'],'y') ax.set_xlim((0,40)) ax.set_ylim((0,6)) ax.grid() ax.set_xlabel('Altitude, km') ax.set_ylabel('$[O3]x10^{12}, cm^{-3}$' ) ax.set_title('Summer') Ht0 = THseasons['Summer'][0]['mean']
Ht0e= THseasons['Summer'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Summer'],'r.--') ax.spines['right'].set_color('red') ax2.tick_params(axis='y', colors='red') ax2.yaxis.label.set_color('red') ax2.set_ylim((0,100)) #4-th plot ax = plt.subplot(2,2,4) ax.plot(X, O3seasons['Fall'],'k') ax.set_xlim((0,40)) ax.set_ylim((0,6)) Ht0 = THseasons['Fall'][0]['mean'] Ht0e= THseasons['Fall'][0]['std'] ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.plot([Ht0,Ht0],[0,6], 'k.--',lw=2) ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,), xycoords='data', xytext=(30, 4.0), arrowprops=dict(arrowstyle="->", lw=2), size=16 ) ax.grid() ax.set_xlabel('Altitude, km') ax.set_title('Fall') ax2 = ax.twinx() ax2.plot(X,O3seasons_Err['Fall'],'r.--') ax.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.set_ylabel('Error,$\%$') ax2.tick_params(axis='y', colors='red') ax2.set_ylim((0,100)) plt.savefig(O3StatFileName_fig)
random_line_split
send_second_level_links.js
// Copyright OpenLogic, Inc.
// First check the MIME type of the URL. If it is the desired type, then make // the AJAX request to get the content (DOM) and extract the relevant links // in the content. function follow_html_mime_type(url) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (this.readyState == this.DONE && this.getResponseHeader('content-type').indexOf("text/html") != -1) { totalRequests += 1; chrome.runtime.sendMessage({ total: totalRequests }); requestDOM(url); } } xhr.send(); } function requestDOM(url) { var domRequest = new XMLHttpRequest(); domRequest.open('GET', url, true); domRequest.onreadystatechange = function() { if (this.readyState == this.DONE && this.status == 200) { var dom = $.parseHTML(this.responseText); extractLinks(dom); } } domRequest.send(); } function extractLinks(doc) { try { var domain = window.parent.location.origin; var aTag = 'a'; if (domain == 'http://sourceforge.net') aTag = 'a.name' var links = $(aTag, doc).toArray(); links = links.map(function(element) { // Proceed only if the link is in the same domain. if (element.href.indexOf(domain) == 0) { // Return an anchor's href attribute, stripping any URL fragment (hash '#'). // If the html specifies a relative path, chrome converts it to an absolute // URL. var href = element.href; var hashIndex = href.indexOf('#'); if (hashIndex > -1) href = href.substr(0, hashIndex); return href; } }); // Remove undefined from the links array. for (var n = links.length - 1; n >= 0; --n) { if (links[n] == undefined) links.splice(n, 1); } links.sort(); totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); chrome.extension.sendRequest(links); } catch (error) { // Do nothing. totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); } } window.sendSecondLevelLinks = function() { var firstLevelLinks = window.getLinks(); for (var index in firstLevelLinks) { var url = firstLevelLinks[index]; var current_location = window.location.href; var domain = window.parent.location.origin; // - skip urls that look like "parents" of the current one if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0) follow_html_mime_type(url); } } window.sendSecondLevelLinks();
// See LICENSE file for license information. // var totalRequests = 0;
random_line_split
send_second_level_links.js
// Copyright OpenLogic, Inc. // See LICENSE file for license information. // var totalRequests = 0; // First check the MIME type of the URL. If it is the desired type, then make // the AJAX request to get the content (DOM) and extract the relevant links // in the content. function follow_html_mime_type(url) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (this.readyState == this.DONE && this.getResponseHeader('content-type').indexOf("text/html") != -1) { totalRequests += 1; chrome.runtime.sendMessage({ total: totalRequests }); requestDOM(url); } } xhr.send(); } function requestDOM(url) { var domRequest = new XMLHttpRequest(); domRequest.open('GET', url, true); domRequest.onreadystatechange = function() { if (this.readyState == this.DONE && this.status == 200) { var dom = $.parseHTML(this.responseText); extractLinks(dom); } } domRequest.send(); } function extractLinks(doc)
window.sendSecondLevelLinks = function() { var firstLevelLinks = window.getLinks(); for (var index in firstLevelLinks) { var url = firstLevelLinks[index]; var current_location = window.location.href; var domain = window.parent.location.origin; // - skip urls that look like "parents" of the current one if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0) follow_html_mime_type(url); } } window.sendSecondLevelLinks();
{ try { var domain = window.parent.location.origin; var aTag = 'a'; if (domain == 'http://sourceforge.net') aTag = 'a.name' var links = $(aTag, doc).toArray(); links = links.map(function(element) { // Proceed only if the link is in the same domain. if (element.href.indexOf(domain) == 0) { // Return an anchor's href attribute, stripping any URL fragment (hash '#'). // If the html specifies a relative path, chrome converts it to an absolute // URL. var href = element.href; var hashIndex = href.indexOf('#'); if (hashIndex > -1) href = href.substr(0, hashIndex); return href; } }); // Remove undefined from the links array. for (var n = links.length - 1; n >= 0; --n) { if (links[n] == undefined) links.splice(n, 1); } links.sort(); totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); chrome.extension.sendRequest(links); } catch (error) { // Do nothing. totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); } }
identifier_body
send_second_level_links.js
// Copyright OpenLogic, Inc. // See LICENSE file for license information. // var totalRequests = 0; // First check the MIME type of the URL. If it is the desired type, then make // the AJAX request to get the content (DOM) and extract the relevant links // in the content. function follow_html_mime_type(url) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (this.readyState == this.DONE && this.getResponseHeader('content-type').indexOf("text/html") != -1)
} xhr.send(); } function requestDOM(url) { var domRequest = new XMLHttpRequest(); domRequest.open('GET', url, true); domRequest.onreadystatechange = function() { if (this.readyState == this.DONE && this.status == 200) { var dom = $.parseHTML(this.responseText); extractLinks(dom); } } domRequest.send(); } function extractLinks(doc) { try { var domain = window.parent.location.origin; var aTag = 'a'; if (domain == 'http://sourceforge.net') aTag = 'a.name' var links = $(aTag, doc).toArray(); links = links.map(function(element) { // Proceed only if the link is in the same domain. if (element.href.indexOf(domain) == 0) { // Return an anchor's href attribute, stripping any URL fragment (hash '#'). // If the html specifies a relative path, chrome converts it to an absolute // URL. var href = element.href; var hashIndex = href.indexOf('#'); if (hashIndex > -1) href = href.substr(0, hashIndex); return href; } }); // Remove undefined from the links array. for (var n = links.length - 1; n >= 0; --n) { if (links[n] == undefined) links.splice(n, 1); } links.sort(); totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); chrome.extension.sendRequest(links); } catch (error) { // Do nothing. totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); } } window.sendSecondLevelLinks = function() { var firstLevelLinks = window.getLinks(); for (var index in firstLevelLinks) { var url = firstLevelLinks[index]; var current_location = window.location.href; var domain = window.parent.location.origin; // - skip urls that look like "parents" of the current one if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0) follow_html_mime_type(url); } } window.sendSecondLevelLinks();
{ totalRequests += 1; chrome.runtime.sendMessage({ total: totalRequests }); requestDOM(url); }
conditional_block
send_second_level_links.js
// Copyright OpenLogic, Inc. // See LICENSE file for license information. // var totalRequests = 0; // First check the MIME type of the URL. If it is the desired type, then make // the AJAX request to get the content (DOM) and extract the relevant links // in the content. function
(url) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (this.readyState == this.DONE && this.getResponseHeader('content-type').indexOf("text/html") != -1) { totalRequests += 1; chrome.runtime.sendMessage({ total: totalRequests }); requestDOM(url); } } xhr.send(); } function requestDOM(url) { var domRequest = new XMLHttpRequest(); domRequest.open('GET', url, true); domRequest.onreadystatechange = function() { if (this.readyState == this.DONE && this.status == 200) { var dom = $.parseHTML(this.responseText); extractLinks(dom); } } domRequest.send(); } function extractLinks(doc) { try { var domain = window.parent.location.origin; var aTag = 'a'; if (domain == 'http://sourceforge.net') aTag = 'a.name' var links = $(aTag, doc).toArray(); links = links.map(function(element) { // Proceed only if the link is in the same domain. if (element.href.indexOf(domain) == 0) { // Return an anchor's href attribute, stripping any URL fragment (hash '#'). // If the html specifies a relative path, chrome converts it to an absolute // URL. var href = element.href; var hashIndex = href.indexOf('#'); if (hashIndex > -1) href = href.substr(0, hashIndex); return href; } }); // Remove undefined from the links array. for (var n = links.length - 1; n >= 0; --n) { if (links[n] == undefined) links.splice(n, 1); } links.sort(); totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); chrome.extension.sendRequest(links); } catch (error) { // Do nothing. totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); } } window.sendSecondLevelLinks = function() { var firstLevelLinks = window.getLinks(); for (var index in firstLevelLinks) { var url = firstLevelLinks[index]; var current_location = window.location.href; var domain = window.parent.location.origin; // - skip urls that look like "parents" of the current one if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0) follow_html_mime_type(url); } } window.sendSecondLevelLinks();
follow_html_mime_type
identifier_name
.ycm_extra_conf.py
#!/usr/bin/python # Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # This .ycm_extra_conf will be picked up automatically for code completion using # YouCompleteMe. # # See https://valloric.github.io/YouCompleteMe/ for instructions on setting up # YouCompleteMe using Vim. This .ycm_extra_conf file also works with any other # completion engine that uses YCMD (https://github.com/Valloric/ycmd). # # Code completion depends on a Clang compilation database. This is placed in a # file named `compile_commands.json` in your execution root path. I.e. it will # be at the path returned by `bazel info execution_root`. # # If the compilation database isn't available, this script will generate one # using tools/cpp/generate_compilation_database.sh. This process can be slow if # you haven't built the sources yet. It's always a good idea to run # generate_compilation_database.sh manually so that you can see the build output # including any errors encountered during compile command generation. # ============================================================================== import json import os import shlex import subprocess import time # If all else fails, then return this list of flags. DEFAULT_FLAGS = [] CANONICAL_SOURCE_FILE = 'kythe/cxx/extractor/cxx_extractor_main.cc' # Full path to directory containing compilation database. This is usually # |execution_root|/compile_commands.json. COMPILATION_DATABASE_PATH = None # Workspace path. WORKSPACE_PATH = None # The compilation database. This is a mapping from the absolute normalized path # of the source file to it's compile command broken down into an array. COMPILATION_DATABASE = {} # If loading the compilation database failed for some reason, # LAST_INIT_FAILURE_TIME contains the value of time.clock() at the time the # failure was encountered. LAST_INIT_FAILURE_TIME = None # If this many seconds have passed since the last failure, then try to generate # the compilation database again. RETRY_TIMEOUT_SECONDS = 120 HEADER_EXTENSIONS = ['.h', '.hpp', '.hh', '.hxx'] SOURCE_EXTENSIONS = ['.cc', '.cpp', '.c', '.m', '.mm', '.cxx'] NORMALIZE_PATH = 1 REMOVE = 2 # List of clang options and what to do with them. Use the '-foo' form for flags # that could be used as '-foo <arg>' and '-foo=<arg>' forms, and use '-foo=' for # flags that can only be used as '-foo=<arg>'. # # Mapping a flag to NORMALIZE_PATH causes its argument to be normalized against # the build directory via ExpandAndNormalizePath(). REMOVE causes both the flag # and its value to be removed. CLANG_OPTION_DISPOSITION = { '-I': NORMALIZE_PATH, '-MF': REMOVE, '-cxx-isystem': NORMALIZE_PATH, '-dependency-dot': REMOVE, '-dependency-file': REMOVE, '-fbuild-session-file': REMOVE, '-fmodule-file': NORMALIZE_PATH, '-fmodule-map-file': NORMALIZE_PATH, '-foptimization-record-file': REMOVE, '-fprebuilt-module-path': NORMALIZE_PATH, '-fprofile-generate=': REMOVE, '-fprofile-instrument-generate=': REMOVE, '-fprofile-user=': REMOVE, '-gcc-tollchain=': NORMALIZE_PATH, '-idirafter': NORMALIZE_PATH, '-iframework': NORMALIZE_PATH, '-imacros': NORMALIZE_PATH, '-include': NORMALIZE_PATH, '-include-pch': NORMALIZE_PATH, '-iprefix': NORMALIZE_PATH, '-iquote': NORMALIZE_PATH, '-isysroot': NORMALIZE_PATH, '-isystem': NORMALIZE_PATH, '-isystem-after': NORMALIZE_PATH, '-ivfsoverlay': NORMALIZE_PATH, '-iwithprefixbefore': NORMALIZE_PATH, '-iwithsysroot': NORMALIZE_PATH, '-o': REMOVE, '-working-directory': NORMALIZE_PATH, } def ProcessOutput(args): """Run the program described by |args| and return its stdout as a stream. |stderr| and |stdin| will be set to /dev/null. Will raise CalledProcessError if the subprocess doesn't complete successfully. """ output = '' with open(os.devnull, 'w') as err: with open(os.devnull, 'r') as inp: output = subprocess.check_output(args, stderr=err, stdin=inp) return str(output).strip() def InitBazelConfig(): """Initialize globals based on Bazel configuration. Initialize COMPILATION_DATABASE_PATH, WORKSPACE_PATH, and CANONICAL_SOURCE_FILE based on Bazel. These values are not expected to change during the session.""" global COMPILATION_DATABASE_PATH global WORKSPACE_PATH global CANONICAL_SOURCE_FILE execution_root = ProcessOutput(['bazel', 'info', 'execution_root']) COMPILATION_DATABASE_PATH = os.path.join(execution_root, 'compile_commands.json') WORKSPACE_PATH = ProcessOutput(['bazel', 'info', 'workspace']) CANONICAL_SOURCE_FILE = ExpandAndNormalizePath(CANONICAL_SOURCE_FILE, WORKSPACE_PATH) def GenerateCompilationDatabaseSlowly(): """Generate compilation database. May take a while.""" script_path = os.path.join(WORKSPACE_PATH, 'tools', 'cpp', 'generate_compilation_database.sh') ProcessOutput(script_path) def ExpandAndNormalizePath(filename, basepath=WORKSPACE_PATH): """Resolves |filename| relative to |basepath| and expands symlinks.""" if not os.path.isabs(filename) and basepath: filename = os.path.join(basepath, filename) filename = os.path.realpath(filename) return str(filename)
use_next_flag_as_value_for = None def HandleFlag(name, value, combine): disposition = CLANG_OPTION_DISPOSITION.get(name, None) if disposition is None and combine: disposition = CLANG_OPTION_DISPOSITION.get(name + '=', None) if disposition == REMOVE: return if disposition == NORMALIZE_PATH: value = ExpandAndNormalizePath(value, basepath) if combine: flags_to_return.append('{}={}'.format(name, value)) else: flags_to_return.extend([name, value]) for flag in flags: if use_next_flag_as_value_for is not None: name = use_next_flag_as_value_for use_next_flag_as_value_for = None HandleFlag(name, flag, combine=False) continue if '=' in flag: # -foo=bar name, value = flag.split('=', 1) HandleFlag(name, value, combine=True) continue if flag in CLANG_OPTION_DISPOSITION: use_next_flag_as_value_for = flag continue if flag.startswith('-I'): HandleFlag('-I', flags[3:], combine=False) continue flags_to_return.append(flag) return flags_to_return def LoadCompilationDatabase(): if not os.path.exists(COMPILATION_DATABASE_PATH): GenerateCompilationDatabaseSlowly() with open(COMPILATION_DATABASE_PATH, 'r') as database: database_dict = json.load(database) global COMPILATION_DATABASE COMPILATION_DATABASE = {} for entry in database_dict: filename = ExpandAndNormalizePath(entry['file'], WORKSPACE_PATH) directory = entry['directory'] command = entry['command'] COMPILATION_DATABASE[filename] = { 'command': command, 'directory': directory } def IsHeaderFile(filename): extension = os.path.splitext(filename)[1] return extension in HEADER_EXTENSIONS def FindAlternateFile(filename): if IsHeaderFile(filename): basename = os.path.splitext(filename)[0] for extension in SOURCE_EXTENSIONS: new_filename = basename + extension if new_filename in COMPILATION_DATABASE: return new_filename # Try something in the same directory. directory = os.path.dirname(filename) for key in COMPILATION_DATABASE.iterkeys(): if key.startswith(directory) and os.path.dirname(key) == directory: return key return CANONICAL_SOURCE_FILE # Entrypoint for YouCompleteMe. def FlagsForFile(filename, **kwargs): global LAST_INIT_FAILURE_TIME if len(COMPILATION_DATABASE) == 0: if LAST_INIT_FAILURE_TIME is not None and time.clock( ) - LAST_INIT_FAILURE_TIME < RETRY_TIMEOUT_SECONDS: return {'flags': DEFAULT_FLAGS} try: InitBazelConfig() LoadCompilationDatabase() except Exception as e: LAST_INIT_FAILURE_TIME = time.clock() return {'flags': DEFAULT_FLAGS} filename = str(os.path.realpath(filename)) if filename not in COMPILATION_DATABASE: filename = FindAlternateFile(filename) if filename not in COMPILATION_DATABASE: return {'flags': DEFAULT_FLAGS} result_dict = COMPILATION_DATABASE[filename] return { 'flags': PrepareCompileFlags(result_dict['command'], result_dict['directory']) } # For testing. if __name__ == '__main__': import sys print FlagsForFile(sys.argv[1])
def PrepareCompileFlags(compile_command, basepath): flags = shlex.split(compile_command) flags_to_return = []
random_line_split
.ycm_extra_conf.py
#!/usr/bin/python # Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # This .ycm_extra_conf will be picked up automatically for code completion using # YouCompleteMe. # # See https://valloric.github.io/YouCompleteMe/ for instructions on setting up # YouCompleteMe using Vim. This .ycm_extra_conf file also works with any other # completion engine that uses YCMD (https://github.com/Valloric/ycmd). # # Code completion depends on a Clang compilation database. This is placed in a # file named `compile_commands.json` in your execution root path. I.e. it will # be at the path returned by `bazel info execution_root`. # # If the compilation database isn't available, this script will generate one # using tools/cpp/generate_compilation_database.sh. This process can be slow if # you haven't built the sources yet. It's always a good idea to run # generate_compilation_database.sh manually so that you can see the build output # including any errors encountered during compile command generation. # ============================================================================== import json import os import shlex import subprocess import time # If all else fails, then return this list of flags. DEFAULT_FLAGS = [] CANONICAL_SOURCE_FILE = 'kythe/cxx/extractor/cxx_extractor_main.cc' # Full path to directory containing compilation database. This is usually # |execution_root|/compile_commands.json. COMPILATION_DATABASE_PATH = None # Workspace path. WORKSPACE_PATH = None # The compilation database. This is a mapping from the absolute normalized path # of the source file to it's compile command broken down into an array. COMPILATION_DATABASE = {} # If loading the compilation database failed for some reason, # LAST_INIT_FAILURE_TIME contains the value of time.clock() at the time the # failure was encountered. LAST_INIT_FAILURE_TIME = None # If this many seconds have passed since the last failure, then try to generate # the compilation database again. RETRY_TIMEOUT_SECONDS = 120 HEADER_EXTENSIONS = ['.h', '.hpp', '.hh', '.hxx'] SOURCE_EXTENSIONS = ['.cc', '.cpp', '.c', '.m', '.mm', '.cxx'] NORMALIZE_PATH = 1 REMOVE = 2 # List of clang options and what to do with them. Use the '-foo' form for flags # that could be used as '-foo <arg>' and '-foo=<arg>' forms, and use '-foo=' for # flags that can only be used as '-foo=<arg>'. # # Mapping a flag to NORMALIZE_PATH causes its argument to be normalized against # the build directory via ExpandAndNormalizePath(). REMOVE causes both the flag # and its value to be removed. CLANG_OPTION_DISPOSITION = { '-I': NORMALIZE_PATH, '-MF': REMOVE, '-cxx-isystem': NORMALIZE_PATH, '-dependency-dot': REMOVE, '-dependency-file': REMOVE, '-fbuild-session-file': REMOVE, '-fmodule-file': NORMALIZE_PATH, '-fmodule-map-file': NORMALIZE_PATH, '-foptimization-record-file': REMOVE, '-fprebuilt-module-path': NORMALIZE_PATH, '-fprofile-generate=': REMOVE, '-fprofile-instrument-generate=': REMOVE, '-fprofile-user=': REMOVE, '-gcc-tollchain=': NORMALIZE_PATH, '-idirafter': NORMALIZE_PATH, '-iframework': NORMALIZE_PATH, '-imacros': NORMALIZE_PATH, '-include': NORMALIZE_PATH, '-include-pch': NORMALIZE_PATH, '-iprefix': NORMALIZE_PATH, '-iquote': NORMALIZE_PATH, '-isysroot': NORMALIZE_PATH, '-isystem': NORMALIZE_PATH, '-isystem-after': NORMALIZE_PATH, '-ivfsoverlay': NORMALIZE_PATH, '-iwithprefixbefore': NORMALIZE_PATH, '-iwithsysroot': NORMALIZE_PATH, '-o': REMOVE, '-working-directory': NORMALIZE_PATH, } def ProcessOutput(args): """Run the program described by |args| and return its stdout as a stream. |stderr| and |stdin| will be set to /dev/null. Will raise CalledProcessError if the subprocess doesn't complete successfully. """ output = '' with open(os.devnull, 'w') as err: with open(os.devnull, 'r') as inp: output = subprocess.check_output(args, stderr=err, stdin=inp) return str(output).strip() def InitBazelConfig(): """Initialize globals based on Bazel configuration. Initialize COMPILATION_DATABASE_PATH, WORKSPACE_PATH, and CANONICAL_SOURCE_FILE based on Bazel. These values are not expected to change during the session.""" global COMPILATION_DATABASE_PATH global WORKSPACE_PATH global CANONICAL_SOURCE_FILE execution_root = ProcessOutput(['bazel', 'info', 'execution_root']) COMPILATION_DATABASE_PATH = os.path.join(execution_root, 'compile_commands.json') WORKSPACE_PATH = ProcessOutput(['bazel', 'info', 'workspace']) CANONICAL_SOURCE_FILE = ExpandAndNormalizePath(CANONICAL_SOURCE_FILE, WORKSPACE_PATH) def
(): """Generate compilation database. May take a while.""" script_path = os.path.join(WORKSPACE_PATH, 'tools', 'cpp', 'generate_compilation_database.sh') ProcessOutput(script_path) def ExpandAndNormalizePath(filename, basepath=WORKSPACE_PATH): """Resolves |filename| relative to |basepath| and expands symlinks.""" if not os.path.isabs(filename) and basepath: filename = os.path.join(basepath, filename) filename = os.path.realpath(filename) return str(filename) def PrepareCompileFlags(compile_command, basepath): flags = shlex.split(compile_command) flags_to_return = [] use_next_flag_as_value_for = None def HandleFlag(name, value, combine): disposition = CLANG_OPTION_DISPOSITION.get(name, None) if disposition is None and combine: disposition = CLANG_OPTION_DISPOSITION.get(name + '=', None) if disposition == REMOVE: return if disposition == NORMALIZE_PATH: value = ExpandAndNormalizePath(value, basepath) if combine: flags_to_return.append('{}={}'.format(name, value)) else: flags_to_return.extend([name, value]) for flag in flags: if use_next_flag_as_value_for is not None: name = use_next_flag_as_value_for use_next_flag_as_value_for = None HandleFlag(name, flag, combine=False) continue if '=' in flag: # -foo=bar name, value = flag.split('=', 1) HandleFlag(name, value, combine=True) continue if flag in CLANG_OPTION_DISPOSITION: use_next_flag_as_value_for = flag continue if flag.startswith('-I'): HandleFlag('-I', flags[3:], combine=False) continue flags_to_return.append(flag) return flags_to_return def LoadCompilationDatabase(): if not os.path.exists(COMPILATION_DATABASE_PATH): GenerateCompilationDatabaseSlowly() with open(COMPILATION_DATABASE_PATH, 'r') as database: database_dict = json.load(database) global COMPILATION_DATABASE COMPILATION_DATABASE = {} for entry in database_dict: filename = ExpandAndNormalizePath(entry['file'], WORKSPACE_PATH) directory = entry['directory'] command = entry['command'] COMPILATION_DATABASE[filename] = { 'command': command, 'directory': directory } def IsHeaderFile(filename): extension = os.path.splitext(filename)[1] return extension in HEADER_EXTENSIONS def FindAlternateFile(filename): if IsHeaderFile(filename): basename = os.path.splitext(filename)[0] for extension in SOURCE_EXTENSIONS: new_filename = basename + extension if new_filename in COMPILATION_DATABASE: return new_filename # Try something in the same directory. directory = os.path.dirname(filename) for key in COMPILATION_DATABASE.iterkeys(): if key.startswith(directory) and os.path.dirname(key) == directory: return key return CANONICAL_SOURCE_FILE # Entrypoint for YouCompleteMe. def FlagsForFile(filename, **kwargs): global LAST_INIT_FAILURE_TIME if len(COMPILATION_DATABASE) == 0: if LAST_INIT_FAILURE_TIME is not None and time.clock( ) - LAST_INIT_FAILURE_TIME < RETRY_TIMEOUT_SECONDS: return {'flags': DEFAULT_FLAGS} try: InitBazelConfig() LoadCompilationDatabase() except Exception as e: LAST_INIT_FAILURE_TIME = time.clock() return {'flags': DEFAULT_FLAGS} filename = str(os.path.realpath(filename)) if filename not in COMPILATION_DATABASE: filename = FindAlternateFile(filename) if filename not in COMPILATION_DATABASE: return {'flags': DEFAULT_FLAGS} result_dict = COMPILATION_DATABASE[filename] return { 'flags': PrepareCompileFlags(result_dict['command'], result_dict['directory']) } # For testing. if __name__ == '__main__': import sys print FlagsForFile(sys.argv[1])
GenerateCompilationDatabaseSlowly
identifier_name
.ycm_extra_conf.py
#!/usr/bin/python # Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # This .ycm_extra_conf will be picked up automatically for code completion using # YouCompleteMe. # # See https://valloric.github.io/YouCompleteMe/ for instructions on setting up # YouCompleteMe using Vim. This .ycm_extra_conf file also works with any other # completion engine that uses YCMD (https://github.com/Valloric/ycmd). # # Code completion depends on a Clang compilation database. This is placed in a # file named `compile_commands.json` in your execution root path. I.e. it will # be at the path returned by `bazel info execution_root`. # # If the compilation database isn't available, this script will generate one # using tools/cpp/generate_compilation_database.sh. This process can be slow if # you haven't built the sources yet. It's always a good idea to run # generate_compilation_database.sh manually so that you can see the build output # including any errors encountered during compile command generation. # ============================================================================== import json import os import shlex import subprocess import time # If all else fails, then return this list of flags. DEFAULT_FLAGS = [] CANONICAL_SOURCE_FILE = 'kythe/cxx/extractor/cxx_extractor_main.cc' # Full path to directory containing compilation database. This is usually # |execution_root|/compile_commands.json. COMPILATION_DATABASE_PATH = None # Workspace path. WORKSPACE_PATH = None # The compilation database. This is a mapping from the absolute normalized path # of the source file to it's compile command broken down into an array. COMPILATION_DATABASE = {} # If loading the compilation database failed for some reason, # LAST_INIT_FAILURE_TIME contains the value of time.clock() at the time the # failure was encountered. LAST_INIT_FAILURE_TIME = None # If this many seconds have passed since the last failure, then try to generate # the compilation database again. RETRY_TIMEOUT_SECONDS = 120 HEADER_EXTENSIONS = ['.h', '.hpp', '.hh', '.hxx'] SOURCE_EXTENSIONS = ['.cc', '.cpp', '.c', '.m', '.mm', '.cxx'] NORMALIZE_PATH = 1 REMOVE = 2 # List of clang options and what to do with them. Use the '-foo' form for flags # that could be used as '-foo <arg>' and '-foo=<arg>' forms, and use '-foo=' for # flags that can only be used as '-foo=<arg>'. # # Mapping a flag to NORMALIZE_PATH causes its argument to be normalized against # the build directory via ExpandAndNormalizePath(). REMOVE causes both the flag # and its value to be removed. CLANG_OPTION_DISPOSITION = { '-I': NORMALIZE_PATH, '-MF': REMOVE, '-cxx-isystem': NORMALIZE_PATH, '-dependency-dot': REMOVE, '-dependency-file': REMOVE, '-fbuild-session-file': REMOVE, '-fmodule-file': NORMALIZE_PATH, '-fmodule-map-file': NORMALIZE_PATH, '-foptimization-record-file': REMOVE, '-fprebuilt-module-path': NORMALIZE_PATH, '-fprofile-generate=': REMOVE, '-fprofile-instrument-generate=': REMOVE, '-fprofile-user=': REMOVE, '-gcc-tollchain=': NORMALIZE_PATH, '-idirafter': NORMALIZE_PATH, '-iframework': NORMALIZE_PATH, '-imacros': NORMALIZE_PATH, '-include': NORMALIZE_PATH, '-include-pch': NORMALIZE_PATH, '-iprefix': NORMALIZE_PATH, '-iquote': NORMALIZE_PATH, '-isysroot': NORMALIZE_PATH, '-isystem': NORMALIZE_PATH, '-isystem-after': NORMALIZE_PATH, '-ivfsoverlay': NORMALIZE_PATH, '-iwithprefixbefore': NORMALIZE_PATH, '-iwithsysroot': NORMALIZE_PATH, '-o': REMOVE, '-working-directory': NORMALIZE_PATH, } def ProcessOutput(args): """Run the program described by |args| and return its stdout as a stream. |stderr| and |stdin| will be set to /dev/null. Will raise CalledProcessError if the subprocess doesn't complete successfully. """ output = '' with open(os.devnull, 'w') as err: with open(os.devnull, 'r') as inp: output = subprocess.check_output(args, stderr=err, stdin=inp) return str(output).strip() def InitBazelConfig(): """Initialize globals based on Bazel configuration. Initialize COMPILATION_DATABASE_PATH, WORKSPACE_PATH, and CANONICAL_SOURCE_FILE based on Bazel. These values are not expected to change during the session.""" global COMPILATION_DATABASE_PATH global WORKSPACE_PATH global CANONICAL_SOURCE_FILE execution_root = ProcessOutput(['bazel', 'info', 'execution_root']) COMPILATION_DATABASE_PATH = os.path.join(execution_root, 'compile_commands.json') WORKSPACE_PATH = ProcessOutput(['bazel', 'info', 'workspace']) CANONICAL_SOURCE_FILE = ExpandAndNormalizePath(CANONICAL_SOURCE_FILE, WORKSPACE_PATH) def GenerateCompilationDatabaseSlowly(): """Generate compilation database. May take a while.""" script_path = os.path.join(WORKSPACE_PATH, 'tools', 'cpp', 'generate_compilation_database.sh') ProcessOutput(script_path) def ExpandAndNormalizePath(filename, basepath=WORKSPACE_PATH): """Resolves |filename| relative to |basepath| and expands symlinks.""" if not os.path.isabs(filename) and basepath: filename = os.path.join(basepath, filename) filename = os.path.realpath(filename) return str(filename) def PrepareCompileFlags(compile_command, basepath):
def LoadCompilationDatabase(): if not os.path.exists(COMPILATION_DATABASE_PATH): GenerateCompilationDatabaseSlowly() with open(COMPILATION_DATABASE_PATH, 'r') as database: database_dict = json.load(database) global COMPILATION_DATABASE COMPILATION_DATABASE = {} for entry in database_dict: filename = ExpandAndNormalizePath(entry['file'], WORKSPACE_PATH) directory = entry['directory'] command = entry['command'] COMPILATION_DATABASE[filename] = { 'command': command, 'directory': directory } def IsHeaderFile(filename): extension = os.path.splitext(filename)[1] return extension in HEADER_EXTENSIONS def FindAlternateFile(filename): if IsHeaderFile(filename): basename = os.path.splitext(filename)[0] for extension in SOURCE_EXTENSIONS: new_filename = basename + extension if new_filename in COMPILATION_DATABASE: return new_filename # Try something in the same directory. directory = os.path.dirname(filename) for key in COMPILATION_DATABASE.iterkeys(): if key.startswith(directory) and os.path.dirname(key) == directory: return key return CANONICAL_SOURCE_FILE # Entrypoint for YouCompleteMe. def FlagsForFile(filename, **kwargs): global LAST_INIT_FAILURE_TIME if len(COMPILATION_DATABASE) == 0: if LAST_INIT_FAILURE_TIME is not None and time.clock( ) - LAST_INIT_FAILURE_TIME < RETRY_TIMEOUT_SECONDS: return {'flags': DEFAULT_FLAGS} try: InitBazelConfig() LoadCompilationDatabase() except Exception as e: LAST_INIT_FAILURE_TIME = time.clock() return {'flags': DEFAULT_FLAGS} filename = str(os.path.realpath(filename)) if filename not in COMPILATION_DATABASE: filename = FindAlternateFile(filename) if filename not in COMPILATION_DATABASE: return {'flags': DEFAULT_FLAGS} result_dict = COMPILATION_DATABASE[filename] return { 'flags': PrepareCompileFlags(result_dict['command'], result_dict['directory']) } # For testing. if __name__ == '__main__': import sys print FlagsForFile(sys.argv[1])
flags = shlex.split(compile_command) flags_to_return = [] use_next_flag_as_value_for = None def HandleFlag(name, value, combine): disposition = CLANG_OPTION_DISPOSITION.get(name, None) if disposition is None and combine: disposition = CLANG_OPTION_DISPOSITION.get(name + '=', None) if disposition == REMOVE: return if disposition == NORMALIZE_PATH: value = ExpandAndNormalizePath(value, basepath) if combine: flags_to_return.append('{}={}'.format(name, value)) else: flags_to_return.extend([name, value]) for flag in flags: if use_next_flag_as_value_for is not None: name = use_next_flag_as_value_for use_next_flag_as_value_for = None HandleFlag(name, flag, combine=False) continue if '=' in flag: # -foo=bar name, value = flag.split('=', 1) HandleFlag(name, value, combine=True) continue if flag in CLANG_OPTION_DISPOSITION: use_next_flag_as_value_for = flag continue if flag.startswith('-I'): HandleFlag('-I', flags[3:], combine=False) continue flags_to_return.append(flag) return flags_to_return
identifier_body
.ycm_extra_conf.py
#!/usr/bin/python # Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # This .ycm_extra_conf will be picked up automatically for code completion using # YouCompleteMe. # # See https://valloric.github.io/YouCompleteMe/ for instructions on setting up # YouCompleteMe using Vim. This .ycm_extra_conf file also works with any other # completion engine that uses YCMD (https://github.com/Valloric/ycmd). # # Code completion depends on a Clang compilation database. This is placed in a # file named `compile_commands.json` in your execution root path. I.e. it will # be at the path returned by `bazel info execution_root`. # # If the compilation database isn't available, this script will generate one # using tools/cpp/generate_compilation_database.sh. This process can be slow if # you haven't built the sources yet. It's always a good idea to run # generate_compilation_database.sh manually so that you can see the build output # including any errors encountered during compile command generation. # ============================================================================== import json import os import shlex import subprocess import time # If all else fails, then return this list of flags. DEFAULT_FLAGS = [] CANONICAL_SOURCE_FILE = 'kythe/cxx/extractor/cxx_extractor_main.cc' # Full path to directory containing compilation database. This is usually # |execution_root|/compile_commands.json. COMPILATION_DATABASE_PATH = None # Workspace path. WORKSPACE_PATH = None # The compilation database. This is a mapping from the absolute normalized path # of the source file to it's compile command broken down into an array. COMPILATION_DATABASE = {} # If loading the compilation database failed for some reason, # LAST_INIT_FAILURE_TIME contains the value of time.clock() at the time the # failure was encountered. LAST_INIT_FAILURE_TIME = None # If this many seconds have passed since the last failure, then try to generate # the compilation database again. RETRY_TIMEOUT_SECONDS = 120 HEADER_EXTENSIONS = ['.h', '.hpp', '.hh', '.hxx'] SOURCE_EXTENSIONS = ['.cc', '.cpp', '.c', '.m', '.mm', '.cxx'] NORMALIZE_PATH = 1 REMOVE = 2 # List of clang options and what to do with them. Use the '-foo' form for flags # that could be used as '-foo <arg>' and '-foo=<arg>' forms, and use '-foo=' for # flags that can only be used as '-foo=<arg>'. # # Mapping a flag to NORMALIZE_PATH causes its argument to be normalized against # the build directory via ExpandAndNormalizePath(). REMOVE causes both the flag # and its value to be removed. CLANG_OPTION_DISPOSITION = { '-I': NORMALIZE_PATH, '-MF': REMOVE, '-cxx-isystem': NORMALIZE_PATH, '-dependency-dot': REMOVE, '-dependency-file': REMOVE, '-fbuild-session-file': REMOVE, '-fmodule-file': NORMALIZE_PATH, '-fmodule-map-file': NORMALIZE_PATH, '-foptimization-record-file': REMOVE, '-fprebuilt-module-path': NORMALIZE_PATH, '-fprofile-generate=': REMOVE, '-fprofile-instrument-generate=': REMOVE, '-fprofile-user=': REMOVE, '-gcc-tollchain=': NORMALIZE_PATH, '-idirafter': NORMALIZE_PATH, '-iframework': NORMALIZE_PATH, '-imacros': NORMALIZE_PATH, '-include': NORMALIZE_PATH, '-include-pch': NORMALIZE_PATH, '-iprefix': NORMALIZE_PATH, '-iquote': NORMALIZE_PATH, '-isysroot': NORMALIZE_PATH, '-isystem': NORMALIZE_PATH, '-isystem-after': NORMALIZE_PATH, '-ivfsoverlay': NORMALIZE_PATH, '-iwithprefixbefore': NORMALIZE_PATH, '-iwithsysroot': NORMALIZE_PATH, '-o': REMOVE, '-working-directory': NORMALIZE_PATH, } def ProcessOutput(args): """Run the program described by |args| and return its stdout as a stream. |stderr| and |stdin| will be set to /dev/null. Will raise CalledProcessError if the subprocess doesn't complete successfully. """ output = '' with open(os.devnull, 'w') as err: with open(os.devnull, 'r') as inp: output = subprocess.check_output(args, stderr=err, stdin=inp) return str(output).strip() def InitBazelConfig(): """Initialize globals based on Bazel configuration. Initialize COMPILATION_DATABASE_PATH, WORKSPACE_PATH, and CANONICAL_SOURCE_FILE based on Bazel. These values are not expected to change during the session.""" global COMPILATION_DATABASE_PATH global WORKSPACE_PATH global CANONICAL_SOURCE_FILE execution_root = ProcessOutput(['bazel', 'info', 'execution_root']) COMPILATION_DATABASE_PATH = os.path.join(execution_root, 'compile_commands.json') WORKSPACE_PATH = ProcessOutput(['bazel', 'info', 'workspace']) CANONICAL_SOURCE_FILE = ExpandAndNormalizePath(CANONICAL_SOURCE_FILE, WORKSPACE_PATH) def GenerateCompilationDatabaseSlowly(): """Generate compilation database. May take a while.""" script_path = os.path.join(WORKSPACE_PATH, 'tools', 'cpp', 'generate_compilation_database.sh') ProcessOutput(script_path) def ExpandAndNormalizePath(filename, basepath=WORKSPACE_PATH): """Resolves |filename| relative to |basepath| and expands symlinks.""" if not os.path.isabs(filename) and basepath: filename = os.path.join(basepath, filename) filename = os.path.realpath(filename) return str(filename) def PrepareCompileFlags(compile_command, basepath): flags = shlex.split(compile_command) flags_to_return = [] use_next_flag_as_value_for = None def HandleFlag(name, value, combine): disposition = CLANG_OPTION_DISPOSITION.get(name, None) if disposition is None and combine: disposition = CLANG_OPTION_DISPOSITION.get(name + '=', None) if disposition == REMOVE: return if disposition == NORMALIZE_PATH: value = ExpandAndNormalizePath(value, basepath) if combine: flags_to_return.append('{}={}'.format(name, value)) else: flags_to_return.extend([name, value]) for flag in flags: if use_next_flag_as_value_for is not None: name = use_next_flag_as_value_for use_next_flag_as_value_for = None HandleFlag(name, flag, combine=False) continue if '=' in flag: # -foo=bar name, value = flag.split('=', 1) HandleFlag(name, value, combine=True) continue if flag in CLANG_OPTION_DISPOSITION: use_next_flag_as_value_for = flag continue if flag.startswith('-I'): HandleFlag('-I', flags[3:], combine=False) continue flags_to_return.append(flag) return flags_to_return def LoadCompilationDatabase(): if not os.path.exists(COMPILATION_DATABASE_PATH): GenerateCompilationDatabaseSlowly() with open(COMPILATION_DATABASE_PATH, 'r') as database: database_dict = json.load(database) global COMPILATION_DATABASE COMPILATION_DATABASE = {} for entry in database_dict: filename = ExpandAndNormalizePath(entry['file'], WORKSPACE_PATH) directory = entry['directory'] command = entry['command'] COMPILATION_DATABASE[filename] = { 'command': command, 'directory': directory } def IsHeaderFile(filename): extension = os.path.splitext(filename)[1] return extension in HEADER_EXTENSIONS def FindAlternateFile(filename): if IsHeaderFile(filename):
# Try something in the same directory. directory = os.path.dirname(filename) for key in COMPILATION_DATABASE.iterkeys(): if key.startswith(directory) and os.path.dirname(key) == directory: return key return CANONICAL_SOURCE_FILE # Entrypoint for YouCompleteMe. def FlagsForFile(filename, **kwargs): global LAST_INIT_FAILURE_TIME if len(COMPILATION_DATABASE) == 0: if LAST_INIT_FAILURE_TIME is not None and time.clock( ) - LAST_INIT_FAILURE_TIME < RETRY_TIMEOUT_SECONDS: return {'flags': DEFAULT_FLAGS} try: InitBazelConfig() LoadCompilationDatabase() except Exception as e: LAST_INIT_FAILURE_TIME = time.clock() return {'flags': DEFAULT_FLAGS} filename = str(os.path.realpath(filename)) if filename not in COMPILATION_DATABASE: filename = FindAlternateFile(filename) if filename not in COMPILATION_DATABASE: return {'flags': DEFAULT_FLAGS} result_dict = COMPILATION_DATABASE[filename] return { 'flags': PrepareCompileFlags(result_dict['command'], result_dict['directory']) } # For testing. if __name__ == '__main__': import sys print FlagsForFile(sys.argv[1])
basename = os.path.splitext(filename)[0] for extension in SOURCE_EXTENSIONS: new_filename = basename + extension if new_filename in COMPILATION_DATABASE: return new_filename
conditional_block
HealthDataManager.js
/* * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, console */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), UrlParams = brackets.getModule("utils/UrlParams").UrlParams, Strings = brackets.getModule("strings"), HealthDataUtils = require("HealthDataUtils"), uuid = require("thirdparty/uuid"); var prefs = PreferencesManager.getExtensionPrefs("healthData"); prefs.definePreference("healthDataTracking", "boolean", true, { description: Strings.DESCRIPTION_HEALTH_DATA_TRACKING }); var ONE_MINUTE = 60 * 1000, ONE_DAY = 24 * 60 * ONE_MINUTE, FIRST_LAUNCH_SEND_DELAY = 30 * ONE_MINUTE, timeoutVar; var params = new UrlParams(); params.parse(); /** * Get the Health Data which will be sent to the server. Initially it is only one time data. */ function getHealthData() { var result = new $.Deferred(), oneTimeHealthData = {}; var userUuid = PreferencesManager.getViewState("UUID"); if (!userUuid) { userUuid = uuid.v4(); PreferencesManager.setViewState("UUID", userUuid); } oneTimeHealthData.uuid = userUuid; oneTimeHealthData.snapshotTime = Date.now(); oneTimeHealthData.os = brackets.platform; oneTimeHealthData.userAgent = navigator.userAgent; oneTimeHealthData.osLanguage = brackets.app.language; oneTimeHealthData.bracketsLanguage = brackets.getLocale(); oneTimeHealthData.bracketsVersion = brackets.metadata.version; HealthDataUtils.getUserInstalledExtensions() .done(function (userInstalledExtensions) { oneTimeHealthData.installedExtensions = userInstalledExtensions; }) .always(function () { return result.resolve(oneTimeHealthData); }); return result.promise(); } /** * Send data to the server */ function sendHealthDataToServer() { var result = new $.Deferred(); getHealthData().done(function (healthData) { var url = brackets.config.healthDataServerURL, data = JSON.stringify(healthData); $.ajax({ url: url,
contentType: "text/plain" }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); } /* * Check if the Health Data is to be sent to the server. If the user has enabled tracking, Health Data will be sent once every 24 hours. * Send Health Data to the server if the period is more than 24 hours. * We are sending the data as soon as the user launches brackets. The data will be sent to the server only after the notification dialog * for opt-out/in is closed. */ function checkHealthDataSend() { var result = new $.Deferred(), isHDTracking = prefs.get("healthDataTracking"); window.clearTimeout(timeoutVar); if (isHDTracking) { var nextTimeToSend = PreferencesManager.getViewState("nextHealthDataSendTime"), currentTime = Date.now(); // Never send data before FIRST_LAUNCH_SEND_DELAY has ellapsed on a fresh install. This gives the user time to read the notification // popup, learn more, and opt out if desired if (!nextTimeToSend) { nextTimeToSend = currentTime + FIRST_LAUNCH_SEND_DELAY; PreferencesManager.setViewState("nextHealthDataSendTime", nextTimeToSend); // don't return yet though - still want to set the timeout below } if (currentTime >= nextTimeToSend) { // Bump up nextHealthDataSendTime now to avoid any chance of sending data again before 24 hours, e.g. if the server request fails // or the code below crashes PreferencesManager.setViewState("nextHealthDataSendTime", currentTime + ONE_DAY); sendHealthDataToServer() .done(function () { result.resolve(); }) .fail(function () { result.reject(); }) .always(function () { timeoutVar = setTimeout(checkHealthDataSend, ONE_DAY); }); } else { timeoutVar = setTimeout(checkHealthDataSend, nextTimeToSend - currentTime); result.reject(); } } else { result.reject(); } return result.promise(); } prefs.on("change", "healthDataTracking", function () { checkHealthDataSend(); }); window.addEventListener("online", function () { checkHealthDataSend(); }); window.addEventListener("offline", function () { window.clearTimeout(timeoutVar); }); AppInit.appReady(function () { checkHealthDataSend(); }); exports.getHealthData = getHealthData; exports.checkHealthDataSend = checkHealthDataSend; });
type: "POST", data: data, dataType: "text",
random_line_split
HealthDataManager.js
/* * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, console */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), UrlParams = brackets.getModule("utils/UrlParams").UrlParams, Strings = brackets.getModule("strings"), HealthDataUtils = require("HealthDataUtils"), uuid = require("thirdparty/uuid"); var prefs = PreferencesManager.getExtensionPrefs("healthData"); prefs.definePreference("healthDataTracking", "boolean", true, { description: Strings.DESCRIPTION_HEALTH_DATA_TRACKING }); var ONE_MINUTE = 60 * 1000, ONE_DAY = 24 * 60 * ONE_MINUTE, FIRST_LAUNCH_SEND_DELAY = 30 * ONE_MINUTE, timeoutVar; var params = new UrlParams(); params.parse(); /** * Get the Health Data which will be sent to the server. Initially it is only one time data. */ function getHealthData()
/** * Send data to the server */ function sendHealthDataToServer() { var result = new $.Deferred(); getHealthData().done(function (healthData) { var url = brackets.config.healthDataServerURL, data = JSON.stringify(healthData); $.ajax({ url: url, type: "POST", data: data, dataType: "text", contentType: "text/plain" }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); } /* * Check if the Health Data is to be sent to the server. If the user has enabled tracking, Health Data will be sent once every 24 hours. * Send Health Data to the server if the period is more than 24 hours. * We are sending the data as soon as the user launches brackets. The data will be sent to the server only after the notification dialog * for opt-out/in is closed. */ function checkHealthDataSend() { var result = new $.Deferred(), isHDTracking = prefs.get("healthDataTracking"); window.clearTimeout(timeoutVar); if (isHDTracking) { var nextTimeToSend = PreferencesManager.getViewState("nextHealthDataSendTime"), currentTime = Date.now(); // Never send data before FIRST_LAUNCH_SEND_DELAY has ellapsed on a fresh install. This gives the user time to read the notification // popup, learn more, and opt out if desired if (!nextTimeToSend) { nextTimeToSend = currentTime + FIRST_LAUNCH_SEND_DELAY; PreferencesManager.setViewState("nextHealthDataSendTime", nextTimeToSend); // don't return yet though - still want to set the timeout below } if (currentTime >= nextTimeToSend) { // Bump up nextHealthDataSendTime now to avoid any chance of sending data again before 24 hours, e.g. if the server request fails // or the code below crashes PreferencesManager.setViewState("nextHealthDataSendTime", currentTime + ONE_DAY); sendHealthDataToServer() .done(function () { result.resolve(); }) .fail(function () { result.reject(); }) .always(function () { timeoutVar = setTimeout(checkHealthDataSend, ONE_DAY); }); } else { timeoutVar = setTimeout(checkHealthDataSend, nextTimeToSend - currentTime); result.reject(); } } else { result.reject(); } return result.promise(); } prefs.on("change", "healthDataTracking", function () { checkHealthDataSend(); }); window.addEventListener("online", function () { checkHealthDataSend(); }); window.addEventListener("offline", function () { window.clearTimeout(timeoutVar); }); AppInit.appReady(function () { checkHealthDataSend(); }); exports.getHealthData = getHealthData; exports.checkHealthDataSend = checkHealthDataSend; });
{ var result = new $.Deferred(), oneTimeHealthData = {}; var userUuid = PreferencesManager.getViewState("UUID"); if (!userUuid) { userUuid = uuid.v4(); PreferencesManager.setViewState("UUID", userUuid); } oneTimeHealthData.uuid = userUuid; oneTimeHealthData.snapshotTime = Date.now(); oneTimeHealthData.os = brackets.platform; oneTimeHealthData.userAgent = navigator.userAgent; oneTimeHealthData.osLanguage = brackets.app.language; oneTimeHealthData.bracketsLanguage = brackets.getLocale(); oneTimeHealthData.bracketsVersion = brackets.metadata.version; HealthDataUtils.getUserInstalledExtensions() .done(function (userInstalledExtensions) { oneTimeHealthData.installedExtensions = userInstalledExtensions; }) .always(function () { return result.resolve(oneTimeHealthData); }); return result.promise(); }
identifier_body
HealthDataManager.js
/* * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, console */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), UrlParams = brackets.getModule("utils/UrlParams").UrlParams, Strings = brackets.getModule("strings"), HealthDataUtils = require("HealthDataUtils"), uuid = require("thirdparty/uuid"); var prefs = PreferencesManager.getExtensionPrefs("healthData"); prefs.definePreference("healthDataTracking", "boolean", true, { description: Strings.DESCRIPTION_HEALTH_DATA_TRACKING }); var ONE_MINUTE = 60 * 1000, ONE_DAY = 24 * 60 * ONE_MINUTE, FIRST_LAUNCH_SEND_DELAY = 30 * ONE_MINUTE, timeoutVar; var params = new UrlParams(); params.parse(); /** * Get the Health Data which will be sent to the server. Initially it is only one time data. */ function getHealthData() { var result = new $.Deferred(), oneTimeHealthData = {}; var userUuid = PreferencesManager.getViewState("UUID"); if (!userUuid) { userUuid = uuid.v4(); PreferencesManager.setViewState("UUID", userUuid); } oneTimeHealthData.uuid = userUuid; oneTimeHealthData.snapshotTime = Date.now(); oneTimeHealthData.os = brackets.platform; oneTimeHealthData.userAgent = navigator.userAgent; oneTimeHealthData.osLanguage = brackets.app.language; oneTimeHealthData.bracketsLanguage = brackets.getLocale(); oneTimeHealthData.bracketsVersion = brackets.metadata.version; HealthDataUtils.getUserInstalledExtensions() .done(function (userInstalledExtensions) { oneTimeHealthData.installedExtensions = userInstalledExtensions; }) .always(function () { return result.resolve(oneTimeHealthData); }); return result.promise(); } /** * Send data to the server */ function sendHealthDataToServer() { var result = new $.Deferred(); getHealthData().done(function (healthData) { var url = brackets.config.healthDataServerURL, data = JSON.stringify(healthData); $.ajax({ url: url, type: "POST", data: data, dataType: "text", contentType: "text/plain" }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); } /* * Check if the Health Data is to be sent to the server. If the user has enabled tracking, Health Data will be sent once every 24 hours. * Send Health Data to the server if the period is more than 24 hours. * We are sending the data as soon as the user launches brackets. The data will be sent to the server only after the notification dialog * for opt-out/in is closed. */ function
() { var result = new $.Deferred(), isHDTracking = prefs.get("healthDataTracking"); window.clearTimeout(timeoutVar); if (isHDTracking) { var nextTimeToSend = PreferencesManager.getViewState("nextHealthDataSendTime"), currentTime = Date.now(); // Never send data before FIRST_LAUNCH_SEND_DELAY has ellapsed on a fresh install. This gives the user time to read the notification // popup, learn more, and opt out if desired if (!nextTimeToSend) { nextTimeToSend = currentTime + FIRST_LAUNCH_SEND_DELAY; PreferencesManager.setViewState("nextHealthDataSendTime", nextTimeToSend); // don't return yet though - still want to set the timeout below } if (currentTime >= nextTimeToSend) { // Bump up nextHealthDataSendTime now to avoid any chance of sending data again before 24 hours, e.g. if the server request fails // or the code below crashes PreferencesManager.setViewState("nextHealthDataSendTime", currentTime + ONE_DAY); sendHealthDataToServer() .done(function () { result.resolve(); }) .fail(function () { result.reject(); }) .always(function () { timeoutVar = setTimeout(checkHealthDataSend, ONE_DAY); }); } else { timeoutVar = setTimeout(checkHealthDataSend, nextTimeToSend - currentTime); result.reject(); } } else { result.reject(); } return result.promise(); } prefs.on("change", "healthDataTracking", function () { checkHealthDataSend(); }); window.addEventListener("online", function () { checkHealthDataSend(); }); window.addEventListener("offline", function () { window.clearTimeout(timeoutVar); }); AppInit.appReady(function () { checkHealthDataSend(); }); exports.getHealthData = getHealthData; exports.checkHealthDataSend = checkHealthDataSend; });
checkHealthDataSend
identifier_name
HealthDataManager.js
/* * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, console */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), UrlParams = brackets.getModule("utils/UrlParams").UrlParams, Strings = brackets.getModule("strings"), HealthDataUtils = require("HealthDataUtils"), uuid = require("thirdparty/uuid"); var prefs = PreferencesManager.getExtensionPrefs("healthData"); prefs.definePreference("healthDataTracking", "boolean", true, { description: Strings.DESCRIPTION_HEALTH_DATA_TRACKING }); var ONE_MINUTE = 60 * 1000, ONE_DAY = 24 * 60 * ONE_MINUTE, FIRST_LAUNCH_SEND_DELAY = 30 * ONE_MINUTE, timeoutVar; var params = new UrlParams(); params.parse(); /** * Get the Health Data which will be sent to the server. Initially it is only one time data. */ function getHealthData() { var result = new $.Deferred(), oneTimeHealthData = {}; var userUuid = PreferencesManager.getViewState("UUID"); if (!userUuid) { userUuid = uuid.v4(); PreferencesManager.setViewState("UUID", userUuid); } oneTimeHealthData.uuid = userUuid; oneTimeHealthData.snapshotTime = Date.now(); oneTimeHealthData.os = brackets.platform; oneTimeHealthData.userAgent = navigator.userAgent; oneTimeHealthData.osLanguage = brackets.app.language; oneTimeHealthData.bracketsLanguage = brackets.getLocale(); oneTimeHealthData.bracketsVersion = brackets.metadata.version; HealthDataUtils.getUserInstalledExtensions() .done(function (userInstalledExtensions) { oneTimeHealthData.installedExtensions = userInstalledExtensions; }) .always(function () { return result.resolve(oneTimeHealthData); }); return result.promise(); } /** * Send data to the server */ function sendHealthDataToServer() { var result = new $.Deferred(); getHealthData().done(function (healthData) { var url = brackets.config.healthDataServerURL, data = JSON.stringify(healthData); $.ajax({ url: url, type: "POST", data: data, dataType: "text", contentType: "text/plain" }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); } /* * Check if the Health Data is to be sent to the server. If the user has enabled tracking, Health Data will be sent once every 24 hours. * Send Health Data to the server if the period is more than 24 hours. * We are sending the data as soon as the user launches brackets. The data will be sent to the server only after the notification dialog * for opt-out/in is closed. */ function checkHealthDataSend() { var result = new $.Deferred(), isHDTracking = prefs.get("healthDataTracking"); window.clearTimeout(timeoutVar); if (isHDTracking) { var nextTimeToSend = PreferencesManager.getViewState("nextHealthDataSendTime"), currentTime = Date.now(); // Never send data before FIRST_LAUNCH_SEND_DELAY has ellapsed on a fresh install. This gives the user time to read the notification // popup, learn more, and opt out if desired if (!nextTimeToSend)
if (currentTime >= nextTimeToSend) { // Bump up nextHealthDataSendTime now to avoid any chance of sending data again before 24 hours, e.g. if the server request fails // or the code below crashes PreferencesManager.setViewState("nextHealthDataSendTime", currentTime + ONE_DAY); sendHealthDataToServer() .done(function () { result.resolve(); }) .fail(function () { result.reject(); }) .always(function () { timeoutVar = setTimeout(checkHealthDataSend, ONE_DAY); }); } else { timeoutVar = setTimeout(checkHealthDataSend, nextTimeToSend - currentTime); result.reject(); } } else { result.reject(); } return result.promise(); } prefs.on("change", "healthDataTracking", function () { checkHealthDataSend(); }); window.addEventListener("online", function () { checkHealthDataSend(); }); window.addEventListener("offline", function () { window.clearTimeout(timeoutVar); }); AppInit.appReady(function () { checkHealthDataSend(); }); exports.getHealthData = getHealthData; exports.checkHealthDataSend = checkHealthDataSend; });
{ nextTimeToSend = currentTime + FIRST_LAUNCH_SEND_DELAY; PreferencesManager.setViewState("nextHealthDataSendTime", nextTimeToSend); // don't return yet though - still want to set the timeout below }
conditional_block
util.js
/** * @fileoverview Common utilities. */ "use strict"; //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var PLUGIN_NAME_PREFIX = "eslint-plugin-", NAMESPACE_REGEX = /^@.*\//i; //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * Merges two config objects. This will not only add missing keys, but will also modify values to match. * @param {Object} target config object * @param {Object} src config object. Overrides in this config object will take priority over base. * @param {boolean} [combine] Whether to combine arrays or not * @returns {Object} merged config object. */ exports.mergeConfigs = function deepmerge(target, src, combine) { /* The MIT License (MIT) Copyright (c) 2012 Nicholas Fisher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This code is taken from deepmerge repo (https://github.com/KyleAMathews/deepmerge) and modified to meet our needs. var array = Array.isArray(src) || Array.isArray(target); var dst = array && [] || {}; combine = !!combine; if (array) { target = target || []; dst = dst.concat(target); if (typeof src !== "object" && !Array.isArray(src)) { src = [src]; } Object.keys(src).forEach(function(e, i) { e = src[i]; if (typeof dst[i] === "undefined") { dst[i] = e; } else if (typeof e === "object") { dst[i] = deepmerge(target[i], e); } else { if (!combine) { dst[i] = e; } else { if (dst.indexOf(e) === -1) { dst.push(e); } } }
Object.keys(target).forEach(function(key) { dst[key] = target[key]; }); } Object.keys(src).forEach(function(key) { if (Array.isArray(src[key]) || Array.isArray(target[key])) { dst[key] = deepmerge(target[key], src[key], key === "plugins"); } else if (typeof src[key] !== "object" || !src[key]) { dst[key] = src[key]; } else { if (!target[key]) { dst[key] = src[key]; } else { dst[key] = deepmerge(target[key], src[key]); } } }); } return dst; }; /** * Removes the prefix `eslint-plugin-` from a plugin name. * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugin without prefix. */ exports.removePluginPrefix = function removePluginPrefix(pluginName) { return pluginName.indexOf(PLUGIN_NAME_PREFIX) === 0 ? pluginName.substring(PLUGIN_NAME_PREFIX.length) : pluginName; }; /** * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugins namepace if it has one. */ exports.getNamespace = function getNamespace(pluginName) { return pluginName.match(NAMESPACE_REGEX) ? pluginName.match(NAMESPACE_REGEX)[0] : ""; }; /** * Removes the namespace from a plugin name. * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugin without the namespace. */ exports.removeNameSpace = function removeNameSpace(pluginName) { return pluginName.replace(NAMESPACE_REGEX, ""); }; exports.PLUGIN_NAME_PREFIX = PLUGIN_NAME_PREFIX;
}); } else { if (target && typeof target === "object") {
random_line_split
util.js
/** * @fileoverview Common utilities. */ "use strict"; //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var PLUGIN_NAME_PREFIX = "eslint-plugin-", NAMESPACE_REGEX = /^@.*\//i; //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * Merges two config objects. This will not only add missing keys, but will also modify values to match. * @param {Object} target config object * @param {Object} src config object. Overrides in this config object will take priority over base. * @param {boolean} [combine] Whether to combine arrays or not * @returns {Object} merged config object. */ exports.mergeConfigs = function deepmerge(target, src, combine) { /* The MIT License (MIT) Copyright (c) 2012 Nicholas Fisher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This code is taken from deepmerge repo (https://github.com/KyleAMathews/deepmerge) and modified to meet our needs. var array = Array.isArray(src) || Array.isArray(target); var dst = array && [] || {}; combine = !!combine; if (array) { target = target || []; dst = dst.concat(target); if (typeof src !== "object" && !Array.isArray(src)) { src = [src]; } Object.keys(src).forEach(function(e, i) { e = src[i]; if (typeof dst[i] === "undefined") { dst[i] = e; } else if (typeof e === "object") { dst[i] = deepmerge(target[i], e); } else { if (!combine) { dst[i] = e; } else
} }); } else { if (target && typeof target === "object") { Object.keys(target).forEach(function(key) { dst[key] = target[key]; }); } Object.keys(src).forEach(function(key) { if (Array.isArray(src[key]) || Array.isArray(target[key])) { dst[key] = deepmerge(target[key], src[key], key === "plugins"); } else if (typeof src[key] !== "object" || !src[key]) { dst[key] = src[key]; } else { if (!target[key]) { dst[key] = src[key]; } else { dst[key] = deepmerge(target[key], src[key]); } } }); } return dst; }; /** * Removes the prefix `eslint-plugin-` from a plugin name. * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugin without prefix. */ exports.removePluginPrefix = function removePluginPrefix(pluginName) { return pluginName.indexOf(PLUGIN_NAME_PREFIX) === 0 ? pluginName.substring(PLUGIN_NAME_PREFIX.length) : pluginName; }; /** * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugins namepace if it has one. */ exports.getNamespace = function getNamespace(pluginName) { return pluginName.match(NAMESPACE_REGEX) ? pluginName.match(NAMESPACE_REGEX)[0] : ""; }; /** * Removes the namespace from a plugin name. * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugin without the namespace. */ exports.removeNameSpace = function removeNameSpace(pluginName) { return pluginName.replace(NAMESPACE_REGEX, ""); }; exports.PLUGIN_NAME_PREFIX = PLUGIN_NAME_PREFIX;
{ if (dst.indexOf(e) === -1) { dst.push(e); } }
conditional_block
relay.js
/** * React Starter Kit for Firebase * https://github.com/kriasoft/react-firebase-starter * Copyright (c) 2015-present Kriasoft | MIT License */ import { graphql } from 'graphql'; import { Environment, Network, RecordSource, Store } from 'relay-runtime'; import schema from './schema'; import { Context } from './context'; export function
(req) { function fetchQuery(operation, variables, cacheConfig) { return graphql({ schema, source: operation.text, contextValue: new Context(req), variableValues: variables, operationName: operation.name, }).then(payload => { // Passes the raw payload up to the caller (see src/router.js). // This is needed in order to hydrate/de-hydrate that // data on the client during the initial page load. cacheConfig.payload = payload; return payload; }); } const recordSource = new RecordSource(); const store = new Store(recordSource); const network = Network.create(fetchQuery); return new Environment({ store, network }); }
createRelay
identifier_name
relay.js
/** * React Starter Kit for Firebase * https://github.com/kriasoft/react-firebase-starter * Copyright (c) 2015-present Kriasoft | MIT License */ import { graphql } from 'graphql'; import { Environment, Network, RecordSource, Store } from 'relay-runtime'; import schema from './schema'; import { Context } from './context';
contextValue: new Context(req), variableValues: variables, operationName: operation.name, }).then(payload => { // Passes the raw payload up to the caller (see src/router.js). // This is needed in order to hydrate/de-hydrate that // data on the client during the initial page load. cacheConfig.payload = payload; return payload; }); } const recordSource = new RecordSource(); const store = new Store(recordSource); const network = Network.create(fetchQuery); return new Environment({ store, network }); }
export function createRelay(req) { function fetchQuery(operation, variables, cacheConfig) { return graphql({ schema, source: operation.text,
random_line_split
relay.js
/** * React Starter Kit for Firebase * https://github.com/kriasoft/react-firebase-starter * Copyright (c) 2015-present Kriasoft | MIT License */ import { graphql } from 'graphql'; import { Environment, Network, RecordSource, Store } from 'relay-runtime'; import schema from './schema'; import { Context } from './context'; export function createRelay(req) { function fetchQuery(operation, variables, cacheConfig)
const recordSource = new RecordSource(); const store = new Store(recordSource); const network = Network.create(fetchQuery); return new Environment({ store, network }); }
{ return graphql({ schema, source: operation.text, contextValue: new Context(req), variableValues: variables, operationName: operation.name, }).then(payload => { // Passes the raw payload up to the caller (see src/router.js). // This is needed in order to hydrate/de-hydrate that // data on the client during the initial page load. cacheConfig.payload = payload; return payload; }); }
identifier_body
binops.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Binop corner cases fn test_nil() { assert!((() == ())); assert!((!(() != ()))); assert!((!(() < ()))); assert!((() <= ())); assert!((!(() > ()))); assert!((() >= ())); } fn test_bool() { assert!((!(true < false))); assert!((!(true <= false))); assert!((true > false)); assert!((true >= false)); assert!((false < true)); assert!((false <= true)); assert!((!(false > true))); assert!((!(false >= true))); // Bools support bitwise binops assert!((false & false == false)); assert!((true & false == false)); assert!((true & true == true)); assert!((false | false == false)); assert!((true | false == true)); assert!((true | true == true)); assert!((false ^ false == false)); assert!((true ^ false == true)); assert!((true ^ true == false)); } fn test_char() { let ch10 = 10 as char; let ch4 = 4 as char; let ch2 = 2 as char; assert!((ch10 + ch4 == 14 as char)); assert!((ch10 - ch4 == 6 as char)); assert!((ch10 * ch4 == 40 as char)); assert!((ch10 / ch4 == ch2)); assert!((ch10 % ch4 == ch2)); assert!((ch10 >> ch2 == ch2)); assert!((ch10 << ch4 == 160 as char)); assert!((ch10 | ch4 == 14 as char)); assert!((ch10 & ch2 == ch2)); assert!((ch10 ^ ch2 == 8 as char)); } fn test_box() { assert!((@10 == @10)); } fn test_ptr() { unsafe { let p1: *u8 = ::core::cast::reinterpret_cast(&0); let p2: *u8 = ::core::cast::reinterpret_cast(&0); let p3: *u8 = ::core::cast::reinterpret_cast(&1); assert!(p1 == p2); assert!(p1 != p3); assert!(p1 < p3); assert!(p1 <= p3); assert!(p3 > p1); assert!(p3 >= p3); assert!(p1 <= p2); assert!(p1 >= p2); } } mod test { #[abi = "cdecl"] #[nolink] pub extern { pub fn rust_get_sched_id() -> libc::intptr_t; pub fn get_task_id() -> libc::intptr_t; } } #[deriving(Eq)] struct p { x: int, y: int, } fn p(x: int, y: int) -> p
fn test_class() { let mut q = p(1, 2); let mut r = p(1, 2); unsafe { error!("q = %x, r = %x", (::core::cast::reinterpret_cast::<*p, uint>(&ptr::addr_of(&q))), (::core::cast::reinterpret_cast::<*p, uint>(&ptr::addr_of(&r)))); } assert!((q == r)); r.y = 17; assert!((r.y != q.y)); assert!((r.y == 17)); assert!((q != r)); } pub fn main() { test_nil(); test_bool(); test_char(); test_box(); test_ptr(); test_class(); }
{ p { x: x, y: y } }
identifier_body
binops.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Binop corner cases fn test_nil() { assert!((() == ())); assert!((!(() != ()))); assert!((!(() < ()))); assert!((() <= ())); assert!((!(() > ()))); assert!((() >= ())); } fn test_bool() { assert!((!(true < false))); assert!((!(true <= false))); assert!((true > false)); assert!((true >= false)); assert!((false < true)); assert!((false <= true)); assert!((!(false > true))); assert!((!(false >= true))); // Bools support bitwise binops assert!((false & false == false)); assert!((true & false == false)); assert!((true & true == true)); assert!((false | false == false)); assert!((true | false == true)); assert!((true | true == true)); assert!((false ^ false == false)); assert!((true ^ false == true)); assert!((true ^ true == false)); } fn test_char() { let ch10 = 10 as char; let ch4 = 4 as char; let ch2 = 2 as char; assert!((ch10 + ch4 == 14 as char)); assert!((ch10 - ch4 == 6 as char)); assert!((ch10 * ch4 == 40 as char)); assert!((ch10 / ch4 == ch2)); assert!((ch10 % ch4 == ch2)); assert!((ch10 >> ch2 == ch2)); assert!((ch10 << ch4 == 160 as char)); assert!((ch10 | ch4 == 14 as char)); assert!((ch10 & ch2 == ch2)); assert!((ch10 ^ ch2 == 8 as char)); } fn test_box() { assert!((@10 == @10)); } fn test_ptr() { unsafe { let p1: *u8 = ::core::cast::reinterpret_cast(&0); let p2: *u8 = ::core::cast::reinterpret_cast(&0); let p3: *u8 = ::core::cast::reinterpret_cast(&1); assert!(p1 == p2); assert!(p1 != p3); assert!(p1 < p3); assert!(p1 <= p3); assert!(p3 > p1); assert!(p3 >= p3); assert!(p1 <= p2); assert!(p1 >= p2); } } mod test { #[abi = "cdecl"] #[nolink] pub extern { pub fn rust_get_sched_id() -> libc::intptr_t; pub fn get_task_id() -> libc::intptr_t; } } #[deriving(Eq)] struct p { x: int, y: int, } fn p(x: int, y: int) -> p { p { x: x, y: y } } fn
() { let mut q = p(1, 2); let mut r = p(1, 2); unsafe { error!("q = %x, r = %x", (::core::cast::reinterpret_cast::<*p, uint>(&ptr::addr_of(&q))), (::core::cast::reinterpret_cast::<*p, uint>(&ptr::addr_of(&r)))); } assert!((q == r)); r.y = 17; assert!((r.y != q.y)); assert!((r.y == 17)); assert!((q != r)); } pub fn main() { test_nil(); test_bool(); test_char(); test_box(); test_ptr(); test_class(); }
test_class
identifier_name
binops.rs
// 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. // Binop corner cases fn test_nil() { assert!((() == ())); assert!((!(() != ()))); assert!((!(() < ()))); assert!((() <= ())); assert!((!(() > ()))); assert!((() >= ())); } fn test_bool() { assert!((!(true < false))); assert!((!(true <= false))); assert!((true > false)); assert!((true >= false)); assert!((false < true)); assert!((false <= true)); assert!((!(false > true))); assert!((!(false >= true))); // Bools support bitwise binops assert!((false & false == false)); assert!((true & false == false)); assert!((true & true == true)); assert!((false | false == false)); assert!((true | false == true)); assert!((true | true == true)); assert!((false ^ false == false)); assert!((true ^ false == true)); assert!((true ^ true == false)); } fn test_char() { let ch10 = 10 as char; let ch4 = 4 as char; let ch2 = 2 as char; assert!((ch10 + ch4 == 14 as char)); assert!((ch10 - ch4 == 6 as char)); assert!((ch10 * ch4 == 40 as char)); assert!((ch10 / ch4 == ch2)); assert!((ch10 % ch4 == ch2)); assert!((ch10 >> ch2 == ch2)); assert!((ch10 << ch4 == 160 as char)); assert!((ch10 | ch4 == 14 as char)); assert!((ch10 & ch2 == ch2)); assert!((ch10 ^ ch2 == 8 as char)); } fn test_box() { assert!((@10 == @10)); } fn test_ptr() { unsafe { let p1: *u8 = ::core::cast::reinterpret_cast(&0); let p2: *u8 = ::core::cast::reinterpret_cast(&0); let p3: *u8 = ::core::cast::reinterpret_cast(&1); assert!(p1 == p2); assert!(p1 != p3); assert!(p1 < p3); assert!(p1 <= p3); assert!(p3 > p1); assert!(p3 >= p3); assert!(p1 <= p2); assert!(p1 >= p2); } } mod test { #[abi = "cdecl"] #[nolink] pub extern { pub fn rust_get_sched_id() -> libc::intptr_t; pub fn get_task_id() -> libc::intptr_t; } } #[deriving(Eq)] struct p { x: int, y: int, } fn p(x: int, y: int) -> p { p { x: x, y: y } } fn test_class() { let mut q = p(1, 2); let mut r = p(1, 2); unsafe { error!("q = %x, r = %x", (::core::cast::reinterpret_cast::<*p, uint>(&ptr::addr_of(&q))), (::core::cast::reinterpret_cast::<*p, uint>(&ptr::addr_of(&r)))); } assert!((q == r)); r.y = 17; assert!((r.y != q.y)); assert!((r.y == 17)); assert!((q != r)); } pub fn main() { test_nil(); test_bool(); test_char(); test_box(); test_ptr(); test_class(); }
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
random_line_split
index.d.ts
// Type definitions for openapi-sampler 1.0 // Project: https://github.com/APIs-guru/openapi-sampler/ // Definitions by: Marcell Toth <https://github.com/marcelltoth> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 3.0 export type OpenApiSchema = any; export type OpenApiSpec = any;
/** * Don't include non-required object properties not specified in `required` property of the schema object */ readonly skipNonRequired?: boolean | undefined; /** * Don't include readOnly object properties */ readonly skipReadOnly?: boolean | undefined; /** * Don't include writeOnly object properties */ readonly skipWriteOnly?: boolean | undefined; /** * Don't log console warning messages */ readonly quiet?: boolean | undefined; } /** * Generates samples based on OpenAPI payload/response schema * @param schema A OpenAPI Schema Object * @param options Options * @param spec whole specification where the schema is taken from. Required only when schema may contain `$ref`. `spec` must not contain any external references. */ export function sample(schema: OpenApiSchema, options?: Options, spec?: OpenApiSpec): unknown;
export interface Options {
random_line_split
portal-directives.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 */ import { ComponentFactoryResolver, ComponentRef, Directive, EmbeddedViewRef, EventEmitter, NgModule, OnDestroy, OnInit, Output, TemplateRef, ViewContainerRef, Inject, } from '@angular/core'; import {DOCUMENT} from '@angular/common'; import {BasePortalOutlet, ComponentPortal, Portal, TemplatePortal, DomPortal} from './portal'; /** * Directive version of a `TemplatePortal`. Because the directive *is* a TemplatePortal, * the directive instance itself can be attached to a host, enabling declarative use of portals. */ @Directive({ selector: '[cdkPortal]', exportAs: 'cdkPortal', }) export class CdkPortal extends TemplatePortal { constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) { super(templateRef, viewContainerRef); } } /** * @deprecated Use `CdkPortal` instead. * @breaking-change 9.0.0 */ @Directive({ selector: '[cdk-portal], [portal]', exportAs: 'cdkPortal', providers: [{ provide: CdkPortal, useExisting: TemplatePortalDirective }] }) export class TemplatePortalDirective extends CdkPortal {} /** * Possible attached references to the CdkPortalOutlet. */ export type CdkPortalOutletAttachedRef = ComponentRef<any> | EmbeddedViewRef<any> | null; /** * Directive version of a PortalOutlet. Because the directive *is* a PortalOutlet, portals can be * directly attached to it, enabling declarative use. * * Usage: * `<ng-template [cdkPortalOutlet]="greeting"></ng-template>` */ @Directive({ selector: '[cdkPortalOutlet]', exportAs: 'cdkPortalOutlet', inputs: ['portal: cdkPortalOutlet'] }) export class CdkPortalOutlet extends BasePortalOutlet implements OnInit, OnDestroy { private _document: Document; /** Whether the portal component is initialized. */ private _isInitialized = false; /** Reference to the currently-attached component/view ref. */ private _attachedRef: CdkPortalOutletAttachedRef; constructor( private _componentFactoryResolver: ComponentFactoryResolver, private _viewContainerRef: ViewContainerRef, /** * @deprecated `_document` parameter to be made required. * @breaking-change 9.0.0 */ @Inject(DOCUMENT) _document?: any) { super(); this._document = _document; } /** Portal associated with the Portal outlet. */ get portal(): Portal<any> | null { return this._attachedPortal; } set portal(portal: Portal<any> | null) { // Ignore the cases where the `portal` is set to a falsy value before the lifecycle hooks have // run. This handles the cases where the user might do something like `<div cdkPortalOutlet>` // and attach a portal programmatically in the parent component. When Angular does the first CD // round, it will fire the setter with empty string, causing the user's content to be cleared. if (this.hasAttached() && !portal && !this._isInitialized) { return; } if (this.hasAttached()) { super.detach(); } if (portal) { super.attach(portal); } this._attachedPortal = portal; } /** Emits when a portal is attached to the outlet. */ @Output() attached: EventEmitter<CdkPortalOutletAttachedRef> = new EventEmitter<CdkPortalOutletAttachedRef>(); /** Component or view reference that is attached to the portal. */ get attachedRef(): CdkPortalOutletAttachedRef { return this._attachedRef; } ngOnInit() { this._isInitialized = true; } ngOnDestroy() { super.dispose(); this._attachedPortal = null; this._attachedRef = null; } /** * Attach the given ComponentPortal to this PortalOutlet using the ComponentFactoryResolver. * * @param portal Portal to be attached to the portal outlet. * @returns Reference to the created component. */ attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> { portal.setAttachedHost(this); // If the portal specifies an origin, use that as the logical location of the component // in the application tree. Otherwise use the location of this PortalOutlet. const viewContainerRef = portal.viewContainerRef != null ? portal.viewContainerRef : this._viewContainerRef; const resolver = portal.componentFactoryResolver || this._componentFactoryResolver; const componentFactory = resolver.resolveComponentFactory(portal.component); const ref = viewContainerRef.createComponent( componentFactory, viewContainerRef.length, portal.injector || viewContainerRef.injector); // If we're using a view container that's different from the injected one (e.g. when the portal // specifies its own) we need to move the component into the outlet, otherwise it'll be rendered // inside of the alternate view container. if (viewContainerRef !== this._viewContainerRef) { this._getRootNode().appendChild((ref.hostView as EmbeddedViewRef<any>).rootNodes[0]); } super.setDisposeFn(() => ref.destroy()); this._attachedPortal = portal; this._attachedRef = ref; this.attached.emit(ref); return ref; } /** * Attach the given TemplatePortal to this PortalHost as an embedded View. * @param portal Portal to be attached. * @returns Reference to the created embedded view. */ attachTemplatePortal<C>(portal: TemplatePortal<C>): EmbeddedViewRef<C> { portal.setAttachedHost(this); const viewRef = this._viewContainerRef.createEmbeddedView(portal.templateRef, portal.context); super.setDisposeFn(() => this._viewContainerRef.clear()); this._attachedPortal = portal; this._attachedRef = viewRef; this.attached.emit(viewRef); return viewRef; } /** * Attaches the given DomPortal to this PortalHost by moving all of the portal content into it. * @param portal Portal to be attached. * @deprecated To be turned into a method. * @breaking-change 10.0.0 */ attachDomPortal = (portal: DomPortal) => { // @breaking-change 9.0.0 Remove check and error once the // `_document` constructor parameter is required. if (!this._document && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('Cannot attach DOM portal without _document constructor parameter'); } const element = portal.element; if (!element.parentNode && (typeof ngDevMode === 'undefined' || ngDevMode))
// Anchor used to save the element's previous position so // that we can restore it when the portal is detached. const anchorNode = this._document.createComment('dom-portal'); portal.setAttachedHost(this); element.parentNode!.insertBefore(anchorNode, element); this._getRootNode().appendChild(element); super.setDisposeFn(() => { if (anchorNode.parentNode) { anchorNode.parentNode!.replaceChild(element, anchorNode); } }); } /** Gets the root node of the portal outlet. */ private _getRootNode(): HTMLElement { const nativeElement: Node = this._viewContainerRef.element.nativeElement; // The directive could be set on a template which will result in a comment // node being the root. Use the comment's parent node if that is the case. return (nativeElement.nodeType === nativeElement.ELEMENT_NODE ? nativeElement : nativeElement.parentNode!) as HTMLElement; } static ngAcceptInputType_portal: Portal<any> | null | undefined | ''; } /** * @deprecated Use `CdkPortalOutlet` instead. * @breaking-change 9.0.0 */ @Directive({ selector: '[cdkPortalHost], [portalHost]', exportAs: 'cdkPortalHost', inputs: ['portal: cdkPortalHost'], providers: [{ provide: CdkPortalOutlet, useExisting: PortalHostDirective }] }) export class PortalHostDirective extends CdkPortalOutlet {} @NgModule({ exports: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective], declarations: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective], }) export class PortalModule {}
{ throw Error('DOM portal content must be attached to a parent node.'); }
conditional_block