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
main.rs
//! # Synacor Challenge //! //! A Rust based runtime for the Synacor challenge architecture. #![warn(missing_docs)] extern crate byteorder; extern crate termion; #[macro_use] extern crate chan; extern crate chan_signal; extern crate libc; extern crate synacor; mod command; mod debugger; use debugger::Debugger; use std::io::Read; use std::fs::File; use std::env::args; fn
() { let binary = if let Some(val) = args().nth(1) { let mut buffer = Vec::new(); let mut in_file = File::open(val) .expect("Failed to open challenge binary."); in_file.read_to_end(&mut buffer) .expect("Failed to read in binary contents."); buffer } else { println!("Usage: debugger <binary> [replay] [injections]"); return; }; let replay = if let Some(val) = args().nth(2) { let mut buffer = String::new(); let mut replay_file = File::open(val) .expect("Failed to open replay file"); replay_file.read_to_string(&mut buffer) .expect("Failed to read in replay file"); let mut buffer: Vec<_> = buffer.chars().collect(); buffer.reverse(); println!("Replay buffer loaded"); buffer } else { Vec::new() }; let injections = if let Some(val) = args().nth(3) { let mut buffer = String::new(); let mut injection_file = File::open(val) .expect("Failed to open injection file"); injection_file.read_to_string(&mut buffer) .expect("Failed to read in injection file"); synacor::Injection::from_json(&buffer) } else { vec![] }; let mut dbg = Debugger::new(binary, replay, &injections); dbg.main_loop(); println!("Goodbye!"); }
main
identifier_name
main.rs
//! # Synacor Challenge //! //! A Rust based runtime for the Synacor challenge architecture. #![warn(missing_docs)] extern crate byteorder; extern crate termion; #[macro_use] extern crate chan; extern crate chan_signal; extern crate libc; extern crate synacor; mod command; mod debugger; use debugger::Debugger; use std::io::Read; use std::fs::File; use std::env::args; fn main() { let binary = if let Some(val) = args().nth(1) { let mut buffer = Vec::new(); let mut in_file = File::open(val) .expect("Failed to open challenge binary."); in_file.read_to_end(&mut buffer) .expect("Failed to read in binary contents."); buffer } else { println!("Usage: debugger <binary> [replay] [injections]"); return; }; let replay = if let Some(val) = args().nth(2)
else { Vec::new() }; let injections = if let Some(val) = args().nth(3) { let mut buffer = String::new(); let mut injection_file = File::open(val) .expect("Failed to open injection file"); injection_file.read_to_string(&mut buffer) .expect("Failed to read in injection file"); synacor::Injection::from_json(&buffer) } else { vec![] }; let mut dbg = Debugger::new(binary, replay, &injections); dbg.main_loop(); println!("Goodbye!"); }
{ let mut buffer = String::new(); let mut replay_file = File::open(val) .expect("Failed to open replay file"); replay_file.read_to_string(&mut buffer) .expect("Failed to read in replay file"); let mut buffer: Vec<_> = buffer.chars().collect(); buffer.reverse(); println!("Replay buffer loaded"); buffer }
conditional_block
main.rs
//! # Synacor Challenge //! //! A Rust based runtime for the Synacor challenge architecture. #![warn(missing_docs)] extern crate byteorder; extern crate termion; #[macro_use] extern crate chan; extern crate chan_signal; extern crate libc; extern crate synacor; mod command; mod debugger; use debugger::Debugger; use std::io::Read; use std::fs::File; use std::env::args; fn main() { let binary = if let Some(val) = args().nth(1) { let mut buffer = Vec::new(); let mut in_file = File::open(val) .expect("Failed to open challenge binary."); in_file.read_to_end(&mut buffer) .expect("Failed to read in binary contents."); buffer } else { println!("Usage: debugger <binary> [replay] [injections]"); return; }; let replay = if let Some(val) = args().nth(2) { let mut buffer = String::new(); let mut replay_file = File::open(val) .expect("Failed to open replay file"); replay_file.read_to_string(&mut buffer) .expect("Failed to read in replay file"); let mut buffer: Vec<_> = buffer.chars().collect(); buffer.reverse(); println!("Replay buffer loaded");
buffer } else { Vec::new() }; let injections = if let Some(val) = args().nth(3) { let mut buffer = String::new(); let mut injection_file = File::open(val) .expect("Failed to open injection file"); injection_file.read_to_string(&mut buffer) .expect("Failed to read in injection file"); synacor::Injection::from_json(&buffer) } else { vec![] }; let mut dbg = Debugger::new(binary, replay, &injections); dbg.main_loop(); println!("Goodbye!"); }
random_line_split
main.rs
//! # Synacor Challenge //! //! A Rust based runtime for the Synacor challenge architecture. #![warn(missing_docs)] extern crate byteorder; extern crate termion; #[macro_use] extern crate chan; extern crate chan_signal; extern crate libc; extern crate synacor; mod command; mod debugger; use debugger::Debugger; use std::io::Read; use std::fs::File; use std::env::args; fn main()
{ let binary = if let Some(val) = args().nth(1) { let mut buffer = Vec::new(); let mut in_file = File::open(val) .expect("Failed to open challenge binary."); in_file.read_to_end(&mut buffer) .expect("Failed to read in binary contents."); buffer } else { println!("Usage: debugger <binary> [replay] [injections]"); return; }; let replay = if let Some(val) = args().nth(2) { let mut buffer = String::new(); let mut replay_file = File::open(val) .expect("Failed to open replay file"); replay_file.read_to_string(&mut buffer) .expect("Failed to read in replay file"); let mut buffer: Vec<_> = buffer.chars().collect(); buffer.reverse(); println!("Replay buffer loaded"); buffer } else { Vec::new() }; let injections = if let Some(val) = args().nth(3) { let mut buffer = String::new(); let mut injection_file = File::open(val) .expect("Failed to open injection file"); injection_file.read_to_string(&mut buffer) .expect("Failed to read in injection file"); synacor::Injection::from_json(&buffer) } else { vec![] }; let mut dbg = Debugger::new(binary, replay, &injections); dbg.main_loop(); println!("Goodbye!"); }
identifier_body
erlang_views.js
// 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. couchTests.erlang_views = function(debug) { var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"}); db.deleteDb(); db.createDb(); if (debug) debugger; run_on_modified_server( [{section: "native_query_servers", key: "erlang", value: "{couch_native_process, start_link, []}"}], function() { // Note we just do some basic 'smoke tests' here - the // test/query_server_spec.rb tests have more comprehensive tests var doc = {_id: "1", integer: 1, string: "str1", array: [1, 2, 3]}; T(db.save(doc).ok); var mfun = 'fun({Doc}) -> ' + ' K = couch_util:get_value(<<"integer">>, Doc, null), ' + ' V = couch_util:get_value(<<"string">>, Doc, null), ' + ' Emit(K, V) ' + 'end.'; // emitting a key value that is undefined should result in that row not // being included in the view results var results = db.query(mfun, null, null, null, "erlang"); T(results.total_rows == 1); T(results.rows[0].key == 1); T(results.rows[0].value == "str1"); // check simple reduction - another doc with same key. var doc = {_id: "2", integer: 1, string: "str2"}; T(db.save(doc).ok); rfun = "fun(Keys, Values, ReReduce) -> length(Values) end."; results = db.query(mfun, rfun, null, null, "erlang"); T(results.rows[0].value == 2); // simple 'list' tests var designDoc = { _id:"_design/erlview", language: "erlang", shows: { simple: 'fun(Doc, {Req}) -> ' + ' {Info} = couch_util:get_value(<<"info">>, Req, {[]}), ' + ' Purged = couch_util:get_value(<<"purge_seq">>, Info, -1), ' + ' Verb = couch_util:get_value(<<"method">>, Req, <<"not_get">>), ' + ' R = list_to_binary(io_lib:format("~b - ~s", [Purged, Verb])), ' + ' {[{<<"code">>, 200}, {<<"headers">>, {[]}}, {<<"body">>, R}]} ' + 'end.' }, lists: { simple_list : 'fun(Head, {Req}) -> ' + ' Send(<<"head">>), ' + ' Fun = fun({Row}, _) -> ' + ' Val = couch_util:get_value(<<"value">>, Row, -1), ' + ' Send(list_to_binary(integer_to_list(Val))), ' + ' {ok, nil} ' + ' end, ' + ' {ok, _} = FoldRows(Fun, nil), ' + ' <<"tail">> ' + 'end. '
}, views: { simple_view : { map: mfun, reduce: rfun } } }; T(db.save(designDoc).ok); var url = "/test_suite_db/_design/erlview/_show/simple/1"; var xhr = CouchDB.request("GET", url); T(xhr.status == 200, "standard get should be 200"); T(xhr.responseText == "0 - GET"); var url = "/test_suite_db/_design/erlview/_list/simple_list/simple_view"; var xhr = CouchDB.request("GET", url); T(xhr.status == 200, "standard get should be 200"); T(xhr.responseText == "head2tail"); // Larger dataset db.deleteDb(); db.createDb(); var words = "foo bar abc def baz xxyz".split(/\s+/); var docs = []; for(var i = 0; i < 250; i++) { var body = []; for(var j = 0; j < 100; j++) { body.push({ word: words[j%words.length], count: j }); } docs.push({ "_id": "test-" + i, "words": body }); } T(db.bulkSave(docs).length, 250, "Saved big doc set."); var mfun = 'fun({Doc}) -> ' + 'Words = couch_util:get_value(<<"words">>, Doc), ' + 'lists:foreach(fun({Word}) -> ' + 'WordString = couch_util:get_value(<<"word">>, Word), ' + 'Count = couch_util:get_value(<<"count">>, Word), ' + 'Emit(WordString , Count) ' + 'end, Words) ' + 'end.'; var rfun = 'fun(Keys, Values, RR) -> length(Values) end.'; var results = db.query(mfun, rfun, null, null, "erlang"); T(results.rows[0].key === null, "Returned a reduced value."); T(results.rows[0].value > 0, "Reduce value exists."); }); };
random_line_split
erlang_views.js
// 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. couchTests.erlang_views = function(debug) { var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"}); db.deleteDb(); db.createDb(); if (debug) debugger; run_on_modified_server( [{section: "native_query_servers", key: "erlang", value: "{couch_native_process, start_link, []}"}], function() { // Note we just do some basic 'smoke tests' here - the // test/query_server_spec.rb tests have more comprehensive tests var doc = {_id: "1", integer: 1, string: "str1", array: [1, 2, 3]}; T(db.save(doc).ok); var mfun = 'fun({Doc}) -> ' + ' K = couch_util:get_value(<<"integer">>, Doc, null), ' + ' V = couch_util:get_value(<<"string">>, Doc, null), ' + ' Emit(K, V) ' + 'end.'; // emitting a key value that is undefined should result in that row not // being included in the view results var results = db.query(mfun, null, null, null, "erlang"); T(results.total_rows == 1); T(results.rows[0].key == 1); T(results.rows[0].value == "str1"); // check simple reduction - another doc with same key. var doc = {_id: "2", integer: 1, string: "str2"}; T(db.save(doc).ok); rfun = "fun(Keys, Values, ReReduce) -> length(Values) end."; results = db.query(mfun, rfun, null, null, "erlang"); T(results.rows[0].value == 2); // simple 'list' tests var designDoc = { _id:"_design/erlview", language: "erlang", shows: { simple: 'fun(Doc, {Req}) -> ' + ' {Info} = couch_util:get_value(<<"info">>, Req, {[]}), ' + ' Purged = couch_util:get_value(<<"purge_seq">>, Info, -1), ' + ' Verb = couch_util:get_value(<<"method">>, Req, <<"not_get">>), ' + ' R = list_to_binary(io_lib:format("~b - ~s", [Purged, Verb])), ' + ' {[{<<"code">>, 200}, {<<"headers">>, {[]}}, {<<"body">>, R}]} ' + 'end.' }, lists: { simple_list : 'fun(Head, {Req}) -> ' + ' Send(<<"head">>), ' + ' Fun = fun({Row}, _) -> ' + ' Val = couch_util:get_value(<<"value">>, Row, -1), ' + ' Send(list_to_binary(integer_to_list(Val))), ' + ' {ok, nil} ' + ' end, ' + ' {ok, _} = FoldRows(Fun, nil), ' + ' <<"tail">> ' + 'end. ' }, views: { simple_view : { map: mfun, reduce: rfun } } }; T(db.save(designDoc).ok); var url = "/test_suite_db/_design/erlview/_show/simple/1"; var xhr = CouchDB.request("GET", url); T(xhr.status == 200, "standard get should be 200"); T(xhr.responseText == "0 - GET"); var url = "/test_suite_db/_design/erlview/_list/simple_list/simple_view"; var xhr = CouchDB.request("GET", url); T(xhr.status == 200, "standard get should be 200"); T(xhr.responseText == "head2tail"); // Larger dataset db.deleteDb(); db.createDb(); var words = "foo bar abc def baz xxyz".split(/\s+/); var docs = []; for(var i = 0; i < 250; i++)
T(db.bulkSave(docs).length, 250, "Saved big doc set."); var mfun = 'fun({Doc}) -> ' + 'Words = couch_util:get_value(<<"words">>, Doc), ' + 'lists:foreach(fun({Word}) -> ' + 'WordString = couch_util:get_value(<<"word">>, Word), ' + 'Count = couch_util:get_value(<<"count">>, Word), ' + 'Emit(WordString , Count) ' + 'end, Words) ' + 'end.'; var rfun = 'fun(Keys, Values, RR) -> length(Values) end.'; var results = db.query(mfun, rfun, null, null, "erlang"); T(results.rows[0].key === null, "Returned a reduced value."); T(results.rows[0].value > 0, "Reduce value exists."); }); };
{ var body = []; for(var j = 0; j < 100; j++) { body.push({ word: words[j%words.length], count: j }); } docs.push({ "_id": "test-" + i, "words": body }); }
conditional_block
rectangle.rs
use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, }
top_left: top_left, bottom_right: Point { x: top_left.x + width as i16, y: top_left.y + height as i16, } } } pub fn centre(&self) -> Point<i16> { Point { x: ((self.top_left.x + self.bottom_right.x) / 2), y: ((self.top_left.y + self.bottom_right.y) / 2), } } pub fn is_intersecting(&self, other: &Rectangle) -> bool { self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x && self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y } pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) { if self.top_left.x < left { let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.top_left.y < top { let diff = top - self.top_left.y; self.top_left.y += diff; self.bottom_right.y += diff; } if self.bottom_right.x > right { let diff = right - self.bottom_right.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.bottom_right.y > bottom { let diff = bottom - self.bottom_right.y; self.top_left.y += diff; self.bottom_right.y += diff; } } }
impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle {
random_line_split
rectangle.rs
use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left, bottom_right: Point { x: top_left.x + width as i16, y: top_left.y + height as i16, } } } pub fn centre(&self) -> Point<i16> { Point { x: ((self.top_left.x + self.bottom_right.x) / 2), y: ((self.top_left.y + self.bottom_right.y) / 2), } } pub fn is_intersecting(&self, other: &Rectangle) -> bool { self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x && self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y } pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) { if self.top_left.x < left
if self.top_left.y < top { let diff = top - self.top_left.y; self.top_left.y += diff; self.bottom_right.y += diff; } if self.bottom_right.x > right { let diff = right - self.bottom_right.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.bottom_right.y > bottom { let diff = bottom - self.bottom_right.y; self.top_left.y += diff; self.bottom_right.y += diff; } } }
{ let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; }
conditional_block
rectangle.rs
use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left, bottom_right: Point { x: top_left.x + width as i16, y: top_left.y + height as i16, } } } pub fn centre(&self) -> Point<i16>
pub fn is_intersecting(&self, other: &Rectangle) -> bool { self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x && self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y } pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) { if self.top_left.x < left { let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.top_left.y < top { let diff = top - self.top_left.y; self.top_left.y += diff; self.bottom_right.y += diff; } if self.bottom_right.x > right { let diff = right - self.bottom_right.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.bottom_right.y > bottom { let diff = bottom - self.bottom_right.y; self.top_left.y += diff; self.bottom_right.y += diff; } } }
{ Point { x: ((self.top_left.x + self.bottom_right.x) / 2), y: ((self.top_left.y + self.bottom_right.y) / 2), } }
identifier_body
rectangle.rs
use point::Point; #[derive(Debug, Hash, Eq, PartialEq)] pub struct Rectangle { pub top_left: Point<i16>, pub bottom_right: Point<i16>, } impl Rectangle { pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle { Rectangle { top_left: top_left, bottom_right: Point { x: top_left.x + width as i16, y: top_left.y + height as i16, } } } pub fn centre(&self) -> Point<i16> { Point { x: ((self.top_left.x + self.bottom_right.x) / 2), y: ((self.top_left.y + self.bottom_right.y) / 2), } } pub fn
(&self, other: &Rectangle) -> bool { self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x && self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y } pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) { if self.top_left.x < left { let diff = left - self.top_left.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.top_left.y < top { let diff = top - self.top_left.y; self.top_left.y += diff; self.bottom_right.y += diff; } if self.bottom_right.x > right { let diff = right - self.bottom_right.x; self.top_left.x += diff; self.bottom_right.x += diff; } if self.bottom_right.y > bottom { let diff = bottom - self.bottom_right.y; self.top_left.y += diff; self.bottom_right.y += diff; } } }
is_intersecting
identifier_name
dep-graph-caller-callee.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that immediate callers have to change when callee changes, but // not callers' callers. // compile-flags: -Z query-dep-graph #![feature(rustc_attrs)] #![allow(dead_code)] fn main() { } mod x { #[rustc_if_this_changed] pub fn x() { } } mod y { use x; // These dependencies SHOULD exist: #[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK pub fn y() { x::x(); }
} mod z { use y; // These are expected to yield errors, because changes to `x` // affect the BODY of `y`, but not its signature. #[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path pub fn z() { y::y(); } }
random_line_split
dep-graph-caller-callee.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that immediate callers have to change when callee changes, but // not callers' callers. // compile-flags: -Z query-dep-graph #![feature(rustc_attrs)] #![allow(dead_code)] fn main() { } mod x { #[rustc_if_this_changed] pub fn x()
} mod y { use x; // These dependencies SHOULD exist: #[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK pub fn y() { x::x(); } } mod z { use y; // These are expected to yield errors, because changes to `x` // affect the BODY of `y`, but not its signature. #[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path pub fn z() { y::y(); } }
{ }
identifier_body
dep-graph-caller-callee.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that immediate callers have to change when callee changes, but // not callers' callers. // compile-flags: -Z query-dep-graph #![feature(rustc_attrs)] #![allow(dead_code)] fn main() { } mod x { #[rustc_if_this_changed] pub fn x() { } } mod y { use x; // These dependencies SHOULD exist: #[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK pub fn y() { x::x(); } } mod z { use y; // These are expected to yield errors, because changes to `x` // affect the BODY of `y`, but not its signature. #[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path pub fn
() { y::y(); } }
z
identifier_name
for-options.directive.ts
import { NgForOf, NgForOfContext } from '@angular/common'; import { ChangeDetectorRef, Directive, forwardRef, Input, IterableDiffers, OnDestroy, TemplateRef, TrackByFunction, ViewContainerRef } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; import { ALuOptionOperator, ILuOptionOperator } from '../option-operator.model'; @Directive({ selector: '[luForOptions]', providers: [ { provide: ALuOptionOperator, useExisting: forwardRef(() => LuForOptionsDirective), multi: true, }, ], }) export class
<T> extends NgForOf<T> implements ILuOptionOperator<T>, OnDestroy { outOptions$; protected _subs = new Subscription(); set inOptions$(options$: Observable<T[]>) { this._subs.add( options$.subscribe((options) => { this.ngForOf = options; this._changeDetectionRef.markForCheck(); }), ); this.outOptions$ = options$; } @Input() set luForOptionsTrackBy(fn: TrackByFunction<T>) { this.ngForTrackBy = fn; } constructor(_viewContainer: ViewContainerRef, _template: TemplateRef<NgForOfContext<T>>, _differs: IterableDiffers, protected _changeDetectionRef: ChangeDetectorRef) { super(_viewContainer, _template, _differs); } ngOnDestroy() { this._subs.unsubscribe(); } }
LuForOptionsDirective
identifier_name
for-options.directive.ts
import { NgForOf, NgForOfContext } from '@angular/common'; import { ChangeDetectorRef, Directive, forwardRef, Input, IterableDiffers, OnDestroy, TemplateRef, TrackByFunction, ViewContainerRef } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; import { ALuOptionOperator, ILuOptionOperator } from '../option-operator.model'; @Directive({ selector: '[luForOptions]', providers: [ { provide: ALuOptionOperator, useExisting: forwardRef(() => LuForOptionsDirective), multi: true, }, ], }) export class LuForOptionsDirective<T> extends NgForOf<T> implements ILuOptionOperator<T>, OnDestroy { outOptions$; protected _subs = new Subscription(); set inOptions$(options$: Observable<T[]>) { this._subs.add( options$.subscribe((options) => { this.ngForOf = options; this._changeDetectionRef.markForCheck(); }), ); this.outOptions$ = options$; } @Input() set luForOptionsTrackBy(fn: TrackByFunction<T>)
constructor(_viewContainer: ViewContainerRef, _template: TemplateRef<NgForOfContext<T>>, _differs: IterableDiffers, protected _changeDetectionRef: ChangeDetectorRef) { super(_viewContainer, _template, _differs); } ngOnDestroy() { this._subs.unsubscribe(); } }
{ this.ngForTrackBy = fn; }
identifier_body
for-options.directive.ts
import { NgForOf, NgForOfContext } from '@angular/common'; import { ChangeDetectorRef, Directive, forwardRef, Input, IterableDiffers, OnDestroy, TemplateRef, TrackByFunction, ViewContainerRef } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; import { ALuOptionOperator, ILuOptionOperator } from '../option-operator.model'; @Directive({ selector: '[luForOptions]',
providers: [ { provide: ALuOptionOperator, useExisting: forwardRef(() => LuForOptionsDirective), multi: true, }, ], }) export class LuForOptionsDirective<T> extends NgForOf<T> implements ILuOptionOperator<T>, OnDestroy { outOptions$; protected _subs = new Subscription(); set inOptions$(options$: Observable<T[]>) { this._subs.add( options$.subscribe((options) => { this.ngForOf = options; this._changeDetectionRef.markForCheck(); }), ); this.outOptions$ = options$; } @Input() set luForOptionsTrackBy(fn: TrackByFunction<T>) { this.ngForTrackBy = fn; } constructor(_viewContainer: ViewContainerRef, _template: TemplateRef<NgForOfContext<T>>, _differs: IterableDiffers, protected _changeDetectionRef: ChangeDetectorRef) { super(_viewContainer, _template, _differs); } ngOnDestroy() { this._subs.unsubscribe(); } }
random_line_split
BSPTree.py
from random import randint, seed, choice, random from numpy import zeros, uint8, cumsum, floor, ceil from math import sqrt, log from collections import namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf):
def get_leafs(self): if self.lchild == None and self.rchild == None: return [self.leaf] else: return self.lchild.get_leafs()+self.rchild.get_leafs() def get_level(self, level, queue): if queue == None: queue = [] if level == 1: queue.push(self) else: if self.lchild != None: self.lchild.get_level(level-1, queue) if self.rchild != None: self.rchild.get_level(level-1, queue) return queue def paint(self, c): self.leaf.paint(c) if self.lchild != None: self.lchild.paint(c) if self.rchild != None: self.rchild.paint(c) class Container(): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.center = (self.x+int(self.w/2),self.y+int(self.h/2)) self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2) def paint(self, c): c.stroke_rectangle(self.x, self.y, self.w, self.h) def draw_path(self,c,container): c.path(self.center[0],self.center[1],container.center[0],container.center[1]) class Canvas: brushes = {"empty":0, "hallway":1, "room":2} def __init__(self, w, h, color = "empty"): self.board = zeros((h,w), dtype=uint8) self.w = w self.h = h self.set_brush(color) def set_brush(self, code): self.color = self.brushes[code] def stroke_rectangle(self, x, y, w, h): self.line(x,y,w,True) self.line(x,y+h-1,w,True) self.line(x,y,h,False) self.line(x+w-1,y,h,False) def filled_rectangle(self, x, y, w, h): self.board[y:y+h,x:x+w] = self.color def line(self, x, y, length, horizontal): if horizontal: self.board[y,x:x+length] = self.color else: self.board[y:y+length,x] = self.color def path(self,x1,y1,x2,y2): self.board[y1:y2+1,x1:x2+1] = self.color def circle(self,x,y,r): for x_offset in range(-r,r+1): for y_offset in range(-r,r+1): if sqrt(x_offset**2+y_offset**2)<r: self.board[x+x_offset,y+y_offset] = self.color def draw(self): im = Image.fromarray(self.board) im.save(MAP_NAME) def __str__(self): return str(self.board) class Room: environments = ["serene", "calm", "wild", "dangerous", "evil"] biomes = ["rock", "rugged", "sand", "mossy", "muddy", "flooded", "gelid", "gloomy", "magma"] biomes_CDF = cumsum([0.22,0.14,0.12,0.10,0.10,0.07,0.06,0.06,0.04,0.03,0.03,0.03]) def __init__(self, container): self.x = container.x+randint(1, floor(container.w/3)) self.y = container.y+randint(1, floor(container.h/3)) self.w = container.w-(self.x-container.x) self.h = container.h-(self.y-container.y) self.w -= randint(0,floor(self.w/3)) self.h -= randint(0,floor(self.w/3)) self.environment = int(min(4,10*(container.distance_from_center/MAP_WIDTH)+random()*2-1)) roll = random()*0.9+(2*container.distance_from_center/MAP_WIDTH)*0.1 self.biome = next(n for n,b in enumerate(self.biomes_CDF) if roll<b) def paint(self,c): c.filled_rectangle(self.x, self.y,self.w, self.h) def random_split(container): if container.w<MIN_ROOM_SIDE and container.h<MIN_ROOM_SIDE: return None def _split_vertical(container): r1 = None r2 = None min_w = int(W_RATIO*container.h)+1 if container.w < 2*min_w: return None r1 = Container(container.x,container.y,randint(min_w, container.w-min_w),container.h) r2 = Container(container.x+r1.w,container.y,container.w-r1.w,container.h) return [r1, r2] def _split_horizontal(container): r1 = None r2 = None min_h = int(H_RATIO*container.w)+1 if container.h < 2*min_h: return None r1 = Container(container.x,container.y,container.w,randint(min_h, container.h-min_h)) r2 = Container(container.x,container.y+r1.h,container.w,container.h-r1.h) return [r1, r2] if randint(0,1) == 0: res = _split_vertical(container) if res == None: return _split_horizontal(container) return res else: res = _split_horizontal(container) if res == None: return _split_vertical(container) return res def split_container(container, iter): root = Tree(container) if iter != 0: sr = random_split(container) if sr!=None: root.lchild = split_container(sr[0], iter-1) root.rchild = split_container(sr[1], iter-1) return root def draw_paths(c, tree): if tree.lchild == None or tree.rchild == None: return tree.lchild.leaf.draw_path(c, tree.rchild.leaf) draw_paths(c, tree.lchild) draw_paths(c, tree.rchild) MAP_WIDTH = 0 MAP_HEIGHT = 0 N_ITERATIONS = 0 H_RATIO = 0 W_RATIO = 0 MIN_ROOM_SIDE = 0 CENTER_HUB_HOLE = 0 CENTER_HUB_RADIO = 0 MAP_NAME = 0 def init(num_players): global MAP_WIDTH,MAP_HEIGHT,N_ITERATIONS,H_RATIO,W_RATIO,MIN_ROOM_SIDE,CENTER_HUB_HOLE,CENTER_HUB_RADIO,MAP_NAME MAP_WIDTH=int(500*sqrt(num_players)) MAP_HEIGHT=MAP_WIDTH N_ITERATIONS=log(MAP_WIDTH*100,2) H_RATIO=0.49 W_RATIO=H_RATIO MIN_ROOM_SIDE = 32 CENTER_HUB_HOLE = 32 CENTER_HUB_RADIO = CENTER_HUB_HOLE-MIN_ROOM_SIDE/2 MAP_NAME="result%s.png"%MAP_WIDTH def main(num_players, seed_number): logger = getLogger('BSPTree') logger.info("Initialising") init(num_players) seed(seed_number) canvas = Canvas(MAP_WIDTH, MAP_HEIGHT) canvas.set_brush("empty") canvas.filled_rectangle(0,0,MAP_WIDTH,MAP_HEIGHT) logger.info("Generating container tree") # -1 on the main container to remove borders to avoid opened border rooms main_container = Container(0, 0, MAP_WIDTH-1, MAP_HEIGHT-1) container_tree = split_container(main_container, N_ITERATIONS) logger.info("Generating hallways") canvas.set_brush("hallway") draw_paths(canvas, container_tree) logger.info("Generating rooms") canvas.set_brush("room") leafs = container_tree.get_leafs() rooms = [] for i in range(0, len(leafs)): if CENTER_HUB_HOLE < leafs[i].distance_from_center < MAP_WIDTH/2: rooms.append(Room(leafs[i])) rooms[-1].paint(canvas) logger.info("Generating hub") canvas.circle(int(MAP_WIDTH/2),int(MAP_HEIGHT/2),int(CENTER_HUB_RADIO)) #canvas.draw() return (rooms, canvas.board)
self.leaf = leaf self.lchild = None self.rchild = None
identifier_body
BSPTree.py
from random import randint, seed, choice, random from numpy import zeros, uint8, cumsum, floor, ceil from math import sqrt, log from collections import namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf): self.leaf = leaf self.lchild = None self.rchild = None def get_leafs(self): if self.lchild == None and self.rchild == None: return [self.leaf] else: return self.lchild.get_leafs()+self.rchild.get_leafs() def get_level(self, level, queue): if queue == None: queue = [] if level == 1: queue.push(self) else: if self.lchild != None: self.lchild.get_level(level-1, queue) if self.rchild != None: self.rchild.get_level(level-1, queue) return queue def paint(self, c): self.leaf.paint(c) if self.lchild != None: self.lchild.paint(c) if self.rchild != None:
class Container(): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.center = (self.x+int(self.w/2),self.y+int(self.h/2)) self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2) def paint(self, c): c.stroke_rectangle(self.x, self.y, self.w, self.h) def draw_path(self,c,container): c.path(self.center[0],self.center[1],container.center[0],container.center[1]) class Canvas: brushes = {"empty":0, "hallway":1, "room":2} def __init__(self, w, h, color = "empty"): self.board = zeros((h,w), dtype=uint8) self.w = w self.h = h self.set_brush(color) def set_brush(self, code): self.color = self.brushes[code] def stroke_rectangle(self, x, y, w, h): self.line(x,y,w,True) self.line(x,y+h-1,w,True) self.line(x,y,h,False) self.line(x+w-1,y,h,False) def filled_rectangle(self, x, y, w, h): self.board[y:y+h,x:x+w] = self.color def line(self, x, y, length, horizontal): if horizontal: self.board[y,x:x+length] = self.color else: self.board[y:y+length,x] = self.color def path(self,x1,y1,x2,y2): self.board[y1:y2+1,x1:x2+1] = self.color def circle(self,x,y,r): for x_offset in range(-r,r+1): for y_offset in range(-r,r+1): if sqrt(x_offset**2+y_offset**2)<r: self.board[x+x_offset,y+y_offset] = self.color def draw(self): im = Image.fromarray(self.board) im.save(MAP_NAME) def __str__(self): return str(self.board) class Room: environments = ["serene", "calm", "wild", "dangerous", "evil"] biomes = ["rock", "rugged", "sand", "mossy", "muddy", "flooded", "gelid", "gloomy", "magma"] biomes_CDF = cumsum([0.22,0.14,0.12,0.10,0.10,0.07,0.06,0.06,0.04,0.03,0.03,0.03]) def __init__(self, container): self.x = container.x+randint(1, floor(container.w/3)) self.y = container.y+randint(1, floor(container.h/3)) self.w = container.w-(self.x-container.x) self.h = container.h-(self.y-container.y) self.w -= randint(0,floor(self.w/3)) self.h -= randint(0,floor(self.w/3)) self.environment = int(min(4,10*(container.distance_from_center/MAP_WIDTH)+random()*2-1)) roll = random()*0.9+(2*container.distance_from_center/MAP_WIDTH)*0.1 self.biome = next(n for n,b in enumerate(self.biomes_CDF) if roll<b) def paint(self,c): c.filled_rectangle(self.x, self.y,self.w, self.h) def random_split(container): if container.w<MIN_ROOM_SIDE and container.h<MIN_ROOM_SIDE: return None def _split_vertical(container): r1 = None r2 = None min_w = int(W_RATIO*container.h)+1 if container.w < 2*min_w: return None r1 = Container(container.x,container.y,randint(min_w, container.w-min_w),container.h) r2 = Container(container.x+r1.w,container.y,container.w-r1.w,container.h) return [r1, r2] def _split_horizontal(container): r1 = None r2 = None min_h = int(H_RATIO*container.w)+1 if container.h < 2*min_h: return None r1 = Container(container.x,container.y,container.w,randint(min_h, container.h-min_h)) r2 = Container(container.x,container.y+r1.h,container.w,container.h-r1.h) return [r1, r2] if randint(0,1) == 0: res = _split_vertical(container) if res == None: return _split_horizontal(container) return res else: res = _split_horizontal(container) if res == None: return _split_vertical(container) return res def split_container(container, iter): root = Tree(container) if iter != 0: sr = random_split(container) if sr!=None: root.lchild = split_container(sr[0], iter-1) root.rchild = split_container(sr[1], iter-1) return root def draw_paths(c, tree): if tree.lchild == None or tree.rchild == None: return tree.lchild.leaf.draw_path(c, tree.rchild.leaf) draw_paths(c, tree.lchild) draw_paths(c, tree.rchild) MAP_WIDTH = 0 MAP_HEIGHT = 0 N_ITERATIONS = 0 H_RATIO = 0 W_RATIO = 0 MIN_ROOM_SIDE = 0 CENTER_HUB_HOLE = 0 CENTER_HUB_RADIO = 0 MAP_NAME = 0 def init(num_players): global MAP_WIDTH,MAP_HEIGHT,N_ITERATIONS,H_RATIO,W_RATIO,MIN_ROOM_SIDE,CENTER_HUB_HOLE,CENTER_HUB_RADIO,MAP_NAME MAP_WIDTH=int(500*sqrt(num_players)) MAP_HEIGHT=MAP_WIDTH N_ITERATIONS=log(MAP_WIDTH*100,2) H_RATIO=0.49 W_RATIO=H_RATIO MIN_ROOM_SIDE = 32 CENTER_HUB_HOLE = 32 CENTER_HUB_RADIO = CENTER_HUB_HOLE-MIN_ROOM_SIDE/2 MAP_NAME="result%s.png"%MAP_WIDTH def main(num_players, seed_number): logger = getLogger('BSPTree') logger.info("Initialising") init(num_players) seed(seed_number) canvas = Canvas(MAP_WIDTH, MAP_HEIGHT) canvas.set_brush("empty") canvas.filled_rectangle(0,0,MAP_WIDTH,MAP_HEIGHT) logger.info("Generating container tree") # -1 on the main container to remove borders to avoid opened border rooms main_container = Container(0, 0, MAP_WIDTH-1, MAP_HEIGHT-1) container_tree = split_container(main_container, N_ITERATIONS) logger.info("Generating hallways") canvas.set_brush("hallway") draw_paths(canvas, container_tree) logger.info("Generating rooms") canvas.set_brush("room") leafs = container_tree.get_leafs() rooms = [] for i in range(0, len(leafs)): if CENTER_HUB_HOLE < leafs[i].distance_from_center < MAP_WIDTH/2: rooms.append(Room(leafs[i])) rooms[-1].paint(canvas) logger.info("Generating hub") canvas.circle(int(MAP_WIDTH/2),int(MAP_HEIGHT/2),int(CENTER_HUB_RADIO)) #canvas.draw() return (rooms, canvas.board)
self.rchild.paint(c)
conditional_block
BSPTree.py
from random import randint, seed, choice, random from numpy import zeros, uint8, cumsum, floor, ceil from math import sqrt, log from collections import namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf): self.leaf = leaf self.lchild = None self.rchild = None def get_leafs(self): if self.lchild == None and self.rchild == None: return [self.leaf] else: return self.lchild.get_leafs()+self.rchild.get_leafs() def get_level(self, level, queue): if queue == None: queue = [] if level == 1: queue.push(self) else: if self.lchild != None: self.lchild.get_level(level-1, queue) if self.rchild != None: self.rchild.get_level(level-1, queue) return queue def paint(self, c): self.leaf.paint(c) if self.lchild != None: self.lchild.paint(c) if self.rchild != None: self.rchild.paint(c) class Container(): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.center = (self.x+int(self.w/2),self.y+int(self.h/2)) self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2) def paint(self, c): c.stroke_rectangle(self.x, self.y, self.w, self.h) def draw_path(self,c,container): c.path(self.center[0],self.center[1],container.center[0],container.center[1]) class Canvas: brushes = {"empty":0, "hallway":1, "room":2} def __init__(self, w, h, color = "empty"): self.board = zeros((h,w), dtype=uint8) self.w = w self.h = h self.set_brush(color) def set_brush(self, code): self.color = self.brushes[code] def stroke_rectangle(self, x, y, w, h): self.line(x,y,w,True) self.line(x,y+h-1,w,True) self.line(x,y,h,False) self.line(x+w-1,y,h,False) def filled_rectangle(self, x, y, w, h): self.board[y:y+h,x:x+w] = self.color def line(self, x, y, length, horizontal): if horizontal: self.board[y,x:x+length] = self.color else: self.board[y:y+length,x] = self.color def path(self,x1,y1,x2,y2): self.board[y1:y2+1,x1:x2+1] = self.color def circle(self,x,y,r): for x_offset in range(-r,r+1): for y_offset in range(-r,r+1): if sqrt(x_offset**2+y_offset**2)<r: self.board[x+x_offset,y+y_offset] = self.color def draw(self): im = Image.fromarray(self.board) im.save(MAP_NAME) def __str__(self): return str(self.board) class Room: environments = ["serene", "calm", "wild", "dangerous", "evil"] biomes = ["rock", "rugged", "sand", "mossy", "muddy", "flooded", "gelid", "gloomy", "magma"] biomes_CDF = cumsum([0.22,0.14,0.12,0.10,0.10,0.07,0.06,0.06,0.04,0.03,0.03,0.03]) def __init__(self, container): self.x = container.x+randint(1, floor(container.w/3)) self.y = container.y+randint(1, floor(container.h/3)) self.w = container.w-(self.x-container.x) self.h = container.h-(self.y-container.y) self.w -= randint(0,floor(self.w/3)) self.h -= randint(0,floor(self.w/3)) self.environment = int(min(4,10*(container.distance_from_center/MAP_WIDTH)+random()*2-1)) roll = random()*0.9+(2*container.distance_from_center/MAP_WIDTH)*0.1 self.biome = next(n for n,b in enumerate(self.biomes_CDF) if roll<b) def paint(self,c): c.filled_rectangle(self.x, self.y,self.w, self.h) def random_split(container): if container.w<MIN_ROOM_SIDE and container.h<MIN_ROOM_SIDE: return None def _split_vertical(container): r1 = None r2 = None min_w = int(W_RATIO*container.h)+1 if container.w < 2*min_w: return None r1 = Container(container.x,container.y,randint(min_w, container.w-min_w),container.h) r2 = Container(container.x+r1.w,container.y,container.w-r1.w,container.h) return [r1, r2] def _split_horizontal(container): r1 = None r2 = None min_h = int(H_RATIO*container.w)+1 if container.h < 2*min_h: return None r1 = Container(container.x,container.y,container.w,randint(min_h, container.h-min_h)) r2 = Container(container.x,container.y+r1.h,container.w,container.h-r1.h) return [r1, r2] if randint(0,1) == 0: res = _split_vertical(container) if res == None: return _split_horizontal(container) return res else: res = _split_horizontal(container) if res == None: return _split_vertical(container) return res def split_container(container, iter): root = Tree(container) if iter != 0: sr = random_split(container) if sr!=None: root.lchild = split_container(sr[0], iter-1) root.rchild = split_container(sr[1], iter-1) return root
if tree.lchild == None or tree.rchild == None: return tree.lchild.leaf.draw_path(c, tree.rchild.leaf) draw_paths(c, tree.lchild) draw_paths(c, tree.rchild) MAP_WIDTH = 0 MAP_HEIGHT = 0 N_ITERATIONS = 0 H_RATIO = 0 W_RATIO = 0 MIN_ROOM_SIDE = 0 CENTER_HUB_HOLE = 0 CENTER_HUB_RADIO = 0 MAP_NAME = 0 def init(num_players): global MAP_WIDTH,MAP_HEIGHT,N_ITERATIONS,H_RATIO,W_RATIO,MIN_ROOM_SIDE,CENTER_HUB_HOLE,CENTER_HUB_RADIO,MAP_NAME MAP_WIDTH=int(500*sqrt(num_players)) MAP_HEIGHT=MAP_WIDTH N_ITERATIONS=log(MAP_WIDTH*100,2) H_RATIO=0.49 W_RATIO=H_RATIO MIN_ROOM_SIDE = 32 CENTER_HUB_HOLE = 32 CENTER_HUB_RADIO = CENTER_HUB_HOLE-MIN_ROOM_SIDE/2 MAP_NAME="result%s.png"%MAP_WIDTH def main(num_players, seed_number): logger = getLogger('BSPTree') logger.info("Initialising") init(num_players) seed(seed_number) canvas = Canvas(MAP_WIDTH, MAP_HEIGHT) canvas.set_brush("empty") canvas.filled_rectangle(0,0,MAP_WIDTH,MAP_HEIGHT) logger.info("Generating container tree") # -1 on the main container to remove borders to avoid opened border rooms main_container = Container(0, 0, MAP_WIDTH-1, MAP_HEIGHT-1) container_tree = split_container(main_container, N_ITERATIONS) logger.info("Generating hallways") canvas.set_brush("hallway") draw_paths(canvas, container_tree) logger.info("Generating rooms") canvas.set_brush("room") leafs = container_tree.get_leafs() rooms = [] for i in range(0, len(leafs)): if CENTER_HUB_HOLE < leafs[i].distance_from_center < MAP_WIDTH/2: rooms.append(Room(leafs[i])) rooms[-1].paint(canvas) logger.info("Generating hub") canvas.circle(int(MAP_WIDTH/2),int(MAP_HEIGHT/2),int(CENTER_HUB_RADIO)) #canvas.draw() return (rooms, canvas.board)
def draw_paths(c, tree):
random_line_split
BSPTree.py
from random import randint, seed, choice, random from numpy import zeros, uint8, cumsum, floor, ceil from math import sqrt, log from collections import namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf): self.leaf = leaf self.lchild = None self.rchild = None def get_leafs(self): if self.lchild == None and self.rchild == None: return [self.leaf] else: return self.lchild.get_leafs()+self.rchild.get_leafs() def get_level(self, level, queue): if queue == None: queue = [] if level == 1: queue.push(self) else: if self.lchild != None: self.lchild.get_level(level-1, queue) if self.rchild != None: self.rchild.get_level(level-1, queue) return queue def paint(self, c): self.leaf.paint(c) if self.lchild != None: self.lchild.paint(c) if self.rchild != None: self.rchild.paint(c) class Container(): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.center = (self.x+int(self.w/2),self.y+int(self.h/2)) self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2) def paint(self, c): c.stroke_rectangle(self.x, self.y, self.w, self.h) def draw_path(self,c,container): c.path(self.center[0],self.center[1],container.center[0],container.center[1]) class Canvas: brushes = {"empty":0, "hallway":1, "room":2} def __init__(self, w, h, color = "empty"): self.board = zeros((h,w), dtype=uint8) self.w = w self.h = h self.set_brush(color) def set_brush(self, code): self.color = self.brushes[code] def stroke_rectangle(self, x, y, w, h): self.line(x,y,w,True) self.line(x,y+h-1,w,True) self.line(x,y,h,False) self.line(x+w-1,y,h,False) def filled_rectangle(self, x, y, w, h): self.board[y:y+h,x:x+w] = self.color def line(self, x, y, length, horizontal): if horizontal: self.board[y,x:x+length] = self.color else: self.board[y:y+length,x] = self.color def path(self,x1,y1,x2,y2): self.board[y1:y2+1,x1:x2+1] = self.color def circle(self,x,y,r): for x_offset in range(-r,r+1): for y_offset in range(-r,r+1): if sqrt(x_offset**2+y_offset**2)<r: self.board[x+x_offset,y+y_offset] = self.color def draw(self): im = Image.fromarray(self.board) im.save(MAP_NAME) def __str__(self): return str(self.board) class Room: environments = ["serene", "calm", "wild", "dangerous", "evil"] biomes = ["rock", "rugged", "sand", "mossy", "muddy", "flooded", "gelid", "gloomy", "magma"] biomes_CDF = cumsum([0.22,0.14,0.12,0.10,0.10,0.07,0.06,0.06,0.04,0.03,0.03,0.03]) def __init__(self, container): self.x = container.x+randint(1, floor(container.w/3)) self.y = container.y+randint(1, floor(container.h/3)) self.w = container.w-(self.x-container.x) self.h = container.h-(self.y-container.y) self.w -= randint(0,floor(self.w/3)) self.h -= randint(0,floor(self.w/3)) self.environment = int(min(4,10*(container.distance_from_center/MAP_WIDTH)+random()*2-1)) roll = random()*0.9+(2*container.distance_from_center/MAP_WIDTH)*0.1 self.biome = next(n for n,b in enumerate(self.biomes_CDF) if roll<b) def paint(self,c): c.filled_rectangle(self.x, self.y,self.w, self.h) def random_split(container): if container.w<MIN_ROOM_SIDE and container.h<MIN_ROOM_SIDE: return None def _split_vertical(container): r1 = None r2 = None min_w = int(W_RATIO*container.h)+1 if container.w < 2*min_w: return None r1 = Container(container.x,container.y,randint(min_w, container.w-min_w),container.h) r2 = Container(container.x+r1.w,container.y,container.w-r1.w,container.h) return [r1, r2] def _split_horizontal(container): r1 = None r2 = None min_h = int(H_RATIO*container.w)+1 if container.h < 2*min_h: return None r1 = Container(container.x,container.y,container.w,randint(min_h, container.h-min_h)) r2 = Container(container.x,container.y+r1.h,container.w,container.h-r1.h) return [r1, r2] if randint(0,1) == 0: res = _split_vertical(container) if res == None: return _split_horizontal(container) return res else: res = _split_horizontal(container) if res == None: return _split_vertical(container) return res def
(container, iter): root = Tree(container) if iter != 0: sr = random_split(container) if sr!=None: root.lchild = split_container(sr[0], iter-1) root.rchild = split_container(sr[1], iter-1) return root def draw_paths(c, tree): if tree.lchild == None or tree.rchild == None: return tree.lchild.leaf.draw_path(c, tree.rchild.leaf) draw_paths(c, tree.lchild) draw_paths(c, tree.rchild) MAP_WIDTH = 0 MAP_HEIGHT = 0 N_ITERATIONS = 0 H_RATIO = 0 W_RATIO = 0 MIN_ROOM_SIDE = 0 CENTER_HUB_HOLE = 0 CENTER_HUB_RADIO = 0 MAP_NAME = 0 def init(num_players): global MAP_WIDTH,MAP_HEIGHT,N_ITERATIONS,H_RATIO,W_RATIO,MIN_ROOM_SIDE,CENTER_HUB_HOLE,CENTER_HUB_RADIO,MAP_NAME MAP_WIDTH=int(500*sqrt(num_players)) MAP_HEIGHT=MAP_WIDTH N_ITERATIONS=log(MAP_WIDTH*100,2) H_RATIO=0.49 W_RATIO=H_RATIO MIN_ROOM_SIDE = 32 CENTER_HUB_HOLE = 32 CENTER_HUB_RADIO = CENTER_HUB_HOLE-MIN_ROOM_SIDE/2 MAP_NAME="result%s.png"%MAP_WIDTH def main(num_players, seed_number): logger = getLogger('BSPTree') logger.info("Initialising") init(num_players) seed(seed_number) canvas = Canvas(MAP_WIDTH, MAP_HEIGHT) canvas.set_brush("empty") canvas.filled_rectangle(0,0,MAP_WIDTH,MAP_HEIGHT) logger.info("Generating container tree") # -1 on the main container to remove borders to avoid opened border rooms main_container = Container(0, 0, MAP_WIDTH-1, MAP_HEIGHT-1) container_tree = split_container(main_container, N_ITERATIONS) logger.info("Generating hallways") canvas.set_brush("hallway") draw_paths(canvas, container_tree) logger.info("Generating rooms") canvas.set_brush("room") leafs = container_tree.get_leafs() rooms = [] for i in range(0, len(leafs)): if CENTER_HUB_HOLE < leafs[i].distance_from_center < MAP_WIDTH/2: rooms.append(Room(leafs[i])) rooms[-1].paint(canvas) logger.info("Generating hub") canvas.circle(int(MAP_WIDTH/2),int(MAP_HEIGHT/2),int(CENTER_HUB_RADIO)) #canvas.draw() return (rooms, canvas.board)
split_container
identifier_name
games.rs
use crate::*; #[get("/newgame")] pub fn newgame<'a>() -> ContRes<'a> { respond_page("newgame", newgame_con()) } pub fn newgame_con() -> Context { let conn = lock_database(); let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap(); let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| { Named { id: row.get(0), name: row.get(1) } }) .unwrap() .map(Result::unwrap) .collect(); let mut ballstmt = conn.prepare("SELECT id, name, img FROM balls").unwrap(); let balls: Vec<_> = ballstmt.query_map(NO_PARAMS, |row| { Ball { id: row.get(0), name: row.get(1), img: row.get(2), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("names", &names); context.insert("balls", &balls); context } #[derive(FromForm)] pub struct NewGame { home: i32, away: i32, home_score: i32, away_score: i32, ball: i32, secret: String, #[allow(dead_code)] submit: IgnoreField } #[post("/newgame/submit", data = "<f>")] pub fn submit_newgame<'a>(f: Form<NewGame>) -> Resp<'a> { let f = f.into_inner(); if f.secret != CONFIG.secret { let mut context = newgame_con(); context.insert("fejl", &"Det indtastede kodeord er forkert 💩"); return Resp::cont(respond_page("newgame_fejl", context)); }
f.home == f.away || f.home_score > 10 || f.away_score > 10 { let mut context = newgame_con(); context.insert("fejl", &"Den indtastede kamp er ikke lovlig 😜"); return Resp::cont(respond_page("newgame_fejl", context)); } let res = lock_database().execute("INSERT INTO games (home_id, away_id, home_score, away_score, dato, \ ball_id) VALUES (?, ?, ?, ?, datetime('now'), ?)", &[&f.home, &f.away, &f.home_score, &f.away_score, &f.ball]); println!("{:?}", res); Resp::red(Redirect::to("/")) } #[get("/games")] pub fn games<'a>() -> ContRes<'a> { let conn = lock_database(); let mut stmt = conn.prepare("SELECT (SELECT name FROM players p WHERE p.id = g.home_id) AS home, \ (SELECT name FROM players p WHERE p.id = g.away_id) AS away, home_score, \ away_score, ball_id, (SELECT img FROM balls b WHERE ball_id = b.id), \ (SELECT name FROM balls b WHERE ball_id = b.id), dato FROM games g WHERE dato > date('now', 'start of month') ORDER BY dato DESC") .unwrap(); let games: Vec<_> = stmt.query_map(NO_PARAMS, |row| { PlayedGame { home: row.get(0), away: row.get(1), home_score: row.get(2), away_score: row.get(3), ball: row.get(5), ball_name: row.get(6), dato: row.get(7), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("games", &games); respond_page("games", context) }
if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score ||
random_line_split
games.rs
use crate::*; #[get("/newgame")] pub fn newgame<'a>() -> ContRes<'a> { respond_page("newgame", newgame_con()) } pub fn newgame_con() -> Context { let conn = lock_database(); let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap(); let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| { Named { id: row.get(0), name: row.get(1) } }) .unwrap() .map(Result::unwrap) .collect(); let mut ballstmt = conn.prepare("SELECT id, name, img FROM balls").unwrap(); let balls: Vec<_> = ballstmt.query_map(NO_PARAMS, |row| { Ball { id: row.get(0), name: row.get(1), img: row.get(2), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("names", &names); context.insert("balls", &balls); context } #[derive(FromForm)] pub struct NewGame { home: i32, away: i32, home_score: i32, away_score: i32, ball: i32, secret: String, #[allow(dead_code)] submit: IgnoreField } #[post("/newgame/submit", data = "<f>")] pub fn submit_newgame<'a>(f: Form<NewGame>) -> Resp<'a> { let f = f.into_inner(); if f.secret != CONFIG.secret
if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score || f.home == f.away || f.home_score > 10 || f.away_score > 10 { let mut context = newgame_con(); context.insert("fejl", &"Den indtastede kamp er ikke lovlig 😜"); return Resp::cont(respond_page("newgame_fejl", context)); } let res = lock_database().execute("INSERT INTO games (home_id, away_id, home_score, away_score, dato, \ ball_id) VALUES (?, ?, ?, ?, datetime('now'), ?)", &[&f.home, &f.away, &f.home_score, &f.away_score, &f.ball]); println!("{:?}", res); Resp::red(Redirect::to("/")) } #[get("/games")] pub fn games<'a>() -> ContRes<'a> { let conn = lock_database(); let mut stmt = conn.prepare("SELECT (SELECT name FROM players p WHERE p.id = g.home_id) AS home, \ (SELECT name FROM players p WHERE p.id = g.away_id) AS away, home_score, \ away_score, ball_id, (SELECT img FROM balls b WHERE ball_id = b.id), \ (SELECT name FROM balls b WHERE ball_id = b.id), dato FROM games g WHERE dato > date('now', 'start of month') ORDER BY dato DESC") .unwrap(); let games: Vec<_> = stmt.query_map(NO_PARAMS, |row| { PlayedGame { home: row.get(0), away: row.get(1), home_score: row.get(2), away_score: row.get(3), ball: row.get(5), ball_name: row.get(6), dato: row.get(7), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("games", &games); respond_page("games", context) }
{ let mut context = newgame_con(); context.insert("fejl", &"Det indtastede kodeord er forkert 💩"); return Resp::cont(respond_page("newgame_fejl", context)); }
conditional_block
games.rs
use crate::*; #[get("/newgame")] pub fn newgame<'a>() -> ContRes<'a> { respond_page("newgame", newgame_con()) } pub fn newgame_con() -> Context
#[derive(FromForm)] pub struct NewGame { home: i32, away: i32, home_score: i32, away_score: i32, ball: i32, secret: String, #[allow(dead_code)] submit: IgnoreField } #[post("/newgame/submit", data = "<f>")] pub fn submit_newgame<'a>(f: Form<NewGame>) -> Resp<'a> { let f = f.into_inner(); if f.secret != CONFIG.secret { let mut context = newgame_con(); context.insert("fejl", &"Det indtastede kodeord er forkert 💩"); return Resp::cont(respond_page("newgame_fejl", context)); } if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score || f.home == f.away || f.home_score > 10 || f.away_score > 10 { let mut context = newgame_con(); context.insert("fejl", &"Den indtastede kamp er ikke lovlig 😜"); return Resp::cont(respond_page("newgame_fejl", context)); } let res = lock_database().execute("INSERT INTO games (home_id, away_id, home_score, away_score, dato, \ ball_id) VALUES (?, ?, ?, ?, datetime('now'), ?)", &[&f.home, &f.away, &f.home_score, &f.away_score, &f.ball]); println!("{:?}", res); Resp::red(Redirect::to("/")) } #[get("/games")] pub fn games<'a>() -> ContRes<'a> { let conn = lock_database(); let mut stmt = conn.prepare("SELECT (SELECT name FROM players p WHERE p.id = g.home_id) AS home, \ (SELECT name FROM players p WHERE p.id = g.away_id) AS away, home_score, \ away_score, ball_id, (SELECT img FROM balls b WHERE ball_id = b.id), \ (SELECT name FROM balls b WHERE ball_id = b.id), dato FROM games g WHERE dato > date('now', 'start of month') ORDER BY dato DESC") .unwrap(); let games: Vec<_> = stmt.query_map(NO_PARAMS, |row| { PlayedGame { home: row.get(0), away: row.get(1), home_score: row.get(2), away_score: row.get(3), ball: row.get(5), ball_name: row.get(6), dato: row.get(7), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("games", &games); respond_page("games", context) }
{ let conn = lock_database(); let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap(); let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| { Named { id: row.get(0), name: row.get(1) } }) .unwrap() .map(Result::unwrap) .collect(); let mut ballstmt = conn.prepare("SELECT id, name, img FROM balls").unwrap(); let balls: Vec<_> = ballstmt.query_map(NO_PARAMS, |row| { Ball { id: row.get(0), name: row.get(1), img: row.get(2), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("names", &names); context.insert("balls", &balls); context }
identifier_body
games.rs
use crate::*; #[get("/newgame")] pub fn newgame<'a>() -> ContRes<'a> { respond_page("newgame", newgame_con()) } pub fn
() -> Context { let conn = lock_database(); let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap(); let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| { Named { id: row.get(0), name: row.get(1) } }) .unwrap() .map(Result::unwrap) .collect(); let mut ballstmt = conn.prepare("SELECT id, name, img FROM balls").unwrap(); let balls: Vec<_> = ballstmt.query_map(NO_PARAMS, |row| { Ball { id: row.get(0), name: row.get(1), img: row.get(2), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("names", &names); context.insert("balls", &balls); context } #[derive(FromForm)] pub struct NewGame { home: i32, away: i32, home_score: i32, away_score: i32, ball: i32, secret: String, #[allow(dead_code)] submit: IgnoreField } #[post("/newgame/submit", data = "<f>")] pub fn submit_newgame<'a>(f: Form<NewGame>) -> Resp<'a> { let f = f.into_inner(); if f.secret != CONFIG.secret { let mut context = newgame_con(); context.insert("fejl", &"Det indtastede kodeord er forkert 💩"); return Resp::cont(respond_page("newgame_fejl", context)); } if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score || f.home == f.away || f.home_score > 10 || f.away_score > 10 { let mut context = newgame_con(); context.insert("fejl", &"Den indtastede kamp er ikke lovlig 😜"); return Resp::cont(respond_page("newgame_fejl", context)); } let res = lock_database().execute("INSERT INTO games (home_id, away_id, home_score, away_score, dato, \ ball_id) VALUES (?, ?, ?, ?, datetime('now'), ?)", &[&f.home, &f.away, &f.home_score, &f.away_score, &f.ball]); println!("{:?}", res); Resp::red(Redirect::to("/")) } #[get("/games")] pub fn games<'a>() -> ContRes<'a> { let conn = lock_database(); let mut stmt = conn.prepare("SELECT (SELECT name FROM players p WHERE p.id = g.home_id) AS home, \ (SELECT name FROM players p WHERE p.id = g.away_id) AS away, home_score, \ away_score, ball_id, (SELECT img FROM balls b WHERE ball_id = b.id), \ (SELECT name FROM balls b WHERE ball_id = b.id), dato FROM games g WHERE dato > date('now', 'start of month') ORDER BY dato DESC") .unwrap(); let games: Vec<_> = stmt.query_map(NO_PARAMS, |row| { PlayedGame { home: row.get(0), away: row.get(1), home_score: row.get(2), away_score: row.get(3), ball: row.get(5), ball_name: row.get(6), dato: row.get(7), } }) .unwrap() .map(Result::unwrap) .collect(); let mut context = create_context("games"); context.insert("games", &games); respond_page("games", context) }
newgame_con
identifier_name
cari.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-baca'; import { TulisArtikelPage } from '../tulis-artikel/tulis-artikel'; import { TulisDiskusiPage } from '../tulis-diskusi/tulis-diskusi'; import '../../providers/user-data'; /* Generated class for the Cari page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-cari', templateUrl: 'cari.html' }) export class CariPage { public searchQuery = ""; public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, public http: Http, public toastCtrl: ToastController) { this.getData(); } ionViewDidLoad() { console.log('Hello CariPage Page'); } notif() { this.navCtrl.push(NotifikasiPage); } getData() { this.limit = 0; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = res.json(); console.log('dapet data'); this.httpErr = false; }, err => {this.showAlert(err.status)}); } getItems(searchbar){ this.getData(); } doInfinite(infiniteScroll) { console.log('Begin async operation'); setTimeout(() => { this.limit = this.limit+5; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = this.posts.concat(res.json()); }); console.log('Async operation has ended'); infiniteScroll.complete(); }, 2000); }
(idArtikel){ this.navCtrl.push(ArtikelBacaPage, idArtikel); } presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Pilihan', buttons: [ { text: 'Tulis Artikel', role: 'tulisArtikel', handler: () => { console.log('Tulis Artikel clicked'); this.navCtrl.push(TulisArtikelPage); } },{ text: 'Tanya/Diskusi', role: 'tulisDiskusi', handler: () => { console.log('Tulis Diskusi clicked'); this.navCtrl.push(TulisDiskusiPage); } },{ text: 'Batal', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); actionSheet.present(); } showAlert(status){ if(status == 0){ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
baca
identifier_name
cari.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-baca'; import { TulisArtikelPage } from '../tulis-artikel/tulis-artikel'; import { TulisDiskusiPage } from '../tulis-diskusi/tulis-diskusi'; import '../../providers/user-data'; /* Generated class for the Cari page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-cari', templateUrl: 'cari.html' }) export class CariPage { public searchQuery = ""; public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, public http: Http, public toastCtrl: ToastController) { this.getData(); } ionViewDidLoad() { console.log('Hello CariPage Page'); } notif() { this.navCtrl.push(NotifikasiPage); } getData() { this.limit = 0; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = res.json(); console.log('dapet data'); this.httpErr = false; }, err => {this.showAlert(err.status)}); } getItems(searchbar){ this.getData(); } doInfinite(infiniteScroll) { console.log('Begin async operation'); setTimeout(() => { this.limit = this.limit+5; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = this.posts.concat(res.json()); }); console.log('Async operation has ended'); infiniteScroll.complete(); }, 2000); } baca(idArtikel){ this.navCtrl.push(ArtikelBacaPage, idArtikel); } presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Pilihan', buttons: [ { text: 'Tulis Artikel', role: 'tulisArtikel', handler: () => { console.log('Tulis Artikel clicked'); this.navCtrl.push(TulisArtikelPage); } },{ text: 'Tanya/Diskusi', role: 'tulisDiskusi', handler: () => { console.log('Tulis Diskusi clicked'); this.navCtrl.push(TulisDiskusiPage); } },{ text: 'Batal', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); actionSheet.present(); } showAlert(status){ if(status == 0)
else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
{ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }
conditional_block
cari.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-baca'; import { TulisArtikelPage } from '../tulis-artikel/tulis-artikel'; import { TulisDiskusiPage } from '../tulis-diskusi/tulis-diskusi'; import '../../providers/user-data'; /* Generated class for the Cari page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-cari', templateUrl: 'cari.html' }) export class CariPage { public searchQuery = ""; public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, public http: Http, public toastCtrl: ToastController) { this.getData(); } ionViewDidLoad() { console.log('Hello CariPage Page'); } notif() { this.navCtrl.push(NotifikasiPage); } getData() { this.limit = 0; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = res.json(); console.log('dapet data'); this.httpErr = false; }, err => {this.showAlert(err.status)}); } getItems(searchbar){ this.getData();
console.log('Begin async operation'); setTimeout(() => { this.limit = this.limit+5; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = this.posts.concat(res.json()); }); console.log('Async operation has ended'); infiniteScroll.complete(); }, 2000); } baca(idArtikel){ this.navCtrl.push(ArtikelBacaPage, idArtikel); } presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Pilihan', buttons: [ { text: 'Tulis Artikel', role: 'tulisArtikel', handler: () => { console.log('Tulis Artikel clicked'); this.navCtrl.push(TulisArtikelPage); } },{ text: 'Tanya/Diskusi', role: 'tulisDiskusi', handler: () => { console.log('Tulis Diskusi clicked'); this.navCtrl.push(TulisDiskusiPage); } },{ text: 'Batal', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); actionSheet.present(); } showAlert(status){ if(status == 0){ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
} doInfinite(infiniteScroll) {
random_line_split
cari.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-baca'; import { TulisArtikelPage } from '../tulis-artikel/tulis-artikel'; import { TulisDiskusiPage } from '../tulis-diskusi/tulis-diskusi'; import '../../providers/user-data'; /* Generated class for the Cari page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-cari', templateUrl: 'cari.html' }) export class CariPage { public searchQuery = ""; public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, public http: Http, public toastCtrl: ToastController) { this.getData(); } ionViewDidLoad() { console.log('Hello CariPage Page'); } notif()
getData() { this.limit = 0; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = res.json(); console.log('dapet data'); this.httpErr = false; }, err => {this.showAlert(err.status)}); } getItems(searchbar){ this.getData(); } doInfinite(infiniteScroll) { console.log('Begin async operation'); setTimeout(() => { this.limit = this.limit+5; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = this.posts.concat(res.json()); }); console.log('Async operation has ended'); infiniteScroll.complete(); }, 2000); } baca(idArtikel){ this.navCtrl.push(ArtikelBacaPage, idArtikel); } presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Pilihan', buttons: [ { text: 'Tulis Artikel', role: 'tulisArtikel', handler: () => { console.log('Tulis Artikel clicked'); this.navCtrl.push(TulisArtikelPage); } },{ text: 'Tanya/Diskusi', role: 'tulisDiskusi', handler: () => { console.log('Tulis Diskusi clicked'); this.navCtrl.push(TulisDiskusiPage); } },{ text: 'Batal', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); actionSheet.present(); } showAlert(status){ if(status == 0){ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
{ this.navCtrl.push(NotifikasiPage); }
identifier_body
models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.contrib.auth.models import User from django.template.loader import render_to_string from django.conf import settings from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.core.mail import send_mail from django.core.exceptions import ImproperlyConfigured from django.utils.http import urlquote from userena.utils import get_gravatar, generate_sha1, get_protocol from userena.managers import UserenaManager, UserenaBaseProfileManager from userena import settings as userena_settings from guardian.shortcuts import get_perms from guardian.shortcuts import assign from easy_thumbnails.fields import ThumbnailerImageField import datetime import random import hashlib PROFILE_PERMISSIONS = ( ('view_profile', 'Can view profile'), ) def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH, 'hash': hash[:10], 'extension': extension} class UserenaSignup(models.Model): """ Userena model which stores all the necessary information to have a full functional user implementation on your Django website. """ user = models.OneToOneField(User, verbose_name=_('user'), related_name='userena_signup') last_active = models.DateTimeField(_('last active'), blank=True, null=True, help_text=_('The last date that the user was active.')) activation_key = models.CharField(_('activation key'), max_length=40, blank=True) activation_notification_send = models.BooleanField(_('notification send'), default=False, help_text=_('Designates whether this user has already got a notification about activating their account.')) email_unconfirmed = models.EmailField(_('unconfirmed email address'), blank=True, help_text=_('Temporary email address when the user requests an email change.')) email_confirmation_key = models.CharField(_('unconfirmed email verification key'), max_length=40, blank=True) email_confirmation_key_created = models.DateTimeField(_('creation date of email confirmation key'), blank=True, null=True) objects = UserenaManager() class Meta: verbose_name = _('userena registration') verbose_name_plural = _('userena registrations') def __unicode__(self): return '%s' % self.user.username def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = timezone.now() self.save() # Send email for activation self.send_confirmation_email() def
(self): """ Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`UserenaUser.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address. """ context= {'user': self.user, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} # Email to the old address subject_old = render_to_string('accounts/emails/confirmation_email_subject_old.txt', context) subject_old = ''.join(subject_old.splitlines()) message_old = render_to_string('accounts/emails/confirmation_email_message_old.txt', context) send_mail(subject_old, message_old, settings.DEFAULT_FROM_EMAIL, [self.user.email]) # Email to the new address subject_new = render_to_string('accounts/emails/confirmation_email_subject_new.txt', context) subject_new = ''.join(subject_new.splitlines()) message_new = render_to_string('accounts/emails/confirmation_email_message_new.txt', context) send_mail(subject_new, message_new, settings.DEFAULT_FROM_EMAIL, [self.email_unconfirmed,]) def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``USERENA_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS) expiration_date = self.user.date_joined + expiration_days if self.activation_key == userena_settings.USERENA_ACTIVATED: return True if timezone.now() >= expiration_date: return True return False def send_activation_email(self, auto_join_secret = False): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ if not auto_join_secret: activation_url = reverse('userena_activate', args=(self.user.username, self.activation_key)) else: if isinstance(auto_join_secret, basestring): auto_join_key = auto_join_secret else: auto_join_key = hashlib.md5(self.activation_key + settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest() activation_url = reverse('auto_join_activate', args=(self.user.username, auto_join_key)) context= {'user': self.user, 'protocol': get_protocol(), 'activation_days': userena_settings.USERENA_ACTIVATION_DAYS, 'activation_url': activation_url, 'site': Site.objects.get_current()} subject = render_to_string('accounts/emails/activation_email_subject.txt', context) subject = ''.join(subject.splitlines()) message = render_to_string('accounts/emails/activation_email_message.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email,]) class UserenaBaseProfile(models.Model): """ Base model needed for extra profile functionality """ PRIVACY_CHOICES = ( ('open', _('Open')), ('registered', _('Registered')), ('closed', _('Closed')), ) MUGSHOT_SETTINGS = {'size': (userena_settings.USERENA_MUGSHOT_SIZE, userena_settings.USERENA_MUGSHOT_SIZE), 'crop': 'smart'} mugshot = ThumbnailerImageField(_('mugshot'), blank=True, upload_to=upload_to_mugshot, resize_source=MUGSHOT_SETTINGS, help_text=_('A personal image displayed in your profile.')) privacy = models.CharField(_('privacy'), max_length=15, choices=PRIVACY_CHOICES, default=userena_settings.USERENA_DEFAULT_PRIVACY, help_text = _('Designates who can view your profile.')) objects = UserenaBaseProfileManager() class Meta: """ Meta options making the model abstract and defining permissions. The model is ``abstract`` because it only supplies basic functionality to a more custom defined model that extends it. This way there is not another join needed. We also define custom permissions because we don't know how the model that extends this one is going to be called. So we don't know what permissions to check. For ex. if the user defines a profile model that is called ``MyProfile``, than the permissions would be ``add_myprofile`` etc. We want to be able to always check ``add_profile``, ``change_profile`` etc. """ abstract = True permissions = PROFILE_PERMISSIONS def __unicode__(self): return 'Profile of %(username)s' % {'username': self.user.username} def get_mugshot_url(self, custom_size = userena_settings.USERENA_MUGSHOT_SIZE): """ Returns the image containing the mugshot for the user. The mugshot can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``USERENA_MUGSHOT_GRAVATAR`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``USERENA_MUGSHOT_DEFAULT``. """ # First check for a mugshot and if any return that. if self.mugshot: return settings.MEDIA_URL +\ settings.MUGSHOTS_DIR +\ self.mugshot.name.split("/")[-1] # Use Gravatar if the user wants to. if userena_settings.USERENA_MUGSHOT_GRAVATAR: if userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials-ssl': d = 'https://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) elif userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials': d = 'http://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) return get_gravatar(self.user.email, custom_size, d) # Gravatar not used, check for a default image. else: if userena_settings.USERENA_MUGSHOT_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'blank']: return userena_settings.USERENA_MUGSHOT_DEFAULT else: return None def get_full_name_or_username(self): """ Returns the full name of the user, or if none is supplied will return the username. Also looks at ``USERENA_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``USERENA_WITHOUT_USERNAMES`` setting. """ user = self.user if user.first_name or user.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _("%(first_name)s %(last_name)s") % \ {'first_name': user.first_name, 'last_name': user.last_name} else: # Fallback to the username if usernames are used if not userena_settings.USERENA_WITHOUT_USERNAMES: name = "%(username)s" % {'username': user.username} else: name = "%(email)s" % {'email': user.email} return name.strip() def can_view_profile(self, user): """ Can the :class:`User` view this profile? Returns a boolean if a user has the rights to view the profile of this user. Users are divided into four groups: ``Open`` Everyone can view your profile ``Closed`` Nobody can view your profile. ``Registered`` Users that are registered on the website and signed in only. ``Admin`` Special cases like superadmin and the owner of the profile. Through the ``privacy`` field a owner of an profile can define what they want to show to whom. :param user: A Django :class:`User` instance. """ # Simple cases first, we don't want to waste CPU and DB hits. # Everyone. if self.privacy == 'open': return True # Registered users. elif self.privacy == 'registered' and isinstance(user, User): return True # Checks done by guardian for owner and admins. elif 'view_profile' in get_perms(user, self): return True # Fallback to closed profile. return False class UserenaLanguageBaseProfile(UserenaBaseProfile): """ Extends the :class:`UserenaBaseProfile` with a language choice. Use this model in combination with ``UserenaLocaleMiddleware`` automatically set the language of users when they are signed in. """ language = models.CharField(_('language'), max_length=5, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE[:2]) class Meta: abstract = True permissions = PROFILE_PERMISSIONS
send_confirmation_email
identifier_name
models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.contrib.auth.models import User from django.template.loader import render_to_string from django.conf import settings from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.core.mail import send_mail from django.core.exceptions import ImproperlyConfigured from django.utils.http import urlquote from userena.utils import get_gravatar, generate_sha1, get_protocol from userena.managers import UserenaManager, UserenaBaseProfileManager from userena import settings as userena_settings from guardian.shortcuts import get_perms from guardian.shortcuts import assign from easy_thumbnails.fields import ThumbnailerImageField import datetime import random import hashlib PROFILE_PERMISSIONS = ( ('view_profile', 'Can view profile'), ) def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH, 'hash': hash[:10], 'extension': extension} class UserenaSignup(models.Model): """ Userena model which stores all the necessary information to have a full functional user implementation on your Django website. """ user = models.OneToOneField(User, verbose_name=_('user'), related_name='userena_signup') last_active = models.DateTimeField(_('last active'), blank=True, null=True, help_text=_('The last date that the user was active.')) activation_key = models.CharField(_('activation key'), max_length=40, blank=True) activation_notification_send = models.BooleanField(_('notification send'), default=False, help_text=_('Designates whether this user has already got a notification about activating their account.')) email_unconfirmed = models.EmailField(_('unconfirmed email address'), blank=True, help_text=_('Temporary email address when the user requests an email change.'))
email_confirmation_key_created = models.DateTimeField(_('creation date of email confirmation key'), blank=True, null=True) objects = UserenaManager() class Meta: verbose_name = _('userena registration') verbose_name_plural = _('userena registrations') def __unicode__(self): return '%s' % self.user.username def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = timezone.now() self.save() # Send email for activation self.send_confirmation_email() def send_confirmation_email(self): """ Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`UserenaUser.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address. """ context= {'user': self.user, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} # Email to the old address subject_old = render_to_string('accounts/emails/confirmation_email_subject_old.txt', context) subject_old = ''.join(subject_old.splitlines()) message_old = render_to_string('accounts/emails/confirmation_email_message_old.txt', context) send_mail(subject_old, message_old, settings.DEFAULT_FROM_EMAIL, [self.user.email]) # Email to the new address subject_new = render_to_string('accounts/emails/confirmation_email_subject_new.txt', context) subject_new = ''.join(subject_new.splitlines()) message_new = render_to_string('accounts/emails/confirmation_email_message_new.txt', context) send_mail(subject_new, message_new, settings.DEFAULT_FROM_EMAIL, [self.email_unconfirmed,]) def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``USERENA_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS) expiration_date = self.user.date_joined + expiration_days if self.activation_key == userena_settings.USERENA_ACTIVATED: return True if timezone.now() >= expiration_date: return True return False def send_activation_email(self, auto_join_secret = False): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ if not auto_join_secret: activation_url = reverse('userena_activate', args=(self.user.username, self.activation_key)) else: if isinstance(auto_join_secret, basestring): auto_join_key = auto_join_secret else: auto_join_key = hashlib.md5(self.activation_key + settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest() activation_url = reverse('auto_join_activate', args=(self.user.username, auto_join_key)) context= {'user': self.user, 'protocol': get_protocol(), 'activation_days': userena_settings.USERENA_ACTIVATION_DAYS, 'activation_url': activation_url, 'site': Site.objects.get_current()} subject = render_to_string('accounts/emails/activation_email_subject.txt', context) subject = ''.join(subject.splitlines()) message = render_to_string('accounts/emails/activation_email_message.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email,]) class UserenaBaseProfile(models.Model): """ Base model needed for extra profile functionality """ PRIVACY_CHOICES = ( ('open', _('Open')), ('registered', _('Registered')), ('closed', _('Closed')), ) MUGSHOT_SETTINGS = {'size': (userena_settings.USERENA_MUGSHOT_SIZE, userena_settings.USERENA_MUGSHOT_SIZE), 'crop': 'smart'} mugshot = ThumbnailerImageField(_('mugshot'), blank=True, upload_to=upload_to_mugshot, resize_source=MUGSHOT_SETTINGS, help_text=_('A personal image displayed in your profile.')) privacy = models.CharField(_('privacy'), max_length=15, choices=PRIVACY_CHOICES, default=userena_settings.USERENA_DEFAULT_PRIVACY, help_text = _('Designates who can view your profile.')) objects = UserenaBaseProfileManager() class Meta: """ Meta options making the model abstract and defining permissions. The model is ``abstract`` because it only supplies basic functionality to a more custom defined model that extends it. This way there is not another join needed. We also define custom permissions because we don't know how the model that extends this one is going to be called. So we don't know what permissions to check. For ex. if the user defines a profile model that is called ``MyProfile``, than the permissions would be ``add_myprofile`` etc. We want to be able to always check ``add_profile``, ``change_profile`` etc. """ abstract = True permissions = PROFILE_PERMISSIONS def __unicode__(self): return 'Profile of %(username)s' % {'username': self.user.username} def get_mugshot_url(self, custom_size = userena_settings.USERENA_MUGSHOT_SIZE): """ Returns the image containing the mugshot for the user. The mugshot can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``USERENA_MUGSHOT_GRAVATAR`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``USERENA_MUGSHOT_DEFAULT``. """ # First check for a mugshot and if any return that. if self.mugshot: return settings.MEDIA_URL +\ settings.MUGSHOTS_DIR +\ self.mugshot.name.split("/")[-1] # Use Gravatar if the user wants to. if userena_settings.USERENA_MUGSHOT_GRAVATAR: if userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials-ssl': d = 'https://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) elif userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials': d = 'http://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) return get_gravatar(self.user.email, custom_size, d) # Gravatar not used, check for a default image. else: if userena_settings.USERENA_MUGSHOT_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'blank']: return userena_settings.USERENA_MUGSHOT_DEFAULT else: return None def get_full_name_or_username(self): """ Returns the full name of the user, or if none is supplied will return the username. Also looks at ``USERENA_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``USERENA_WITHOUT_USERNAMES`` setting. """ user = self.user if user.first_name or user.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _("%(first_name)s %(last_name)s") % \ {'first_name': user.first_name, 'last_name': user.last_name} else: # Fallback to the username if usernames are used if not userena_settings.USERENA_WITHOUT_USERNAMES: name = "%(username)s" % {'username': user.username} else: name = "%(email)s" % {'email': user.email} return name.strip() def can_view_profile(self, user): """ Can the :class:`User` view this profile? Returns a boolean if a user has the rights to view the profile of this user. Users are divided into four groups: ``Open`` Everyone can view your profile ``Closed`` Nobody can view your profile. ``Registered`` Users that are registered on the website and signed in only. ``Admin`` Special cases like superadmin and the owner of the profile. Through the ``privacy`` field a owner of an profile can define what they want to show to whom. :param user: A Django :class:`User` instance. """ # Simple cases first, we don't want to waste CPU and DB hits. # Everyone. if self.privacy == 'open': return True # Registered users. elif self.privacy == 'registered' and isinstance(user, User): return True # Checks done by guardian for owner and admins. elif 'view_profile' in get_perms(user, self): return True # Fallback to closed profile. return False class UserenaLanguageBaseProfile(UserenaBaseProfile): """ Extends the :class:`UserenaBaseProfile` with a language choice. Use this model in combination with ``UserenaLocaleMiddleware`` automatically set the language of users when they are signed in. """ language = models.CharField(_('language'), max_length=5, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE[:2]) class Meta: abstract = True permissions = PROFILE_PERMISSIONS
email_confirmation_key = models.CharField(_('unconfirmed email verification key'), max_length=40, blank=True)
random_line_split
models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.contrib.auth.models import User from django.template.loader import render_to_string from django.conf import settings from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.core.mail import send_mail from django.core.exceptions import ImproperlyConfigured from django.utils.http import urlquote from userena.utils import get_gravatar, generate_sha1, get_protocol from userena.managers import UserenaManager, UserenaBaseProfileManager from userena import settings as userena_settings from guardian.shortcuts import get_perms from guardian.shortcuts import assign from easy_thumbnails.fields import ThumbnailerImageField import datetime import random import hashlib PROFILE_PERMISSIONS = ( ('view_profile', 'Can view profile'), ) def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH, 'hash': hash[:10], 'extension': extension} class UserenaSignup(models.Model): """ Userena model which stores all the necessary information to have a full functional user implementation on your Django website. """ user = models.OneToOneField(User, verbose_name=_('user'), related_name='userena_signup') last_active = models.DateTimeField(_('last active'), blank=True, null=True, help_text=_('The last date that the user was active.')) activation_key = models.CharField(_('activation key'), max_length=40, blank=True) activation_notification_send = models.BooleanField(_('notification send'), default=False, help_text=_('Designates whether this user has already got a notification about activating their account.')) email_unconfirmed = models.EmailField(_('unconfirmed email address'), blank=True, help_text=_('Temporary email address when the user requests an email change.')) email_confirmation_key = models.CharField(_('unconfirmed email verification key'), max_length=40, blank=True) email_confirmation_key_created = models.DateTimeField(_('creation date of email confirmation key'), blank=True, null=True) objects = UserenaManager() class Meta: verbose_name = _('userena registration') verbose_name_plural = _('userena registrations') def __unicode__(self):
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = timezone.now() self.save() # Send email for activation self.send_confirmation_email() def send_confirmation_email(self): """ Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`UserenaUser.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address. """ context= {'user': self.user, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} # Email to the old address subject_old = render_to_string('accounts/emails/confirmation_email_subject_old.txt', context) subject_old = ''.join(subject_old.splitlines()) message_old = render_to_string('accounts/emails/confirmation_email_message_old.txt', context) send_mail(subject_old, message_old, settings.DEFAULT_FROM_EMAIL, [self.user.email]) # Email to the new address subject_new = render_to_string('accounts/emails/confirmation_email_subject_new.txt', context) subject_new = ''.join(subject_new.splitlines()) message_new = render_to_string('accounts/emails/confirmation_email_message_new.txt', context) send_mail(subject_new, message_new, settings.DEFAULT_FROM_EMAIL, [self.email_unconfirmed,]) def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``USERENA_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS) expiration_date = self.user.date_joined + expiration_days if self.activation_key == userena_settings.USERENA_ACTIVATED: return True if timezone.now() >= expiration_date: return True return False def send_activation_email(self, auto_join_secret = False): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ if not auto_join_secret: activation_url = reverse('userena_activate', args=(self.user.username, self.activation_key)) else: if isinstance(auto_join_secret, basestring): auto_join_key = auto_join_secret else: auto_join_key = hashlib.md5(self.activation_key + settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest() activation_url = reverse('auto_join_activate', args=(self.user.username, auto_join_key)) context= {'user': self.user, 'protocol': get_protocol(), 'activation_days': userena_settings.USERENA_ACTIVATION_DAYS, 'activation_url': activation_url, 'site': Site.objects.get_current()} subject = render_to_string('accounts/emails/activation_email_subject.txt', context) subject = ''.join(subject.splitlines()) message = render_to_string('accounts/emails/activation_email_message.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email,]) class UserenaBaseProfile(models.Model): """ Base model needed for extra profile functionality """ PRIVACY_CHOICES = ( ('open', _('Open')), ('registered', _('Registered')), ('closed', _('Closed')), ) MUGSHOT_SETTINGS = {'size': (userena_settings.USERENA_MUGSHOT_SIZE, userena_settings.USERENA_MUGSHOT_SIZE), 'crop': 'smart'} mugshot = ThumbnailerImageField(_('mugshot'), blank=True, upload_to=upload_to_mugshot, resize_source=MUGSHOT_SETTINGS, help_text=_('A personal image displayed in your profile.')) privacy = models.CharField(_('privacy'), max_length=15, choices=PRIVACY_CHOICES, default=userena_settings.USERENA_DEFAULT_PRIVACY, help_text = _('Designates who can view your profile.')) objects = UserenaBaseProfileManager() class Meta: """ Meta options making the model abstract and defining permissions. The model is ``abstract`` because it only supplies basic functionality to a more custom defined model that extends it. This way there is not another join needed. We also define custom permissions because we don't know how the model that extends this one is going to be called. So we don't know what permissions to check. For ex. if the user defines a profile model that is called ``MyProfile``, than the permissions would be ``add_myprofile`` etc. We want to be able to always check ``add_profile``, ``change_profile`` etc. """ abstract = True permissions = PROFILE_PERMISSIONS def __unicode__(self): return 'Profile of %(username)s' % {'username': self.user.username} def get_mugshot_url(self, custom_size = userena_settings.USERENA_MUGSHOT_SIZE): """ Returns the image containing the mugshot for the user. The mugshot can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``USERENA_MUGSHOT_GRAVATAR`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``USERENA_MUGSHOT_DEFAULT``. """ # First check for a mugshot and if any return that. if self.mugshot: return settings.MEDIA_URL +\ settings.MUGSHOTS_DIR +\ self.mugshot.name.split("/")[-1] # Use Gravatar if the user wants to. if userena_settings.USERENA_MUGSHOT_GRAVATAR: if userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials-ssl': d = 'https://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) elif userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials': d = 'http://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) return get_gravatar(self.user.email, custom_size, d) # Gravatar not used, check for a default image. else: if userena_settings.USERENA_MUGSHOT_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'blank']: return userena_settings.USERENA_MUGSHOT_DEFAULT else: return None def get_full_name_or_username(self): """ Returns the full name of the user, or if none is supplied will return the username. Also looks at ``USERENA_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``USERENA_WITHOUT_USERNAMES`` setting. """ user = self.user if user.first_name or user.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _("%(first_name)s %(last_name)s") % \ {'first_name': user.first_name, 'last_name': user.last_name} else: # Fallback to the username if usernames are used if not userena_settings.USERENA_WITHOUT_USERNAMES: name = "%(username)s" % {'username': user.username} else: name = "%(email)s" % {'email': user.email} return name.strip() def can_view_profile(self, user): """ Can the :class:`User` view this profile? Returns a boolean if a user has the rights to view the profile of this user. Users are divided into four groups: ``Open`` Everyone can view your profile ``Closed`` Nobody can view your profile. ``Registered`` Users that are registered on the website and signed in only. ``Admin`` Special cases like superadmin and the owner of the profile. Through the ``privacy`` field a owner of an profile can define what they want to show to whom. :param user: A Django :class:`User` instance. """ # Simple cases first, we don't want to waste CPU and DB hits. # Everyone. if self.privacy == 'open': return True # Registered users. elif self.privacy == 'registered' and isinstance(user, User): return True # Checks done by guardian for owner and admins. elif 'view_profile' in get_perms(user, self): return True # Fallback to closed profile. return False class UserenaLanguageBaseProfile(UserenaBaseProfile): """ Extends the :class:`UserenaBaseProfile` with a language choice. Use this model in combination with ``UserenaLocaleMiddleware`` automatically set the language of users when they are signed in. """ language = models.CharField(_('language'), max_length=5, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE[:2]) class Meta: abstract = True permissions = PROFILE_PERMISSIONS
return '%s' % self.user.username
identifier_body
models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.contrib.auth.models import User from django.template.loader import render_to_string from django.conf import settings from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.core.mail import send_mail from django.core.exceptions import ImproperlyConfigured from django.utils.http import urlquote from userena.utils import get_gravatar, generate_sha1, get_protocol from userena.managers import UserenaManager, UserenaBaseProfileManager from userena import settings as userena_settings from guardian.shortcuts import get_perms from guardian.shortcuts import assign from easy_thumbnails.fields import ThumbnailerImageField import datetime import random import hashlib PROFILE_PERMISSIONS = ( ('view_profile', 'Can view profile'), ) def upload_to_mugshot(instance, filename): """ Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the mugshot directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH, 'hash': hash[:10], 'extension': extension} class UserenaSignup(models.Model): """ Userena model which stores all the necessary information to have a full functional user implementation on your Django website. """ user = models.OneToOneField(User, verbose_name=_('user'), related_name='userena_signup') last_active = models.DateTimeField(_('last active'), blank=True, null=True, help_text=_('The last date that the user was active.')) activation_key = models.CharField(_('activation key'), max_length=40, blank=True) activation_notification_send = models.BooleanField(_('notification send'), default=False, help_text=_('Designates whether this user has already got a notification about activating their account.')) email_unconfirmed = models.EmailField(_('unconfirmed email address'), blank=True, help_text=_('Temporary email address when the user requests an email change.')) email_confirmation_key = models.CharField(_('unconfirmed email verification key'), max_length=40, blank=True) email_confirmation_key_created = models.DateTimeField(_('creation date of email confirmation key'), blank=True, null=True) objects = UserenaManager() class Meta: verbose_name = _('userena registration') verbose_name_plural = _('userena registrations') def __unicode__(self): return '%s' % self.user.username def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.user.username) self.email_confirmation_key = hash self.email_confirmation_key_created = timezone.now() self.save() # Send email for activation self.send_confirmation_email() def send_confirmation_email(self): """ Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`UserenaUser.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address. """ context= {'user': self.user, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} # Email to the old address subject_old = render_to_string('accounts/emails/confirmation_email_subject_old.txt', context) subject_old = ''.join(subject_old.splitlines()) message_old = render_to_string('accounts/emails/confirmation_email_message_old.txt', context) send_mail(subject_old, message_old, settings.DEFAULT_FROM_EMAIL, [self.user.email]) # Email to the new address subject_new = render_to_string('accounts/emails/confirmation_email_subject_new.txt', context) subject_new = ''.join(subject_new.splitlines()) message_new = render_to_string('accounts/emails/confirmation_email_message_new.txt', context) send_mail(subject_new, message_new, settings.DEFAULT_FROM_EMAIL, [self.email_unconfirmed,]) def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``USERENA_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``USERENA_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS) expiration_date = self.user.date_joined + expiration_days if self.activation_key == userena_settings.USERENA_ACTIVATED: return True if timezone.now() >= expiration_date: return True return False def send_activation_email(self, auto_join_secret = False): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ if not auto_join_secret: activation_url = reverse('userena_activate', args=(self.user.username, self.activation_key)) else: if isinstance(auto_join_secret, basestring):
else: auto_join_key = hashlib.md5(self.activation_key + settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest() activation_url = reverse('auto_join_activate', args=(self.user.username, auto_join_key)) context= {'user': self.user, 'protocol': get_protocol(), 'activation_days': userena_settings.USERENA_ACTIVATION_DAYS, 'activation_url': activation_url, 'site': Site.objects.get_current()} subject = render_to_string('accounts/emails/activation_email_subject.txt', context) subject = ''.join(subject.splitlines()) message = render_to_string('accounts/emails/activation_email_message.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email,]) class UserenaBaseProfile(models.Model): """ Base model needed for extra profile functionality """ PRIVACY_CHOICES = ( ('open', _('Open')), ('registered', _('Registered')), ('closed', _('Closed')), ) MUGSHOT_SETTINGS = {'size': (userena_settings.USERENA_MUGSHOT_SIZE, userena_settings.USERENA_MUGSHOT_SIZE), 'crop': 'smart'} mugshot = ThumbnailerImageField(_('mugshot'), blank=True, upload_to=upload_to_mugshot, resize_source=MUGSHOT_SETTINGS, help_text=_('A personal image displayed in your profile.')) privacy = models.CharField(_('privacy'), max_length=15, choices=PRIVACY_CHOICES, default=userena_settings.USERENA_DEFAULT_PRIVACY, help_text = _('Designates who can view your profile.')) objects = UserenaBaseProfileManager() class Meta: """ Meta options making the model abstract and defining permissions. The model is ``abstract`` because it only supplies basic functionality to a more custom defined model that extends it. This way there is not another join needed. We also define custom permissions because we don't know how the model that extends this one is going to be called. So we don't know what permissions to check. For ex. if the user defines a profile model that is called ``MyProfile``, than the permissions would be ``add_myprofile`` etc. We want to be able to always check ``add_profile``, ``change_profile`` etc. """ abstract = True permissions = PROFILE_PERMISSIONS def __unicode__(self): return 'Profile of %(username)s' % {'username': self.user.username} def get_mugshot_url(self, custom_size = userena_settings.USERENA_MUGSHOT_SIZE): """ Returns the image containing the mugshot for the user. The mugshot can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``USERENA_MUGSHOT_GRAVATAR`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``USERENA_MUGSHOT_DEFAULT``. """ # First check for a mugshot and if any return that. if self.mugshot: return settings.MEDIA_URL +\ settings.MUGSHOTS_DIR +\ self.mugshot.name.split("/")[-1] # Use Gravatar if the user wants to. if userena_settings.USERENA_MUGSHOT_GRAVATAR: if userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials-ssl': d = 'https://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) elif userena_settings.USERENA_MUGSHOT_DEFAULT == 'blank-unitials': d = 'http://unitials.com/mugshot/%s/%s.png' % ( custom_size, self.get_initials() ) return get_gravatar(self.user.email, custom_size, d) # Gravatar not used, check for a default image. else: if userena_settings.USERENA_MUGSHOT_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'blank']: return userena_settings.USERENA_MUGSHOT_DEFAULT else: return None def get_full_name_or_username(self): """ Returns the full name of the user, or if none is supplied will return the username. Also looks at ``USERENA_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``USERENA_WITHOUT_USERNAMES`` setting. """ user = self.user if user.first_name or user.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _("%(first_name)s %(last_name)s") % \ {'first_name': user.first_name, 'last_name': user.last_name} else: # Fallback to the username if usernames are used if not userena_settings.USERENA_WITHOUT_USERNAMES: name = "%(username)s" % {'username': user.username} else: name = "%(email)s" % {'email': user.email} return name.strip() def can_view_profile(self, user): """ Can the :class:`User` view this profile? Returns a boolean if a user has the rights to view the profile of this user. Users are divided into four groups: ``Open`` Everyone can view your profile ``Closed`` Nobody can view your profile. ``Registered`` Users that are registered on the website and signed in only. ``Admin`` Special cases like superadmin and the owner of the profile. Through the ``privacy`` field a owner of an profile can define what they want to show to whom. :param user: A Django :class:`User` instance. """ # Simple cases first, we don't want to waste CPU and DB hits. # Everyone. if self.privacy == 'open': return True # Registered users. elif self.privacy == 'registered' and isinstance(user, User): return True # Checks done by guardian for owner and admins. elif 'view_profile' in get_perms(user, self): return True # Fallback to closed profile. return False class UserenaLanguageBaseProfile(UserenaBaseProfile): """ Extends the :class:`UserenaBaseProfile` with a language choice. Use this model in combination with ``UserenaLocaleMiddleware`` automatically set the language of users when they are signed in. """ language = models.CharField(_('language'), max_length=5, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE[:2]) class Meta: abstract = True permissions = PROFILE_PERMISSIONS
auto_join_key = auto_join_secret
conditional_block
control.py
#!/usr/bin/env python # coding:utf-8 import sys, os from twisted.internet import reactor from bottle import Bottle from bottle import request from bottle import response from bottle import redirect from bottle import static_file from bottle import abort from hashlib import md5 from urlparse import urljoin from toughradius.console.base import * from toughradius.console.libs import utils import time import bottle import decimal import datetime import functools import subprocess import platform app = Bottle() @app.route('/static/:path#.+#') def route_static(path, render): static_path = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'static') return static_file(path, root=static_path) @app.get('/', apply=auth_ctl) def control_index(render): return render("index") @app.route('/dashboard', apply=auth_ctl) def
(render): return render("index", **locals())
index
identifier_name
control.py
#!/usr/bin/env python # coding:utf-8 import sys, os from twisted.internet import reactor from bottle import Bottle from bottle import request from bottle import response from bottle import redirect from bottle import static_file from bottle import abort from hashlib import md5 from urlparse import urljoin from toughradius.console.base import * from toughradius.console.libs import utils import time import bottle import decimal import datetime import functools import subprocess import platform app = Bottle() @app.route('/static/:path#.+#') def route_static(path, render):
@app.get('/', apply=auth_ctl) def control_index(render): return render("index") @app.route('/dashboard', apply=auth_ctl) def index(render): return render("index", **locals())
static_path = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'static') return static_file(path, root=static_path)
identifier_body
html_completions.py
import sublime, sublime_plugin import re def match(rex, str): m = rex.match(str) if m: return m.group(0) else: return None # This responds to on_query_completions, but conceptually it's expanding # expressions, rather than completing words. #
# Only trigger within HTML if not view.match_selector(locations[0], "text.html - source - meta.tag, punctuation.definition.tag.begin"): return [] # Get the contents of each line, from the beginning of the line to # each point lines = [view.substr(sublime.Region(view.line(l).a, l)) for l in locations] # Reverse the contents of each line, to simulate having the regex # match backwards lines = [l[::-1] for l in lines] # Check the first location looks like an expression rex = re.compile("([\w-]+)([.#])(\w+)") expr = match(rex, lines[0]) if not expr: return [] # Ensure that all other lines have identical expressions for i in xrange(1, len(lines)): ex = match(rex, lines[i]) if ex != expr: return [] # Return the completions arg, op, tag = rex.match(expr).groups() arg = arg[::-1] tag = tag[::-1] expr = expr[::-1] if op == '.': snippet = "<{0} class=\"{1}\">$1</{0}>$0".format(tag, arg) else: snippet = "<{0} id=\"{1}\">$1</{0}>$0".format(tag, arg) return [(expr, snippet)] # Provide completions that match just after typing an opening angle bracket class TagCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML if not view.match_selector(locations[0], "text.html - source"): return [] pt = locations[0] - len(prefix) - 1 ch = view.substr(sublime.Region(pt, pt + 1)) if ch != '<': return [] return ([ ("a\tTag", "a href=\"$1\">$2</a>"), ("abbr\tTag", "abbr>$1</abbr>"), ("acronym\tTag", "acronym>$1</acronym>"), ("address\tTag", "address>$1</address>"), ("applet\tTag", "applet>$1</applet>"), ("area\tTag", "area>$1</area>"), ("b\tTag", "b>$1</b>"), ("base\tTag", "base>$1</base>"), ("big\tTag", "big>$1</big>"), ("blockquote\tTag", "blockquote>$1</blockquote>"), ("body\tTag", "body>$1</body>"), ("button\tTag", "button>$1</button>"), ("center\tTag", "center>$1</center>"), ("caption\tTag", "caption>$1</caption>"), ("cdata\tTag", "cdata>$1</cdata>"), ("cite\tTag", "cite>$1</cite>"), ("col\tTag", "col>$1</col>"), ("colgroup\tTag", "colgroup>$1</colgroup>"), ("code\tTag", "code>$1</code>"), ("div\tTag", "div>$1</div>"), ("dd\tTag", "dd>$1</dd>"), ("del\tTag", "del>$1</del>"), ("dfn\tTag", "dfn>$1</dfn>"), ("dl\tTag", "dl>$1</dl>"), ("dt\tTag", "dt>$1</dt>"), ("em\tTag", "em>$1</em>"), ("fieldset\tTag", "fieldset>$1</fieldset>"), ("font\tTag", "font>$1</font>"), ("form\tTag", "form>$1</form>"), ("frame\tTag", "frame>$1</frame>"), ("frameset\tTag", "frameset>$1</frameset>"), ("head\tTag", "head>$1</head>"), ("h1\tTag", "h1>$1</h1>"), ("h2\tTag", "h2>$1</h2>"), ("h3\tTag", "h3>$1</h3>"), ("h4\tTag", "h4>$1</h4>"), ("h5\tTag", "h5>$1</h5>"), ("h6\tTag", "h6>$1</h6>"), ("i\tTag", "i>$1</i>"), ("iframe\tTag", "iframe src=\"$1\"></iframe>"), ("ins\tTag", "ins>$1</ins>"), ("kbd\tTag", "kbd>$1</kbd>"), ("li\tTag", "li>$1</li>"), ("label\tTag", "label>$1</label>"), ("legend\tTag", "legend>$1</legend>"), ("link\tTag", "link rel=\"stylesheet\" type=\"text/css\" href=\"$1\">"), ("map\tTag", "map>$1</map>"), ("noframes\tTag", "noframes>$1</noframes>"), ("object\tTag", "object>$1</object>"), ("ol\tTag", "ol>$1</ol>"), ("optgroup\tTag", "optgroup>$1</optgroup>"), ("option\tTag", "option>$0</option>"), ("p\tTag", "p>$1</p>"), ("pre\tTag", "pre>$1</pre>"), ("span\tTag", "span>$1</span>"), ("samp\tTag", "samp>$1</samp>"), ("script\tTag", "script type=\"${1:text/javascript}\">$0</script>"), ("style\tTag", "style type=\"${1:text/css}\">$0</style>"), ("select\tTag", "select>$1</select>"), ("small\tTag", "small>$1</small>"), ("strong\tTag", "strong>$1</strong>"), ("sub\tTag", "sub>$1</sub>"), ("sup\tTag", "sup>$1</sup>"), ("table\tTag", "table>$1</table>"), ("tbody\tTag", "tbody>$1</tbody>"), ("td\tTag", "td>$1</td>"), ("textarea\tTag", "textarea>$1</textarea>"), ("tfoot\tTag", "tfoot>$1</tfoot>"), ("th\tTag", "th>$1</th>"), ("thead\tTag", "thead>$1</thead>"), ("title\tTag", "title>$1</title>"), ("tr\tTag", "tr>$1</tr>"), ("tt\tTag", "tt>$1</tt>"), ("u\tTag", "u>$1</u>"), ("ul\tTag", "ul>$1</ul>"), ("var\tTag", "var>$1</var>"), ("br\tTag", "br>"), ("embed\tTag", "embed>"), ("hr\tTag", "hr>"), ("img\tTag", "img src=\"$1\">"), ("input\tTag", "input>"), ("meta\tTag", "meta>"), ("param\tTag", "param name=\"$1\" value=\"$2\">"), ("article\tTag", "article>$1</article>"), ("aside\tTag", "aside>$1</aside>"), ("audio\tTag", "audio>$1</audio>"), ("canvas\tTag", "canvas>$1</canvas>"), ("footer\tTag", "footer>$1</footer>"), ("header\tTag", "header>$1</header>"), ("nav\tTag", "nav>$1</nav>"), ("section\tTag", "section>$1</section>"), ("video\tTag", "video>$1</video>"), ("A\tTag", "A HREF=\"$1\">$2</A>"), ("ABBR\tTag", "ABBR>$1</ABBR>"), ("ACRONYM\tTag", "ACRONYM>$1</ACRONYM>"), ("ADDRESS\tTag", "ADDRESS>$1</ADDRESS>"), ("APPLET\tTag", "APPLET>$1</APPLET>"), ("AREA\tTag", "AREA>$1</AREA>"), ("B\tTag", "B>$1</B>"), ("BASE\tTag", "BASE>$1</BASE>"), ("BIG\tTag", "BIG>$1</BIG>"), ("BLOCKQUOTE\tTag", "BLOCKQUOTE>$1</BLOCKQUOTE>"), ("BODY\tTag", "BODY>$1</BODY>"), ("BUTTON\tTag", "BUTTON>$1</BUTTON>"), ("CENTER\tTag", "CENTER>$1</CENTER>"), ("CAPTION\tTag", "CAPTION>$1</CAPTION>"), ("CDATA\tTag", "CDATA>$1</CDATA>"), ("CITE\tTag", "CITE>$1</CITE>"), ("COL\tTag", "COL>$1</COL>"), ("COLGROUP\tTag", "COLGROUP>$1</COLGROUP>"), ("CODE\tTag", "CODE>$1</CODE>"), ("DIV\tTag", "DIV>$1</DIV>"), ("DD\tTag", "DD>$1</DD>"), ("DEL\tTag", "DEL>$1</DEL>"), ("DFN\tTag", "DFN>$1</DFN>"), ("DL\tTag", "DL>$1</DL>"), ("DT\tTag", "DT>$1</DT>"), ("EM\tTag", "EM>$1</EM>"), ("FIELDSET\tTag", "FIELDSET>$1</FIELDSET>"), ("FONT\tTag", "FONT>$1</FONT>"), ("FORM\tTag", "FORM>$1</FORM>"), ("FRAME\tTag", "FRAME>$1</FRAME>"), ("FRAMESET\tTag", "FRAMESET>$1</FRAMESET>"), ("HEAD\tTag", "HEAD>$1</HEAD>"), ("H1\tTag", "H1>$1</H1>"), ("H2\tTag", "H2>$1</H2>"), ("H3\tTag", "H3>$1</H3>"), ("H4\tTag", "H4>$1</H4>"), ("H5\tTag", "H5>$1</H5>"), ("H6\tTag", "H6>$1</H6>"), ("I\tTag", "I>$1</I>"), ("IFRAME\tTag", "IFRAME src=\"$1\"></IFRAME>"), ("INS\tTag", "INS>$1</INS>"), ("KBD\tTag", "KBD>$1</KBD>"), ("LI\tTag", "LI>$1</LI>"), ("LABEL\tTag", "LABEL>$1</LABEL>"), ("LEGEND\tTag", "LEGEND>$1</LEGEND>"), ("LINK\tTag", "LINK>$1</LINK>"), ("MAP\tTag", "MAP>$1</MAP>"), ("NOFRAMES\tTag", "NOFRAMES>$1</NOFRAMES>"), ("OBJECT\tTag", "OBJECT>$1</OBJECT>"), ("OL\tTag", "OL>$1</OL>"), ("OPTGROUP\tTag", "OPTGROUP>$1</OPTGROUP>"), ("OPTION\tTag", "OPTION>$1</OPTION>"), ("P\tTag", "P>$1</P>"), ("PRE\tTag", "PRE>$1</PRE>"), ("SPAN\tTag", "SPAN>$1</SPAN>"), ("SAMP\tTag", "SAMP>$1</SAMP>"), ("SCRIPT\tTag", "SCRIPT TYPE=\"${1:text/javascript}\">$0</SCRIPT>"), ("STYLE\tTag", "STYLE TYPE=\"${1:text/css}\">$0</STYLE>"), ("SELECT\tTag", "SELECT>$1</SELECT>"), ("SMALL\tTag", "SMALL>$1</SMALL>"), ("STRONG\tTag", "STRONG>$1</STRONG>"), ("SUB\tTag", "SUB>$1</SUB>"), ("SUP\tTag", "SUP>$1</SUP>"), ("TABLE\tTag", "TABLE>$1</TABLE>"), ("TBODY\tTag", "TBODY>$1</TBODY>"), ("TD\tTag", "TD>$1</TD>"), ("TEXTAREA\tTag", "TEXTAREA>$1</TEXTAREA>"), ("TFOOT\tTag", "TFOOT>$1</TFOOT>"), ("TH\tTag", "TH>$1</TH>"), ("THEAD\tTag", "THEAD>$1</THEAD>"), ("TITLE\tTag", "TITLE>$1</TITLE>"), ("TR\tTag", "TR>$1</TR>"), ("TT\tTag", "TT>$1</TT>"), ("U\tTag", "U>$1</U>"), ("UL\tTag", "UL>$1</UL>"), ("VAR\tTag", "VAR>$1</VAR>"), ("BR\tTag", "BR>"), ("EMBED\tTag", "EMBED>"), ("HR\tTag", "HR>"), ("IMG\tTag", "IMG SRC=\"$1\">"), ("INPUT\tTag", "INPUT>"), ("META\tTag", "META>"), ("PARAM\tTag", "PARAM NAME=\"$1\" VALUE=\"$2\">)"), ("ARTICLE\tTag", "ARTICLE>$1</ARTICLE>"), ("ASIDE\tTag", "ASIDE>$1</ASIDE>"), ("AUDIO\tTag", "AUDIO>$1</AUDIO>"), ("CANVAS\tTag", "CANVAS>$1</CANVAS>"), ("FOOTER\tTag", "FOOTER>$1</FOOTER>"), ("HEADER\tTag", "HEADER>$1</HEADER>"), ("NAV\tTag", "NAV>$1</NAV>"), ("SECTION\tTag", "SECTION>$1</SECTION>"), ("VIDEO\tTag", "VIDEO>$1</VIDEO>") ], sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
# It expands these simple expressions: # tag.class # tag#id class HtmlCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations):
random_line_split
html_completions.py
import sublime, sublime_plugin import re def match(rex, str): m = rex.match(str) if m: return m.group(0) else: return None # This responds to on_query_completions, but conceptually it's expanding # expressions, rather than completing words. # # It expands these simple expressions: # tag.class # tag#id class HtmlCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML if not view.match_selector(locations[0], "text.html - source - meta.tag, punctuation.definition.tag.begin"): return [] # Get the contents of each line, from the beginning of the line to # each point lines = [view.substr(sublime.Region(view.line(l).a, l)) for l in locations] # Reverse the contents of each line, to simulate having the regex # match backwards lines = [l[::-1] for l in lines] # Check the first location looks like an expression rex = re.compile("([\w-]+)([.#])(\w+)") expr = match(rex, lines[0]) if not expr: return [] # Ensure that all other lines have identical expressions for i in xrange(1, len(lines)): ex = match(rex, lines[i]) if ex != expr: return [] # Return the completions arg, op, tag = rex.match(expr).groups() arg = arg[::-1] tag = tag[::-1] expr = expr[::-1] if op == '.': snippet = "<{0} class=\"{1}\">$1</{0}>$0".format(tag, arg) else:
return [(expr, snippet)] # Provide completions that match just after typing an opening angle bracket class TagCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML if not view.match_selector(locations[0], "text.html - source"): return [] pt = locations[0] - len(prefix) - 1 ch = view.substr(sublime.Region(pt, pt + 1)) if ch != '<': return [] return ([ ("a\tTag", "a href=\"$1\">$2</a>"), ("abbr\tTag", "abbr>$1</abbr>"), ("acronym\tTag", "acronym>$1</acronym>"), ("address\tTag", "address>$1</address>"), ("applet\tTag", "applet>$1</applet>"), ("area\tTag", "area>$1</area>"), ("b\tTag", "b>$1</b>"), ("base\tTag", "base>$1</base>"), ("big\tTag", "big>$1</big>"), ("blockquote\tTag", "blockquote>$1</blockquote>"), ("body\tTag", "body>$1</body>"), ("button\tTag", "button>$1</button>"), ("center\tTag", "center>$1</center>"), ("caption\tTag", "caption>$1</caption>"), ("cdata\tTag", "cdata>$1</cdata>"), ("cite\tTag", "cite>$1</cite>"), ("col\tTag", "col>$1</col>"), ("colgroup\tTag", "colgroup>$1</colgroup>"), ("code\tTag", "code>$1</code>"), ("div\tTag", "div>$1</div>"), ("dd\tTag", "dd>$1</dd>"), ("del\tTag", "del>$1</del>"), ("dfn\tTag", "dfn>$1</dfn>"), ("dl\tTag", "dl>$1</dl>"), ("dt\tTag", "dt>$1</dt>"), ("em\tTag", "em>$1</em>"), ("fieldset\tTag", "fieldset>$1</fieldset>"), ("font\tTag", "font>$1</font>"), ("form\tTag", "form>$1</form>"), ("frame\tTag", "frame>$1</frame>"), ("frameset\tTag", "frameset>$1</frameset>"), ("head\tTag", "head>$1</head>"), ("h1\tTag", "h1>$1</h1>"), ("h2\tTag", "h2>$1</h2>"), ("h3\tTag", "h3>$1</h3>"), ("h4\tTag", "h4>$1</h4>"), ("h5\tTag", "h5>$1</h5>"), ("h6\tTag", "h6>$1</h6>"), ("i\tTag", "i>$1</i>"), ("iframe\tTag", "iframe src=\"$1\"></iframe>"), ("ins\tTag", "ins>$1</ins>"), ("kbd\tTag", "kbd>$1</kbd>"), ("li\tTag", "li>$1</li>"), ("label\tTag", "label>$1</label>"), ("legend\tTag", "legend>$1</legend>"), ("link\tTag", "link rel=\"stylesheet\" type=\"text/css\" href=\"$1\">"), ("map\tTag", "map>$1</map>"), ("noframes\tTag", "noframes>$1</noframes>"), ("object\tTag", "object>$1</object>"), ("ol\tTag", "ol>$1</ol>"), ("optgroup\tTag", "optgroup>$1</optgroup>"), ("option\tTag", "option>$0</option>"), ("p\tTag", "p>$1</p>"), ("pre\tTag", "pre>$1</pre>"), ("span\tTag", "span>$1</span>"), ("samp\tTag", "samp>$1</samp>"), ("script\tTag", "script type=\"${1:text/javascript}\">$0</script>"), ("style\tTag", "style type=\"${1:text/css}\">$0</style>"), ("select\tTag", "select>$1</select>"), ("small\tTag", "small>$1</small>"), ("strong\tTag", "strong>$1</strong>"), ("sub\tTag", "sub>$1</sub>"), ("sup\tTag", "sup>$1</sup>"), ("table\tTag", "table>$1</table>"), ("tbody\tTag", "tbody>$1</tbody>"), ("td\tTag", "td>$1</td>"), ("textarea\tTag", "textarea>$1</textarea>"), ("tfoot\tTag", "tfoot>$1</tfoot>"), ("th\tTag", "th>$1</th>"), ("thead\tTag", "thead>$1</thead>"), ("title\tTag", "title>$1</title>"), ("tr\tTag", "tr>$1</tr>"), ("tt\tTag", "tt>$1</tt>"), ("u\tTag", "u>$1</u>"), ("ul\tTag", "ul>$1</ul>"), ("var\tTag", "var>$1</var>"), ("br\tTag", "br>"), ("embed\tTag", "embed>"), ("hr\tTag", "hr>"), ("img\tTag", "img src=\"$1\">"), ("input\tTag", "input>"), ("meta\tTag", "meta>"), ("param\tTag", "param name=\"$1\" value=\"$2\">"), ("article\tTag", "article>$1</article>"), ("aside\tTag", "aside>$1</aside>"), ("audio\tTag", "audio>$1</audio>"), ("canvas\tTag", "canvas>$1</canvas>"), ("footer\tTag", "footer>$1</footer>"), ("header\tTag", "header>$1</header>"), ("nav\tTag", "nav>$1</nav>"), ("section\tTag", "section>$1</section>"), ("video\tTag", "video>$1</video>"), ("A\tTag", "A HREF=\"$1\">$2</A>"), ("ABBR\tTag", "ABBR>$1</ABBR>"), ("ACRONYM\tTag", "ACRONYM>$1</ACRONYM>"), ("ADDRESS\tTag", "ADDRESS>$1</ADDRESS>"), ("APPLET\tTag", "APPLET>$1</APPLET>"), ("AREA\tTag", "AREA>$1</AREA>"), ("B\tTag", "B>$1</B>"), ("BASE\tTag", "BASE>$1</BASE>"), ("BIG\tTag", "BIG>$1</BIG>"), ("BLOCKQUOTE\tTag", "BLOCKQUOTE>$1</BLOCKQUOTE>"), ("BODY\tTag", "BODY>$1</BODY>"), ("BUTTON\tTag", "BUTTON>$1</BUTTON>"), ("CENTER\tTag", "CENTER>$1</CENTER>"), ("CAPTION\tTag", "CAPTION>$1</CAPTION>"), ("CDATA\tTag", "CDATA>$1</CDATA>"), ("CITE\tTag", "CITE>$1</CITE>"), ("COL\tTag", "COL>$1</COL>"), ("COLGROUP\tTag", "COLGROUP>$1</COLGROUP>"), ("CODE\tTag", "CODE>$1</CODE>"), ("DIV\tTag", "DIV>$1</DIV>"), ("DD\tTag", "DD>$1</DD>"), ("DEL\tTag", "DEL>$1</DEL>"), ("DFN\tTag", "DFN>$1</DFN>"), ("DL\tTag", "DL>$1</DL>"), ("DT\tTag", "DT>$1</DT>"), ("EM\tTag", "EM>$1</EM>"), ("FIELDSET\tTag", "FIELDSET>$1</FIELDSET>"), ("FONT\tTag", "FONT>$1</FONT>"), ("FORM\tTag", "FORM>$1</FORM>"), ("FRAME\tTag", "FRAME>$1</FRAME>"), ("FRAMESET\tTag", "FRAMESET>$1</FRAMESET>"), ("HEAD\tTag", "HEAD>$1</HEAD>"), ("H1\tTag", "H1>$1</H1>"), ("H2\tTag", "H2>$1</H2>"), ("H3\tTag", "H3>$1</H3>"), ("H4\tTag", "H4>$1</H4>"), ("H5\tTag", "H5>$1</H5>"), ("H6\tTag", "H6>$1</H6>"), ("I\tTag", "I>$1</I>"), ("IFRAME\tTag", "IFRAME src=\"$1\"></IFRAME>"), ("INS\tTag", "INS>$1</INS>"), ("KBD\tTag", "KBD>$1</KBD>"), ("LI\tTag", "LI>$1</LI>"), ("LABEL\tTag", "LABEL>$1</LABEL>"), ("LEGEND\tTag", "LEGEND>$1</LEGEND>"), ("LINK\tTag", "LINK>$1</LINK>"), ("MAP\tTag", "MAP>$1</MAP>"), ("NOFRAMES\tTag", "NOFRAMES>$1</NOFRAMES>"), ("OBJECT\tTag", "OBJECT>$1</OBJECT>"), ("OL\tTag", "OL>$1</OL>"), ("OPTGROUP\tTag", "OPTGROUP>$1</OPTGROUP>"), ("OPTION\tTag", "OPTION>$1</OPTION>"), ("P\tTag", "P>$1</P>"), ("PRE\tTag", "PRE>$1</PRE>"), ("SPAN\tTag", "SPAN>$1</SPAN>"), ("SAMP\tTag", "SAMP>$1</SAMP>"), ("SCRIPT\tTag", "SCRIPT TYPE=\"${1:text/javascript}\">$0</SCRIPT>"), ("STYLE\tTag", "STYLE TYPE=\"${1:text/css}\">$0</STYLE>"), ("SELECT\tTag", "SELECT>$1</SELECT>"), ("SMALL\tTag", "SMALL>$1</SMALL>"), ("STRONG\tTag", "STRONG>$1</STRONG>"), ("SUB\tTag", "SUB>$1</SUB>"), ("SUP\tTag", "SUP>$1</SUP>"), ("TABLE\tTag", "TABLE>$1</TABLE>"), ("TBODY\tTag", "TBODY>$1</TBODY>"), ("TD\tTag", "TD>$1</TD>"), ("TEXTAREA\tTag", "TEXTAREA>$1</TEXTAREA>"), ("TFOOT\tTag", "TFOOT>$1</TFOOT>"), ("TH\tTag", "TH>$1</TH>"), ("THEAD\tTag", "THEAD>$1</THEAD>"), ("TITLE\tTag", "TITLE>$1</TITLE>"), ("TR\tTag", "TR>$1</TR>"), ("TT\tTag", "TT>$1</TT>"), ("U\tTag", "U>$1</U>"), ("UL\tTag", "UL>$1</UL>"), ("VAR\tTag", "VAR>$1</VAR>"), ("BR\tTag", "BR>"), ("EMBED\tTag", "EMBED>"), ("HR\tTag", "HR>"), ("IMG\tTag", "IMG SRC=\"$1\">"), ("INPUT\tTag", "INPUT>"), ("META\tTag", "META>"), ("PARAM\tTag", "PARAM NAME=\"$1\" VALUE=\"$2\">)"), ("ARTICLE\tTag", "ARTICLE>$1</ARTICLE>"), ("ASIDE\tTag", "ASIDE>$1</ASIDE>"), ("AUDIO\tTag", "AUDIO>$1</AUDIO>"), ("CANVAS\tTag", "CANVAS>$1</CANVAS>"), ("FOOTER\tTag", "FOOTER>$1</FOOTER>"), ("HEADER\tTag", "HEADER>$1</HEADER>"), ("NAV\tTag", "NAV>$1</NAV>"), ("SECTION\tTag", "SECTION>$1</SECTION>"), ("VIDEO\tTag", "VIDEO>$1</VIDEO>") ], sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
snippet = "<{0} id=\"{1}\">$1</{0}>$0".format(tag, arg)
conditional_block
html_completions.py
import sublime, sublime_plugin import re def match(rex, str): m = rex.match(str) if m: return m.group(0) else: return None # This responds to on_query_completions, but conceptually it's expanding # expressions, rather than completing words. # # It expands these simple expressions: # tag.class # tag#id class
(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML if not view.match_selector(locations[0], "text.html - source - meta.tag, punctuation.definition.tag.begin"): return [] # Get the contents of each line, from the beginning of the line to # each point lines = [view.substr(sublime.Region(view.line(l).a, l)) for l in locations] # Reverse the contents of each line, to simulate having the regex # match backwards lines = [l[::-1] for l in lines] # Check the first location looks like an expression rex = re.compile("([\w-]+)([.#])(\w+)") expr = match(rex, lines[0]) if not expr: return [] # Ensure that all other lines have identical expressions for i in xrange(1, len(lines)): ex = match(rex, lines[i]) if ex != expr: return [] # Return the completions arg, op, tag = rex.match(expr).groups() arg = arg[::-1] tag = tag[::-1] expr = expr[::-1] if op == '.': snippet = "<{0} class=\"{1}\">$1</{0}>$0".format(tag, arg) else: snippet = "<{0} id=\"{1}\">$1</{0}>$0".format(tag, arg) return [(expr, snippet)] # Provide completions that match just after typing an opening angle bracket class TagCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML if not view.match_selector(locations[0], "text.html - source"): return [] pt = locations[0] - len(prefix) - 1 ch = view.substr(sublime.Region(pt, pt + 1)) if ch != '<': return [] return ([ ("a\tTag", "a href=\"$1\">$2</a>"), ("abbr\tTag", "abbr>$1</abbr>"), ("acronym\tTag", "acronym>$1</acronym>"), ("address\tTag", "address>$1</address>"), ("applet\tTag", "applet>$1</applet>"), ("area\tTag", "area>$1</area>"), ("b\tTag", "b>$1</b>"), ("base\tTag", "base>$1</base>"), ("big\tTag", "big>$1</big>"), ("blockquote\tTag", "blockquote>$1</blockquote>"), ("body\tTag", "body>$1</body>"), ("button\tTag", "button>$1</button>"), ("center\tTag", "center>$1</center>"), ("caption\tTag", "caption>$1</caption>"), ("cdata\tTag", "cdata>$1</cdata>"), ("cite\tTag", "cite>$1</cite>"), ("col\tTag", "col>$1</col>"), ("colgroup\tTag", "colgroup>$1</colgroup>"), ("code\tTag", "code>$1</code>"), ("div\tTag", "div>$1</div>"), ("dd\tTag", "dd>$1</dd>"), ("del\tTag", "del>$1</del>"), ("dfn\tTag", "dfn>$1</dfn>"), ("dl\tTag", "dl>$1</dl>"), ("dt\tTag", "dt>$1</dt>"), ("em\tTag", "em>$1</em>"), ("fieldset\tTag", "fieldset>$1</fieldset>"), ("font\tTag", "font>$1</font>"), ("form\tTag", "form>$1</form>"), ("frame\tTag", "frame>$1</frame>"), ("frameset\tTag", "frameset>$1</frameset>"), ("head\tTag", "head>$1</head>"), ("h1\tTag", "h1>$1</h1>"), ("h2\tTag", "h2>$1</h2>"), ("h3\tTag", "h3>$1</h3>"), ("h4\tTag", "h4>$1</h4>"), ("h5\tTag", "h5>$1</h5>"), ("h6\tTag", "h6>$1</h6>"), ("i\tTag", "i>$1</i>"), ("iframe\tTag", "iframe src=\"$1\"></iframe>"), ("ins\tTag", "ins>$1</ins>"), ("kbd\tTag", "kbd>$1</kbd>"), ("li\tTag", "li>$1</li>"), ("label\tTag", "label>$1</label>"), ("legend\tTag", "legend>$1</legend>"), ("link\tTag", "link rel=\"stylesheet\" type=\"text/css\" href=\"$1\">"), ("map\tTag", "map>$1</map>"), ("noframes\tTag", "noframes>$1</noframes>"), ("object\tTag", "object>$1</object>"), ("ol\tTag", "ol>$1</ol>"), ("optgroup\tTag", "optgroup>$1</optgroup>"), ("option\tTag", "option>$0</option>"), ("p\tTag", "p>$1</p>"), ("pre\tTag", "pre>$1</pre>"), ("span\tTag", "span>$1</span>"), ("samp\tTag", "samp>$1</samp>"), ("script\tTag", "script type=\"${1:text/javascript}\">$0</script>"), ("style\tTag", "style type=\"${1:text/css}\">$0</style>"), ("select\tTag", "select>$1</select>"), ("small\tTag", "small>$1</small>"), ("strong\tTag", "strong>$1</strong>"), ("sub\tTag", "sub>$1</sub>"), ("sup\tTag", "sup>$1</sup>"), ("table\tTag", "table>$1</table>"), ("tbody\tTag", "tbody>$1</tbody>"), ("td\tTag", "td>$1</td>"), ("textarea\tTag", "textarea>$1</textarea>"), ("tfoot\tTag", "tfoot>$1</tfoot>"), ("th\tTag", "th>$1</th>"), ("thead\tTag", "thead>$1</thead>"), ("title\tTag", "title>$1</title>"), ("tr\tTag", "tr>$1</tr>"), ("tt\tTag", "tt>$1</tt>"), ("u\tTag", "u>$1</u>"), ("ul\tTag", "ul>$1</ul>"), ("var\tTag", "var>$1</var>"), ("br\tTag", "br>"), ("embed\tTag", "embed>"), ("hr\tTag", "hr>"), ("img\tTag", "img src=\"$1\">"), ("input\tTag", "input>"), ("meta\tTag", "meta>"), ("param\tTag", "param name=\"$1\" value=\"$2\">"), ("article\tTag", "article>$1</article>"), ("aside\tTag", "aside>$1</aside>"), ("audio\tTag", "audio>$1</audio>"), ("canvas\tTag", "canvas>$1</canvas>"), ("footer\tTag", "footer>$1</footer>"), ("header\tTag", "header>$1</header>"), ("nav\tTag", "nav>$1</nav>"), ("section\tTag", "section>$1</section>"), ("video\tTag", "video>$1</video>"), ("A\tTag", "A HREF=\"$1\">$2</A>"), ("ABBR\tTag", "ABBR>$1</ABBR>"), ("ACRONYM\tTag", "ACRONYM>$1</ACRONYM>"), ("ADDRESS\tTag", "ADDRESS>$1</ADDRESS>"), ("APPLET\tTag", "APPLET>$1</APPLET>"), ("AREA\tTag", "AREA>$1</AREA>"), ("B\tTag", "B>$1</B>"), ("BASE\tTag", "BASE>$1</BASE>"), ("BIG\tTag", "BIG>$1</BIG>"), ("BLOCKQUOTE\tTag", "BLOCKQUOTE>$1</BLOCKQUOTE>"), ("BODY\tTag", "BODY>$1</BODY>"), ("BUTTON\tTag", "BUTTON>$1</BUTTON>"), ("CENTER\tTag", "CENTER>$1</CENTER>"), ("CAPTION\tTag", "CAPTION>$1</CAPTION>"), ("CDATA\tTag", "CDATA>$1</CDATA>"), ("CITE\tTag", "CITE>$1</CITE>"), ("COL\tTag", "COL>$1</COL>"), ("COLGROUP\tTag", "COLGROUP>$1</COLGROUP>"), ("CODE\tTag", "CODE>$1</CODE>"), ("DIV\tTag", "DIV>$1</DIV>"), ("DD\tTag", "DD>$1</DD>"), ("DEL\tTag", "DEL>$1</DEL>"), ("DFN\tTag", "DFN>$1</DFN>"), ("DL\tTag", "DL>$1</DL>"), ("DT\tTag", "DT>$1</DT>"), ("EM\tTag", "EM>$1</EM>"), ("FIELDSET\tTag", "FIELDSET>$1</FIELDSET>"), ("FONT\tTag", "FONT>$1</FONT>"), ("FORM\tTag", "FORM>$1</FORM>"), ("FRAME\tTag", "FRAME>$1</FRAME>"), ("FRAMESET\tTag", "FRAMESET>$1</FRAMESET>"), ("HEAD\tTag", "HEAD>$1</HEAD>"), ("H1\tTag", "H1>$1</H1>"), ("H2\tTag", "H2>$1</H2>"), ("H3\tTag", "H3>$1</H3>"), ("H4\tTag", "H4>$1</H4>"), ("H5\tTag", "H5>$1</H5>"), ("H6\tTag", "H6>$1</H6>"), ("I\tTag", "I>$1</I>"), ("IFRAME\tTag", "IFRAME src=\"$1\"></IFRAME>"), ("INS\tTag", "INS>$1</INS>"), ("KBD\tTag", "KBD>$1</KBD>"), ("LI\tTag", "LI>$1</LI>"), ("LABEL\tTag", "LABEL>$1</LABEL>"), ("LEGEND\tTag", "LEGEND>$1</LEGEND>"), ("LINK\tTag", "LINK>$1</LINK>"), ("MAP\tTag", "MAP>$1</MAP>"), ("NOFRAMES\tTag", "NOFRAMES>$1</NOFRAMES>"), ("OBJECT\tTag", "OBJECT>$1</OBJECT>"), ("OL\tTag", "OL>$1</OL>"), ("OPTGROUP\tTag", "OPTGROUP>$1</OPTGROUP>"), ("OPTION\tTag", "OPTION>$1</OPTION>"), ("P\tTag", "P>$1</P>"), ("PRE\tTag", "PRE>$1</PRE>"), ("SPAN\tTag", "SPAN>$1</SPAN>"), ("SAMP\tTag", "SAMP>$1</SAMP>"), ("SCRIPT\tTag", "SCRIPT TYPE=\"${1:text/javascript}\">$0</SCRIPT>"), ("STYLE\tTag", "STYLE TYPE=\"${1:text/css}\">$0</STYLE>"), ("SELECT\tTag", "SELECT>$1</SELECT>"), ("SMALL\tTag", "SMALL>$1</SMALL>"), ("STRONG\tTag", "STRONG>$1</STRONG>"), ("SUB\tTag", "SUB>$1</SUB>"), ("SUP\tTag", "SUP>$1</SUP>"), ("TABLE\tTag", "TABLE>$1</TABLE>"), ("TBODY\tTag", "TBODY>$1</TBODY>"), ("TD\tTag", "TD>$1</TD>"), ("TEXTAREA\tTag", "TEXTAREA>$1</TEXTAREA>"), ("TFOOT\tTag", "TFOOT>$1</TFOOT>"), ("TH\tTag", "TH>$1</TH>"), ("THEAD\tTag", "THEAD>$1</THEAD>"), ("TITLE\tTag", "TITLE>$1</TITLE>"), ("TR\tTag", "TR>$1</TR>"), ("TT\tTag", "TT>$1</TT>"), ("U\tTag", "U>$1</U>"), ("UL\tTag", "UL>$1</UL>"), ("VAR\tTag", "VAR>$1</VAR>"), ("BR\tTag", "BR>"), ("EMBED\tTag", "EMBED>"), ("HR\tTag", "HR>"), ("IMG\tTag", "IMG SRC=\"$1\">"), ("INPUT\tTag", "INPUT>"), ("META\tTag", "META>"), ("PARAM\tTag", "PARAM NAME=\"$1\" VALUE=\"$2\">)"), ("ARTICLE\tTag", "ARTICLE>$1</ARTICLE>"), ("ASIDE\tTag", "ASIDE>$1</ASIDE>"), ("AUDIO\tTag", "AUDIO>$1</AUDIO>"), ("CANVAS\tTag", "CANVAS>$1</CANVAS>"), ("FOOTER\tTag", "FOOTER>$1</FOOTER>"), ("HEADER\tTag", "HEADER>$1</HEADER>"), ("NAV\tTag", "NAV>$1</NAV>"), ("SECTION\tTag", "SECTION>$1</SECTION>"), ("VIDEO\tTag", "VIDEO>$1</VIDEO>") ], sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
HtmlCompletions
identifier_name
html_completions.py
import sublime, sublime_plugin import re def match(rex, str): m = rex.match(str) if m: return m.group(0) else: return None # This responds to on_query_completions, but conceptually it's expanding # expressions, rather than completing words. # # It expands these simple expressions: # tag.class # tag#id class HtmlCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML
# Provide completions that match just after typing an opening angle bracket class TagCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): # Only trigger within HTML if not view.match_selector(locations[0], "text.html - source"): return [] pt = locations[0] - len(prefix) - 1 ch = view.substr(sublime.Region(pt, pt + 1)) if ch != '<': return [] return ([ ("a\tTag", "a href=\"$1\">$2</a>"), ("abbr\tTag", "abbr>$1</abbr>"), ("acronym\tTag", "acronym>$1</acronym>"), ("address\tTag", "address>$1</address>"), ("applet\tTag", "applet>$1</applet>"), ("area\tTag", "area>$1</area>"), ("b\tTag", "b>$1</b>"), ("base\tTag", "base>$1</base>"), ("big\tTag", "big>$1</big>"), ("blockquote\tTag", "blockquote>$1</blockquote>"), ("body\tTag", "body>$1</body>"), ("button\tTag", "button>$1</button>"), ("center\tTag", "center>$1</center>"), ("caption\tTag", "caption>$1</caption>"), ("cdata\tTag", "cdata>$1</cdata>"), ("cite\tTag", "cite>$1</cite>"), ("col\tTag", "col>$1</col>"), ("colgroup\tTag", "colgroup>$1</colgroup>"), ("code\tTag", "code>$1</code>"), ("div\tTag", "div>$1</div>"), ("dd\tTag", "dd>$1</dd>"), ("del\tTag", "del>$1</del>"), ("dfn\tTag", "dfn>$1</dfn>"), ("dl\tTag", "dl>$1</dl>"), ("dt\tTag", "dt>$1</dt>"), ("em\tTag", "em>$1</em>"), ("fieldset\tTag", "fieldset>$1</fieldset>"), ("font\tTag", "font>$1</font>"), ("form\tTag", "form>$1</form>"), ("frame\tTag", "frame>$1</frame>"), ("frameset\tTag", "frameset>$1</frameset>"), ("head\tTag", "head>$1</head>"), ("h1\tTag", "h1>$1</h1>"), ("h2\tTag", "h2>$1</h2>"), ("h3\tTag", "h3>$1</h3>"), ("h4\tTag", "h4>$1</h4>"), ("h5\tTag", "h5>$1</h5>"), ("h6\tTag", "h6>$1</h6>"), ("i\tTag", "i>$1</i>"), ("iframe\tTag", "iframe src=\"$1\"></iframe>"), ("ins\tTag", "ins>$1</ins>"), ("kbd\tTag", "kbd>$1</kbd>"), ("li\tTag", "li>$1</li>"), ("label\tTag", "label>$1</label>"), ("legend\tTag", "legend>$1</legend>"), ("link\tTag", "link rel=\"stylesheet\" type=\"text/css\" href=\"$1\">"), ("map\tTag", "map>$1</map>"), ("noframes\tTag", "noframes>$1</noframes>"), ("object\tTag", "object>$1</object>"), ("ol\tTag", "ol>$1</ol>"), ("optgroup\tTag", "optgroup>$1</optgroup>"), ("option\tTag", "option>$0</option>"), ("p\tTag", "p>$1</p>"), ("pre\tTag", "pre>$1</pre>"), ("span\tTag", "span>$1</span>"), ("samp\tTag", "samp>$1</samp>"), ("script\tTag", "script type=\"${1:text/javascript}\">$0</script>"), ("style\tTag", "style type=\"${1:text/css}\">$0</style>"), ("select\tTag", "select>$1</select>"), ("small\tTag", "small>$1</small>"), ("strong\tTag", "strong>$1</strong>"), ("sub\tTag", "sub>$1</sub>"), ("sup\tTag", "sup>$1</sup>"), ("table\tTag", "table>$1</table>"), ("tbody\tTag", "tbody>$1</tbody>"), ("td\tTag", "td>$1</td>"), ("textarea\tTag", "textarea>$1</textarea>"), ("tfoot\tTag", "tfoot>$1</tfoot>"), ("th\tTag", "th>$1</th>"), ("thead\tTag", "thead>$1</thead>"), ("title\tTag", "title>$1</title>"), ("tr\tTag", "tr>$1</tr>"), ("tt\tTag", "tt>$1</tt>"), ("u\tTag", "u>$1</u>"), ("ul\tTag", "ul>$1</ul>"), ("var\tTag", "var>$1</var>"), ("br\tTag", "br>"), ("embed\tTag", "embed>"), ("hr\tTag", "hr>"), ("img\tTag", "img src=\"$1\">"), ("input\tTag", "input>"), ("meta\tTag", "meta>"), ("param\tTag", "param name=\"$1\" value=\"$2\">"), ("article\tTag", "article>$1</article>"), ("aside\tTag", "aside>$1</aside>"), ("audio\tTag", "audio>$1</audio>"), ("canvas\tTag", "canvas>$1</canvas>"), ("footer\tTag", "footer>$1</footer>"), ("header\tTag", "header>$1</header>"), ("nav\tTag", "nav>$1</nav>"), ("section\tTag", "section>$1</section>"), ("video\tTag", "video>$1</video>"), ("A\tTag", "A HREF=\"$1\">$2</A>"), ("ABBR\tTag", "ABBR>$1</ABBR>"), ("ACRONYM\tTag", "ACRONYM>$1</ACRONYM>"), ("ADDRESS\tTag", "ADDRESS>$1</ADDRESS>"), ("APPLET\tTag", "APPLET>$1</APPLET>"), ("AREA\tTag", "AREA>$1</AREA>"), ("B\tTag", "B>$1</B>"), ("BASE\tTag", "BASE>$1</BASE>"), ("BIG\tTag", "BIG>$1</BIG>"), ("BLOCKQUOTE\tTag", "BLOCKQUOTE>$1</BLOCKQUOTE>"), ("BODY\tTag", "BODY>$1</BODY>"), ("BUTTON\tTag", "BUTTON>$1</BUTTON>"), ("CENTER\tTag", "CENTER>$1</CENTER>"), ("CAPTION\tTag", "CAPTION>$1</CAPTION>"), ("CDATA\tTag", "CDATA>$1</CDATA>"), ("CITE\tTag", "CITE>$1</CITE>"), ("COL\tTag", "COL>$1</COL>"), ("COLGROUP\tTag", "COLGROUP>$1</COLGROUP>"), ("CODE\tTag", "CODE>$1</CODE>"), ("DIV\tTag", "DIV>$1</DIV>"), ("DD\tTag", "DD>$1</DD>"), ("DEL\tTag", "DEL>$1</DEL>"), ("DFN\tTag", "DFN>$1</DFN>"), ("DL\tTag", "DL>$1</DL>"), ("DT\tTag", "DT>$1</DT>"), ("EM\tTag", "EM>$1</EM>"), ("FIELDSET\tTag", "FIELDSET>$1</FIELDSET>"), ("FONT\tTag", "FONT>$1</FONT>"), ("FORM\tTag", "FORM>$1</FORM>"), ("FRAME\tTag", "FRAME>$1</FRAME>"), ("FRAMESET\tTag", "FRAMESET>$1</FRAMESET>"), ("HEAD\tTag", "HEAD>$1</HEAD>"), ("H1\tTag", "H1>$1</H1>"), ("H2\tTag", "H2>$1</H2>"), ("H3\tTag", "H3>$1</H3>"), ("H4\tTag", "H4>$1</H4>"), ("H5\tTag", "H5>$1</H5>"), ("H6\tTag", "H6>$1</H6>"), ("I\tTag", "I>$1</I>"), ("IFRAME\tTag", "IFRAME src=\"$1\"></IFRAME>"), ("INS\tTag", "INS>$1</INS>"), ("KBD\tTag", "KBD>$1</KBD>"), ("LI\tTag", "LI>$1</LI>"), ("LABEL\tTag", "LABEL>$1</LABEL>"), ("LEGEND\tTag", "LEGEND>$1</LEGEND>"), ("LINK\tTag", "LINK>$1</LINK>"), ("MAP\tTag", "MAP>$1</MAP>"), ("NOFRAMES\tTag", "NOFRAMES>$1</NOFRAMES>"), ("OBJECT\tTag", "OBJECT>$1</OBJECT>"), ("OL\tTag", "OL>$1</OL>"), ("OPTGROUP\tTag", "OPTGROUP>$1</OPTGROUP>"), ("OPTION\tTag", "OPTION>$1</OPTION>"), ("P\tTag", "P>$1</P>"), ("PRE\tTag", "PRE>$1</PRE>"), ("SPAN\tTag", "SPAN>$1</SPAN>"), ("SAMP\tTag", "SAMP>$1</SAMP>"), ("SCRIPT\tTag", "SCRIPT TYPE=\"${1:text/javascript}\">$0</SCRIPT>"), ("STYLE\tTag", "STYLE TYPE=\"${1:text/css}\">$0</STYLE>"), ("SELECT\tTag", "SELECT>$1</SELECT>"), ("SMALL\tTag", "SMALL>$1</SMALL>"), ("STRONG\tTag", "STRONG>$1</STRONG>"), ("SUB\tTag", "SUB>$1</SUB>"), ("SUP\tTag", "SUP>$1</SUP>"), ("TABLE\tTag", "TABLE>$1</TABLE>"), ("TBODY\tTag", "TBODY>$1</TBODY>"), ("TD\tTag", "TD>$1</TD>"), ("TEXTAREA\tTag", "TEXTAREA>$1</TEXTAREA>"), ("TFOOT\tTag", "TFOOT>$1</TFOOT>"), ("TH\tTag", "TH>$1</TH>"), ("THEAD\tTag", "THEAD>$1</THEAD>"), ("TITLE\tTag", "TITLE>$1</TITLE>"), ("TR\tTag", "TR>$1</TR>"), ("TT\tTag", "TT>$1</TT>"), ("U\tTag", "U>$1</U>"), ("UL\tTag", "UL>$1</UL>"), ("VAR\tTag", "VAR>$1</VAR>"), ("BR\tTag", "BR>"), ("EMBED\tTag", "EMBED>"), ("HR\tTag", "HR>"), ("IMG\tTag", "IMG SRC=\"$1\">"), ("INPUT\tTag", "INPUT>"), ("META\tTag", "META>"), ("PARAM\tTag", "PARAM NAME=\"$1\" VALUE=\"$2\">)"), ("ARTICLE\tTag", "ARTICLE>$1</ARTICLE>"), ("ASIDE\tTag", "ASIDE>$1</ASIDE>"), ("AUDIO\tTag", "AUDIO>$1</AUDIO>"), ("CANVAS\tTag", "CANVAS>$1</CANVAS>"), ("FOOTER\tTag", "FOOTER>$1</FOOTER>"), ("HEADER\tTag", "HEADER>$1</HEADER>"), ("NAV\tTag", "NAV>$1</NAV>"), ("SECTION\tTag", "SECTION>$1</SECTION>"), ("VIDEO\tTag", "VIDEO>$1</VIDEO>") ], sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
if not view.match_selector(locations[0], "text.html - source - meta.tag, punctuation.definition.tag.begin"): return [] # Get the contents of each line, from the beginning of the line to # each point lines = [view.substr(sublime.Region(view.line(l).a, l)) for l in locations] # Reverse the contents of each line, to simulate having the regex # match backwards lines = [l[::-1] for l in lines] # Check the first location looks like an expression rex = re.compile("([\w-]+)([.#])(\w+)") expr = match(rex, lines[0]) if not expr: return [] # Ensure that all other lines have identical expressions for i in xrange(1, len(lines)): ex = match(rex, lines[i]) if ex != expr: return [] # Return the completions arg, op, tag = rex.match(expr).groups() arg = arg[::-1] tag = tag[::-1] expr = expr[::-1] if op == '.': snippet = "<{0} class=\"{1}\">$1</{0}>$0".format(tag, arg) else: snippet = "<{0} id=\"{1}\">$1</{0}>$0".format(tag, arg) return [(expr, snippet)]
identifier_body
ch4_ex4.1.4.py
#!/usr/bin/env python # # Created by Samvel Khalatyan on Mar 23, 2014 # Copyright (c) 2014 Samvel Khalatyan. All rights reserved # # Use of this source code is governed by a license that can be found in # the LICENSE file. import random import unittest from lib import unigraph class UnigraphExtra(unigraph.Unigraph): def has_edge(self, left_vertex, right_vertex): if left_vertex == right_vertex: return True else: return right_vertex in self._vertices[left_vertex] class UnigraphEdgeTestCase(unittest.TestCase):
if "__main__" == __name__: unittest.main()
def setUp(self): self.graph = UnigraphExtra(random.randrange(10, 15)) for edge in range(2 * self.graph.vertices()): f, t = (random.randrange(self.graph.vertices()) for x in range(2)) self.graph.add_edge(f, t) def test_edge(self): for vertex in range(self.graph.vertices()): existing_vertices = set(self.graph._vertices[vertex]) all_vertices = set(range(self.graph.vertices())) missing_vertices = all_vertices - all_vertices for adj_vertex in existing_vertices: self.assertTrue(self.graph.has_edge(vertex, adj_vertex)) for adj_vertex in missing_vertices: self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) def test_self_loop(self): for vertex in range(self.graph.vertices()): self.assertTrue(self.graph.has_edge(vertex, vertex))
identifier_body
ch4_ex4.1.4.py
#!/usr/bin/env python # # Created by Samvel Khalatyan on Mar 23, 2014 # Copyright (c) 2014 Samvel Khalatyan. All rights reserved # # Use of this source code is governed by a license that can be found in # the LICENSE file. import random import unittest from lib import unigraph class UnigraphExtra(unigraph.Unigraph): def has_edge(self, left_vertex, right_vertex): if left_vertex == right_vertex: return True else: return right_vertex in self._vertices[left_vertex] class UnigraphEdgeTestCase(unittest.TestCase): def setUp(self): self.graph = UnigraphExtra(random.randrange(10, 15)) for edge in range(2 * self.graph.vertices()): f, t = (random.randrange(self.graph.vertices()) for x in range(2)) self.graph.add_edge(f, t) def test_edge(self): for vertex in range(self.graph.vertices()): existing_vertices = set(self.graph._vertices[vertex]) all_vertices = set(range(self.graph.vertices())) missing_vertices = all_vertices - all_vertices for adj_vertex in existing_vertices: self.assertTrue(self.graph.has_edge(vertex, adj_vertex)) for adj_vertex in missing_vertices: self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) def test_self_loop(self):
self.assertTrue(self.graph.has_edge(vertex, vertex)) if "__main__" == __name__: unittest.main()
for vertex in range(self.graph.vertices()):
random_line_split
ch4_ex4.1.4.py
#!/usr/bin/env python # # Created by Samvel Khalatyan on Mar 23, 2014 # Copyright (c) 2014 Samvel Khalatyan. All rights reserved # # Use of this source code is governed by a license that can be found in # the LICENSE file. import random import unittest from lib import unigraph class UnigraphExtra(unigraph.Unigraph): def has_edge(self, left_vertex, right_vertex): if left_vertex == right_vertex: return True else: return right_vertex in self._vertices[left_vertex] class UnigraphEdgeTestCase(unittest.TestCase): def setUp(self): self.graph = UnigraphExtra(random.randrange(10, 15)) for edge in range(2 * self.graph.vertices()): f, t = (random.randrange(self.graph.vertices()) for x in range(2)) self.graph.add_edge(f, t) def test_edge(self): for vertex in range(self.graph.vertices()): existing_vertices = set(self.graph._vertices[vertex]) all_vertices = set(range(self.graph.vertices())) missing_vertices = all_vertices - all_vertices for adj_vertex in existing_vertices: self.assertTrue(self.graph.has_edge(vertex, adj_vertex)) for adj_vertex in missing_vertices: self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) def
(self): for vertex in range(self.graph.vertices()): self.assertTrue(self.graph.has_edge(vertex, vertex)) if "__main__" == __name__: unittest.main()
test_self_loop
identifier_name
ch4_ex4.1.4.py
#!/usr/bin/env python # # Created by Samvel Khalatyan on Mar 23, 2014 # Copyright (c) 2014 Samvel Khalatyan. All rights reserved # # Use of this source code is governed by a license that can be found in # the LICENSE file. import random import unittest from lib import unigraph class UnigraphExtra(unigraph.Unigraph): def has_edge(self, left_vertex, right_vertex): if left_vertex == right_vertex: return True else: return right_vertex in self._vertices[left_vertex] class UnigraphEdgeTestCase(unittest.TestCase): def setUp(self): self.graph = UnigraphExtra(random.randrange(10, 15)) for edge in range(2 * self.graph.vertices()): f, t = (random.randrange(self.graph.vertices()) for x in range(2)) self.graph.add_edge(f, t) def test_edge(self): for vertex in range(self.graph.vertices()): existing_vertices = set(self.graph._vertices[vertex]) all_vertices = set(range(self.graph.vertices())) missing_vertices = all_vertices - all_vertices for adj_vertex in existing_vertices: self.assertTrue(self.graph.has_edge(vertex, adj_vertex)) for adj_vertex in missing_vertices:
def test_self_loop(self): for vertex in range(self.graph.vertices()): self.assertTrue(self.graph.has_edge(vertex, vertex)) if "__main__" == __name__: unittest.main()
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
conditional_block
util.rs
#![allow(dead_code)] use std::env; use std::fs::{self, File}; use std::io::{Read, Write}; #[cfg(unix)] use std::os::unix::fs::symlink as symlink_file; #[cfg(windows)] use std::os::windows::fs::symlink_file; use std::path::Path; use std::process::{Command, Stdio}; use std::str::from_utf8; #[macro_export] macro_rules! assert_empty_stderr( ($cond:expr) => ( if $cond.stderr.len() > 0 { panic!(format!("stderr: {}", $cond.stderr)) } ); ); pub struct CmdResult { pub success: bool, pub stdout: String, pub stderr: String, } pub fn run(cmd: &mut Command) -> CmdResult { let prog = cmd.output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn run_piped_stdin<T: AsRef<[u8]>>(cmd: &mut Command, input: T)-> CmdResult { let mut command = cmd .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); command.stdin .take() .unwrap_or_else(|| panic!("Could not take child process stdin")) .write_all(input.as_ref()) .unwrap_or_else(|e| panic!("{}", e)); let prog = command.wait_with_output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn get_file_contents(name: &str) -> String { let mut f = File::open(Path::new(name)).unwrap(); let mut contents = String::new(); let _ = f.read_to_string(&mut contents); contents } pub fn mkdir(dir: &str) { fs::create_dir(Path::new(dir)).unwrap(); } pub fn make_file(name: &str) -> File { match File::create(Path::new(name)) { Ok(f) => f, Err(e) => panic!("{}", e) } } pub fn touch(file: &str)
pub fn symlink(src: &str, dst: &str) { symlink_file(src, dst).unwrap(); } pub fn is_symlink(path: &str) -> bool { match fs::symlink_metadata(path) { Ok(m) => m.file_type().is_symlink(), Err(_) => false } } pub fn resolve_link(path: &str) -> String { match fs::read_link(path) { Ok(p) => p.to_str().unwrap().to_owned(), Err(_) => "".to_string() } } pub fn metadata(path: &str) -> fs::Metadata { match fs::metadata(path) { Ok(m) => m, Err(e) => panic!("{}", e) } } pub fn file_exists(path: &str) -> bool { match fs::metadata(path) { Ok(m) => m.is_file(), Err(_) => false } } pub fn dir_exists(path: &str) -> bool { match fs::metadata(path) { Ok(m) => m.is_dir(), Err(_) => false } } pub fn cleanup(path: &'static str) { let p = Path::new(path); match fs::metadata(p) { Ok(m) => if m.is_file() { fs::remove_file(&p).unwrap(); } else { fs::remove_dir(&p).unwrap(); }, Err(_) => {} } } pub fn current_directory() -> String { env::current_dir().unwrap().into_os_string().into_string().unwrap() } pub fn repeat_str(s: &str, n: u32) -> String { let mut repeated = String::new(); for _ in 0 .. n { repeated.push_str(s); } repeated }
{ File::create(Path::new(file)).unwrap(); }
identifier_body
util.rs
#![allow(dead_code)] use std::env; use std::fs::{self, File}; use std::io::{Read, Write}; #[cfg(unix)] use std::os::unix::fs::symlink as symlink_file; #[cfg(windows)] use std::os::windows::fs::symlink_file; use std::path::Path; use std::process::{Command, Stdio}; use std::str::from_utf8; #[macro_export] macro_rules! assert_empty_stderr( ($cond:expr) => ( if $cond.stderr.len() > 0 { panic!(format!("stderr: {}", $cond.stderr)) } ); ); pub struct CmdResult { pub success: bool, pub stdout: String, pub stderr: String, } pub fn run(cmd: &mut Command) -> CmdResult { let prog = cmd.output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn run_piped_stdin<T: AsRef<[u8]>>(cmd: &mut Command, input: T)-> CmdResult { let mut command = cmd .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); command.stdin .take() .unwrap_or_else(|| panic!("Could not take child process stdin")) .write_all(input.as_ref()) .unwrap_or_else(|e| panic!("{}", e)); let prog = command.wait_with_output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn get_file_contents(name: &str) -> String { let mut f = File::open(Path::new(name)).unwrap(); let mut contents = String::new(); let _ = f.read_to_string(&mut contents); contents } pub fn mkdir(dir: &str) { fs::create_dir(Path::new(dir)).unwrap(); } pub fn make_file(name: &str) -> File { match File::create(Path::new(name)) { Ok(f) => f, Err(e) => panic!("{}", e) }
pub fn touch(file: &str) { File::create(Path::new(file)).unwrap(); } pub fn symlink(src: &str, dst: &str) { symlink_file(src, dst).unwrap(); } pub fn is_symlink(path: &str) -> bool { match fs::symlink_metadata(path) { Ok(m) => m.file_type().is_symlink(), Err(_) => false } } pub fn resolve_link(path: &str) -> String { match fs::read_link(path) { Ok(p) => p.to_str().unwrap().to_owned(), Err(_) => "".to_string() } } pub fn metadata(path: &str) -> fs::Metadata { match fs::metadata(path) { Ok(m) => m, Err(e) => panic!("{}", e) } } pub fn file_exists(path: &str) -> bool { match fs::metadata(path) { Ok(m) => m.is_file(), Err(_) => false } } pub fn dir_exists(path: &str) -> bool { match fs::metadata(path) { Ok(m) => m.is_dir(), Err(_) => false } } pub fn cleanup(path: &'static str) { let p = Path::new(path); match fs::metadata(p) { Ok(m) => if m.is_file() { fs::remove_file(&p).unwrap(); } else { fs::remove_dir(&p).unwrap(); }, Err(_) => {} } } pub fn current_directory() -> String { env::current_dir().unwrap().into_os_string().into_string().unwrap() } pub fn repeat_str(s: &str, n: u32) -> String { let mut repeated = String::new(); for _ in 0 .. n { repeated.push_str(s); } repeated }
}
random_line_split
util.rs
#![allow(dead_code)] use std::env; use std::fs::{self, File}; use std::io::{Read, Write}; #[cfg(unix)] use std::os::unix::fs::symlink as symlink_file; #[cfg(windows)] use std::os::windows::fs::symlink_file; use std::path::Path; use std::process::{Command, Stdio}; use std::str::from_utf8; #[macro_export] macro_rules! assert_empty_stderr( ($cond:expr) => ( if $cond.stderr.len() > 0 { panic!(format!("stderr: {}", $cond.stderr)) } ); ); pub struct CmdResult { pub success: bool, pub stdout: String, pub stderr: String, } pub fn run(cmd: &mut Command) -> CmdResult { let prog = cmd.output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn run_piped_stdin<T: AsRef<[u8]>>(cmd: &mut Command, input: T)-> CmdResult { let mut command = cmd .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); command.stdin .take() .unwrap_or_else(|| panic!("Could not take child process stdin")) .write_all(input.as_ref()) .unwrap_or_else(|e| panic!("{}", e)); let prog = command.wait_with_output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn get_file_contents(name: &str) -> String { let mut f = File::open(Path::new(name)).unwrap(); let mut contents = String::new(); let _ = f.read_to_string(&mut contents); contents } pub fn mkdir(dir: &str) { fs::create_dir(Path::new(dir)).unwrap(); } pub fn make_file(name: &str) -> File { match File::create(Path::new(name)) { Ok(f) => f, Err(e) => panic!("{}", e) } } pub fn touch(file: &str) { File::create(Path::new(file)).unwrap(); } pub fn symlink(src: &str, dst: &str) { symlink_file(src, dst).unwrap(); } pub fn is_symlink(path: &str) -> bool { match fs::symlink_metadata(path) { Ok(m) => m.file_type().is_symlink(), Err(_) => false } } pub fn resolve_link(path: &str) -> String { match fs::read_link(path) { Ok(p) => p.to_str().unwrap().to_owned(), Err(_) => "".to_string() } } pub fn
(path: &str) -> fs::Metadata { match fs::metadata(path) { Ok(m) => m, Err(e) => panic!("{}", e) } } pub fn file_exists(path: &str) -> bool { match fs::metadata(path) { Ok(m) => m.is_file(), Err(_) => false } } pub fn dir_exists(path: &str) -> bool { match fs::metadata(path) { Ok(m) => m.is_dir(), Err(_) => false } } pub fn cleanup(path: &'static str) { let p = Path::new(path); match fs::metadata(p) { Ok(m) => if m.is_file() { fs::remove_file(&p).unwrap(); } else { fs::remove_dir(&p).unwrap(); }, Err(_) => {} } } pub fn current_directory() -> String { env::current_dir().unwrap().into_os_string().into_string().unwrap() } pub fn repeat_str(s: &str, n: u32) -> String { let mut repeated = String::new(); for _ in 0 .. n { repeated.push_str(s); } repeated }
metadata
identifier_name
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as path from 'path'; import { languages, window, commands, workspace, ExtensionContext } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, RequestType, Range, TextEdit } from 'vscode-languageclient'; import { activateColorDecorations } from './colorDecorators'; import * as nls from 'vscode-nls'; let localize = nls.loadMessageBundle(); namespace ColorSymbolRequest { export const type: RequestType<string, Range[], any, any> = new RequestType('css/colorSymbols'); } // this method is called when vs code is activated export function activate(context: ExtensionContext) { // The server is implemented in node let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js')); // The debug options for the server let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] }; // If the extension is launch in debug mode the debug server options are use // Otherwise the run options are used let serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; // Options to control the language client let clientOptions: LanguageClientOptions = { documentSelector: ['css', 'less', 'scss'], synchronize: { configurationSection: ['css', 'scss', 'less'] }, initializationOptions: { } }; // Create the language client and start the client. let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions); let disposable = client.start(); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); client.onReady().then(_ => { let colorRequestor = (uri: string) => { return client.sendRequest(ColorSymbolRequest.type, uri).then(ranges => ranges.map(client.protocol2CodeConverter.asRange)); }; let isDecoratorEnabled = (languageId: string) => { return workspace.getConfiguration().get<boolean>(languageId + '.colorDecorators.enable'); }; disposable = activateColorDecorations(colorRequestor, { css: true, scss: true, less: true }, isDecoratorEnabled); context.subscriptions.push(disposable); }); languages.setLanguageConfiguration('css', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('less', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('scss', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g }); commands.registerCommand('_css.applyCodeAction', applyCodeAction); function
(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }).then(success => { if (!success) { window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.'); } }); } } }
applyCodeAction
identifier_name
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as path from 'path'; import { languages, window, commands, workspace, ExtensionContext } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, RequestType, Range, TextEdit } from 'vscode-languageclient'; import { activateColorDecorations } from './colorDecorators'; import * as nls from 'vscode-nls'; let localize = nls.loadMessageBundle(); namespace ColorSymbolRequest { export const type: RequestType<string, Range[], any, any> = new RequestType('css/colorSymbols'); } // this method is called when vs code is activated export function activate(context: ExtensionContext) { // The server is implemented in node let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js'));
// If the extension is launch in debug mode the debug server options are use // Otherwise the run options are used let serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; // Options to control the language client let clientOptions: LanguageClientOptions = { documentSelector: ['css', 'less', 'scss'], synchronize: { configurationSection: ['css', 'scss', 'less'] }, initializationOptions: { } }; // Create the language client and start the client. let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions); let disposable = client.start(); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); client.onReady().then(_ => { let colorRequestor = (uri: string) => { return client.sendRequest(ColorSymbolRequest.type, uri).then(ranges => ranges.map(client.protocol2CodeConverter.asRange)); }; let isDecoratorEnabled = (languageId: string) => { return workspace.getConfiguration().get<boolean>(languageId + '.colorDecorators.enable'); }; disposable = activateColorDecorations(colorRequestor, { css: true, scss: true, less: true }, isDecoratorEnabled); context.subscriptions.push(disposable); }); languages.setLanguageConfiguration('css', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('less', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('scss', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g }); commands.registerCommand('_css.applyCodeAction', applyCodeAction); function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }).then(success => { if (!success) { window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.'); } }); } } }
// The debug options for the server let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] };
random_line_split
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as path from 'path'; import { languages, window, commands, workspace, ExtensionContext } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, RequestType, Range, TextEdit } from 'vscode-languageclient'; import { activateColorDecorations } from './colorDecorators'; import * as nls from 'vscode-nls'; let localize = nls.loadMessageBundle(); namespace ColorSymbolRequest { export const type: RequestType<string, Range[], any, any> = new RequestType('css/colorSymbols'); } // this method is called when vs code is activated export function activate(context: ExtensionContext)
{ // The server is implemented in node let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js')); // The debug options for the server let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] }; // If the extension is launch in debug mode the debug server options are use // Otherwise the run options are used let serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; // Options to control the language client let clientOptions: LanguageClientOptions = { documentSelector: ['css', 'less', 'scss'], synchronize: { configurationSection: ['css', 'scss', 'less'] }, initializationOptions: { } }; // Create the language client and start the client. let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions); let disposable = client.start(); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); client.onReady().then(_ => { let colorRequestor = (uri: string) => { return client.sendRequest(ColorSymbolRequest.type, uri).then(ranges => ranges.map(client.protocol2CodeConverter.asRange)); }; let isDecoratorEnabled = (languageId: string) => { return workspace.getConfiguration().get<boolean>(languageId + '.colorDecorators.enable'); }; disposable = activateColorDecorations(colorRequestor, { css: true, scss: true, less: true }, isDecoratorEnabled); context.subscriptions.push(disposable); }); languages.setLanguageConfiguration('css', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('less', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('scss', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g }); commands.registerCommand('_css.applyCodeAction', applyCodeAction); function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }).then(success => { if (!success) { window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.'); } }); } } }
identifier_body
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as path from 'path'; import { languages, window, commands, workspace, ExtensionContext } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, RequestType, Range, TextEdit } from 'vscode-languageclient'; import { activateColorDecorations } from './colorDecorators'; import * as nls from 'vscode-nls'; let localize = nls.loadMessageBundle(); namespace ColorSymbolRequest { export const type: RequestType<string, Range[], any, any> = new RequestType('css/colorSymbols'); } // this method is called when vs code is activated export function activate(context: ExtensionContext) { // The server is implemented in node let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js')); // The debug options for the server let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] }; // If the extension is launch in debug mode the debug server options are use // Otherwise the run options are used let serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; // Options to control the language client let clientOptions: LanguageClientOptions = { documentSelector: ['css', 'less', 'scss'], synchronize: { configurationSection: ['css', 'scss', 'less'] }, initializationOptions: { } }; // Create the language client and start the client. let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions); let disposable = client.start(); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); client.onReady().then(_ => { let colorRequestor = (uri: string) => { return client.sendRequest(ColorSymbolRequest.type, uri).then(ranges => ranges.map(client.protocol2CodeConverter.asRange)); }; let isDecoratorEnabled = (languageId: string) => { return workspace.getConfiguration().get<boolean>(languageId + '.colorDecorators.enable'); }; disposable = activateColorDecorations(colorRequestor, { css: true, scss: true, less: true }, isDecoratorEnabled); context.subscriptions.push(disposable); }); languages.setLanguageConfiguration('css', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('less', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); languages.setLanguageConfiguration('scss', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g }); commands.registerCommand('_css.applyCodeAction', applyCodeAction); function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }).then(success => { if (!success)
}); } } }
{ window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.'); }
conditional_block
stream.py
import os import asyncio import logging from functools import partial from collections import deque from lxml import etree from . import stanzas from .stanzas import Iq from .parser import Parser from .utils import signalEvent from .utils import benchmark as timedWait from . import getLogger log = getLogger(__name__) if "VEX_TIMED_WAITS" in os.environ and int(os.environ["VEX_TIMED_WAITS"]): from .metrics import ValueMetric stream_wait_met = ValueMetric("stream:wait_time", type_=float) else: stream_wait_met = None _ENFORCE_TIMEOUTS = bool("VEX_ENFORCE_TIMEOUTS" in os.environ and int(os.environ["VEX_ENFORCE_TIMEOUTS"])) class QueuedStanza: def __init__(self, s): self.task_set = set() self.stanza = s class ParserTask(asyncio.Task): def __init__(self, stream, loop=None): super().__init__(self._run(), loop=loop) self._parser = Parser() self._data_queue = asyncio.Queue() self._stream = stream def parse(self, bytes_): self._data_queue.put_nowait(bytes_) def reset(self): self._parser.reset() async def _run(self): while True: try: data = await self._data_queue.get() elems = self._parser.parse(data) for e in elems: stanza = stanzas.makeStanza(e) if log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA IN]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) await self._stream._handleStanza(stanza) except asyncio.CancelledError: pass except Exception as ex: log.exception(ex) class
(asyncio.Protocol): """Base class for XMPP streams.""" def __init__(self, creds, state_callbacks=None, mixins=None, default_timeout=None): self.creds = creds self._transport = None self._waiter_futures = [] self._tls_active = False self._callbacks = state_callbacks self._mixins = mixins or [] for mixin in self._mixins: for name, obj in mixin._exports: if name in self.__dict__: raise ValueError("Mixin '%s' exports ambiguous " "data named '%s'" % (str(mixin), name)) else: # Add the symbol to the stream's namespace self.__dict__[name] = obj self._parser_task = ParserTask(self) self.default_timeout = default_timeout # Stream errors self.error = None self._stanza_queue = deque(maxlen=10) @property def connected(self): if not self._transport: return False else: if (getattr(self._transport, "_closing") and self._transport._closing): # SSL transport return False return True @property def tls_active(self): return self._tls_active @property def jid(self): return self.creds.jid def close(self): if self.connected: self.send(b"</stream:stream>") self._transport.close() self._parser_task.cancel() def send(self, data): """Send ``data`` which can be a vexmpp.stanza.Stanza, lxml.etree.Element, a str, or bytes. The the case of bytes the encoding MUST be utf-8 encoded (per XMPP specification). In the case of Stanza and Element the Mixin.onSend callback is invoked. Currently there is not a Mixin callback for strings or bytes. """ def _send(bytes_): if not self._transport: log.warn("Data send with disconnected transport") return self._transport.write(bytes_) log.debug("[BYTES OUT]: %s", bytes_) stanza = None if isinstance(data, stanzas.Stanza): stanza = data raw_data = data.toXml() elif isinstance(data, str): raw_data = data.encode("utf-8") elif isinstance(data, etree._Element): stanza = stanzas.Stanza(xml=data) raw_data = etree.tostring(data, encoding="utf-8") elif isinstance(data, bytes): raw_data = data else: raise ValueError("Unable to send type {}".format(type(data))) if stanza and log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA OUT]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) _send(raw_data) if stanza: for m in self._mixins: hook = partial(m.onSend, self, stanza) asyncio.ensure_future(self._runMixin(hook)) async def sendAndWaitIq(self, child_ns, to=None, child_name="query", type="get", raise_on_error=False, timeout=None, id_prefix=None): iq = Iq(to=to, type=type, request=(child_name, child_ns), id_prefix=id_prefix) resp = await self.sendAndWait(iq, raise_on_error=raise_on_error, timeout=timeout) return resp async def sendAndWait(self, stanza, raise_on_error=False, timeout=None): if not stanza.id: stanza.setId() xpath = "/%s[@id='%s']" % (stanza.name, stanza.id) self.send(stanza) resp = await self.wait([(xpath, None)], timeout=timeout) if resp.error is not None and raise_on_error: raise resp.error else: return resp async def negotiate(self, timeout=None): raise NotImplementedError() async def wait(self, xpaths, timeout=None): """``xpaths`` is a 2-tuple of the form (xpath, nsmap), or a list of the same tuples to wait on a choice of matches. The first matched stanza is returned. Passing a ``timeout`` argument will raise a asyncio.TimeoutError if not matches are found.""" global stream_wait_met if not isinstance(xpaths, list): xpaths = [xpaths] if timeout is None and self.default_timeout: timeout = self.default_timeout log.debug("Stream wait for %s [timeout=%s]" % (xpaths, timeout)) if _ENFORCE_TIMEOUTS and not timeout: raise RuntimeError("Timeout not set error") fut = _StreamWaitFuture(xpaths) # Run thru queue. Note, once a tasklet has seen a stanza it is skipped # by _StreamWaitFuture.matchStanza for queued_stanza in self._stanza_queue: matched = fut.matchStanza(queued_stanza) if matched: return queued_stanza.stanza self._waiter_futures.append(fut) try: with timedWait() as timer_stat: match = await asyncio.wait_for(fut, timeout) if stream_wait_met: stream_wait_met.update(timer_stat["total"]) log.debug("Stream wait - time: {:.3f} " "min/max/avg: {:.6f}/{:.6f}/{:.6f}" .format(stream_wait_met.value, stream_wait_met.min, stream_wait_met.max, stream_wait_met.average)) return match except asyncio.TimeoutError as ex: raise asyncio.TimeoutError( "Timeout ({}s) while waiting for xpaths: {}" .format(timeout, xpaths)) from ex finally: self._waiter_futures.remove(fut) # asyncio.Protocol implementation def connection_made(self, transport, tls=False): log.debug("Connection_made: %s", transport) self._transport = transport self._tls_active = tls signalEvent(self._callbacks, "connected", self, tls) def starttls_made(self, transport): self.connection_made(transport, tls=True) async def _handleStanza(self, stanza): if isinstance(stanza, stanzas.StreamError): signalEvent(self._callbacks, "streamError", self, stanza) self._transport.close() return for m in self._mixins: hook = partial(m.onStanza, self, stanza) asyncio.ensure_future(self._runMixin(hook)) self._stanza_queue.append(QueuedStanza(stanza)) if self._waiter_futures: for queued_stanza in self._stanza_queue: for fut in [f for f in self._waiter_futures if not f.done()]: matched = fut.matchStanza(queued_stanza) if matched: # XXX: How useful is this since _stanza_queue? # Yield the event loop, which is essential for a handle # and wait in quick succession. await asyncio.sleep(0) # asyncio.Protocol implementation def data_received(self, data): log.debug('[BYTES IN]: {!r}'.format(data.decode())) self._parser_task.parse(data) # asyncio.Protocol implementation def connection_lost(self, reason): self._transport = None self._tls_active = False log.debug('The server closed the connection: %s' % str(reason)) signalEvent(self._callbacks, "disconnected", self, reason) @property def default_timeout(self): return self._default_timeout @default_timeout.setter def default_timeout(self, t): if t is not None: t = int(t) self._default_timeout = t async def _runMixin(self, functor): try: await functor() except: log.exception("{} mixin error".format(functor.__class__.__name__)) class Mixin(object): def __init__(self, export_tuples=None): """ ``export_tuples`` is a list of 2-tuples (name, obj) that added to the stream object's __dict__, as in __dict__[name] = obj. By default no values are exported. """ self._exports = export_tuples if export_tuples else [] async def postSession(self, stream): """Called after stream negotiation and session creation.""" pass async def onStanza(self, stream, stanza): """Called for each incoming Stanza. See :func:`vexmpp.utils.xpathFilter` for a decorator that can filter only the stanzas the implementation is interested in. """ pass async def onSend(self, stream, stanza): """Called for each outgoing stanza.""" pass class StreamCallbacks: def connected(self, stream, tls_active): pass def disconnected(self, stream, reason): pass def streamError(self, stream, error): pass class _StreamWaitFuture(asyncio.Future): def __init__(self, xpaths, *args, loop=None): super().__init__(*args, loop=loop) self._xpaths = xpaths self._task = asyncio.Task.current_task() def matchStanza(self, queued_stanza): log.debug(f"MatchStanza: {queued_stanza.stanza.toXml()} xpaths: " "{0} - @{1}".format(self._xpaths, id(self._task))) if self._task in queued_stanza.task_set: # seen this... return False queued_stanza.task_set.add(self._task) stanza = queued_stanza.stanza for xp, nsmap in self._xpaths: log.debug("MatchStanza: Testing xpath {} against stanza {}" .format((xp, nsmap), stanza.toXml())) if stanza.xml.xpath(xp, namespaces=nsmap): log.debug("MatchStanza: matched") self.set_result(stanza) return True log.debug("MatchStanza: NOT matched") return False
Stream
identifier_name
stream.py
import os import asyncio import logging from functools import partial from collections import deque from lxml import etree from . import stanzas from .stanzas import Iq from .parser import Parser from .utils import signalEvent from .utils import benchmark as timedWait from . import getLogger log = getLogger(__name__) if "VEX_TIMED_WAITS" in os.environ and int(os.environ["VEX_TIMED_WAITS"]): from .metrics import ValueMetric stream_wait_met = ValueMetric("stream:wait_time", type_=float) else: stream_wait_met = None _ENFORCE_TIMEOUTS = bool("VEX_ENFORCE_TIMEOUTS" in os.environ and int(os.environ["VEX_ENFORCE_TIMEOUTS"])) class QueuedStanza: def __init__(self, s): self.task_set = set() self.stanza = s class ParserTask(asyncio.Task): def __init__(self, stream, loop=None): super().__init__(self._run(), loop=loop) self._parser = Parser() self._data_queue = asyncio.Queue() self._stream = stream def parse(self, bytes_): self._data_queue.put_nowait(bytes_) def reset(self): self._parser.reset() async def _run(self): while True: try: data = await self._data_queue.get() elems = self._parser.parse(data) for e in elems: stanza = stanzas.makeStanza(e) if log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA IN]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) await self._stream._handleStanza(stanza) except asyncio.CancelledError: pass except Exception as ex: log.exception(ex) class Stream(asyncio.Protocol): """Base class for XMPP streams.""" def __init__(self, creds, state_callbacks=None, mixins=None, default_timeout=None):
@property def connected(self): if not self._transport: return False else: if (getattr(self._transport, "_closing") and self._transport._closing): # SSL transport return False return True @property def tls_active(self): return self._tls_active @property def jid(self): return self.creds.jid def close(self): if self.connected: self.send(b"</stream:stream>") self._transport.close() self._parser_task.cancel() def send(self, data): """Send ``data`` which can be a vexmpp.stanza.Stanza, lxml.etree.Element, a str, or bytes. The the case of bytes the encoding MUST be utf-8 encoded (per XMPP specification). In the case of Stanza and Element the Mixin.onSend callback is invoked. Currently there is not a Mixin callback for strings or bytes. """ def _send(bytes_): if not self._transport: log.warn("Data send with disconnected transport") return self._transport.write(bytes_) log.debug("[BYTES OUT]: %s", bytes_) stanza = None if isinstance(data, stanzas.Stanza): stanza = data raw_data = data.toXml() elif isinstance(data, str): raw_data = data.encode("utf-8") elif isinstance(data, etree._Element): stanza = stanzas.Stanza(xml=data) raw_data = etree.tostring(data, encoding="utf-8") elif isinstance(data, bytes): raw_data = data else: raise ValueError("Unable to send type {}".format(type(data))) if stanza and log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA OUT]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) _send(raw_data) if stanza: for m in self._mixins: hook = partial(m.onSend, self, stanza) asyncio.ensure_future(self._runMixin(hook)) async def sendAndWaitIq(self, child_ns, to=None, child_name="query", type="get", raise_on_error=False, timeout=None, id_prefix=None): iq = Iq(to=to, type=type, request=(child_name, child_ns), id_prefix=id_prefix) resp = await self.sendAndWait(iq, raise_on_error=raise_on_error, timeout=timeout) return resp async def sendAndWait(self, stanza, raise_on_error=False, timeout=None): if not stanza.id: stanza.setId() xpath = "/%s[@id='%s']" % (stanza.name, stanza.id) self.send(stanza) resp = await self.wait([(xpath, None)], timeout=timeout) if resp.error is not None and raise_on_error: raise resp.error else: return resp async def negotiate(self, timeout=None): raise NotImplementedError() async def wait(self, xpaths, timeout=None): """``xpaths`` is a 2-tuple of the form (xpath, nsmap), or a list of the same tuples to wait on a choice of matches. The first matched stanza is returned. Passing a ``timeout`` argument will raise a asyncio.TimeoutError if not matches are found.""" global stream_wait_met if not isinstance(xpaths, list): xpaths = [xpaths] if timeout is None and self.default_timeout: timeout = self.default_timeout log.debug("Stream wait for %s [timeout=%s]" % (xpaths, timeout)) if _ENFORCE_TIMEOUTS and not timeout: raise RuntimeError("Timeout not set error") fut = _StreamWaitFuture(xpaths) # Run thru queue. Note, once a tasklet has seen a stanza it is skipped # by _StreamWaitFuture.matchStanza for queued_stanza in self._stanza_queue: matched = fut.matchStanza(queued_stanza) if matched: return queued_stanza.stanza self._waiter_futures.append(fut) try: with timedWait() as timer_stat: match = await asyncio.wait_for(fut, timeout) if stream_wait_met: stream_wait_met.update(timer_stat["total"]) log.debug("Stream wait - time: {:.3f} " "min/max/avg: {:.6f}/{:.6f}/{:.6f}" .format(stream_wait_met.value, stream_wait_met.min, stream_wait_met.max, stream_wait_met.average)) return match except asyncio.TimeoutError as ex: raise asyncio.TimeoutError( "Timeout ({}s) while waiting for xpaths: {}" .format(timeout, xpaths)) from ex finally: self._waiter_futures.remove(fut) # asyncio.Protocol implementation def connection_made(self, transport, tls=False): log.debug("Connection_made: %s", transport) self._transport = transport self._tls_active = tls signalEvent(self._callbacks, "connected", self, tls) def starttls_made(self, transport): self.connection_made(transport, tls=True) async def _handleStanza(self, stanza): if isinstance(stanza, stanzas.StreamError): signalEvent(self._callbacks, "streamError", self, stanza) self._transport.close() return for m in self._mixins: hook = partial(m.onStanza, self, stanza) asyncio.ensure_future(self._runMixin(hook)) self._stanza_queue.append(QueuedStanza(stanza)) if self._waiter_futures: for queued_stanza in self._stanza_queue: for fut in [f for f in self._waiter_futures if not f.done()]: matched = fut.matchStanza(queued_stanza) if matched: # XXX: How useful is this since _stanza_queue? # Yield the event loop, which is essential for a handle # and wait in quick succession. await asyncio.sleep(0) # asyncio.Protocol implementation def data_received(self, data): log.debug('[BYTES IN]: {!r}'.format(data.decode())) self._parser_task.parse(data) # asyncio.Protocol implementation def connection_lost(self, reason): self._transport = None self._tls_active = False log.debug('The server closed the connection: %s' % str(reason)) signalEvent(self._callbacks, "disconnected", self, reason) @property def default_timeout(self): return self._default_timeout @default_timeout.setter def default_timeout(self, t): if t is not None: t = int(t) self._default_timeout = t async def _runMixin(self, functor): try: await functor() except: log.exception("{} mixin error".format(functor.__class__.__name__)) class Mixin(object): def __init__(self, export_tuples=None): """ ``export_tuples`` is a list of 2-tuples (name, obj) that added to the stream object's __dict__, as in __dict__[name] = obj. By default no values are exported. """ self._exports = export_tuples if export_tuples else [] async def postSession(self, stream): """Called after stream negotiation and session creation.""" pass async def onStanza(self, stream, stanza): """Called for each incoming Stanza. See :func:`vexmpp.utils.xpathFilter` for a decorator that can filter only the stanzas the implementation is interested in. """ pass async def onSend(self, stream, stanza): """Called for each outgoing stanza.""" pass class StreamCallbacks: def connected(self, stream, tls_active): pass def disconnected(self, stream, reason): pass def streamError(self, stream, error): pass class _StreamWaitFuture(asyncio.Future): def __init__(self, xpaths, *args, loop=None): super().__init__(*args, loop=loop) self._xpaths = xpaths self._task = asyncio.Task.current_task() def matchStanza(self, queued_stanza): log.debug(f"MatchStanza: {queued_stanza.stanza.toXml()} xpaths: " "{0} - @{1}".format(self._xpaths, id(self._task))) if self._task in queued_stanza.task_set: # seen this... return False queued_stanza.task_set.add(self._task) stanza = queued_stanza.stanza for xp, nsmap in self._xpaths: log.debug("MatchStanza: Testing xpath {} against stanza {}" .format((xp, nsmap), stanza.toXml())) if stanza.xml.xpath(xp, namespaces=nsmap): log.debug("MatchStanza: matched") self.set_result(stanza) return True log.debug("MatchStanza: NOT matched") return False
self.creds = creds self._transport = None self._waiter_futures = [] self._tls_active = False self._callbacks = state_callbacks self._mixins = mixins or [] for mixin in self._mixins: for name, obj in mixin._exports: if name in self.__dict__: raise ValueError("Mixin '%s' exports ambiguous " "data named '%s'" % (str(mixin), name)) else: # Add the symbol to the stream's namespace self.__dict__[name] = obj self._parser_task = ParserTask(self) self.default_timeout = default_timeout # Stream errors self.error = None self._stanza_queue = deque(maxlen=10)
identifier_body
stream.py
import os import asyncio import logging from functools import partial from collections import deque from lxml import etree from . import stanzas from .stanzas import Iq from .parser import Parser from .utils import signalEvent from .utils import benchmark as timedWait from . import getLogger log = getLogger(__name__) if "VEX_TIMED_WAITS" in os.environ and int(os.environ["VEX_TIMED_WAITS"]): from .metrics import ValueMetric stream_wait_met = ValueMetric("stream:wait_time", type_=float) else: stream_wait_met = None _ENFORCE_TIMEOUTS = bool("VEX_ENFORCE_TIMEOUTS" in os.environ and int(os.environ["VEX_ENFORCE_TIMEOUTS"])) class QueuedStanza: def __init__(self, s): self.task_set = set() self.stanza = s class ParserTask(asyncio.Task): def __init__(self, stream, loop=None): super().__init__(self._run(), loop=loop) self._parser = Parser() self._data_queue = asyncio.Queue() self._stream = stream def parse(self, bytes_): self._data_queue.put_nowait(bytes_) def reset(self): self._parser.reset() async def _run(self): while True: try: data = await self._data_queue.get() elems = self._parser.parse(data) for e in elems: stanza = stanzas.makeStanza(e) if log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA IN]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) await self._stream._handleStanza(stanza) except asyncio.CancelledError: pass except Exception as ex: log.exception(ex) class Stream(asyncio.Protocol): """Base class for XMPP streams.""" def __init__(self, creds, state_callbacks=None, mixins=None, default_timeout=None): self.creds = creds self._transport = None self._waiter_futures = [] self._tls_active = False self._callbacks = state_callbacks self._mixins = mixins or [] for mixin in self._mixins: for name, obj in mixin._exports: if name in self.__dict__: raise ValueError("Mixin '%s' exports ambiguous " "data named '%s'" % (str(mixin), name)) else: # Add the symbol to the stream's namespace self.__dict__[name] = obj self._parser_task = ParserTask(self) self.default_timeout = default_timeout # Stream errors self.error = None self._stanza_queue = deque(maxlen=10) @property def connected(self): if not self._transport: return False else: if (getattr(self._transport, "_closing") and self._transport._closing): # SSL transport return False return True @property def tls_active(self): return self._tls_active @property def jid(self): return self.creds.jid def close(self): if self.connected: self.send(b"</stream:stream>") self._transport.close() self._parser_task.cancel() def send(self, data): """Send ``data`` which can be a vexmpp.stanza.Stanza, lxml.etree.Element, a str, or bytes. The the case of bytes the encoding MUST be utf-8 encoded (per XMPP specification). In the case of Stanza and Element the Mixin.onSend callback is invoked. Currently there is not a Mixin callback for strings or bytes. """ def _send(bytes_): if not self._transport: log.warn("Data send with disconnected transport") return self._transport.write(bytes_) log.debug("[BYTES OUT]: %s", bytes_) stanza = None if isinstance(data, stanzas.Stanza): stanza = data raw_data = data.toXml() elif isinstance(data, str): raw_data = data.encode("utf-8") elif isinstance(data, etree._Element): stanza = stanzas.Stanza(xml=data) raw_data = etree.tostring(data, encoding="utf-8") elif isinstance(data, bytes): raw_data = data else: raise ValueError("Unable to send type {}".format(type(data))) if stanza and log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA OUT]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) _send(raw_data) if stanza: for m in self._mixins: hook = partial(m.onSend, self, stanza) asyncio.ensure_future(self._runMixin(hook)) async def sendAndWaitIq(self, child_ns, to=None, child_name="query", type="get", raise_on_error=False, timeout=None, id_prefix=None): iq = Iq(to=to, type=type, request=(child_name, child_ns), id_prefix=id_prefix) resp = await self.sendAndWait(iq, raise_on_error=raise_on_error, timeout=timeout) return resp async def sendAndWait(self, stanza, raise_on_error=False, timeout=None): if not stanza.id: stanza.setId() xpath = "/%s[@id='%s']" % (stanza.name, stanza.id) self.send(stanza) resp = await self.wait([(xpath, None)], timeout=timeout) if resp.error is not None and raise_on_error: raise resp.error else: return resp async def negotiate(self, timeout=None): raise NotImplementedError() async def wait(self, xpaths, timeout=None): """``xpaths`` is a 2-tuple of the form (xpath, nsmap), or a list of the same tuples to wait on a choice of matches. The first matched stanza is returned. Passing a ``timeout`` argument will raise a asyncio.TimeoutError if not matches are found.""" global stream_wait_met if not isinstance(xpaths, list): xpaths = [xpaths] if timeout is None and self.default_timeout: timeout = self.default_timeout log.debug("Stream wait for %s [timeout=%s]" % (xpaths, timeout)) if _ENFORCE_TIMEOUTS and not timeout: raise RuntimeError("Timeout not set error") fut = _StreamWaitFuture(xpaths) # Run thru queue. Note, once a tasklet has seen a stanza it is skipped # by _StreamWaitFuture.matchStanza for queued_stanza in self._stanza_queue: matched = fut.matchStanza(queued_stanza) if matched: return queued_stanza.stanza self._waiter_futures.append(fut) try: with timedWait() as timer_stat: match = await asyncio.wait_for(fut, timeout) if stream_wait_met: stream_wait_met.update(timer_stat["total"]) log.debug("Stream wait - time: {:.3f} " "min/max/avg: {:.6f}/{:.6f}/{:.6f}" .format(stream_wait_met.value, stream_wait_met.min, stream_wait_met.max, stream_wait_met.average)) return match except asyncio.TimeoutError as ex: raise asyncio.TimeoutError( "Timeout ({}s) while waiting for xpaths: {}" .format(timeout, xpaths)) from ex finally: self._waiter_futures.remove(fut) # asyncio.Protocol implementation def connection_made(self, transport, tls=False): log.debug("Connection_made: %s", transport) self._transport = transport self._tls_active = tls signalEvent(self._callbacks, "connected", self, tls) def starttls_made(self, transport): self.connection_made(transport, tls=True) async def _handleStanza(self, stanza): if isinstance(stanza, stanzas.StreamError): signalEvent(self._callbacks, "streamError", self, stanza) self._transport.close() return for m in self._mixins: hook = partial(m.onStanza, self, stanza) asyncio.ensure_future(self._runMixin(hook)) self._stanza_queue.append(QueuedStanza(stanza)) if self._waiter_futures: for queued_stanza in self._stanza_queue: for fut in [f for f in self._waiter_futures if not f.done()]: matched = fut.matchStanza(queued_stanza) if matched: # XXX: How useful is this since _stanza_queue? # Yield the event loop, which is essential for a handle # and wait in quick succession. await asyncio.sleep(0) # asyncio.Protocol implementation def data_received(self, data): log.debug('[BYTES IN]: {!r}'.format(data.decode())) self._parser_task.parse(data) # asyncio.Protocol implementation def connection_lost(self, reason): self._transport = None self._tls_active = False log.debug('The server closed the connection: %s' % str(reason)) signalEvent(self._callbacks, "disconnected", self, reason) @property def default_timeout(self): return self._default_timeout @default_timeout.setter def default_timeout(self, t): if t is not None: t = int(t) self._default_timeout = t async def _runMixin(self, functor): try: await functor() except: log.exception("{} mixin error".format(functor.__class__.__name__)) class Mixin(object): def __init__(self, export_tuples=None): """ ``export_tuples`` is a list of 2-tuples (name, obj) that added to the stream object's __dict__, as in __dict__[name] = obj. By default no values are exported. """ self._exports = export_tuples if export_tuples else [] async def postSession(self, stream): """Called after stream negotiation and session creation.""" pass async def onStanza(self, stream, stanza): """Called for each incoming Stanza. See :func:`vexmpp.utils.xpathFilter` for a decorator that can filter only the stanzas the implementation is interested in. """ pass async def onSend(self, stream, stanza): """Called for each outgoing stanza.""" pass class StreamCallbacks: def connected(self, stream, tls_active): pass def disconnected(self, stream, reason): pass def streamError(self, stream, error): pass class _StreamWaitFuture(asyncio.Future): def __init__(self, xpaths, *args, loop=None): super().__init__(*args, loop=loop) self._xpaths = xpaths self._task = asyncio.Task.current_task() def matchStanza(self, queued_stanza): log.debug(f"MatchStanza: {queued_stanza.stanza.toXml()} xpaths: " "{0} - @{1}".format(self._xpaths, id(self._task))) if self._task in queued_stanza.task_set: # seen this... return False queued_stanza.task_set.add(self._task) stanza = queued_stanza.stanza for xp, nsmap in self._xpaths: log.debug("MatchStanza: Testing xpath {} against stanza {}" .format((xp, nsmap), stanza.toXml())) if stanza.xml.xpath(xp, namespaces=nsmap):
self.set_result(stanza) return True log.debug("MatchStanza: NOT matched") return False
log.debug("MatchStanza: matched")
random_line_split
stream.py
import os import asyncio import logging from functools import partial from collections import deque from lxml import etree from . import stanzas from .stanzas import Iq from .parser import Parser from .utils import signalEvent from .utils import benchmark as timedWait from . import getLogger log = getLogger(__name__) if "VEX_TIMED_WAITS" in os.environ and int(os.environ["VEX_TIMED_WAITS"]): from .metrics import ValueMetric stream_wait_met = ValueMetric("stream:wait_time", type_=float) else: stream_wait_met = None _ENFORCE_TIMEOUTS = bool("VEX_ENFORCE_TIMEOUTS" in os.environ and int(os.environ["VEX_ENFORCE_TIMEOUTS"])) class QueuedStanza: def __init__(self, s): self.task_set = set() self.stanza = s class ParserTask(asyncio.Task): def __init__(self, stream, loop=None): super().__init__(self._run(), loop=loop) self._parser = Parser() self._data_queue = asyncio.Queue() self._stream = stream def parse(self, bytes_): self._data_queue.put_nowait(bytes_) def reset(self): self._parser.reset() async def _run(self): while True: try: data = await self._data_queue.get() elems = self._parser.parse(data) for e in elems: stanza = stanzas.makeStanza(e) if log.getEffectiveLevel() <= logging.VERBOSE:
await self._stream._handleStanza(stanza) except asyncio.CancelledError: pass except Exception as ex: log.exception(ex) class Stream(asyncio.Protocol): """Base class for XMPP streams.""" def __init__(self, creds, state_callbacks=None, mixins=None, default_timeout=None): self.creds = creds self._transport = None self._waiter_futures = [] self._tls_active = False self._callbacks = state_callbacks self._mixins = mixins or [] for mixin in self._mixins: for name, obj in mixin._exports: if name in self.__dict__: raise ValueError("Mixin '%s' exports ambiguous " "data named '%s'" % (str(mixin), name)) else: # Add the symbol to the stream's namespace self.__dict__[name] = obj self._parser_task = ParserTask(self) self.default_timeout = default_timeout # Stream errors self.error = None self._stanza_queue = deque(maxlen=10) @property def connected(self): if not self._transport: return False else: if (getattr(self._transport, "_closing") and self._transport._closing): # SSL transport return False return True @property def tls_active(self): return self._tls_active @property def jid(self): return self.creds.jid def close(self): if self.connected: self.send(b"</stream:stream>") self._transport.close() self._parser_task.cancel() def send(self, data): """Send ``data`` which can be a vexmpp.stanza.Stanza, lxml.etree.Element, a str, or bytes. The the case of bytes the encoding MUST be utf-8 encoded (per XMPP specification). In the case of Stanza and Element the Mixin.onSend callback is invoked. Currently there is not a Mixin callback for strings or bytes. """ def _send(bytes_): if not self._transport: log.warn("Data send with disconnected transport") return self._transport.write(bytes_) log.debug("[BYTES OUT]: %s", bytes_) stanza = None if isinstance(data, stanzas.Stanza): stanza = data raw_data = data.toXml() elif isinstance(data, str): raw_data = data.encode("utf-8") elif isinstance(data, etree._Element): stanza = stanzas.Stanza(xml=data) raw_data = etree.tostring(data, encoding="utf-8") elif isinstance(data, bytes): raw_data = data else: raise ValueError("Unable to send type {}".format(type(data))) if stanza and log.getEffectiveLevel() <= logging.VERBOSE: log.verbose("[STANZA OUT]:\n%s" % stanza.toXml(pprint=True).decode("utf-8")) _send(raw_data) if stanza: for m in self._mixins: hook = partial(m.onSend, self, stanza) asyncio.ensure_future(self._runMixin(hook)) async def sendAndWaitIq(self, child_ns, to=None, child_name="query", type="get", raise_on_error=False, timeout=None, id_prefix=None): iq = Iq(to=to, type=type, request=(child_name, child_ns), id_prefix=id_prefix) resp = await self.sendAndWait(iq, raise_on_error=raise_on_error, timeout=timeout) return resp async def sendAndWait(self, stanza, raise_on_error=False, timeout=None): if not stanza.id: stanza.setId() xpath = "/%s[@id='%s']" % (stanza.name, stanza.id) self.send(stanza) resp = await self.wait([(xpath, None)], timeout=timeout) if resp.error is not None and raise_on_error: raise resp.error else: return resp async def negotiate(self, timeout=None): raise NotImplementedError() async def wait(self, xpaths, timeout=None): """``xpaths`` is a 2-tuple of the form (xpath, nsmap), or a list of the same tuples to wait on a choice of matches. The first matched stanza is returned. Passing a ``timeout`` argument will raise a asyncio.TimeoutError if not matches are found.""" global stream_wait_met if not isinstance(xpaths, list): xpaths = [xpaths] if timeout is None and self.default_timeout: timeout = self.default_timeout log.debug("Stream wait for %s [timeout=%s]" % (xpaths, timeout)) if _ENFORCE_TIMEOUTS and not timeout: raise RuntimeError("Timeout not set error") fut = _StreamWaitFuture(xpaths) # Run thru queue. Note, once a tasklet has seen a stanza it is skipped # by _StreamWaitFuture.matchStanza for queued_stanza in self._stanza_queue: matched = fut.matchStanza(queued_stanza) if matched: return queued_stanza.stanza self._waiter_futures.append(fut) try: with timedWait() as timer_stat: match = await asyncio.wait_for(fut, timeout) if stream_wait_met: stream_wait_met.update(timer_stat["total"]) log.debug("Stream wait - time: {:.3f} " "min/max/avg: {:.6f}/{:.6f}/{:.6f}" .format(stream_wait_met.value, stream_wait_met.min, stream_wait_met.max, stream_wait_met.average)) return match except asyncio.TimeoutError as ex: raise asyncio.TimeoutError( "Timeout ({}s) while waiting for xpaths: {}" .format(timeout, xpaths)) from ex finally: self._waiter_futures.remove(fut) # asyncio.Protocol implementation def connection_made(self, transport, tls=False): log.debug("Connection_made: %s", transport) self._transport = transport self._tls_active = tls signalEvent(self._callbacks, "connected", self, tls) def starttls_made(self, transport): self.connection_made(transport, tls=True) async def _handleStanza(self, stanza): if isinstance(stanza, stanzas.StreamError): signalEvent(self._callbacks, "streamError", self, stanza) self._transport.close() return for m in self._mixins: hook = partial(m.onStanza, self, stanza) asyncio.ensure_future(self._runMixin(hook)) self._stanza_queue.append(QueuedStanza(stanza)) if self._waiter_futures: for queued_stanza in self._stanza_queue: for fut in [f for f in self._waiter_futures if not f.done()]: matched = fut.matchStanza(queued_stanza) if matched: # XXX: How useful is this since _stanza_queue? # Yield the event loop, which is essential for a handle # and wait in quick succession. await asyncio.sleep(0) # asyncio.Protocol implementation def data_received(self, data): log.debug('[BYTES IN]: {!r}'.format(data.decode())) self._parser_task.parse(data) # asyncio.Protocol implementation def connection_lost(self, reason): self._transport = None self._tls_active = False log.debug('The server closed the connection: %s' % str(reason)) signalEvent(self._callbacks, "disconnected", self, reason) @property def default_timeout(self): return self._default_timeout @default_timeout.setter def default_timeout(self, t): if t is not None: t = int(t) self._default_timeout = t async def _runMixin(self, functor): try: await functor() except: log.exception("{} mixin error".format(functor.__class__.__name__)) class Mixin(object): def __init__(self, export_tuples=None): """ ``export_tuples`` is a list of 2-tuples (name, obj) that added to the stream object's __dict__, as in __dict__[name] = obj. By default no values are exported. """ self._exports = export_tuples if export_tuples else [] async def postSession(self, stream): """Called after stream negotiation and session creation.""" pass async def onStanza(self, stream, stanza): """Called for each incoming Stanza. See :func:`vexmpp.utils.xpathFilter` for a decorator that can filter only the stanzas the implementation is interested in. """ pass async def onSend(self, stream, stanza): """Called for each outgoing stanza.""" pass class StreamCallbacks: def connected(self, stream, tls_active): pass def disconnected(self, stream, reason): pass def streamError(self, stream, error): pass class _StreamWaitFuture(asyncio.Future): def __init__(self, xpaths, *args, loop=None): super().__init__(*args, loop=loop) self._xpaths = xpaths self._task = asyncio.Task.current_task() def matchStanza(self, queued_stanza): log.debug(f"MatchStanza: {queued_stanza.stanza.toXml()} xpaths: " "{0} - @{1}".format(self._xpaths, id(self._task))) if self._task in queued_stanza.task_set: # seen this... return False queued_stanza.task_set.add(self._task) stanza = queued_stanza.stanza for xp, nsmap in self._xpaths: log.debug("MatchStanza: Testing xpath {} against stanza {}" .format((xp, nsmap), stanza.toXml())) if stanza.xml.xpath(xp, namespaces=nsmap): log.debug("MatchStanza: matched") self.set_result(stanza) return True log.debug("MatchStanza: NOT matched") return False
log.verbose("[STANZA IN]:\n%s" % stanza.toXml(pprint=True).decode("utf-8"))
conditional_block
app.js
var express = require('express'); var swig = require('swig'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var compression = require('compression'); var cluster = require('cluster'); var app = express(); var env = app.get('env') || 'development'; app.set('env', env); var boot = function(){ app.set('port', process.env.PORT || 8150); app.engine('tpl', swig.renderFile); app.set('view engine', 'tpl'); app.set('views', __dirname + '/templates'); if ('development' == env) { app.set('view cache', false); swig.setDefaults({cache: false}); } //app.use(cookieParser('user_specified')); //session encrypted cookie //app.use(bodyParser.urlencoded({ extended: false })); // post body app.use(compression()); // gzip app.use(function(req, res, next) { //Can add some request intercepter next(); }); // load route require('fs').readdirSync(__dirname + '/routes').forEach(function(file) { require(__dirname + '/routes/' + file)(app); }); app.use(function(req, res, next) { res.status(404).json({ERROR: 'Page not found.'}); }); app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).json({ERROR: 'Internal server error.'}); }); app.listen(app.get('port')); console.log('Application Started on http://localhost:' + app.get('port')); }; if (cluster.isMaster && app.get('env') == 'production') { // Add cluster support var cpuCount = require('os').cpus().length; for (var i = 0; i < cpuCount; i++)
} else { boot(); //require('./utils/functions').swig(swig); //swig extension }
{ cluster.fork(); }
conditional_block
app.js
var express = require('express'); var swig = require('swig'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var compression = require('compression'); var cluster = require('cluster'); var app = express(); var env = app.get('env') || 'development'; app.set('env', env); var boot = function(){ app.set('port', process.env.PORT || 8150); app.engine('tpl', swig.renderFile); app.set('view engine', 'tpl'); app.set('views', __dirname + '/templates'); if ('development' == env) { app.set('view cache', false); swig.setDefaults({cache: false}); } //app.use(cookieParser('user_specified')); //session encrypted cookie //app.use(bodyParser.urlencoded({ extended: false })); // post body app.use(compression()); // gzip app.use(function(req, res, next) { //Can add some request intercepter next(); }); // load route require('fs').readdirSync(__dirname + '/routes').forEach(function(file) { require(__dirname + '/routes/' + file)(app); }); app.use(function(req, res, next) { res.status(404).json({ERROR: 'Page not found.'}); }); app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).json({ERROR: 'Internal server error.'}); }); app.listen(app.get('port'));
if (cluster.isMaster && app.get('env') == 'production') { // Add cluster support var cpuCount = require('os').cpus().length; for (var i = 0; i < cpuCount; i++) { cluster.fork(); } } else { boot(); //require('./utils/functions').swig(swig); //swig extension }
console.log('Application Started on http://localhost:' + app.get('port')); };
random_line_split
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use cssparser::{Parser, ParserInput, RGBA}; use cssparser::Color as CSSColor; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::js::Root; use dom::bindings::num::Finite; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[derive(JSTraceable, Clone, HeapSizeOf)] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> Root<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl CanvasGradientMethods for CanvasGradient { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(&self, offset: Finite<f64>, color: DOMString) -> ErrorResult { if *offset < 0f64 || *offset > 1f64 { return Err(Error::IndexSize);
let color = CSSColor::parse(&mut parser); let color = if parser.is_exhausted() { match color { Ok(CSSColor::RGBA(rgba)) => rgba, Ok(CSSColor::CurrentColor) => RGBA::new(0, 0, 0, 255), _ => return Err(Error::Syntax) } } else { return Err(Error::Syntax) }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: color, }); Ok(()) } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for &'a CanvasGradient { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) } CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
} let mut input = ParserInput::new(&color); let mut parser = Parser::new(&mut input);
random_line_split
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use cssparser::{Parser, ParserInput, RGBA}; use cssparser::Color as CSSColor; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::js::Root; use dom::bindings::num::Finite; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[derive(JSTraceable, Clone, HeapSizeOf)] pub enum
{ Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> Root<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl CanvasGradientMethods for CanvasGradient { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(&self, offset: Finite<f64>, color: DOMString) -> ErrorResult { if *offset < 0f64 || *offset > 1f64 { return Err(Error::IndexSize); } let mut input = ParserInput::new(&color); let mut parser = Parser::new(&mut input); let color = CSSColor::parse(&mut parser); let color = if parser.is_exhausted() { match color { Ok(CSSColor::RGBA(rgba)) => rgba, Ok(CSSColor::CurrentColor) => RGBA::new(0, 0, 0, 255), _ => return Err(Error::Syntax) } } else { return Err(Error::Syntax) }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: color, }); Ok(()) } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for &'a CanvasGradient { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) } CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
CanvasGradientStyle
identifier_name
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use cssparser::{Parser, ParserInput, RGBA}; use cssparser::Color as CSSColor; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::js::Root; use dom::bindings::num::Finite; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[derive(JSTraceable, Clone, HeapSizeOf)] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> Root<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl CanvasGradientMethods for CanvasGradient { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(&self, offset: Finite<f64>, color: DOMString) -> ErrorResult { if *offset < 0f64 || *offset > 1f64 { return Err(Error::IndexSize); } let mut input = ParserInput::new(&color); let mut parser = Parser::new(&mut input); let color = CSSColor::parse(&mut parser); let color = if parser.is_exhausted() { match color { Ok(CSSColor::RGBA(rgba)) => rgba, Ok(CSSColor::CurrentColor) => RGBA::new(0, 0, 0, 255), _ => return Err(Error::Syntax) } } else { return Err(Error::Syntax) }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: color, }); Ok(()) } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for &'a CanvasGradient { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) =>
CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
{ FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }
conditional_block
prerender.js
'use strict'; import optimist from 'optimist'; import fs from 'fs'; import { resolve } from 'path'; // import { renderPath } from '../dist/server-bundle'; // nginx will look for $uri with the .html extension const prerenderRoutes = [ { path: '/', filename: 'index.html' }, { path: '/counters', filename: 'counters.html' }, { path: '/todos', filename: 'todos.html' } ];
/* prerenderRoutes.forEach((route) => { fs.writeFile( resolve(__dirname, argv.out + route.filename), resolvePath(route.path), (err) => { if(err) { return console.log(err); // eslint-disable-line } console.log(`${route.filename} saved...`); //eslint-disable-line }); }); */
let argv = optimist .alias('o', 'out') .default('o', 'site/') .argv;
random_line_split
FluxUtils.tsx
import { Dispatcher } from "flux"; import { ReduceStore, Container } from "flux/utils"; import * as React from "react"; interface Payload { type: string; } const basicDispatcher = new Dispatcher<Payload>(); // Sample Reduce Store class CounterStore extends ReduceStore<number, any> { getInitialState(): number { return 0; } reduce(state: number, action: Payload): number { switch (action.type) { case 'increment': return state + 1; case 'square': return state * state; default: return state; } } } const Store = new CounterStore(basicDispatcher); // Sample Flux container with Store interface Props { a: string; b: boolean; } interface State { counter: number; } class CounterContainer extends React.Component<Props, State> { static
(): Container.StoresList { return [Store]; } static calculateState(prevState: State, props: Props): State { return { counter: Store.getState() - (props.b ? 0 : 1) }; } render() { return <div> {this.state.counter} </div>; } } const ContainerComponent1 = Container.create(CounterContainer, { withProps: true }); <ContainerComponent1 a="string" b={false} />; const ContainerComponent2 = Container.create<Props>(CounterContainer, { withProps: true }); <ContainerComponent2 a="string" b={false} />; const ContainerComponent3 = Container.create<Props, State>(CounterContainer, { withProps: true }); <ContainerComponent3 a="string" b={false} />; // Functional flux container with Store const FunctionalContainerComponent = Container.createFunctional( (props: State) => { return <div> {props.counter} </div>; }, (props: Props) => [Store], (prevState: State, props: Props) => ({ counter: Store.getState() }) ); <FunctionalContainerComponent a="string" b={false} />;
getStores
identifier_name
FluxUtils.tsx
import { Dispatcher } from "flux"; import { ReduceStore, Container } from "flux/utils"; import * as React from "react"; interface Payload { type: string; } const basicDispatcher = new Dispatcher<Payload>(); // Sample Reduce Store class CounterStore extends ReduceStore<number, any> { getInitialState(): number { return 0; } reduce(state: number, action: Payload): number {
case 'square': return state * state; default: return state; } } } const Store = new CounterStore(basicDispatcher); // Sample Flux container with Store interface Props { a: string; b: boolean; } interface State { counter: number; } class CounterContainer extends React.Component<Props, State> { static getStores(): Container.StoresList { return [Store]; } static calculateState(prevState: State, props: Props): State { return { counter: Store.getState() - (props.b ? 0 : 1) }; } render() { return <div> {this.state.counter} </div>; } } const ContainerComponent1 = Container.create(CounterContainer, { withProps: true }); <ContainerComponent1 a="string" b={false} />; const ContainerComponent2 = Container.create<Props>(CounterContainer, { withProps: true }); <ContainerComponent2 a="string" b={false} />; const ContainerComponent3 = Container.create<Props, State>(CounterContainer, { withProps: true }); <ContainerComponent3 a="string" b={false} />; // Functional flux container with Store const FunctionalContainerComponent = Container.createFunctional( (props: State) => { return <div> {props.counter} </div>; }, (props: Props) => [Store], (prevState: State, props: Props) => ({ counter: Store.getState() }) ); <FunctionalContainerComponent a="string" b={false} />;
switch (action.type) { case 'increment': return state + 1;
random_line_split
FluxUtils.tsx
import { Dispatcher } from "flux"; import { ReduceStore, Container } from "flux/utils"; import * as React from "react"; interface Payload { type: string; } const basicDispatcher = new Dispatcher<Payload>(); // Sample Reduce Store class CounterStore extends ReduceStore<number, any> { getInitialState(): number { return 0; } reduce(state: number, action: Payload): number
} const Store = new CounterStore(basicDispatcher); // Sample Flux container with Store interface Props { a: string; b: boolean; } interface State { counter: number; } class CounterContainer extends React.Component<Props, State> { static getStores(): Container.StoresList { return [Store]; } static calculateState(prevState: State, props: Props): State { return { counter: Store.getState() - (props.b ? 0 : 1) }; } render() { return <div> {this.state.counter} </div>; } } const ContainerComponent1 = Container.create(CounterContainer, { withProps: true }); <ContainerComponent1 a="string" b={false} />; const ContainerComponent2 = Container.create<Props>(CounterContainer, { withProps: true }); <ContainerComponent2 a="string" b={false} />; const ContainerComponent3 = Container.create<Props, State>(CounterContainer, { withProps: true }); <ContainerComponent3 a="string" b={false} />; // Functional flux container with Store const FunctionalContainerComponent = Container.createFunctional( (props: State) => { return <div> {props.counter} </div>; }, (props: Props) => [Store], (prevState: State, props: Props) => ({ counter: Store.getState() }) ); <FunctionalContainerComponent a="string" b={false} />;
{ switch (action.type) { case 'increment': return state + 1; case 'square': return state * state; default: return state; } }
identifier_body
lib.rs
//! A Rust crate to connect a HD44780 lcd display //! //! # Example //! ```no_run //! use pi_lcd::*; //! //! // create a new lcd //! let lcd = HD44780::new(11,10,[6,5,4,1],20,4); //! //! // send a String to the lcd at row 0 //! lcd.send_string("Hello World".to_string(),0); //! ``` extern crate cupi; extern crate regex; use cupi::{CuPi, PinOutput, DigitalWrite}; use std::time::Duration; use std::cell::RefCell; use regex::Regex; static CGRAM_ADDRESS: u8 = 0x40; static COMMAND: bool = false; static DATA: bool = true; /// The display handle pub struct HD44780 { rs: RefCell<PinOutput>, e: RefCell<PinOutput>, data: Vec<RefCell<PinOutput>>, cols: u32, rows: u32, lines: Vec<u8>, } impl HD44780 { /// Creates a new HD44780 instance with `disp_rs` as rs pin, `disp_e` as enabled pin, `datalines` as data4 to data7 /// /// `disp_cols` are the number of columns /// `disp_rows` are the number of rows pub fn new(disp_rs: u32, disp_e: u32, datalines: [u32; 4], disp_cols: u32, disp_rows: u32) -> HD44780 { let raspi = CuPi::new().unwrap(); let rs = RefCell::new(raspi.pin(disp_rs as usize).unwrap().output()); let e = RefCell::new(raspi.pin(disp_e as usize).unwrap().output()); let mut data: Vec<RefCell<PinOutput>> = Vec::new(); for x in 0..4 { data.push(RefCell::new(raspi.pin(datalines[x] as usize).unwrap().output())); } let lines: Vec<u8>; match disp_rows { 1 => lines = vec![0x80], 2 => lines = vec![0x80, 0xC0], 3 => lines = vec![0x80, 0xC0, 0x94], 4 => lines = vec![0x80, 0xC0, 0x94, 0xD4], _ => lines = vec![0x80], }; let result = HD44780 { rs: rs, e: e, data: data, cols: disp_cols, rows: disp_rows, lines: lines, }; result } /// Initializes the display and clears it pub fn init(&self) { self.command(0x33); self.command(0x32); self.command(0x28); self.command(0x0C); self.command(0x06); self.clear(); } /// Clears the display pub fn clear(&self) { self.command(0x01); } /// Sends a given byte as a command pub fn command(&self, bits: u8) { self.send_byte(bits, COMMAND); } /// Parses a String and and outputs it to the given row pub fn send_string(&self, text: String, row: u32) { let re_char: Regex = Regex::new(r"^\\cg:([0-7])").unwrap(); let mut message: Vec<u8> = Vec::new(); let col = self.cols; let row = row % self.rows; // TODO: implement check for custom characters for i in text.chars() { message.push(i as u8); } message.truncate(col as usize); self.select_row(row); self.write(message); } /// Creates a new custom character from a bitmap on the given `address` pub fn create_char(&self, address: u8, bitmap: [u8; 8]) -> Result<u8, &'static str> { // send new custom character to cgram address match address { 0...7 => { self.command(CGRAM_ADDRESS | address << 3); for row in &bitmap { self.send_byte(bitmap[*row as usize], DATA); } Ok(address) }, _ => Err("address must be between 0 and 7"), } } fn select_row(&self, row: u32) { // select the row where the String should be printed at self.send_byte(self.lines[row as usize], COMMAND); } fn write(&self, charlist: Vec<u8>) { // send every single char to send_byte for x in charlist { self.send_byte(x, DATA); } } fn send_byte(&self, bits: u8, mode: bool) { if mode { self.rs.borrow_mut().high().unwrap(); } else { self.rs.borrow_mut().low().unwrap(); } self.data[0].borrow_mut().low().unwrap(); self.data[1].borrow_mut().low().unwrap(); self.data[2].borrow_mut().low().unwrap(); self.data[3].borrow_mut().low().unwrap(); if bits & 0x10 == 0x10 { self.data[0].borrow_mut().high().unwrap(); } if bits & 0x20 == 0x20 { self.data[1].borrow_mut().high().unwrap(); } if bits & 0x40 == 0x40 { self.data[2].borrow_mut().high().unwrap(); } if bits & 0x80 == 0x80 { self.data[3].borrow_mut().high().unwrap(); } e_wait(); self.e.borrow_mut().high().unwrap(); e_wait(); self.e.borrow_mut().low().unwrap(); self.data[0].borrow_mut().low().unwrap(); self.data[1].borrow_mut().low().unwrap(); self.data[2].borrow_mut().low().unwrap(); self.data[3].borrow_mut().low().unwrap(); if bits & 0x01 == 0x01 { self.data[0].borrow_mut().high().unwrap(); } if bits & 0x02 == 0x02 { self.data[1].borrow_mut().high().unwrap();
} if bits & 0x04 == 0x04 { self.data[2].borrow_mut().high().unwrap(); } if bits & 0x08 == 0x08 { self.data[3].borrow_mut().high().unwrap(); } e_wait(); self.e.borrow_mut().high().unwrap(); e_wait(); self.e.borrow_mut().low().unwrap(); } } /// Waits 50 ns to let the display recognize the enabled pin pub fn e_wait() { std::thread::sleep(Duration::new(0, 50)); }
random_line_split
lib.rs
//! A Rust crate to connect a HD44780 lcd display //! //! # Example //! ```no_run //! use pi_lcd::*; //! //! // create a new lcd //! let lcd = HD44780::new(11,10,[6,5,4,1],20,4); //! //! // send a String to the lcd at row 0 //! lcd.send_string("Hello World".to_string(),0); //! ``` extern crate cupi; extern crate regex; use cupi::{CuPi, PinOutput, DigitalWrite}; use std::time::Duration; use std::cell::RefCell; use regex::Regex; static CGRAM_ADDRESS: u8 = 0x40; static COMMAND: bool = false; static DATA: bool = true; /// The display handle pub struct HD44780 { rs: RefCell<PinOutput>, e: RefCell<PinOutput>, data: Vec<RefCell<PinOutput>>, cols: u32, rows: u32, lines: Vec<u8>, } impl HD44780 { /// Creates a new HD44780 instance with `disp_rs` as rs pin, `disp_e` as enabled pin, `datalines` as data4 to data7 /// /// `disp_cols` are the number of columns /// `disp_rows` are the number of rows pub fn new(disp_rs: u32, disp_e: u32, datalines: [u32; 4], disp_cols: u32, disp_rows: u32) -> HD44780 { let raspi = CuPi::new().unwrap(); let rs = RefCell::new(raspi.pin(disp_rs as usize).unwrap().output()); let e = RefCell::new(raspi.pin(disp_e as usize).unwrap().output()); let mut data: Vec<RefCell<PinOutput>> = Vec::new(); for x in 0..4 { data.push(RefCell::new(raspi.pin(datalines[x] as usize).unwrap().output())); } let lines: Vec<u8>; match disp_rows { 1 => lines = vec![0x80], 2 => lines = vec![0x80, 0xC0], 3 => lines = vec![0x80, 0xC0, 0x94], 4 => lines = vec![0x80, 0xC0, 0x94, 0xD4], _ => lines = vec![0x80], }; let result = HD44780 { rs: rs, e: e, data: data, cols: disp_cols, rows: disp_rows, lines: lines, }; result } /// Initializes the display and clears it pub fn init(&self) { self.command(0x33); self.command(0x32); self.command(0x28); self.command(0x0C); self.command(0x06); self.clear(); } /// Clears the display pub fn clear(&self) { self.command(0x01); } /// Sends a given byte as a command pub fn command(&self, bits: u8) { self.send_byte(bits, COMMAND); } /// Parses a String and and outputs it to the given row pub fn send_string(&self, text: String, row: u32) { let re_char: Regex = Regex::new(r"^\\cg:([0-7])").unwrap(); let mut message: Vec<u8> = Vec::new(); let col = self.cols; let row = row % self.rows; // TODO: implement check for custom characters for i in text.chars() { message.push(i as u8); } message.truncate(col as usize); self.select_row(row); self.write(message); } /// Creates a new custom character from a bitmap on the given `address` pub fn create_char(&self, address: u8, bitmap: [u8; 8]) -> Result<u8, &'static str> { // send new custom character to cgram address match address { 0...7 => { self.command(CGRAM_ADDRESS | address << 3); for row in &bitmap { self.send_byte(bitmap[*row as usize], DATA); } Ok(address) }, _ => Err("address must be between 0 and 7"), } } fn select_row(&self, row: u32) { // select the row where the String should be printed at self.send_byte(self.lines[row as usize], COMMAND); } fn write(&self, charlist: Vec<u8>) { // send every single char to send_byte for x in charlist { self.send_byte(x, DATA); } } fn send_byte(&self, bits: u8, mode: bool) { if mode { self.rs.borrow_mut().high().unwrap(); } else { self.rs.borrow_mut().low().unwrap(); } self.data[0].borrow_mut().low().unwrap(); self.data[1].borrow_mut().low().unwrap(); self.data[2].borrow_mut().low().unwrap(); self.data[3].borrow_mut().low().unwrap(); if bits & 0x10 == 0x10 { self.data[0].borrow_mut().high().unwrap(); } if bits & 0x20 == 0x20 { self.data[1].borrow_mut().high().unwrap(); } if bits & 0x40 == 0x40 { self.data[2].borrow_mut().high().unwrap(); } if bits & 0x80 == 0x80 { self.data[3].borrow_mut().high().unwrap(); } e_wait(); self.e.borrow_mut().high().unwrap(); e_wait(); self.e.borrow_mut().low().unwrap(); self.data[0].borrow_mut().low().unwrap(); self.data[1].borrow_mut().low().unwrap(); self.data[2].borrow_mut().low().unwrap(); self.data[3].borrow_mut().low().unwrap(); if bits & 0x01 == 0x01 { self.data[0].borrow_mut().high().unwrap(); } if bits & 0x02 == 0x02 { self.data[1].borrow_mut().high().unwrap(); } if bits & 0x04 == 0x04 { self.data[2].borrow_mut().high().unwrap(); } if bits & 0x08 == 0x08 { self.data[3].borrow_mut().high().unwrap(); } e_wait(); self.e.borrow_mut().high().unwrap(); e_wait(); self.e.borrow_mut().low().unwrap(); } } /// Waits 50 ns to let the display recognize the enabled pin pub fn
() { std::thread::sleep(Duration::new(0, 50)); }
e_wait
identifier_name
lib.rs
//! A Rust crate to connect a HD44780 lcd display //! //! # Example //! ```no_run //! use pi_lcd::*; //! //! // create a new lcd //! let lcd = HD44780::new(11,10,[6,5,4,1],20,4); //! //! // send a String to the lcd at row 0 //! lcd.send_string("Hello World".to_string(),0); //! ``` extern crate cupi; extern crate regex; use cupi::{CuPi, PinOutput, DigitalWrite}; use std::time::Duration; use std::cell::RefCell; use regex::Regex; static CGRAM_ADDRESS: u8 = 0x40; static COMMAND: bool = false; static DATA: bool = true; /// The display handle pub struct HD44780 { rs: RefCell<PinOutput>, e: RefCell<PinOutput>, data: Vec<RefCell<PinOutput>>, cols: u32, rows: u32, lines: Vec<u8>, } impl HD44780 { /// Creates a new HD44780 instance with `disp_rs` as rs pin, `disp_e` as enabled pin, `datalines` as data4 to data7 /// /// `disp_cols` are the number of columns /// `disp_rows` are the number of rows pub fn new(disp_rs: u32, disp_e: u32, datalines: [u32; 4], disp_cols: u32, disp_rows: u32) -> HD44780 { let raspi = CuPi::new().unwrap(); let rs = RefCell::new(raspi.pin(disp_rs as usize).unwrap().output()); let e = RefCell::new(raspi.pin(disp_e as usize).unwrap().output()); let mut data: Vec<RefCell<PinOutput>> = Vec::new(); for x in 0..4 { data.push(RefCell::new(raspi.pin(datalines[x] as usize).unwrap().output())); } let lines: Vec<u8>; match disp_rows { 1 => lines = vec![0x80], 2 => lines = vec![0x80, 0xC0], 3 => lines = vec![0x80, 0xC0, 0x94], 4 => lines = vec![0x80, 0xC0, 0x94, 0xD4], _ => lines = vec![0x80], }; let result = HD44780 { rs: rs, e: e, data: data, cols: disp_cols, rows: disp_rows, lines: lines, }; result } /// Initializes the display and clears it pub fn init(&self) { self.command(0x33); self.command(0x32); self.command(0x28); self.command(0x0C); self.command(0x06); self.clear(); } /// Clears the display pub fn clear(&self) { self.command(0x01); } /// Sends a given byte as a command pub fn command(&self, bits: u8) { self.send_byte(bits, COMMAND); } /// Parses a String and and outputs it to the given row pub fn send_string(&self, text: String, row: u32) { let re_char: Regex = Regex::new(r"^\\cg:([0-7])").unwrap(); let mut message: Vec<u8> = Vec::new(); let col = self.cols; let row = row % self.rows; // TODO: implement check for custom characters for i in text.chars() { message.push(i as u8); } message.truncate(col as usize); self.select_row(row); self.write(message); } /// Creates a new custom character from a bitmap on the given `address` pub fn create_char(&self, address: u8, bitmap: [u8; 8]) -> Result<u8, &'static str>
fn select_row(&self, row: u32) { // select the row where the String should be printed at self.send_byte(self.lines[row as usize], COMMAND); } fn write(&self, charlist: Vec<u8>) { // send every single char to send_byte for x in charlist { self.send_byte(x, DATA); } } fn send_byte(&self, bits: u8, mode: bool) { if mode { self.rs.borrow_mut().high().unwrap(); } else { self.rs.borrow_mut().low().unwrap(); } self.data[0].borrow_mut().low().unwrap(); self.data[1].borrow_mut().low().unwrap(); self.data[2].borrow_mut().low().unwrap(); self.data[3].borrow_mut().low().unwrap(); if bits & 0x10 == 0x10 { self.data[0].borrow_mut().high().unwrap(); } if bits & 0x20 == 0x20 { self.data[1].borrow_mut().high().unwrap(); } if bits & 0x40 == 0x40 { self.data[2].borrow_mut().high().unwrap(); } if bits & 0x80 == 0x80 { self.data[3].borrow_mut().high().unwrap(); } e_wait(); self.e.borrow_mut().high().unwrap(); e_wait(); self.e.borrow_mut().low().unwrap(); self.data[0].borrow_mut().low().unwrap(); self.data[1].borrow_mut().low().unwrap(); self.data[2].borrow_mut().low().unwrap(); self.data[3].borrow_mut().low().unwrap(); if bits & 0x01 == 0x01 { self.data[0].borrow_mut().high().unwrap(); } if bits & 0x02 == 0x02 { self.data[1].borrow_mut().high().unwrap(); } if bits & 0x04 == 0x04 { self.data[2].borrow_mut().high().unwrap(); } if bits & 0x08 == 0x08 { self.data[3].borrow_mut().high().unwrap(); } e_wait(); self.e.borrow_mut().high().unwrap(); e_wait(); self.e.borrow_mut().low().unwrap(); } } /// Waits 50 ns to let the display recognize the enabled pin pub fn e_wait() { std::thread::sleep(Duration::new(0, 50)); }
{ // send new custom character to cgram address match address { 0...7 => { self.command(CGRAM_ADDRESS | address << 3); for row in &bitmap { self.send_byte(bitmap[*row as usize], DATA); } Ok(address) }, _ => Err("address must be between 0 and 7"), } }
identifier_body
constellation_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling between these two components. use compositor_msg::Epoch; use canvas_traits::CanvasMsg; use euclid::rect::Rect; use euclid::size::{Size2D, TypedSize2D}; use euclid::scale_factor::ScaleFactor; use hyper::header::Headers; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use layers::geometry::DevicePixel; use offscreen_gl_context::GLContextAttributes; use png::Image; use util::cursor::Cursor; use util::geometry::{PagePx, ViewportPx}; use std::collections::HashMap; use std::sync::mpsc::{channel, Sender, Receiver}; use style::viewport::ViewportConstraints; use url::Url; use webdriver_msg::{WebDriverScriptCommand, LoadStatus}; #[derive(Clone)] pub struct ConstellationChan(pub Sender<Msg>); impl ConstellationChan { pub fn new() -> (Receiver<Msg>, ConstellationChan) { let (chan, port) = channel(); (port, ConstellationChan(chan)) } } #[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)] pub enum IFrameSandboxState { IFrameSandboxed, IFrameUnsandboxed } // We pass this info to various tasks, so it lives in a separate, cloneable struct. #[derive(Clone, Copy, Deserialize, Serialize)] pub struct Failure { pub pipeline_id: PipelineId, pub parent_info: Option<(PipelineId, SubpageId)>, } #[derive(Copy, Clone, Deserialize, Serialize)] pub struct WindowSizeData { /// The size of the initial layout viewport, before parsing an /// http://www.w3.org/TR/css-device-adapt/#initial-viewport pub initial_viewport: TypedSize2D<ViewportPx, f32>, /// The "viewing area" in page px. See `PagePx` documentation for details. pub visible_viewport: TypedSize2D<PagePx, f32>, /// The resolution of the window in dppx, not including any "pinch zoom" factor. pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>, } #[derive(PartialEq, Eq, Copy, Clone, Deserialize, Serialize)] pub enum KeyState { Pressed, Released, Repeated, } //N.B. Based on the glutin key enum #[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize)] pub enum Key { Space, Apostrophe, Comma, Minus, Period, Slash, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Semicolon, Equal, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, LeftBracket, Backslash, RightBracket, GraveAccent, World1, World2, Escape, Enter, Tab, Backspace, Insert, Delete, Right, Left, Down, Up, PageUp, PageDown, Home, End, CapsLock, ScrollLock, NumLock, PrintScreen, Pause, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, F25, Kp0, Kp1, Kp2, Kp3, Kp4, Kp5, Kp6, Kp7, Kp8, Kp9, KpDecimal, KpDivide, KpMultiply, KpSubtract, KpAdd, KpEnter, KpEqual, LeftShift, LeftControl, LeftAlt, LeftSuper, RightShift, RightControl, RightAlt, RightSuper, Menu, } bitflags! { #[derive(Deserialize, Serialize)] flags KeyModifiers: u8 { const NONE = 0x00, const SHIFT = 0x01, const CONTROL = 0x02, const ALT = 0x04, const SUPER = 0x08, } } /// Specifies the type of focus event that is sent to a pipeline #[derive(Copy, Clone, PartialEq)] pub enum FocusType { Element, // The first focus message - focus the element itself Parent, // Focusing a parent element (an iframe) } /// Messages from the compositor and script to the constellation. #[derive(Deserialize, Serialize)] pub enum Msg { Exit, Failure(Failure), InitLoadUrl(Url), LoadComplete(PipelineId), FrameRect(PipelineId, SubpageId, Rect<f32>), LoadUrl(PipelineId, LoadData), ScriptLoadedURLInIFrame(Url, PipelineId, SubpageId, Option<SubpageId>, IFrameSandboxState), Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection), PainterReady(PipelineId), ResizedWindow(WindowSizeData), KeyEvent(Key, KeyState, KeyModifiers), /// Requests that the constellation inform the compositor of the title of the pipeline /// immediately. GetPipelineTitle(PipelineId), /// Requests that the constellation inform the compositor of the a cursor change. SetCursor(Cursor), /// Dispatch a mozbrowser event to a given iframe. Only available in experimental mode. MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent), /// Indicates whether this pipeline is currently running animations. ChangeRunningAnimationsState(PipelineId, AnimationState), /// Requests that the constellation instruct layout to begin a new tick of the animation. TickAnimation(PipelineId), /// Request that the constellation send the current pipeline id for the provided frame /// id, or for the root frame if this is None, over a provided channel GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>), /// Request that the constellation send the FrameId corresponding to the document /// with the provided parent pipeline id and subpage id GetFrame(PipelineId, SubpageId, IpcSender<Option<FrameId>>), /// Notifies the constellation that this frame has received focus. Focus(PipelineId), /// Requests that the constellation retrieve the current contents of the clipboard GetClipboardContents(IpcSender<String>), /// Requests that the constellation set the contents of the clipboard SetClipboardContents(String), /// Dispatch a webdriver command WebDriverCommand(WebDriverCommandMsg), /// Notifies the constellation that the viewport has been constrained in some manner ViewportConstrained(PipelineId, ViewportConstraints), /// Query the constellation to see if the current compositor output is stable IsReadyToSaveImage(HashMap<PipelineId, Epoch>), /// Notification that this iframe should be removed. RemoveIFrame(PipelineId, SubpageId), /// Favicon detected NewFavicon(Url), /// <head> tag finished parsing HeadParsed, /// Requests that a new 2D canvas thread be created. (This is done in the constellation because /// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.) CreateCanvasPaintTask(Size2D<i32>, IpcSender<(IpcSender<CanvasMsg>, usize)>), /// Requests that a new WebGL thread be created. (This is done in the constellation because /// WebGL uses the GPU and we don't want to give untrusted content access to the GPU.) CreateWebGLPaintTask(Size2D<i32>, GLContextAttributes, IpcSender<Result<(IpcSender<CanvasMsg>, usize), String>>), } #[derive(Clone, Eq, PartialEq, Deserialize, Serialize)] pub enum AnimationState { AnimationsPresent, AnimationCallbacksPresent, NoAnimationsPresent, NoAnimationCallbacksPresent, } // https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events #[derive(Deserialize, Serialize)] pub enum MozBrowserEvent { /// Sent when the scroll position within a browser <iframe> changes. AsyncScroll, /// Sent when window.close() is called within a browser <iframe>. Close, /// Sent when a browser <iframe> tries to open a context menu. This allows /// handling <menuitem> element available within the browser <iframe>'s content. ContextMenu, /// Sent when an error occurred while trying to load content within a browser <iframe>. Error, /// Sent when the favicon of a browser <iframe> changes. IconChange, /// Sent when the browser <iframe> has finished loading all its assets. LoadEnd, /// Sent when the browser <iframe> starts to load a new page. LoadStart, /// Sent when a browser <iframe>'s location changes. LocationChange(String), /// Sent when window.open() is called within a browser <iframe>. OpenWindow, /// Sent when the SSL state changes within a browser <iframe>. SecurityChange, /// Sent when alert(), confirm(), or prompt() is called within a browser <iframe>. ShowModalPrompt, /// Sent when the document.title changes within a browser <iframe>. TitleChange(String), /// Sent when an HTTP authentification is requested. UsernameAndPasswordRequired, /// Sent when a link to a search engine is found. OpenSearch, } impl MozBrowserEvent { pub fn name(&self) -> &'static str { match *self { MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll", MozBrowserEvent::Close => "mozbrowserclose", MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu", MozBrowserEvent::Error => "mozbrowsererror", MozBrowserEvent::IconChange => "mozbrowsericonchange", MozBrowserEvent::LoadEnd => "mozbrowserloadend", MozBrowserEvent::LoadStart => "mozbrowserloadstart", MozBrowserEvent::LocationChange(_) => "mozbrowserlocationchange", MozBrowserEvent::OpenWindow => "mozbrowseropenwindow", MozBrowserEvent::SecurityChange => "mozbrowsersecuritychange", MozBrowserEvent::ShowModalPrompt => "mozbrowsershowmodalprompt", MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange", MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired", MozBrowserEvent::OpenSearch => "mozbrowseropensearch" } } pub fn
(&self) -> Option<String> { match *self { MozBrowserEvent::AsyncScroll | MozBrowserEvent::Close | MozBrowserEvent::ContextMenu | MozBrowserEvent::Error | MozBrowserEvent::IconChange | MozBrowserEvent::LoadEnd | MozBrowserEvent::LoadStart | MozBrowserEvent::OpenWindow | MozBrowserEvent::SecurityChange | MozBrowserEvent::ShowModalPrompt | MozBrowserEvent::UsernameAndPasswordRequired | MozBrowserEvent::OpenSearch => None, MozBrowserEvent::LocationChange(ref new_location) => Some(new_location.clone()), MozBrowserEvent::TitleChange(ref new_title) => Some(new_title.clone()), } } } #[derive(Deserialize, Serialize)] pub enum WebDriverCommandMsg { LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>), Refresh(PipelineId, IpcSender<LoadStatus>), ScriptCommand(PipelineId, WebDriverScriptCommand), TakeScreenshot(PipelineId, IpcSender<Option<Image>>) } /// Similar to net::resource_task::LoadData /// can be passed to LoadUrl to load a page with GET/POST /// parameters or headers #[derive(Clone, Deserialize, Serialize)] pub struct LoadData { pub url: Url, pub method: Method, pub headers: Headers, pub data: Option<Vec<u8>>, } impl LoadData { pub fn new(url: Url) -> LoadData { LoadData { url: url, method: Method::Get, headers: Headers::new(), data: None, } } } #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub enum NavigationDirection { Forward, Back, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct FrameId(pub u32); #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct WorkerId(pub u32); #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct PipelineId(pub u32); #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct SubpageId(pub u32); // The type of pipeline exit. During complete shutdowns, pipelines do not have to // release resources automatically released on process termination. #[derive(Copy, Clone, Debug, Deserialize, Serialize)] pub enum PipelineExitType { PipelineOnly, Complete, }
detail
identifier_name
constellation_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling between these two components. use compositor_msg::Epoch; use canvas_traits::CanvasMsg; use euclid::rect::Rect; use euclid::size::{Size2D, TypedSize2D}; use euclid::scale_factor::ScaleFactor; use hyper::header::Headers; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use layers::geometry::DevicePixel; use offscreen_gl_context::GLContextAttributes; use png::Image; use util::cursor::Cursor; use util::geometry::{PagePx, ViewportPx}; use std::collections::HashMap; use std::sync::mpsc::{channel, Sender, Receiver}; use style::viewport::ViewportConstraints; use url::Url; use webdriver_msg::{WebDriverScriptCommand, LoadStatus}; #[derive(Clone)] pub struct ConstellationChan(pub Sender<Msg>); impl ConstellationChan { pub fn new() -> (Receiver<Msg>, ConstellationChan) { let (chan, port) = channel(); (port, ConstellationChan(chan)) } } #[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)] pub enum IFrameSandboxState { IFrameSandboxed, IFrameUnsandboxed } // We pass this info to various tasks, so it lives in a separate, cloneable struct. #[derive(Clone, Copy, Deserialize, Serialize)] pub struct Failure { pub pipeline_id: PipelineId, pub parent_info: Option<(PipelineId, SubpageId)>, } #[derive(Copy, Clone, Deserialize, Serialize)] pub struct WindowSizeData { /// The size of the initial layout viewport, before parsing an /// http://www.w3.org/TR/css-device-adapt/#initial-viewport pub initial_viewport: TypedSize2D<ViewportPx, f32>, /// The "viewing area" in page px. See `PagePx` documentation for details. pub visible_viewport: TypedSize2D<PagePx, f32>, /// The resolution of the window in dppx, not including any "pinch zoom" factor. pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>, } #[derive(PartialEq, Eq, Copy, Clone, Deserialize, Serialize)] pub enum KeyState { Pressed, Released, Repeated, } //N.B. Based on the glutin key enum #[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize)] pub enum Key { Space, Apostrophe, Comma, Minus, Period, Slash, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Semicolon, Equal, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, LeftBracket, Backslash, RightBracket, GraveAccent, World1, World2, Escape, Enter, Tab, Backspace, Insert, Delete, Right, Left, Down, Up, PageUp, PageDown, Home, End, CapsLock, ScrollLock, NumLock, PrintScreen, Pause, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, F25, Kp0, Kp1, Kp2, Kp3, Kp4, Kp5, Kp6, Kp7, Kp8, Kp9, KpDecimal, KpDivide, KpMultiply, KpSubtract, KpAdd, KpEnter, KpEqual, LeftShift, LeftControl, LeftAlt, LeftSuper, RightShift, RightControl, RightAlt, RightSuper, Menu, } bitflags! { #[derive(Deserialize, Serialize)] flags KeyModifiers: u8 { const NONE = 0x00, const SHIFT = 0x01, const CONTROL = 0x02, const ALT = 0x04, const SUPER = 0x08, } } /// Specifies the type of focus event that is sent to a pipeline #[derive(Copy, Clone, PartialEq)] pub enum FocusType { Element, // The first focus message - focus the element itself Parent, // Focusing a parent element (an iframe) } /// Messages from the compositor and script to the constellation. #[derive(Deserialize, Serialize)] pub enum Msg { Exit, Failure(Failure), InitLoadUrl(Url), LoadComplete(PipelineId), FrameRect(PipelineId, SubpageId, Rect<f32>), LoadUrl(PipelineId, LoadData), ScriptLoadedURLInIFrame(Url, PipelineId, SubpageId, Option<SubpageId>, IFrameSandboxState), Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection), PainterReady(PipelineId), ResizedWindow(WindowSizeData), KeyEvent(Key, KeyState, KeyModifiers), /// Requests that the constellation inform the compositor of the title of the pipeline /// immediately. GetPipelineTitle(PipelineId), /// Requests that the constellation inform the compositor of the a cursor change. SetCursor(Cursor), /// Dispatch a mozbrowser event to a given iframe. Only available in experimental mode. MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent), /// Indicates whether this pipeline is currently running animations. ChangeRunningAnimationsState(PipelineId, AnimationState), /// Requests that the constellation instruct layout to begin a new tick of the animation. TickAnimation(PipelineId), /// Request that the constellation send the current pipeline id for the provided frame /// id, or for the root frame if this is None, over a provided channel GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>), /// Request that the constellation send the FrameId corresponding to the document
/// Requests that the constellation retrieve the current contents of the clipboard GetClipboardContents(IpcSender<String>), /// Requests that the constellation set the contents of the clipboard SetClipboardContents(String), /// Dispatch a webdriver command WebDriverCommand(WebDriverCommandMsg), /// Notifies the constellation that the viewport has been constrained in some manner ViewportConstrained(PipelineId, ViewportConstraints), /// Query the constellation to see if the current compositor output is stable IsReadyToSaveImage(HashMap<PipelineId, Epoch>), /// Notification that this iframe should be removed. RemoveIFrame(PipelineId, SubpageId), /// Favicon detected NewFavicon(Url), /// <head> tag finished parsing HeadParsed, /// Requests that a new 2D canvas thread be created. (This is done in the constellation because /// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.) CreateCanvasPaintTask(Size2D<i32>, IpcSender<(IpcSender<CanvasMsg>, usize)>), /// Requests that a new WebGL thread be created. (This is done in the constellation because /// WebGL uses the GPU and we don't want to give untrusted content access to the GPU.) CreateWebGLPaintTask(Size2D<i32>, GLContextAttributes, IpcSender<Result<(IpcSender<CanvasMsg>, usize), String>>), } #[derive(Clone, Eq, PartialEq, Deserialize, Serialize)] pub enum AnimationState { AnimationsPresent, AnimationCallbacksPresent, NoAnimationsPresent, NoAnimationCallbacksPresent, } // https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events #[derive(Deserialize, Serialize)] pub enum MozBrowserEvent { /// Sent when the scroll position within a browser <iframe> changes. AsyncScroll, /// Sent when window.close() is called within a browser <iframe>. Close, /// Sent when a browser <iframe> tries to open a context menu. This allows /// handling <menuitem> element available within the browser <iframe>'s content. ContextMenu, /// Sent when an error occurred while trying to load content within a browser <iframe>. Error, /// Sent when the favicon of a browser <iframe> changes. IconChange, /// Sent when the browser <iframe> has finished loading all its assets. LoadEnd, /// Sent when the browser <iframe> starts to load a new page. LoadStart, /// Sent when a browser <iframe>'s location changes. LocationChange(String), /// Sent when window.open() is called within a browser <iframe>. OpenWindow, /// Sent when the SSL state changes within a browser <iframe>. SecurityChange, /// Sent when alert(), confirm(), or prompt() is called within a browser <iframe>. ShowModalPrompt, /// Sent when the document.title changes within a browser <iframe>. TitleChange(String), /// Sent when an HTTP authentification is requested. UsernameAndPasswordRequired, /// Sent when a link to a search engine is found. OpenSearch, } impl MozBrowserEvent { pub fn name(&self) -> &'static str { match *self { MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll", MozBrowserEvent::Close => "mozbrowserclose", MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu", MozBrowserEvent::Error => "mozbrowsererror", MozBrowserEvent::IconChange => "mozbrowsericonchange", MozBrowserEvent::LoadEnd => "mozbrowserloadend", MozBrowserEvent::LoadStart => "mozbrowserloadstart", MozBrowserEvent::LocationChange(_) => "mozbrowserlocationchange", MozBrowserEvent::OpenWindow => "mozbrowseropenwindow", MozBrowserEvent::SecurityChange => "mozbrowsersecuritychange", MozBrowserEvent::ShowModalPrompt => "mozbrowsershowmodalprompt", MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange", MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired", MozBrowserEvent::OpenSearch => "mozbrowseropensearch" } } pub fn detail(&self) -> Option<String> { match *self { MozBrowserEvent::AsyncScroll | MozBrowserEvent::Close | MozBrowserEvent::ContextMenu | MozBrowserEvent::Error | MozBrowserEvent::IconChange | MozBrowserEvent::LoadEnd | MozBrowserEvent::LoadStart | MozBrowserEvent::OpenWindow | MozBrowserEvent::SecurityChange | MozBrowserEvent::ShowModalPrompt | MozBrowserEvent::UsernameAndPasswordRequired | MozBrowserEvent::OpenSearch => None, MozBrowserEvent::LocationChange(ref new_location) => Some(new_location.clone()), MozBrowserEvent::TitleChange(ref new_title) => Some(new_title.clone()), } } } #[derive(Deserialize, Serialize)] pub enum WebDriverCommandMsg { LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>), Refresh(PipelineId, IpcSender<LoadStatus>), ScriptCommand(PipelineId, WebDriverScriptCommand), TakeScreenshot(PipelineId, IpcSender<Option<Image>>) } /// Similar to net::resource_task::LoadData /// can be passed to LoadUrl to load a page with GET/POST /// parameters or headers #[derive(Clone, Deserialize, Serialize)] pub struct LoadData { pub url: Url, pub method: Method, pub headers: Headers, pub data: Option<Vec<u8>>, } impl LoadData { pub fn new(url: Url) -> LoadData { LoadData { url: url, method: Method::Get, headers: Headers::new(), data: None, } } } #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub enum NavigationDirection { Forward, Back, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct FrameId(pub u32); #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct WorkerId(pub u32); #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct PipelineId(pub u32); #[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)] pub struct SubpageId(pub u32); // The type of pipeline exit. During complete shutdowns, pipelines do not have to // release resources automatically released on process termination. #[derive(Copy, Clone, Debug, Deserialize, Serialize)] pub enum PipelineExitType { PipelineOnly, Complete, }
/// with the provided parent pipeline id and subpage id GetFrame(PipelineId, SubpageId, IpcSender<Option<FrameId>>), /// Notifies the constellation that this frame has received focus. Focus(PipelineId),
random_line_split
copyProperties.js
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule copyProperties */ 'use strict'; /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function copyProperties(obj, a, b, c, d, e, f) { obj = obj || {}; if (process.env.NODE_ENV !== 'production') { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++]; for (var k in v) { obj[k] = v[k]; } // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString !== 'undefined') && (obj.toString !== v.toString))
} return obj; } module.exports = copyProperties;
{ obj.toString = v.toString; }
conditional_block
copyProperties.js
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule copyProperties */ 'use strict'; /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function copyProperties(obj, a, b, c, d, e, f) { obj = obj || {}; if (process.env.NODE_ENV !== 'production') { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++];
} // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString !== 'undefined') && (obj.toString !== v.toString)) { obj.toString = v.toString; } } return obj; } module.exports = copyProperties;
for (var k in v) { obj[k] = v[k];
random_line_split
copyProperties.js
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule copyProperties */ 'use strict'; /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function copyProperties(obj, a, b, c, d, e, f)
module.exports = copyProperties;
{ obj = obj || {}; if (process.env.NODE_ENV !== 'production') { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++]; for (var k in v) { obj[k] = v[k]; } // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString !== 'undefined') && (obj.toString !== v.toString)) { obj.toString = v.toString; } } return obj; }
identifier_body
copyProperties.js
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule copyProperties */ 'use strict'; /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function
(obj, a, b, c, d, e, f) { obj = obj || {}; if (process.env.NODE_ENV !== 'production') { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++]; for (var k in v) { obj[k] = v[k]; } // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString !== 'undefined') && (obj.toString !== v.toString)) { obj.toString = v.toString; } } return obj; } module.exports = copyProperties;
copyProperties
identifier_name
update-downloads.rs
#![deny(warnings)] #![feature(std_misc, core, os, io, env)] extern crate "cargo-registry" as cargo_registry; extern crate postgres; extern crate semver; extern crate time; extern crate env_logger; use std::env; use std::collections::HashMap; use std::time::Duration; use cargo_registry::{VersionDownload, Version, Model}; static LIMIT: i64 = 10000; #[allow(dead_code)] // dead in tests fn main() { env_logger::init().unwrap(); let daemon = env::args().nth(1).as_ref().map(|s| s.to_str().unwrap()) == Some("daemon"); let sleep = env::args().nth(2).map(|s| s.to_str().unwrap().parse::<i64>().unwrap()); loop { let conn = postgres::Connection::connect(env("DATABASE_URL").as_slice(), &postgres::SslMode::None).unwrap(); { let tx = conn.transaction().unwrap(); update(&tx).unwrap(); tx.set_commit(); tx.finish().unwrap(); } drop(conn); if daemon { std::old_io::timer::sleep(Duration::seconds(sleep.unwrap())); } else { break } } } fn env(s: &str) -> String { match env::var_string(s).ok() { Some(s) => s, None => panic!("must have `{}` defined", s), } } fn update(tx: &postgres::Transaction) -> postgres::Result<()> { let mut max = 0; loop { let tx = try!(tx.transaction()); { let stmt = try!(tx.prepare("SELECT * FROM version_downloads \ WHERE processed = FALSE AND id > $1 ORDER BY id ASC LIMIT $2")); let mut rows = try!(stmt.query(&[&max, &LIMIT])); match try!(collect(&tx, &mut rows)) { None => break, Some(m) => max = m, } } tx.set_commit(); try!(tx.finish()); } Ok(()) } fn collect(tx: &postgres::Transaction, rows: &mut postgres::Rows) -> postgres::Result<Option<i32>> { // Anything older than 24 hours ago will be frozen and will not be queried // against again. let cutoff = time::now_utc().to_timespec(); let cutoff = cutoff + Duration::days(-1); let mut map = HashMap::new(); for row in rows.by_ref() { let download: VersionDownload = Model::from_row(&row); assert!(map.insert(download.id, download).is_none()); } println!("updating {} versions", map.len()); if map.len() == 0 { return Ok(None) } let mut max = 0; let mut total = 0; for (id, download) in map.iter() { if *id > max { max = *id; } if download.counted == download.downloads { continue } let amt = download.downloads - download.counted; let crate_id = Version::find(tx, download.version_id).unwrap().crate_id; // Update the total number of version downloads try!(tx.execute("UPDATE versions SET downloads = downloads + $1 WHERE id = $2", &[&amt, &download.version_id])); // Update the total number of crate downloads try!(tx.execute("UPDATE crates SET downloads = downloads + $1 WHERE id = $2", &[&amt, &crate_id])); // Update the total number of crate downloads for today let cnt = try!(tx.execute("UPDATE crate_downloads SET downloads = downloads + $2 WHERE crate_id = $1 AND date = date($3)", &[&crate_id, &amt, &download.date])); if cnt == 0 { try!(tx.execute("INSERT INTO crate_downloads (crate_id, downloads, date) VALUES ($1, $2, $3)", &[&crate_id, &amt, &download.date])); } // Flag this row as having been processed if we're passed the cutoff, // and unconditionally increment the number of counted downloads. try!(tx.execute("UPDATE version_downloads SET processed = $2, counted = downloads WHERE id = $1", &[id, &(download.date < cutoff)])); total += amt as i64; } // After everything else is done, update the global counter of total // downloads. try!(tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1", &[&total])); Ok(Some(max)) } #[cfg(test)] mod test { use std::collections::HashMap; use postgres; use semver; use cargo_registry::{Version, Crate, User}; fn conn() -> postgres::Connection { postgres::Connection::connect(::env("TEST_DATABASE_URL").as_slice(), &postgres::SslMode::None).unwrap() } fn user(conn: &postgres::Transaction) -> User{ User::find_or_insert(conn, "login", None, None, None, "access_token", "api_token").unwrap() } fn crate_downloads(tx: &postgres::Transaction, id: i32, expected: usize) { let stmt = tx.prepare("SELECT * FROM crate_downloads WHERE crate_id = $1").unwrap(); let dl: i32 = stmt.query(&[&id]).unwrap() .next().unwrap().get("downloads"); assert_eq!(dl, expected as i32); } #[test] fn increment() { let conn = conn(); let tx = conn.transaction().unwrap(); let user = user(&tx); let krate = Crate::find_or_insert(&tx, "foo", user.id, &None, &None, &None, &None, &[], &None, &None, &None).unwrap(); let version = Version::insert(&tx, krate.id, &semver::Version::parse("1.0.0").unwrap(), &HashMap::new(), &[]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, false)", &[&version.id]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, true)", &[&version.id]).unwrap(); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 1); assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 1); crate_downloads(&tx, krate.id, 1); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 1); } #[test] fn increment_a_little() { let conn = conn(); let tx = conn.transaction().unwrap(); let user = user(&tx); let krate = Crate::find_or_insert(&tx, "foo", user.id, &None, &None, &None, &None, &[], &None, &None, &None).unwrap(); let version = Version::insert(&tx, krate.id, &semver::Version::parse("1.0.0").unwrap(), &HashMap::new(), &[]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 2, 1, current_date, false)", &[&version.id]).unwrap();
tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, false)", &[&version.id]).unwrap(); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2); assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 2); crate_downloads(&tx, krate.id, 2); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2); } }
random_line_split
update-downloads.rs
#![deny(warnings)] #![feature(std_misc, core, os, io, env)] extern crate "cargo-registry" as cargo_registry; extern crate postgres; extern crate semver; extern crate time; extern crate env_logger; use std::env; use std::collections::HashMap; use std::time::Duration; use cargo_registry::{VersionDownload, Version, Model}; static LIMIT: i64 = 10000; #[allow(dead_code)] // dead in tests fn main() { env_logger::init().unwrap(); let daemon = env::args().nth(1).as_ref().map(|s| s.to_str().unwrap()) == Some("daemon"); let sleep = env::args().nth(2).map(|s| s.to_str().unwrap().parse::<i64>().unwrap()); loop { let conn = postgres::Connection::connect(env("DATABASE_URL").as_slice(), &postgres::SslMode::None).unwrap(); { let tx = conn.transaction().unwrap(); update(&tx).unwrap(); tx.set_commit(); tx.finish().unwrap(); } drop(conn); if daemon { std::old_io::timer::sleep(Duration::seconds(sleep.unwrap())); } else { break } } } fn env(s: &str) -> String { match env::var_string(s).ok() { Some(s) => s, None => panic!("must have `{}` defined", s), } } fn update(tx: &postgres::Transaction) -> postgres::Result<()> { let mut max = 0; loop { let tx = try!(tx.transaction()); { let stmt = try!(tx.prepare("SELECT * FROM version_downloads \ WHERE processed = FALSE AND id > $1 ORDER BY id ASC LIMIT $2")); let mut rows = try!(stmt.query(&[&max, &LIMIT])); match try!(collect(&tx, &mut rows)) { None => break, Some(m) => max = m, } } tx.set_commit(); try!(tx.finish()); } Ok(()) } fn collect(tx: &postgres::Transaction, rows: &mut postgres::Rows) -> postgres::Result<Option<i32>> { // Anything older than 24 hours ago will be frozen and will not be queried // against again. let cutoff = time::now_utc().to_timespec(); let cutoff = cutoff + Duration::days(-1); let mut map = HashMap::new(); for row in rows.by_ref() { let download: VersionDownload = Model::from_row(&row); assert!(map.insert(download.id, download).is_none()); } println!("updating {} versions", map.len()); if map.len() == 0 { return Ok(None) } let mut max = 0; let mut total = 0; for (id, download) in map.iter() { if *id > max { max = *id; } if download.counted == download.downloads { continue } let amt = download.downloads - download.counted; let crate_id = Version::find(tx, download.version_id).unwrap().crate_id; // Update the total number of version downloads try!(tx.execute("UPDATE versions SET downloads = downloads + $1 WHERE id = $2", &[&amt, &download.version_id])); // Update the total number of crate downloads try!(tx.execute("UPDATE crates SET downloads = downloads + $1 WHERE id = $2", &[&amt, &crate_id])); // Update the total number of crate downloads for today let cnt = try!(tx.execute("UPDATE crate_downloads SET downloads = downloads + $2 WHERE crate_id = $1 AND date = date($3)", &[&crate_id, &amt, &download.date])); if cnt == 0 { try!(tx.execute("INSERT INTO crate_downloads (crate_id, downloads, date) VALUES ($1, $2, $3)", &[&crate_id, &amt, &download.date])); } // Flag this row as having been processed if we're passed the cutoff, // and unconditionally increment the number of counted downloads. try!(tx.execute("UPDATE version_downloads SET processed = $2, counted = downloads WHERE id = $1", &[id, &(download.date < cutoff)])); total += amt as i64; } // After everything else is done, update the global counter of total // downloads. try!(tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1", &[&total])); Ok(Some(max)) } #[cfg(test)] mod test { use std::collections::HashMap; use postgres; use semver; use cargo_registry::{Version, Crate, User}; fn conn() -> postgres::Connection { postgres::Connection::connect(::env("TEST_DATABASE_URL").as_slice(), &postgres::SslMode::None).unwrap() } fn
(conn: &postgres::Transaction) -> User{ User::find_or_insert(conn, "login", None, None, None, "access_token", "api_token").unwrap() } fn crate_downloads(tx: &postgres::Transaction, id: i32, expected: usize) { let stmt = tx.prepare("SELECT * FROM crate_downloads WHERE crate_id = $1").unwrap(); let dl: i32 = stmt.query(&[&id]).unwrap() .next().unwrap().get("downloads"); assert_eq!(dl, expected as i32); } #[test] fn increment() { let conn = conn(); let tx = conn.transaction().unwrap(); let user = user(&tx); let krate = Crate::find_or_insert(&tx, "foo", user.id, &None, &None, &None, &None, &[], &None, &None, &None).unwrap(); let version = Version::insert(&tx, krate.id, &semver::Version::parse("1.0.0").unwrap(), &HashMap::new(), &[]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, false)", &[&version.id]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, true)", &[&version.id]).unwrap(); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 1); assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 1); crate_downloads(&tx, krate.id, 1); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 1); } #[test] fn increment_a_little() { let conn = conn(); let tx = conn.transaction().unwrap(); let user = user(&tx); let krate = Crate::find_or_insert(&tx, "foo", user.id, &None, &None, &None, &None, &[], &None, &None, &None).unwrap(); let version = Version::insert(&tx, krate.id, &semver::Version::parse("1.0.0").unwrap(), &HashMap::new(), &[]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 2, 1, current_date, false)", &[&version.id]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, false)", &[&version.id]).unwrap(); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2); assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 2); crate_downloads(&tx, krate.id, 2); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2); } }
user
identifier_name
update-downloads.rs
#![deny(warnings)] #![feature(std_misc, core, os, io, env)] extern crate "cargo-registry" as cargo_registry; extern crate postgres; extern crate semver; extern crate time; extern crate env_logger; use std::env; use std::collections::HashMap; use std::time::Duration; use cargo_registry::{VersionDownload, Version, Model}; static LIMIT: i64 = 10000; #[allow(dead_code)] // dead in tests fn main() { env_logger::init().unwrap(); let daemon = env::args().nth(1).as_ref().map(|s| s.to_str().unwrap()) == Some("daemon"); let sleep = env::args().nth(2).map(|s| s.to_str().unwrap().parse::<i64>().unwrap()); loop { let conn = postgres::Connection::connect(env("DATABASE_URL").as_slice(), &postgres::SslMode::None).unwrap(); { let tx = conn.transaction().unwrap(); update(&tx).unwrap(); tx.set_commit(); tx.finish().unwrap(); } drop(conn); if daemon { std::old_io::timer::sleep(Duration::seconds(sleep.unwrap())); } else { break } } } fn env(s: &str) -> String { match env::var_string(s).ok() { Some(s) => s, None => panic!("must have `{}` defined", s), } } fn update(tx: &postgres::Transaction) -> postgres::Result<()> { let mut max = 0; loop { let tx = try!(tx.transaction()); { let stmt = try!(tx.prepare("SELECT * FROM version_downloads \ WHERE processed = FALSE AND id > $1 ORDER BY id ASC LIMIT $2")); let mut rows = try!(stmt.query(&[&max, &LIMIT])); match try!(collect(&tx, &mut rows)) { None => break, Some(m) => max = m, } } tx.set_commit(); try!(tx.finish()); } Ok(()) } fn collect(tx: &postgres::Transaction, rows: &mut postgres::Rows) -> postgres::Result<Option<i32>> { // Anything older than 24 hours ago will be frozen and will not be queried // against again. let cutoff = time::now_utc().to_timespec(); let cutoff = cutoff + Duration::days(-1); let mut map = HashMap::new(); for row in rows.by_ref() { let download: VersionDownload = Model::from_row(&row); assert!(map.insert(download.id, download).is_none()); } println!("updating {} versions", map.len()); if map.len() == 0 { return Ok(None) } let mut max = 0; let mut total = 0; for (id, download) in map.iter() { if *id > max { max = *id; } if download.counted == download.downloads { continue } let amt = download.downloads - download.counted; let crate_id = Version::find(tx, download.version_id).unwrap().crate_id; // Update the total number of version downloads try!(tx.execute("UPDATE versions SET downloads = downloads + $1 WHERE id = $2", &[&amt, &download.version_id])); // Update the total number of crate downloads try!(tx.execute("UPDATE crates SET downloads = downloads + $1 WHERE id = $2", &[&amt, &crate_id])); // Update the total number of crate downloads for today let cnt = try!(tx.execute("UPDATE crate_downloads SET downloads = downloads + $2 WHERE crate_id = $1 AND date = date($3)", &[&crate_id, &amt, &download.date])); if cnt == 0 { try!(tx.execute("INSERT INTO crate_downloads (crate_id, downloads, date) VALUES ($1, $2, $3)", &[&crate_id, &amt, &download.date])); } // Flag this row as having been processed if we're passed the cutoff, // and unconditionally increment the number of counted downloads. try!(tx.execute("UPDATE version_downloads SET processed = $2, counted = downloads WHERE id = $1", &[id, &(download.date < cutoff)])); total += amt as i64; } // After everything else is done, update the global counter of total // downloads. try!(tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1", &[&total])); Ok(Some(max)) } #[cfg(test)] mod test { use std::collections::HashMap; use postgres; use semver; use cargo_registry::{Version, Crate, User}; fn conn() -> postgres::Connection { postgres::Connection::connect(::env("TEST_DATABASE_URL").as_slice(), &postgres::SslMode::None).unwrap() } fn user(conn: &postgres::Transaction) -> User{ User::find_or_insert(conn, "login", None, None, None, "access_token", "api_token").unwrap() } fn crate_downloads(tx: &postgres::Transaction, id: i32, expected: usize) { let stmt = tx.prepare("SELECT * FROM crate_downloads WHERE crate_id = $1").unwrap(); let dl: i32 = stmt.query(&[&id]).unwrap() .next().unwrap().get("downloads"); assert_eq!(dl, expected as i32); } #[test] fn increment() { let conn = conn(); let tx = conn.transaction().unwrap(); let user = user(&tx); let krate = Crate::find_or_insert(&tx, "foo", user.id, &None, &None, &None, &None, &[], &None, &None, &None).unwrap(); let version = Version::insert(&tx, krate.id, &semver::Version::parse("1.0.0").unwrap(), &HashMap::new(), &[]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, false)", &[&version.id]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, true)", &[&version.id]).unwrap(); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 1); assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 1); crate_downloads(&tx, krate.id, 1); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 1); } #[test] fn increment_a_little()
}
{ let conn = conn(); let tx = conn.transaction().unwrap(); let user = user(&tx); let krate = Crate::find_or_insert(&tx, "foo", user.id, &None, &None, &None, &None, &[], &None, &None, &None).unwrap(); let version = Version::insert(&tx, krate.id, &semver::Version::parse("1.0.0").unwrap(), &HashMap::new(), &[]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 2, 1, current_date, false)", &[&version.id]).unwrap(); tx.execute("INSERT INTO version_downloads \ (version_id, downloads, counted, date, processed) VALUES ($1, 1, 0, current_date, false)", &[&version.id]).unwrap(); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2); assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 2); crate_downloads(&tx, krate.id, 2); ::update(&tx).unwrap(); assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2); }
identifier_body
TextOutput.js
import {appendHtml, combine} from './../util'; const ELEMENT_NAMES = { frameName: 'text-frame', messageName: 'text-message', indicatorName: 'text-indicator' }; let createElements = (container, names) => { const elements = '\ <div class="text-frame" id="' + names.frameName + '">\ <span class="text-message" id="' + names.messageName + '"></span>\ <span id="' + names.indicatorName + '">▼</span>\ </div>'; appendHtml(container, elements); } export default class TextOutput { constructor(parent, engine) { let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames); if (!engine.overrides.useCustomElements) { createElements(parent, elementNames); } this._textMessages = []; this.engine = engine; this.textMessageFrame = document.getElementById(elementNames.frameName); this.textMessage = document.getElementById(elementNames.messageName); this.textIndicator = document.getElementById(elementNames.indicatorName) this.textMessageFrame.onclick = () => engine.drawMessages(); engine.clearText = combine(engine.clearText, this.clearText.bind(this)); engine.displayText = combine(engine.displayText, this.displayText.bind(this)); engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this)); engine.actionExecutor.registerAction("text", (options, engine, player, callback) => { engine.displayText(options.text.split("\n")); }, false, true); } cl
) { this._textMessages = []; this.textMessageFrame.classList.remove("in"); this.textMessage.innerHTML = ""; this.textIndicator.classList.remove("in"); this.engine.unpause(); } displayText (text) { this._textMessages = this._textMessages.concat(text); } drawMessages () { if (this._textMessages.length > 0) { this.engine.pause(); const text = this._textMessages.splice(0, 1)[0]; this.textMessage.innerHTML = text; if (!("in" in this.textMessageFrame.classList)) { this.textMessageFrame.classList.add("in"); } if (this._textMessages.length >= 1) { this.textIndicator.classList.add("in"); } else { this.textIndicator.classList.remove("in"); } } else { this.clearText(); } } }
earText (
identifier_name
TextOutput.js
import {appendHtml, combine} from './../util'; const ELEMENT_NAMES = { frameName: 'text-frame', messageName: 'text-message', indicatorName: 'text-indicator' }; let createElements = (container, names) => { const elements = '\ <div class="text-frame" id="' + names.frameName + '">\ <span class="text-message" id="' + names.messageName + '"></span>\ <span id="' + names.indicatorName + '">▼</span>\ </div>'; appendHtml(container, elements); } export default class TextOutput { constructor(parent, engine) {
createElements(parent, elementNames); } this._textMessages = []; this.engine = engine; this.textMessageFrame = document.getElementById(elementNames.frameName); this.textMessage = document.getElementById(elementNames.messageName); this.textIndicator = document.getElementById(elementNames.indicatorName) this.textMessageFrame.onclick = () => engine.drawMessages(); engine.clearText = combine(engine.clearText, this.clearText.bind(this)); engine.displayText = combine(engine.displayText, this.displayText.bind(this)); engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this)); engine.actionExecutor.registerAction("text", (options, engine, player, callback) => { engine.displayText(options.text.split("\n")); }, false, true); } clearText () { this._textMessages = []; this.textMessageFrame.classList.remove("in"); this.textMessage.innerHTML = ""; this.textIndicator.classList.remove("in"); this.engine.unpause(); } displayText (text) { this._textMessages = this._textMessages.concat(text); } drawMessages () { if (this._textMessages.length > 0) { this.engine.pause(); const text = this._textMessages.splice(0, 1)[0]; this.textMessage.innerHTML = text; if (!("in" in this.textMessageFrame.classList)) { this.textMessageFrame.classList.add("in"); } if (this._textMessages.length >= 1) { this.textIndicator.classList.add("in"); } else { this.textIndicator.classList.remove("in"); } } else { this.clearText(); } } }
let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames); if (!engine.overrides.useCustomElements) {
random_line_split
TextOutput.js
import {appendHtml, combine} from './../util'; const ELEMENT_NAMES = { frameName: 'text-frame', messageName: 'text-message', indicatorName: 'text-indicator' }; let createElements = (container, names) => { const elements = '\ <div class="text-frame" id="' + names.frameName + '">\ <span class="text-message" id="' + names.messageName + '"></span>\ <span id="' + names.indicatorName + '">▼</span>\ </div>'; appendHtml(container, elements); } export default class TextOutput { constructor(parent, engine) { let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames); if (!engine.overrides.useCustomElements) { createElements(parent, elementNames); } this._textMessages = []; this.engine = engine; this.textMessageFrame = document.getElementById(elementNames.frameName); this.textMessage = document.getElementById(elementNames.messageName); this.textIndicator = document.getElementById(elementNames.indicatorName) this.textMessageFrame.onclick = () => engine.drawMessages(); engine.clearText = combine(engine.clearText, this.clearText.bind(this)); engine.displayText = combine(engine.displayText, this.displayText.bind(this)); engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this)); engine.actionExecutor.registerAction("text", (options, engine, player, callback) => { engine.displayText(options.text.split("\n")); }, false, true); } clearText () { this._textMessages = []; this.textMessageFrame.classList.remove("in"); this.textMessage.innerHTML = ""; this.textIndicator.classList.remove("in"); this.engine.unpause(); } displayText (text) { this._textMessages = this._textMessages.concat(text); } drawMessages () { if (this._textMessages.length > 0) { this.engine.pause(); const text = this._textMessages.splice(0, 1)[0]; this.textMessage.innerHTML = text; if (!("in" in this.textMessageFrame.classList)) { this.textMessageFrame.classList.add("in"); } if (this._textMessages.length >= 1) { this.textIndicator.classList.add("in"); } else {
} else { this.clearText(); } } }
this.textIndicator.classList.remove("in"); }
conditional_block
artistphoto.py
################################################################# # This file is part of glyr # + a command-line tool and library to download various sort of music related metadata. # + Copyright (C) [2011-2012] [Christopher Pahl] # + Hosted at: https://github.com/sahib/glyr # # glyr 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. # # glyr 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 glyr. If not, see <http://www.gnu.org/licenses/>. ################################################################# #!/usr/bin/env python # encoding: utf-8 from tests.__common__ import * not_found_options = { 'get_type': 'artistphoto', 'artist': 'HorseTheBand', 'album': 'Given, but not used.', 'title': 'Accidentally given' } TESTCASES = [{ # {{{ 'name': 'bbcmusic', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'The Rolling Stones' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'discogs', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'Nirvana' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'flickr', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'Die Ärzte' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'google', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'DeVildRiVeR' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'lastfm', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'Alestorm' }, 'expect': len_greater_0 }, {
'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'singerpictures', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'Equilibrium' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'rhapsody', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'In Flames' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'expect': len_equal_0 }], } ]
'options': not_found_options,
random_line_split
issue-5791.rs
// Copyright 2013 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. // pretty-expanded FIXME #23616 #![feature(libc)] extern crate libc; extern { #[link_name = "malloc"] fn malloc1(len: libc::c_int) -> *const libc::c_void; #[link_name = "malloc"] fn malloc2(len: libc::c_int, foo: libc::c_int) -> *const libc::c_void; } pub fn
() {}
main
identifier_name
issue-5791.rs
// Copyright 2013 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. // pretty-expanded FIXME #23616 #![feature(libc)] extern crate libc; extern {
fn malloc2(len: libc::c_int, foo: libc::c_int) -> *const libc::c_void; } pub fn main () {}
#[link_name = "malloc"] fn malloc1(len: libc::c_int) -> *const libc::c_void; #[link_name = "malloc"]
random_line_split
issue-5791.rs
// Copyright 2013 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. // pretty-expanded FIXME #23616 #![feature(libc)] extern crate libc; extern { #[link_name = "malloc"] fn malloc1(len: libc::c_int) -> *const libc::c_void; #[link_name = "malloc"] fn malloc2(len: libc::c_int, foo: libc::c_int) -> *const libc::c_void; } pub fn main ()
{}
identifier_body
manager.py
# Copyright 2012 OpenStack Foundation # # 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. """ Cert manager manages x509 certificates. **Related Flags** :cert_topic: What :mod:`rpc` topic to listen to (default: `cert`). :cert_manager: The module name of a class derived from :class:`manager.Manager` (default: :class:`nova.cert.manager.Manager`). """ import base64 from oslo import messaging from nova import crypto from nova import manager class CertManager(manager.Manager): target = messaging.Target(version='2.0') def __init__(self, *args, **kwargs): super(CertManager, self).__init__(service_name='cert', *args, **kwargs) def
(self): crypto.ensure_ca_filesystem() def revoke_certs_by_user(self, context, user_id): """Revoke all user certs.""" return crypto.revoke_certs_by_user(user_id) def revoke_certs_by_project(self, context, project_id): """Revoke all project certs.""" return crypto.revoke_certs_by_project(project_id) def revoke_certs_by_user_and_project(self, context, user_id, project_id): """Revoke certs for user in project.""" return crypto.revoke_certs_by_user_and_project(user_id, project_id) def generate_x509_cert(self, context, user_id, project_id): """Generate and sign a cert for user in project.""" return crypto.generate_x509_cert(user_id, project_id) def fetch_ca(self, context, project_id): """Get root ca for a project.""" return crypto.fetch_ca(project_id) def fetch_crl(self, context, project_id): """Get crl for a project.""" return crypto.fetch_crl(project_id) def decrypt_text(self, context, project_id, text): """Decrypt base64 encoded text using the projects private key.""" return crypto.decrypt_text(project_id, base64.b64decode(text))
init_host
identifier_name
manager.py
# Copyright 2012 OpenStack Foundation #
# 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. """ Cert manager manages x509 certificates. **Related Flags** :cert_topic: What :mod:`rpc` topic to listen to (default: `cert`). :cert_manager: The module name of a class derived from :class:`manager.Manager` (default: :class:`nova.cert.manager.Manager`). """ import base64 from oslo import messaging from nova import crypto from nova import manager class CertManager(manager.Manager): target = messaging.Target(version='2.0') def __init__(self, *args, **kwargs): super(CertManager, self).__init__(service_name='cert', *args, **kwargs) def init_host(self): crypto.ensure_ca_filesystem() def revoke_certs_by_user(self, context, user_id): """Revoke all user certs.""" return crypto.revoke_certs_by_user(user_id) def revoke_certs_by_project(self, context, project_id): """Revoke all project certs.""" return crypto.revoke_certs_by_project(project_id) def revoke_certs_by_user_and_project(self, context, user_id, project_id): """Revoke certs for user in project.""" return crypto.revoke_certs_by_user_and_project(user_id, project_id) def generate_x509_cert(self, context, user_id, project_id): """Generate and sign a cert for user in project.""" return crypto.generate_x509_cert(user_id, project_id) def fetch_ca(self, context, project_id): """Get root ca for a project.""" return crypto.fetch_ca(project_id) def fetch_crl(self, context, project_id): """Get crl for a project.""" return crypto.fetch_crl(project_id) def decrypt_text(self, context, project_id, text): """Decrypt base64 encoded text using the projects private key.""" return crypto.decrypt_text(project_id, base64.b64decode(text))
# Licensed under the Apache License, Version 2.0 (the "License"); you may
random_line_split
manager.py
# Copyright 2012 OpenStack Foundation # # 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. """ Cert manager manages x509 certificates. **Related Flags** :cert_topic: What :mod:`rpc` topic to listen to (default: `cert`). :cert_manager: The module name of a class derived from :class:`manager.Manager` (default: :class:`nova.cert.manager.Manager`). """ import base64 from oslo import messaging from nova import crypto from nova import manager class CertManager(manager.Manager): target = messaging.Target(version='2.0') def __init__(self, *args, **kwargs):
def init_host(self): crypto.ensure_ca_filesystem() def revoke_certs_by_user(self, context, user_id): """Revoke all user certs.""" return crypto.revoke_certs_by_user(user_id) def revoke_certs_by_project(self, context, project_id): """Revoke all project certs.""" return crypto.revoke_certs_by_project(project_id) def revoke_certs_by_user_and_project(self, context, user_id, project_id): """Revoke certs for user in project.""" return crypto.revoke_certs_by_user_and_project(user_id, project_id) def generate_x509_cert(self, context, user_id, project_id): """Generate and sign a cert for user in project.""" return crypto.generate_x509_cert(user_id, project_id) def fetch_ca(self, context, project_id): """Get root ca for a project.""" return crypto.fetch_ca(project_id) def fetch_crl(self, context, project_id): """Get crl for a project.""" return crypto.fetch_crl(project_id) def decrypt_text(self, context, project_id, text): """Decrypt base64 encoded text using the projects private key.""" return crypto.decrypt_text(project_id, base64.b64decode(text))
super(CertManager, self).__init__(service_name='cert', *args, **kwargs)
identifier_body
lib.rs
// this module adds some functionality based on the required implementations // here like: `LinkedList::pop_back` or `Clone for LinkedList<T>` // You are free to use anything in it, but it's mainly for the test framework. mod pre_implemented; pub struct LinkedList<T>(std::marker::PhantomData<T>); pub struct Cursor<'a, T>(std::marker::PhantomData<&'a mut T>); pub struct Iter<'a, T>(std::marker::PhantomData<&'a T>); impl<T> LinkedList<T> { pub fn new() -> Self { unimplemented!() } // You may be wondering why it's necessary to have is_empty() // when it can easily be determined from len(). // It's good custom to have both because len() can be expensive for some types, // whereas is_empty() is almost always cheap. // (Also ask yourself whether len() is expensive for LinkedList) pub fn is_empty(&self) -> bool { unimplemented!() } pub fn len(&self) -> usize { unimplemented!() } /// Return a cursor positioned on the front element pub fn cursor_front(&mut self) -> Cursor<'_, T> { unimplemented!() } /// Return a cursor positioned on the back element pub fn cursor_back(&mut self) -> Cursor<'_, T> { unimplemented!() } /// Return an iterator that moves from front to back pub fn iter(&self) -> Iter<'_, T>
} // the cursor is expected to act as if it is at the position of an element // and it also has to work with and be able to insert into an empty list. impl<T> Cursor<'_, T> { /// Take a mutable reference to the current element pub fn peek_mut(&mut self) -> Option<&mut T> { unimplemented!() } /// Move one position forward (towards the back) and /// return a reference to the new position #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option<&mut T> { unimplemented!() } /// Move one position backward (towards the front) and /// return a reference to the new position pub fn prev(&mut self) -> Option<&mut T> { unimplemented!() } /// Remove and return the element at the current position and move the cursor /// to the neighboring element that's closest to the back. This can be /// either the next or previous position. pub fn take(&mut self) -> Option<T> { unimplemented!() } pub fn insert_after(&mut self, _element: T) { unimplemented!() } pub fn insert_before(&mut self, _element: T) { unimplemented!() } } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { unimplemented!() } }
{ unimplemented!() }
identifier_body
lib.rs
// this module adds some functionality based on the required implementations // here like: `LinkedList::pop_back` or `Clone for LinkedList<T>` // You are free to use anything in it, but it's mainly for the test framework. mod pre_implemented; pub struct LinkedList<T>(std::marker::PhantomData<T>); pub struct Cursor<'a, T>(std::marker::PhantomData<&'a mut T>); pub struct Iter<'a, T>(std::marker::PhantomData<&'a T>); impl<T> LinkedList<T> { pub fn new() -> Self { unimplemented!() } // You may be wondering why it's necessary to have is_empty() // when it can easily be determined from len(). // It's good custom to have both because len() can be expensive for some types, // whereas is_empty() is almost always cheap. // (Also ask yourself whether len() is expensive for LinkedList) pub fn is_empty(&self) -> bool { unimplemented!() } pub fn len(&self) -> usize { unimplemented!() } /// Return a cursor positioned on the front element pub fn cursor_front(&mut self) -> Cursor<'_, T> { unimplemented!() } /// Return a cursor positioned on the back element pub fn cursor_back(&mut self) -> Cursor<'_, T> { unimplemented!() } /// Return an iterator that moves from front to back pub fn iter(&self) -> Iter<'_, T> { unimplemented!() } } // the cursor is expected to act as if it is at the position of an element // and it also has to work with and be able to insert into an empty list. impl<T> Cursor<'_, T> { /// Take a mutable reference to the current element pub fn peek_mut(&mut self) -> Option<&mut T> { unimplemented!() } /// Move one position forward (towards the back) and /// return a reference to the new position #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option<&mut T> { unimplemented!() }
/// return a reference to the new position pub fn prev(&mut self) -> Option<&mut T> { unimplemented!() } /// Remove and return the element at the current position and move the cursor /// to the neighboring element that's closest to the back. This can be /// either the next or previous position. pub fn take(&mut self) -> Option<T> { unimplemented!() } pub fn insert_after(&mut self, _element: T) { unimplemented!() } pub fn insert_before(&mut self, _element: T) { unimplemented!() } } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { unimplemented!() } }
/// Move one position backward (towards the front) and
random_line_split
lib.rs
// this module adds some functionality based on the required implementations // here like: `LinkedList::pop_back` or `Clone for LinkedList<T>` // You are free to use anything in it, but it's mainly for the test framework. mod pre_implemented; pub struct LinkedList<T>(std::marker::PhantomData<T>); pub struct Cursor<'a, T>(std::marker::PhantomData<&'a mut T>); pub struct Iter<'a, T>(std::marker::PhantomData<&'a T>); impl<T> LinkedList<T> { pub fn new() -> Self { unimplemented!() } // You may be wondering why it's necessary to have is_empty() // when it can easily be determined from len(). // It's good custom to have both because len() can be expensive for some types, // whereas is_empty() is almost always cheap. // (Also ask yourself whether len() is expensive for LinkedList) pub fn is_empty(&self) -> bool { unimplemented!() } pub fn len(&self) -> usize { unimplemented!() } /// Return a cursor positioned on the front element pub fn
(&mut self) -> Cursor<'_, T> { unimplemented!() } /// Return a cursor positioned on the back element pub fn cursor_back(&mut self) -> Cursor<'_, T> { unimplemented!() } /// Return an iterator that moves from front to back pub fn iter(&self) -> Iter<'_, T> { unimplemented!() } } // the cursor is expected to act as if it is at the position of an element // and it also has to work with and be able to insert into an empty list. impl<T> Cursor<'_, T> { /// Take a mutable reference to the current element pub fn peek_mut(&mut self) -> Option<&mut T> { unimplemented!() } /// Move one position forward (towards the back) and /// return a reference to the new position #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option<&mut T> { unimplemented!() } /// Move one position backward (towards the front) and /// return a reference to the new position pub fn prev(&mut self) -> Option<&mut T> { unimplemented!() } /// Remove and return the element at the current position and move the cursor /// to the neighboring element that's closest to the back. This can be /// either the next or previous position. pub fn take(&mut self) -> Option<T> { unimplemented!() } pub fn insert_after(&mut self, _element: T) { unimplemented!() } pub fn insert_before(&mut self, _element: T) { unimplemented!() } } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { unimplemented!() } }
cursor_front
identifier_name
temporary_page.rs
//! Temporarily map a page //! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html) use memory::Frame; use super::{ActivePageTable, Page, VirtualAddress}; use super::entry::EntryFlags; use super::table::{Table, Level1}; pub struct TemporaryPage { page: Page, } impl TemporaryPage { pub fn
(page: Page) -> TemporaryPage { TemporaryPage { page: page, } } pub fn start_address (&self) -> VirtualAddress { self.page.start_address() } /// Maps the temporary page to the given frame in the active table. /// Returns the start address of the temporary page. pub fn map(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> VirtualAddress { assert!(active_table.translate_page(self.page).is_none(), "temporary page is already mapped"); active_table.map_to(self.page, frame, flags); self.page.start_address() } /// Maps the temporary page to the given page table frame in the active /// table. Returns a reference to the now mapped table. pub fn map_table_frame(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> &mut Table<Level1> { unsafe { &mut *(self.map(frame, flags, active_table).get() as *mut Table<Level1>) } } /// Unmaps the temporary page in the active table. pub fn unmap(&mut self, active_table: &mut ActivePageTable) { active_table.unmap(self.page) } }
new
identifier_name
temporary_page.rs
//! Temporarily map a page //! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html) use memory::Frame; use super::{ActivePageTable, Page, VirtualAddress}; use super::entry::EntryFlags; use super::table::{Table, Level1}; pub struct TemporaryPage { page: Page, } impl TemporaryPage { pub fn new(page: Page) -> TemporaryPage { TemporaryPage { page: page, } } pub fn start_address (&self) -> VirtualAddress
/// Maps the temporary page to the given frame in the active table. /// Returns the start address of the temporary page. pub fn map(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> VirtualAddress { assert!(active_table.translate_page(self.page).is_none(), "temporary page is already mapped"); active_table.map_to(self.page, frame, flags); self.page.start_address() } /// Maps the temporary page to the given page table frame in the active /// table. Returns a reference to the now mapped table. pub fn map_table_frame(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> &mut Table<Level1> { unsafe { &mut *(self.map(frame, flags, active_table).get() as *mut Table<Level1>) } } /// Unmaps the temporary page in the active table. pub fn unmap(&mut self, active_table: &mut ActivePageTable) { active_table.unmap(self.page) } }
{ self.page.start_address() }
identifier_body
temporary_page.rs
//! Temporarily map a page //! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html) use memory::Frame; use super::{ActivePageTable, Page, VirtualAddress}; use super::entry::EntryFlags; use super::table::{Table, Level1}; pub struct TemporaryPage { page: Page, } impl TemporaryPage { pub fn new(page: Page) -> TemporaryPage { TemporaryPage { page: page, } } pub fn start_address (&self) -> VirtualAddress { self.page.start_address() } /// Maps the temporary page to the given frame in the active table. /// Returns the start address of the temporary page. pub fn map(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> VirtualAddress { assert!(active_table.translate_page(self.page).is_none(), "temporary page is already mapped"); active_table.map_to(self.page, frame, flags); self.page.start_address() } /// Maps the temporary page to the given page table frame in the active /// table. Returns a reference to the now mapped table. pub fn map_table_frame(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> &mut Table<Level1> {
} /// Unmaps the temporary page in the active table. pub fn unmap(&mut self, active_table: &mut ActivePageTable) { active_table.unmap(self.page) } }
unsafe { &mut *(self.map(frame, flags, active_table).get() as *mut Table<Level1>) }
random_line_split
borrow-tuple-fields.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. #![allow(unknown_features)] #![feature(box_syntax)] struct Foo(Box<isize>, isize); struct
(isize, isize); fn main() { let x: (Box<_>, _) = (box 1, 2); let r = &x.0; let y = x; //~ ERROR cannot move out of `x` because it is borrowed let mut x = (1, 2); let a = &x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as let mut x = (1, 2); let a = &mut x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time let x = Foo(box 1, 2); let r = &x.0; let y = x; //~ ERROR cannot move out of `x` because it is borrowed let mut x = Bar(1, 2); let a = &x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as let mut x = Bar(1, 2); let a = &mut x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time }
Bar
identifier_name
borrow-tuple-fields.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. #![allow(unknown_features)]
struct Foo(Box<isize>, isize); struct Bar(isize, isize); fn main() { let x: (Box<_>, _) = (box 1, 2); let r = &x.0; let y = x; //~ ERROR cannot move out of `x` because it is borrowed let mut x = (1, 2); let a = &x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as let mut x = (1, 2); let a = &mut x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time let x = Foo(box 1, 2); let r = &x.0; let y = x; //~ ERROR cannot move out of `x` because it is borrowed let mut x = Bar(1, 2); let a = &x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as let mut x = Bar(1, 2); let a = &mut x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time }
#![feature(box_syntax)]
random_line_split
os.rs
#![deny(unsafe_op_in_unsafe_fn)] use crate::any::Any; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::os::wasi::prelude::*; use crate::path::{self, PathBuf}; use crate::str; use crate::sys::memchr; use crate::sys::unsupported; use crate::vec; // Add a few symbols not in upstream `libc` just yet. mod libc { pub use libc::*; extern "C" { pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; pub fn chdir(dir: *const c_char) -> c_int; } } #[cfg(not(target_feature = "atomics"))] pub unsafe fn env_lock() -> impl Any { // No need for a lock if we're single-threaded, but this function will need // to get implemented for multi-threaded scenarios } pub fn errno() -> i32 { extern "C" { #[thread_local] static errno: libc::c_int; } unsafe { errno as i32 } } pub fn error_string(errno: i32) -> String { let mut buf = [0 as libc::c_char; 1024]; let p = buf.as_mut_ptr(); unsafe { if libc::strerror_r(errno as libc::c_int, p, buf.len()) < 0 { panic!("strerror_r failure"); } str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned() } } pub fn getcwd() -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(512); loop { unsafe { let ptr = buf.as_mut_ptr() as *mut libc::c_char; if !libc::getcwd(ptr, buf.capacity()).is_null() { let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len(); buf.set_len(len); buf.shrink_to_fit(); return Ok(PathBuf::from(OsString::from_vec(buf))); } else { let error = io::Error::last_os_error(); if error.raw_os_error() != Some(libc::ERANGE) { return Err(error); } } // Trigger the internal buffer resizing logic of `Vec` by requiring // more space than the current capacity. let cap = buf.capacity(); buf.set_len(cap); buf.reserve(1); } } } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let p = CString::new(p.as_bytes())?; unsafe { match libc::chdir(p.as_ptr()) == (0 as libc::c_int) { true => Ok(()), false => Err(io::Error::last_os_error()), } } } pub struct SplitPaths<'a>(!, PhantomData<&'a ()>); pub fn split_paths(_unparsed: &OsStr) -> SplitPaths<'_> { panic!("unsupported") } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { self.0 } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item = T>, T: AsRef<OsStr>, { Err(JoinPathsError) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { "not supported on wasm yet".fmt(f) } } impl StdError for JoinPathsError { #[allow(deprecated)] fn description(&self) -> &str { "not supported on wasm yet" } } pub fn current_exe() -> io::Result<PathBuf> { unsupported() } pub struct Env { iter: vec::IntoIter<(OsString, OsString)>, } impl !Send for Env {} impl !Sync for Env {} impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } pub fn env() -> Env { unsafe { let _guard = env_lock(); let mut environ = libc::environ; let mut result = Vec::new(); if !environ.is_null() { while !(*environ).is_null() { if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) { result.push(key_value); } environ = environ.add(1); } } return Env { iter: result.into_iter() }; } // See src/libstd/sys/unix/os.rs, same as that fn parse(input: &[u8]) -> Option<(OsString, OsString)> { if input.is_empty() { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); pos.map(|p| { ( OsStringExt::from_vec(input[..p].to_vec()), OsStringExt::from_vec(input[p + 1..].to_vec()), ) }) } } pub fn getenv(k: &OsStr) -> Option<OsString> { let k = CString::new(k.as_bytes()).ok()?; unsafe { let _guard = env_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()>
pub fn unsetenv(n: &OsStr) -> io::Result<()> { let nbuf = CString::new(n.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::unsetenv(nbuf.as_ptr())).map(drop) } } pub fn temp_dir() -> PathBuf { panic!("no filesystem on wasm") } pub fn home_dir() -> Option<PathBuf> { None } pub fn exit(code: i32) -> ! { unsafe { libc::exit(code) } } pub fn getpid() -> u32 { panic!("unsupported"); } #[doc(hidden)] pub trait IsMinusOne { fn is_minus_one(&self) -> bool; } macro_rules! impl_is_minus_one { ($($t:ident)*) => ($(impl IsMinusOne for $t { fn is_minus_one(&self) -> bool { *self == -1 } })*) } impl_is_minus_one! { i8 i16 i32 i64 isize } fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> { if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) } }
{ let k = CString::new(k.as_bytes())?; let v = CString::new(v.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop) } }
identifier_body
os.rs
#![deny(unsafe_op_in_unsafe_fn)] use crate::any::Any; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::os::wasi::prelude::*; use crate::path::{self, PathBuf}; use crate::str; use crate::sys::memchr; use crate::sys::unsupported; use crate::vec; // Add a few symbols not in upstream `libc` just yet. mod libc { pub use libc::*; extern "C" { pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; pub fn chdir(dir: *const c_char) -> c_int; } } #[cfg(not(target_feature = "atomics"))] pub unsafe fn env_lock() -> impl Any { // No need for a lock if we're single-threaded, but this function will need // to get implemented for multi-threaded scenarios } pub fn errno() -> i32 { extern "C" { #[thread_local] static errno: libc::c_int; } unsafe { errno as i32 } } pub fn error_string(errno: i32) -> String { let mut buf = [0 as libc::c_char; 1024]; let p = buf.as_mut_ptr(); unsafe { if libc::strerror_r(errno as libc::c_int, p, buf.len()) < 0 { panic!("strerror_r failure"); } str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned() } } pub fn getcwd() -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(512); loop { unsafe { let ptr = buf.as_mut_ptr() as *mut libc::c_char; if !libc::getcwd(ptr, buf.capacity()).is_null()
else { let error = io::Error::last_os_error(); if error.raw_os_error() != Some(libc::ERANGE) { return Err(error); } } // Trigger the internal buffer resizing logic of `Vec` by requiring // more space than the current capacity. let cap = buf.capacity(); buf.set_len(cap); buf.reserve(1); } } } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let p = CString::new(p.as_bytes())?; unsafe { match libc::chdir(p.as_ptr()) == (0 as libc::c_int) { true => Ok(()), false => Err(io::Error::last_os_error()), } } } pub struct SplitPaths<'a>(!, PhantomData<&'a ()>); pub fn split_paths(_unparsed: &OsStr) -> SplitPaths<'_> { panic!("unsupported") } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { self.0 } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item = T>, T: AsRef<OsStr>, { Err(JoinPathsError) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { "not supported on wasm yet".fmt(f) } } impl StdError for JoinPathsError { #[allow(deprecated)] fn description(&self) -> &str { "not supported on wasm yet" } } pub fn current_exe() -> io::Result<PathBuf> { unsupported() } pub struct Env { iter: vec::IntoIter<(OsString, OsString)>, } impl !Send for Env {} impl !Sync for Env {} impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } pub fn env() -> Env { unsafe { let _guard = env_lock(); let mut environ = libc::environ; let mut result = Vec::new(); if !environ.is_null() { while !(*environ).is_null() { if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) { result.push(key_value); } environ = environ.add(1); } } return Env { iter: result.into_iter() }; } // See src/libstd/sys/unix/os.rs, same as that fn parse(input: &[u8]) -> Option<(OsString, OsString)> { if input.is_empty() { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); pos.map(|p| { ( OsStringExt::from_vec(input[..p].to_vec()), OsStringExt::from_vec(input[p + 1..].to_vec()), ) }) } } pub fn getenv(k: &OsStr) -> Option<OsString> { let k = CString::new(k.as_bytes()).ok()?; unsafe { let _guard = env_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = CString::new(k.as_bytes())?; let v = CString::new(v.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop) } } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let nbuf = CString::new(n.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::unsetenv(nbuf.as_ptr())).map(drop) } } pub fn temp_dir() -> PathBuf { panic!("no filesystem on wasm") } pub fn home_dir() -> Option<PathBuf> { None } pub fn exit(code: i32) -> ! { unsafe { libc::exit(code) } } pub fn getpid() -> u32 { panic!("unsupported"); } #[doc(hidden)] pub trait IsMinusOne { fn is_minus_one(&self) -> bool; } macro_rules! impl_is_minus_one { ($($t:ident)*) => ($(impl IsMinusOne for $t { fn is_minus_one(&self) -> bool { *self == -1 } })*) } impl_is_minus_one! { i8 i16 i32 i64 isize } fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> { if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) } }
{ let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len(); buf.set_len(len); buf.shrink_to_fit(); return Ok(PathBuf::from(OsString::from_vec(buf))); }
conditional_block
os.rs
#![deny(unsafe_op_in_unsafe_fn)] use crate::any::Any; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::os::wasi::prelude::*; use crate::path::{self, PathBuf}; use crate::str; use crate::sys::memchr; use crate::sys::unsupported; use crate::vec; // Add a few symbols not in upstream `libc` just yet. mod libc { pub use libc::*; extern "C" { pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; pub fn chdir(dir: *const c_char) -> c_int; } } #[cfg(not(target_feature = "atomics"))] pub unsafe fn env_lock() -> impl Any { // No need for a lock if we're single-threaded, but this function will need // to get implemented for multi-threaded scenarios } pub fn errno() -> i32 { extern "C" { #[thread_local] static errno: libc::c_int; } unsafe { errno as i32 } } pub fn error_string(errno: i32) -> String { let mut buf = [0 as libc::c_char; 1024]; let p = buf.as_mut_ptr(); unsafe { if libc::strerror_r(errno as libc::c_int, p, buf.len()) < 0 { panic!("strerror_r failure"); } str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned() } } pub fn getcwd() -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(512); loop { unsafe { let ptr = buf.as_mut_ptr() as *mut libc::c_char; if !libc::getcwd(ptr, buf.capacity()).is_null() { let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len(); buf.set_len(len); buf.shrink_to_fit(); return Ok(PathBuf::from(OsString::from_vec(buf))); } else { let error = io::Error::last_os_error(); if error.raw_os_error() != Some(libc::ERANGE) { return Err(error); } } // Trigger the internal buffer resizing logic of `Vec` by requiring // more space than the current capacity. let cap = buf.capacity(); buf.set_len(cap); buf.reserve(1); } } } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let p = CString::new(p.as_bytes())?; unsafe { match libc::chdir(p.as_ptr()) == (0 as libc::c_int) { true => Ok(()), false => Err(io::Error::last_os_error()), } } } pub struct SplitPaths<'a>(!, PhantomData<&'a ()>); pub fn split_paths(_unparsed: &OsStr) -> SplitPaths<'_> { panic!("unsupported") } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { self.0 } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item = T>, T: AsRef<OsStr>, { Err(JoinPathsError) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { "not supported on wasm yet".fmt(f) } } impl StdError for JoinPathsError { #[allow(deprecated)] fn description(&self) -> &str { "not supported on wasm yet" } } pub fn current_exe() -> io::Result<PathBuf> { unsupported() } pub struct Env { iter: vec::IntoIter<(OsString, OsString)>, } impl !Send for Env {} impl !Sync for Env {} impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } pub fn env() -> Env { unsafe { let _guard = env_lock(); let mut environ = libc::environ; let mut result = Vec::new(); if !environ.is_null() { while !(*environ).is_null() { if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) { result.push(key_value); } environ = environ.add(1); } } return Env { iter: result.into_iter() }; } // See src/libstd/sys/unix/os.rs, same as that fn parse(input: &[u8]) -> Option<(OsString, OsString)> { if input.is_empty() { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); pos.map(|p| { ( OsStringExt::from_vec(input[..p].to_vec()), OsStringExt::from_vec(input[p + 1..].to_vec()), ) }) } } pub fn getenv(k: &OsStr) -> Option<OsString> { let k = CString::new(k.as_bytes()).ok()?; unsafe { let _guard = env_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
} } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = CString::new(k.as_bytes())?; let v = CString::new(v.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop) } } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let nbuf = CString::new(n.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::unsetenv(nbuf.as_ptr())).map(drop) } } pub fn temp_dir() -> PathBuf { panic!("no filesystem on wasm") } pub fn home_dir() -> Option<PathBuf> { None } pub fn exit(code: i32) -> ! { unsafe { libc::exit(code) } } pub fn getpid() -> u32 { panic!("unsupported"); } #[doc(hidden)] pub trait IsMinusOne { fn is_minus_one(&self) -> bool; } macro_rules! impl_is_minus_one { ($($t:ident)*) => ($(impl IsMinusOne for $t { fn is_minus_one(&self) -> bool { *self == -1 } })*) } impl_is_minus_one! { i8 i16 i32 i64 isize } fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> { if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) } }
if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) }
random_line_split
os.rs
#![deny(unsafe_op_in_unsafe_fn)] use crate::any::Any; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::os::wasi::prelude::*; use crate::path::{self, PathBuf}; use crate::str; use crate::sys::memchr; use crate::sys::unsupported; use crate::vec; // Add a few symbols not in upstream `libc` just yet. mod libc { pub use libc::*; extern "C" { pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; pub fn chdir(dir: *const c_char) -> c_int; } } #[cfg(not(target_feature = "atomics"))] pub unsafe fn env_lock() -> impl Any { // No need for a lock if we're single-threaded, but this function will need // to get implemented for multi-threaded scenarios } pub fn errno() -> i32 { extern "C" { #[thread_local] static errno: libc::c_int; } unsafe { errno as i32 } } pub fn error_string(errno: i32) -> String { let mut buf = [0 as libc::c_char; 1024]; let p = buf.as_mut_ptr(); unsafe { if libc::strerror_r(errno as libc::c_int, p, buf.len()) < 0 { panic!("strerror_r failure"); } str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned() } } pub fn getcwd() -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(512); loop { unsafe { let ptr = buf.as_mut_ptr() as *mut libc::c_char; if !libc::getcwd(ptr, buf.capacity()).is_null() { let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len(); buf.set_len(len); buf.shrink_to_fit(); return Ok(PathBuf::from(OsString::from_vec(buf))); } else { let error = io::Error::last_os_error(); if error.raw_os_error() != Some(libc::ERANGE) { return Err(error); } } // Trigger the internal buffer resizing logic of `Vec` by requiring // more space than the current capacity. let cap = buf.capacity(); buf.set_len(cap); buf.reserve(1); } } } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let p = CString::new(p.as_bytes())?; unsafe { match libc::chdir(p.as_ptr()) == (0 as libc::c_int) { true => Ok(()), false => Err(io::Error::last_os_error()), } } } pub struct SplitPaths<'a>(!, PhantomData<&'a ()>); pub fn split_paths(_unparsed: &OsStr) -> SplitPaths<'_> { panic!("unsupported") } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { self.0 } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item = T>, T: AsRef<OsStr>, { Err(JoinPathsError) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { "not supported on wasm yet".fmt(f) } } impl StdError for JoinPathsError { #[allow(deprecated)] fn description(&self) -> &str { "not supported on wasm yet" } } pub fn
() -> io::Result<PathBuf> { unsupported() } pub struct Env { iter: vec::IntoIter<(OsString, OsString)>, } impl !Send for Env {} impl !Sync for Env {} impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } pub fn env() -> Env { unsafe { let _guard = env_lock(); let mut environ = libc::environ; let mut result = Vec::new(); if !environ.is_null() { while !(*environ).is_null() { if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) { result.push(key_value); } environ = environ.add(1); } } return Env { iter: result.into_iter() }; } // See src/libstd/sys/unix/os.rs, same as that fn parse(input: &[u8]) -> Option<(OsString, OsString)> { if input.is_empty() { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); pos.map(|p| { ( OsStringExt::from_vec(input[..p].to_vec()), OsStringExt::from_vec(input[p + 1..].to_vec()), ) }) } } pub fn getenv(k: &OsStr) -> Option<OsString> { let k = CString::new(k.as_bytes()).ok()?; unsafe { let _guard = env_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) } } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = CString::new(k.as_bytes())?; let v = CString::new(v.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop) } } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let nbuf = CString::new(n.as_bytes())?; unsafe { let _guard = env_lock(); cvt(libc::unsetenv(nbuf.as_ptr())).map(drop) } } pub fn temp_dir() -> PathBuf { panic!("no filesystem on wasm") } pub fn home_dir() -> Option<PathBuf> { None } pub fn exit(code: i32) -> ! { unsafe { libc::exit(code) } } pub fn getpid() -> u32 { panic!("unsupported"); } #[doc(hidden)] pub trait IsMinusOne { fn is_minus_one(&self) -> bool; } macro_rules! impl_is_minus_one { ($($t:ident)*) => ($(impl IsMinusOne for $t { fn is_minus_one(&self) -> bool { *self == -1 } })*) } impl_is_minus_one! { i8 i16 i32 i64 isize } fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> { if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) } }
current_exe
identifier_name
atom.rs
use joker::word::{Atom, Name}; use tristate::TriState; pub trait AtomExt { fn is_strict_reserved(&self) -> TriState; fn is_illegal_strict_binding(&self) -> bool; }
match self { &Name::Atom(ref atom) => atom.is_strict_reserved(), _ => TriState::No } } fn is_illegal_strict_binding(&self) -> bool { match *self { Name::Atom(ref atom) => atom.is_illegal_strict_binding(), _ => false } } } impl AtomExt for Atom { fn is_strict_reserved(&self) -> TriState { match *self { // 11.6.2.2 Atom::Await => TriState::Unknown, // 12.1.1 Atom::Implements | Atom::Interface | Atom::Let | Atom::Package | Atom::Private | Atom::Protected | Atom::Public | Atom::Static | Atom::Yield => TriState::Yes, _ => TriState::No } } // 12.1.1 fn is_illegal_strict_binding(&self) -> bool { match *self { Atom::Arguments | Atom::Eval => true, _ => false } } }
impl AtomExt for Name { fn is_strict_reserved(&self) -> TriState {
random_line_split
atom.rs
use joker::word::{Atom, Name}; use tristate::TriState; pub trait AtomExt { fn is_strict_reserved(&self) -> TriState; fn is_illegal_strict_binding(&self) -> bool; } impl AtomExt for Name { fn is_strict_reserved(&self) -> TriState { match self { &Name::Atom(ref atom) => atom.is_strict_reserved(), _ => TriState::No } } fn
(&self) -> bool { match *self { Name::Atom(ref atom) => atom.is_illegal_strict_binding(), _ => false } } } impl AtomExt for Atom { fn is_strict_reserved(&self) -> TriState { match *self { // 11.6.2.2 Atom::Await => TriState::Unknown, // 12.1.1 Atom::Implements | Atom::Interface | Atom::Let | Atom::Package | Atom::Private | Atom::Protected | Atom::Public | Atom::Static | Atom::Yield => TriState::Yes, _ => TriState::No } } // 12.1.1 fn is_illegal_strict_binding(&self) -> bool { match *self { Atom::Arguments | Atom::Eval => true, _ => false } } }
is_illegal_strict_binding
identifier_name
atom.rs
use joker::word::{Atom, Name}; use tristate::TriState; pub trait AtomExt { fn is_strict_reserved(&self) -> TriState; fn is_illegal_strict_binding(&self) -> bool; } impl AtomExt for Name { fn is_strict_reserved(&self) -> TriState { match self { &Name::Atom(ref atom) => atom.is_strict_reserved(), _ => TriState::No } } fn is_illegal_strict_binding(&self) -> bool { match *self { Name::Atom(ref atom) => atom.is_illegal_strict_binding(), _ => false } } } impl AtomExt for Atom { fn is_strict_reserved(&self) -> TriState
// 12.1.1 fn is_illegal_strict_binding(&self) -> bool { match *self { Atom::Arguments | Atom::Eval => true, _ => false } } }
{ match *self { // 11.6.2.2 Atom::Await => TriState::Unknown, // 12.1.1 Atom::Implements | Atom::Interface | Atom::Let | Atom::Package | Atom::Private | Atom::Protected | Atom::Public | Atom::Static | Atom::Yield => TriState::Yes, _ => TriState::No } }
identifier_body
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn main() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo() > span.hi(). // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
// 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
random_line_split