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
ExceptionDecoService.js
'use strict'; angular .module('app.module') .factory('exception', exception); exception.$inject = ['logger']; function exception(logger)
/* angular //TODO: get back to this .module('blocks.exception') .config(exceptionConfig); exceptionConfig.$inject = ['$provide']; function exceptionConfig($provide) { $provide.decorator('$exceptionHandler', extendExceptionHandler); } extendExceptionHandler.$inject = ['$delegate']; function extendExcep...
{ var service = { catcher: catcher }; return service; function catcher(message) { return function(reason) { logger.error(message, reason); }; } }
identifier_body
ExceptionDecoService.js
'use strict'; angular .module('app.module') .factory('exception', exception); exception.$inject = ['logger']; function exception(logger) { var service = { catcher: catcher }; return service; function catcher(message) { return function(reason) { logger.error(message...
extendExceptionHandler.$inject = ['$delegate']; function extendExceptionHandler($delegate) { return function(exception, cause) { $delegate(exception, cause); var errorData = { exception: exception, cause: cause }; //toastr.error(exception.msg, errorData); ...
}
random_line_split
ExceptionDecoService.js
'use strict'; angular .module('app.module') .factory('exception', exception); exception.$inject = ['logger']; function exception(logger) { var service = { catcher: catcher }; return service; function
(message) { return function(reason) { logger.error(message, reason); }; } } /* angular //TODO: get back to this .module('blocks.exception') .config(exceptionConfig); exceptionConfig.$inject = ['$provide']; function exceptionConfig($provide) { $provide.decorator('$exception...
catcher
identifier_name
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
else { // No overflow, good to go (overflow1, ticks) } } /// Calculates the elapsed period in SysTicks between `start` and the current value. pub fn get_since(start: usize) -> usize { let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let de...
{ // A overflow occurred while we were reading the tick register // Should be safe to try again (overflow2, get_ticks()) }
conditional_block
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
lazy_static! { /// total number of times SysTick has wrapped pub static ref SYSTICK_WRAP_COUNT:AtomicUsize = ATOMIC_USIZE_INIT; } // **************************************************************************** // // Private Types // // **************************************************************************...
// // **************************************************************************** /// SysTick is a 24-bit timer pub const SYSTICK_MAX: usize = (1 << 24) - 1;
random_line_split
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
() { SYSTICK_WRAP_COUNT.fetch_add(1, Ordering::Relaxed); } /// Returns how many times SysTick has overflowed. pub fn get_overflows() -> usize { SYSTICK_WRAP_COUNT.load(Ordering::Relaxed) } /// Gets the current SysTick value pub fn get_ticks() -> usize { unsafe { (*cm_periph::SYST::ptr()).cvr.read() as usi...
isr
identifier_name
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since pow...
/// How long since the system booted in ticks. /// The u64 is good for 584,000 years. pub fn run_time_ticks() -> u64 { let (overflows, ticks) = get_overflows_ticks(); let mut result: u64; result = overflows as u64; result *= (SYSTICK_MAX + 1) as u64; result += (SYSTICK_MAX - ticks) as u64; res...
{ let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let delta = start.wrapping_sub(now) & SYSTICK_MAX; delta }
identifier_body
groupbox.py
from collections import namedtuple from cairo import LINE_JOIN_ROUND from zorro.di import di, dependency, has_dependencies from tilenol.groups import GroupManager from tilenol.commands import CommandDispatcher from .base import Widget from tilenol.theme import Theme from tilenol.window import Window GroupState = na...
(self, *, filled=False, first_letter=False, right=False): super().__init__(right=right) self.filled = filled self.first_letter = first_letter def __zorro_di_done__(self): self.state = di(self).inject(State()) bar = self.theme.bar self.font = bar.font self.ina...
__init__
identifier_name
groupbox.py
from collections import namedtuple from cairo import LINE_JOIN_ROUND from zorro.di import di, dependency, has_dependencies from tilenol.groups import GroupManager from tilenol.commands import CommandDispatcher from .base import Widget from tilenol.theme import Theme from tilenol.window import Window GroupState = na...
def __init__(self): self._state = None def dirty(self): return self._state != self._read() def update(self): nval = self._read() if nval != self._state: self._state = nval return True def _read(self): cur = self.commander.get('group') ...
commander = dependency(CommandDispatcher, 'commander') gman = dependency(GroupManager, 'group-manager')
random_line_split
groupbox.py
from collections import namedtuple from cairo import LINE_JOIN_ROUND from zorro.di import di, dependency, has_dependencies from tilenol.groups import GroupManager from tilenol.commands import CommandDispatcher from .base import Widget from tilenol.theme import Theme from tilenol.window import Window GroupState = na...
sx, sy, w, h, ax, ay = canvas.text_extents(gname) if gs.active: canvas.set_source(self.selected_color) if self.filled: canvas.rectangle(x, 0, ax + between, self.height) canvas.fill() else: ...
gname = gname[0]
conditional_block
groupbox.py
from collections import namedtuple from cairo import LINE_JOIN_ROUND from zorro.di import di, dependency, has_dependencies from tilenol.groups import GroupManager from tilenol.commands import CommandDispatcher from .base import Widget from tilenol.theme import Theme from tilenol.window import Window GroupState = na...
@property def groups(self): return self._state @has_dependencies class Groupbox(Widget): theme = dependency(Theme, 'theme') def __init__(self, *, filled=False, first_letter=False, right=False): super().__init__(right=right) self.filled = filled self.first_letter = f...
cur = self.commander.get('group') visgr = self.gman.current_groups.values() return tuple(GroupState(g.name, g.empty, g is cur, g in visgr, g.has_urgent_windows) for g in self.gman.groups)
identifier_body
dropdowndemo.ts
import {Component} from '@angular/core'; import {SelectItem} from '../../../components/common/api'; @Component({ templateUrl: 'showcase/demo/dropdown/dropdown.html', }) export class DropdownDemo { cities: SelectItem[]; selectedCity: any; cars: SelectItem[]; selectedCar: string; selecte...
() { this.cities = []; this.cities.push({label:'Select City', value:null}); this.cities.push({label:'New York', value:{id:1, name: 'New York', code: 'NY'}}); this.cities.push({label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}}); this.cities.push({label:'London', value:{id:3, n...
constructor
identifier_name
dropdowndemo.ts
import {Component} from '@angular/core'; import {SelectItem} from '../../../components/common/api'; @Component({ templateUrl: 'showcase/demo/dropdown/dropdown.html', }) export class DropdownDemo { cities: SelectItem[]; selectedCity: any; cars: SelectItem[]; selectedCar: string; selecte...
}
{ this.cities = []; this.cities.push({label:'Select City', value:null}); this.cities.push({label:'New York', value:{id:1, name: 'New York', code: 'NY'}}); this.cities.push({label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}}); this.cities.push({label:'London', value:{id:3, name...
identifier_body
dropdowndemo.ts
import {Component} from '@angular/core'; import {SelectItem} from '../../../components/common/api'; @Component({ templateUrl: 'showcase/demo/dropdown/dropdown.html', }) export class DropdownDemo { cities: SelectItem[]; selectedCity: any; cars: SelectItem[]; selectedCar: string; selecte...
this.cities.push({label:'Select City', value:null}); this.cities.push({label:'New York', value:{id:1, name: 'New York', code: 'NY'}}); this.cities.push({label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}}); this.cities.push({label:'London', value:{id:3, name: 'London', code: 'LDN'}}); ...
this.cities = [];
random_line_split
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql...
() { let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limi...
main
identifier_name
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql...
{ let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limit, ...
identifier_body
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql...
solidate_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), }; let calculate_threads = CalculateThreads { calculate_rx, mysql_uri, retry_interval, calculation_threads, calculation_limit, transaction_mapper: transaction_mapper.clone(), }; let zm...
transaction_mapper: transaction_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let solidate_thread = SolidateThread {
random_line_split
discriminant_value-wrapper.rs
// Copyright 2016 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 ...
Second(u64) } pub fn main() { assert!(mem::discriminant(&ADT::First(0,0)) == mem::discriminant(&ADT::First(1,1))); assert!(mem::discriminant(&ADT::Second(5)) == mem::discriminant(&ADT::Second(6))); assert!(mem::discriminant(&ADT::First(2,2)) != mem::discriminant(&ADT::Second(2))); let _ = mem::di...
enum ADT { First(u32, u32),
random_line_split
discriminant_value-wrapper.rs
// Copyright 2016 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 ...
{ First(u32, u32), Second(u64) } pub fn main() { assert!(mem::discriminant(&ADT::First(0,0)) == mem::discriminant(&ADT::First(1,1))); assert!(mem::discriminant(&ADT::Second(5)) == mem::discriminant(&ADT::Second(6))); assert!(mem::discriminant(&ADT::First(2,2)) != mem::discriminant(&ADT::Second(2)...
ADT
identifier_name
notes.module.ts
// (C) Copyright 2015 Moodle Pty Ltd. // // 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 agree...
(courseOptionsDelegate: CoreCourseOptionsDelegate, courseOptionHandler: AddonNotesCourseOptionHandler, userDelegate: CoreUserDelegate, userHandler: AddonNotesUserHandler, cronDelegate: CoreCronDelegate, syncHandler: AddonNotesSyncCronHandler) { // Register handlers. courseOption...
constructor
identifier_name
notes.module.ts
// (C) Copyright 2015 Moodle Pty Ltd. // // 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 agree...
} }
random_line_split
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
assert!(full_text.is_err()); // Delta doesn't match base_text let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\xFF\x00\x00\x01\x00\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); } }
b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adelta", ]; let full_text = get_full_text(&base_text[..], &deltas);
random_line_split
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
#[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My deltafied data", full_text[..]...
{ let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); }
identifier_body
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
unsafe { let patch: *mut mpatch_flist = mpatch_fold( deltas as *const Vec<&[u8]> as *mut c_void, Some(get_next_link), 0, deltas.len() as isize, ); if patch.is_null() { return Err("mpatch failed to process the deltas"); } ...
{ return Ok(base_text.to_vec()); }
conditional_block
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_lin...
() { let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\...
no_deltas_empty_base
identifier_name
feedback.js
$(function() { $.getJSON('api', updateFeedback); $('.feedback-form').submit(function(e) { e.preventDefault(); $.post('api', { name: $('#feedback-form-name').val(), title: $('#feedback-form-title').val(), message: $('#feedback-form-message').val() }, updateFeedback); }); $('.feedb...
});
{ var output = ''; $.each(data,function(key, item) { output += ' <div class="feedback-item item-list media-list">'; output += ' <div class="feedback-item media">'; output += ' <div class="media-left"><button class="feedback-delete btn btn-xs btn-danger"><span id="' + key + '" class=...
identifier_body
feedback.js
$(function() { $.getJSON('api', updateFeedback); $('.feedback-form').submit(function(e) { e.preventDefault(); $.post('api', { name: $('#feedback-form-name').val(), title: $('#feedback-form-title').val(), message: $('#feedback-form-message').val() }, updateFeedback); }); $('.feedb...
var output = ''; $.each(data,function(key, item) { output += ' <div class="feedback-item item-list media-list">'; output += ' <div class="feedback-item media">'; output += ' <div class="media-left"><button class="feedback-delete btn btn-xs btn-danger"><span id="' + key + '" class="g...
}); //ajax } // the target is a delete button }); //feedback messages function updateFeedback(data) {
random_line_split
feedback.js
$(function() { $.getJSON('api', updateFeedback); $('.feedback-form').submit(function(e) { e.preventDefault(); $.post('api', { name: $('#feedback-form-name').val(), title: $('#feedback-form-title').val(), message: $('#feedback-form-message').val() }, updateFeedback); }); $('.feedb...
(data) { var output = ''; $.each(data,function(key, item) { output += ' <div class="feedback-item item-list media-list">'; output += ' <div class="feedback-item media">'; output += ' <div class="media-left"><button class="feedback-delete btn btn-xs btn-danger"><span id="' + key + '"...
updateFeedback
identifier_name
feedback.js
$(function() { $.getJSON('api', updateFeedback); $('.feedback-form').submit(function(e) { e.preventDefault(); $.post('api', { name: $('#feedback-form-name').val(), title: $('#feedback-form-title').val(), message: $('#feedback-form-message').val() }, updateFeedback); }); $('.feedb...
}); //feedback messages function updateFeedback(data) { var output = ''; $.each(data,function(key, item) { output += ' <div class="feedback-item item-list media-list">'; output += ' <div class="feedback-item media">'; output += ' <div class="media-left"><button class="feedback...
{ $.ajax({ url: 'api/' + e.target.id, type: 'DELETE', success: updateFeedback }); //ajax } // the target is a delete button
conditional_block
web_reserver-bak.py
import web import json import datetime import time import uuid #from mimerender import mimerender #import mimerender from onsa_jeroen import * render_xml = lambda result: "<result>%s</result>"%result render_json = lambda **result: json.dumps(result,sort_keys=True,indent=4) render_html = lambda result: "<html><body>%s<...
print query("uva4k") #if __name__ == "__main__":
global result client,client_nsa = createClient() nsa = getNSA(nsa) qr = yield client.query(client_nsa, nsa, None, "Summary", connection_ids = [] ) #result = qr result = "blaaa"
identifier_body
web_reserver-bak.py
import web import json import datetime import time import uuid #from mimerender import mimerender #import mimerender from onsa_jeroen import * render_xml = lambda result: "<result>%s</result>"%result render_json = lambda **result: json.dumps(result,sort_keys=True,indent=4) render_html = lambda result: "<html><body>%s<...
(*args, **kwargs): global result d=defer.maybeDeferred(func, *args, **kwargs) while 1: reactor.doSelect(1) print result time.sleep(1) #return result return sync_func @syncmyCall @defer.inlineCallbacks def query (nsa): global result c...
sync_func
identifier_name
web_reserver-bak.py
import web import json import datetime import time import uuid #from mimerender import mimerender #import mimerender from onsa_jeroen import * render_xml = lambda result: "<result>%s</result>"%result render_json = lambda **result: json.dumps(result,sort_keys=True,indent=4) render_html = lambda result: "<html><body>%s<...
client,client_nsa = createClient() nsa = getNSA(nsa) qr = yield client.query(client_nsa, nsa, None, "Summary", connection_ids = [] ) #result = qr result = "blaaa" print query("uva4k") #if __name__ == "__main__":
@syncmyCall @defer.inlineCallbacks def query (nsa): global result
random_line_split
web_reserver-bak.py
import web import json import datetime import time import uuid #from mimerender import mimerender #import mimerender from onsa_jeroen import * render_xml = lambda result: "<result>%s</result>"%result render_json = lambda **result: json.dumps(result,sort_keys=True,indent=4) render_html = lambda result: "<html><body>%s<...
return sync_func @syncmyCall @defer.inlineCallbacks def query (nsa): global result client,client_nsa = createClient() nsa = getNSA(nsa) qr = yield client.query(client_nsa, nsa, None, "Summary", connection_ids = [] ) #result = qr result = "blaaa" print query("uva4k") #if __name__ == "__mai...
reactor.doSelect(1) print result time.sleep(1) #return result
conditional_block
histogram_dataselect_page.py
import sys #from functools import partial from PyQt4 import QtCore, QtGui from PyQt4.Qt import * from ome_globals import * import ui_histogram_dataselect_page class HistogramDataSelectPage(QWizardPage, ui_histogram_dataselect_page.Ui_WizardPage): def __init__(self, model, prev_hist_var=None, parent=None): ...
(self): return True def get_selected_var(self): idx = self.comboBox.currentIndex() data = self.comboBox.itemData(idx) col = data.toInt()[0] return self.model.get_variable_assigned_to_column(col)
isComplete
identifier_name
histogram_dataselect_page.py
import sys #from functools import partial from PyQt4 import QtCore, QtGui from PyQt4.Qt import * from ome_globals import * import ui_histogram_dataselect_page class HistogramDataSelectPage(QWizardPage, ui_histogram_dataselect_page.Ui_WizardPage): def __init__(self, model, prev_hist_var=None, parent=None): ...
# set default selection if given self.comboBox.setCurrentIndex(default_index) self.completeChanged.emit() def isComplete(self): return True def get_selected_var(self): idx = self.comboBox.currentIndex() data = self.comboBox.itemData(idx...
default_index = index_of_item
conditional_block
histogram_dataselect_page.py
import sys #from functools import partial from PyQt4 import QtCore, QtGui from PyQt4.Qt import * from ome_globals import * import ui_histogram_dataselect_page class HistogramDataSelectPage(QWizardPage, ui_histogram_dataselect_page.Ui_WizardPage): def __init__(self, model, prev_hist_var=None, parent=None): ...
return True def get_selected_var(self): idx = self.comboBox.currentIndex() data = self.comboBox.itemData(idx) col = data.toInt()[0] return self.model.get_variable_assigned_to_column(col)
def isComplete(self):
random_line_split
histogram_dataselect_page.py
import sys #from functools import partial from PyQt4 import QtCore, QtGui from PyQt4.Qt import * from ome_globals import * import ui_histogram_dataselect_page class HistogramDataSelectPage(QWizardPage, ui_histogram_dataselect_page.Ui_WizardPage):
def __init__(self, model, prev_hist_var=None, parent=None): super(HistogramDataSelectPage, self).__init__(parent) self.setupUi(self) self.model = model self.prev_hist_var = prev_hist_var self._populate_combo_box() def _populate_combo_box(self): ...
identifier_body
units.py
order = ['','K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] class Sizes(object): _BASE = 1000. def toSize(self, value, input='', output='K'): """ Convert value in other measurement """ input = order.index(input) output = order.index(output) factor = input - output ...
output = order[output] return self.toSize(value, input, output), output class Bytes(Sizes): _BASE = 1024.
output = 0
conditional_block
units.py
order = ['','K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] class Sizes(object): _BASE = 1000. def toSize(self, value, input='', output='K'): """ Convert value in other measurement """ input = order.index(input) output = order.index(output) factor = input - output ...
output = len(order) - 1 elif output < 0: output = 0 output = order[output] return self.toSize(value, input, output), output class Bytes(Sizes): _BASE = 1024.
if output > len(order):
random_line_split
units.py
order = ['','K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] class Sizes(object): _BASE = 1000. def
(self, value, input='', output='K'): """ Convert value in other measurement """ input = order.index(input) output = order.index(output) factor = input - output return value * (self._BASE ** factor) def converToBestUnit(self, value, input=''): devider ...
toSize
identifier_name
units.py
order = ['','K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] class Sizes(object): _BASE = 1000. def toSize(self, value, input='', output='K'): """ Convert value in other measurement """ input = order.index(input) output = order.index(output) factor = input - output ...
_BASE = 1024.
identifier_body
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_ident...
} pub fn id(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) ...
scoped_idents: Default::default(), shaped_idents: Default::default(), element_bindings: Default::default(), }
random_line_split
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_ident...
pub fn add_element_binding( &mut self, key: String, common_binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.element_bindings.insert(key, common_binding); Ok(()) } pub fn get_element_binding(&mut self, key: &str) -> Option<CommonBindings<T>> ...
{ self.shaped_idents.get(key).map(|v| v.to_owned()) }
identifier_body
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_ident...
(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) -> Option<CommonBind...
id
identifier_name
console.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for console input and output. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import codecs import locale import re import math import multiprocessing i...
tchWindows(object): def __init__(self): import msvcrt # pylint: disable=W0611 def __call__(self): import msvcrt return msvcrt.getch() class _GetchMacCarbon(object): """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string i...
(self): import tty # pylint: disable=W0611 import sys # pylint: disable=W0611 # import termios now or else you'll get the Unix # version on the Mac import termios # pylint: disable=W0611 def __call__(self): import sys import tty import termios ...
identifier_body
console.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for console input and output. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import codecs import locale import re import math import multiprocessing i...
pass return get_ipython @classproperty def OutStream(cls): if not hasattr(cls, '_OutStream'): cls._OutStream = None try: cls.get_ipython() except NameError: return None try: from ipykern...
except ImportError:
random_line_split
console.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for console input and output. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import codecs import locale import re import math import multiprocessing i...
return results class Spinner(object): """ A class to display a spinner in the terminal. It is designed to be used with the ``with`` statement:: with Spinner("Reticulating splines", "green") as s: for item in enumerate(items): s.next() """ _default_un...
p = multiprocessing.Pool() for i, result in enumerate( p.imap_unordered(function, items, chunksize=chunksize)): bar.update(i) results.append(result) p.close() p.join()
conditional_block
console.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for console input and output. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import codecs import locale import re import math import multiprocessing i...
xc_type, exc_value, traceback): return self._obj.__exit__(exc_type, exc_value, traceback) def update(self, value): """ Update the progress bar to the given value (out of the total given to the constructor. """ if self._is_spinner: next(self._iter) ...
(self, e
identifier_name
parse_csvn.py
#!/usr/bin/env python # Copyright (c) 2015, Scott D. Peckham #------------------------------------------------------ # S.D. Peckham # July 9, 2015 # # Tool to break CSDMS Standard Variable Names into # all of their component parts, then save results in # various formats. (e.g. Turtle TTL format) # # Example of use at...
( in_file='CSN_VarNames_v0.83.txt' ): #-------------------------------------------------- # Open input file that contains copied names table #-------------------------------------------------- try: in_unit = open( in_file, 'r' ) except: print 'SORRY: Could not open TXT file named:' ...
parse_names
identifier_name
parse_csvn.py
#!/usr/bin/env python # Copyright (c) 2015, Scott D. Peckham #------------------------------------------------------ # S.D. Peckham # July 9, 2015 # # Tool to break CSDMS Standard Variable Names into # all of their component parts, then save results in # various formats. (e.g. Turtle TTL format) # # Example of use at...
# parse_names() #------------------------------------------------------ if (__name__ == "__main__"): #----------------------------------------------------- # Note: First arg in sys.argv is the command itself. #----------------------------------------------------- n_args = ...
try: in_unit = open( in_file, 'r' ) except: print 'SORRY: Could not open TXT file named:' print ' ' + in_file #------------------------- # Open new CSV text file #------------------------- ## pos = in_file.rfind('.') ## prefix = in_file[0:pos] ## out_file ...
identifier_body
parse_csvn.py
#!/usr/bin/env python # Copyright (c) 2015, Scott D. Peckham #------------------------------------------------------ # S.D. Peckham # July 9, 2015 # # Tool to break CSDMS Standard Variable Names into # all of their component parts, then save results in # various formats. (e.g. Turtle TTL format) # # Example of use at...
else: print 'ERROR: Invalid number of arguments.' #-----------------------------------------------------------------------
parse_names( sys.argv[1] )
conditional_block
parse_csvn.py
#!/usr/bin/env python # Copyright (c) 2015, Scott D. Peckham #------------------------------------------------------ # S.D. Peckham # July 9, 2015 # # Tool to break CSDMS Standard Variable Names into # all of their component parts, then save results in # various formats. (e.g. Turtle TTL format) # # Example of use at...
#------------------------ # Write TTL file header #------------------------ out_unit.write( '@prefix dc: <http://purl.org/dc/elements/1.1/> .' + '\n' ) out_unit.write( '@prefix ns: <http://example.org/ns#> .' + '\n' ) out_unit.write( '@prefix vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> ...
return out_unit = open( out_file, 'w' )
random_line_split
ex6.py
#!/usr/bin/env python ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. ''' from netmiko import ConnectHandler from getpass import getpass from routers import pynet_rtr1, pynet_rtr2, pynet_jnpr_srx1 def
(): ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. ''' ip_address = raw_input("Please enter IP: ") password = getpass() pynet_rtr1['ip'] = ip_address pynet_rtr2['ip'] = ip_address pynet_jnpr_srx1['ip'] = ip_address pynet_rtr1['password'] = passw...
main
identifier_name
ex6.py
#!/usr/bin/env python ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. ''' from netmiko import ConnectHandler from getpass import getpass from routers import pynet_rtr1, pynet_rtr2, pynet_jnpr_srx1 def main(): ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, an...
main()
conditional_block
ex6.py
#!/usr/bin/env python ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. ''' from netmiko import ConnectHandler from getpass import getpass from routers import pynet_rtr1, pynet_rtr2, pynet_jnpr_srx1 def main(): ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, an...
main()
print ">>> {}: \n".format(ssh_conn.ip) print output print ">>>\n" if __name__ == '__main__':
random_line_split
ex6.py
#!/usr/bin/env python ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. ''' from netmiko import ConnectHandler from getpass import getpass from routers import pynet_rtr1, pynet_rtr2, pynet_jnpr_srx1 def main():
if __name__ == '__main__': main()
''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. ''' ip_address = raw_input("Please enter IP: ") password = getpass() pynet_rtr1['ip'] = ip_address pynet_rtr2['ip'] = ip_address pynet_jnpr_srx1['ip'] = ip_address pynet_rtr1['password'] = password ...
identifier_body
mitele.py
import logging import re from streamlink.plugin import Plugin from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json log = logging.getLogger(__name__) class Mitele(Plugin): _url_re = re.compile(r"ht...
gdata = self.session.http.post(self.gate_url, acceptable_status=(200, 403, 404), data=pdata, schema=self.gate_schema) log.trace("{0!r}".format(gdata)) if gdata.get("code"): ...
log.error("{0} - {1}".format(pdata["code"], pdata["message"])) return
conditional_block
mitele.py
import logging import re from streamlink.plugin import Plugin from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json log = logging.getLogger(__name__) class Mitele(Plugin): _url_re = re.compile(r"ht...
}, validate.get("locations"), validate.get(0), ), error_schema, )) gate_schema = validate.Schema( validate.transform(parse_json), validate.any( { "mimeType": validate.text, "stream": validate.url(), ...
"ogn": validate.any(None, validate.text), }],
random_line_split
mitele.py
import logging import re from streamlink.plugin import Plugin from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json log = logging.getLogger(__name__) class Mitele(Plugin): _url_re = re.compile(r"ht...
@classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None def _get_streams(self): channel = self._url_re.match(self.url).group("channel") pdata = self.session.http.get(self.pdata_url.format(channel=channel), accepta...
super(Mitele, self).__init__(url) self.session.http.headers.update({ "User-Agent": useragents.FIREFOX, "Referer": self.url })
identifier_body
mitele.py
import logging import re from streamlink.plugin import Plugin from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json log = logging.getLogger(__name__) class Mitele(Plugin): _url_re = re.compile(r"ht...
(self): channel = self._url_re.match(self.url).group("channel") pdata = self.session.http.get(self.pdata_url.format(channel=channel), acceptable_status=(200, 403, 404), schema=self.pdata_schema) log.trace("{0!r}".format...
_get_streams
identifier_name
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (...
impl<'a> Invocation<'a> { pub fn new(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).e...
opts: &'a [String], }
random_line_split
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (...
pub fn run(&self) { use std::io::fs::File; use serialize::ebml::reader::Decoder; use serialize::ebml::Doc; // don't try-block this; if we can't read the state file, we really do need to fail!(). let state = { let state_bytes = try!({try!(File::open(self.state_fi...
{ Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is more than likely a bug"), opts: opts, } }
identifier_body
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (...
Cxx => { } Ar => { } Ld => { } } } }
{ }
conditional_block
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (...
(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is m...
new
identifier_name
Maze.py
# Copyright 2010 by Dana Larose # This file is part of crashRun. # crashRun 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. # crashR...
if self.length % 2 == 0: self.length -= 1 self.map = [] self.__tf = TerrainFactory() self.__ds_nodes = [] self.__wall = self.__tf.get_terrain_tile(CYBERSPACE_WALL) self.__floor = self.__tf.get_terrain_tile(CYBERSPACE_FLOOR) self.__gen_initial_map() ...
self.width -= 1
conditional_block
Maze.py
# Copyright 2010 by Dana Larose # This file is part of crashRun. # crashRun 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
# GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with crashRun. If not, see <http://www.gnu.org/licenses/>. from random import choice from .DisjointSet import DSNode from .DisjointSet import union from .DisjointSet import find from .DisjointS...
# (at your option) any later version. # crashRun 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
random_line_split
Maze.py
# Copyright 2010 by Dana Larose # This file is part of crashRun. # crashRun 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. # crashR...
def __get_candidate(self, node): _candidates = [] _nr = node.value[0] _nc = node.value[1] if self.in_bounds(_nr - 2, _nc) and self.map[_nr-1][_nc].get_type() == CYBERSPACE_WALL: _c_node = self.__ds_nodes[_nr//2-1][_nc//2] if find(_c_node) !=...
return row >= 0 and row < self.length and col >= 0 and col < self.width
identifier_body
Maze.py
# Copyright 2010 by Dana Larose # This file is part of crashRun. # crashRun 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. # crashR...
(self, node): _candidates = [] _nr = node.value[0] _nc = node.value[1] if self.in_bounds(_nr - 2, _nc) and self.map[_nr-1][_nc].get_type() == CYBERSPACE_WALL: _c_node = self.__ds_nodes[_nr//2-1][_nc//2] if find(_c_node) != find(node): _can...
__get_candidate
identifier_name
views.py
from d51.django.auth.decorators import auth_required from django.contrib.sites.models import Site from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ImproperlyConfigured from .services import...
url=full_url_to_share, ) try: url.send(service_name, request.user, request.POST) except SharingServiceInvalidForm: service = load_service(service_name, url) input = [] if request.method != 'POST' else [request.POST] form = service.g...
else: full_url_to_share = 'http://%s%s' % ((Site.objects.get_current().domain, url_to_share)) if url_to_share.find(':') == -1 else url_to_share url, created = URL.objects.get_or_create(
random_line_split
views.py
from d51.django.auth.decorators import auth_required from django.contrib.sites.models import Site from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ImproperlyConfigured from .services import...
response = HttpResponseRedirect(request.GET.get('next', '/')) url_to_share = request.GET.get(SHARE_KEY, None) if url_to_share is None: # TODO change to a 400 raise Http404 else: full_url_to_share = 'http://%s%s' % ((Site.objects.get_current().domain, url_to_share)) if url_to_share.f...
identifier_body
views.py
from d51.django.auth.decorators import auth_required from django.contrib.sites.models import Site from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ImproperlyConfigured from .services import...
(request, service_name): # TODO: this view needs testing response = HttpResponseRedirect(request.GET.get('next', '/')) url_to_share = request.GET.get(SHARE_KEY, None) if url_to_share is None: # TODO change to a 400 raise Http404 else: full_url_to_share = 'http://%s%s' % ((S...
share_url
identifier_name
views.py
from d51.django.auth.decorators import auth_required from django.contrib.sites.models import Site from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ImproperlyConfigured from .services import...
return response
full_url_to_share = 'http://%s%s' % ((Site.objects.get_current().domain, url_to_share)) if url_to_share.find(':') == -1 else url_to_share url, created = URL.objects.get_or_create( url=full_url_to_share, ) try: url.send(service_name, request.user, request.POST) ...
conditional_block
cursor.py
# coding=utf-8 """cursor.py - Cursor handler.""" from __future__ import absolute_import import gobject import gtk NORMAL, GRAB, WAIT = range(3) class CursorHandler(object): def __init__(self, window): self._window = window self._timer_id = None self._auto_hide = False self._curre...
elif cursor == GRAB: mode = gtk.gdk.Cursor(gtk.gdk.FLEUR) elif cursor == WAIT: mode = gtk.gdk.Cursor(gtk.gdk.WATCH) else: mode = cursor self._window.set_cursor(mode) self._current_cursor = cursor if self._auto_hide: if curs...
mode = None
conditional_block
cursor.py
# coding=utf-8 """cursor.py - Cursor handler.""" from __future__ import absolute_import import gobject import gtk NORMAL, GRAB, WAIT = range(3) class CursorHandler(object): def __init__(self, window): self._window = window self._timer_id = None self._auto_hide = False self._curre...
def auto_hide_off(self): """Signal that the cursor should *not* auto-hide from now on.""" self._auto_hide = False self._kill_timer() if self._current_cursor == NORMAL: self.set_cursor_type(NORMAL) def refresh(self): """Refresh the current cursor (i.e. displ...
"""Signal that the cursor should auto-hide from now on (e.g. that we are entering fullscreen). """ self._auto_hide = True if self._current_cursor == NORMAL: self._set_hide_timer()
identifier_body
cursor.py
# coding=utf-8 """cursor.py - Cursor handler.""" from __future__ import absolute_import import gobject import gtk NORMAL, GRAB, WAIT = range(3) class CursorHandler(object): def __init__(self, window): self._window = window self._timer_id = None self._auto_hide = False self._curre...
we are entering fullscreen). """ self._auto_hide = True if self._current_cursor == NORMAL: self._set_hide_timer() def auto_hide_off(self): """Signal that the cursor should *not* auto-hide from now on.""" self._auto_hide = False self._kill_timer() ...
def auto_hide_on(self): """Signal that the cursor should auto-hide from now on (e.g. that
random_line_split
cursor.py
# coding=utf-8 """cursor.py - Cursor handler.""" from __future__ import absolute_import import gobject import gtk NORMAL, GRAB, WAIT = range(3) class CursorHandler(object): def
(self, window): self._window = window self._timer_id = None self._auto_hide = False self._current_cursor = NORMAL def set_cursor_type(self, cursor): """Set the cursor to type <cursor>. Supported cursor types are available as constants in this module. If <cursor> is n...
__init__
identifier_name
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target
{ Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), ...
identifier_body
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn
() -> Target { Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string()...
target
identifier_name
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target {
options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), env: "newlib".to_string(), vendor: "espressif".to_string(), linker_flavor: LinkerFlavor::Gcc, linker: Some("riscv32-esp-elf-gcc".to_string()), ...
Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(),
random_line_split
build.rs
extern crate rustc_version; extern crate rusoto_codegen; extern crate rayon; use std::env; use std::path::Path; use std::io::Write; use std::fs::File; use rusoto_codegen::{Service, generate}; use rayon::prelude::*; /// Parses and generates variables used to construct a User-Agent. /// /// This is used to create a Us...
["sqs", "2012-11-05"], ["ssm", "2014-11-06"], ["storagegateway", "2013-06-30"], ["sts", "2011-06-15"], ["swf", "2012-01-25"], ["waf", "2015-08-24"], ["workspaces", "2015-04-08"] }; let count: usize = services.into_par_iter().map(|service| generate(service...
["s3", "2006-03-01"], ["sdb", "2009-04-15"], ["sns", "2010-03-31"],
random_line_split
build.rs
extern crate rustc_version; extern crate rusoto_codegen; extern crate rayon; use std::env; use std::path::Path; use std::io::Write; use std::fs::File; use rusoto_codegen::{Service, generate}; use rayon::prelude::*; /// Parses and generates variables used to construct a User-Agent. /// /// This is used to create a Us...
/* gamelift/2015-10-01/service-2.json: "protocol":"json" support/2013-04-15/service-2.json: "protocol":"json" */ // expand to use cfg!() so codegen only gets run for services // in the features list macro_rules! services { ( $( [$name:expr, $date:expr] ),* ) => { { let mut services = Ve...
{ let rust_version = rustc_version::version(); let mut f = File::create(&output_path.join("user_agent_vars.rs")) .expect("Could not create user agent file"); f.write_all(format!("static RUST_VERSION: &'static str = \"{}\";", rust_version).as_bytes()) .expect("Unable to write user age...
identifier_body
build.rs
extern crate rustc_version; extern crate rusoto_codegen; extern crate rayon; use std::env; use std::path::Path; use std::io::Write; use std::fs::File; use rusoto_codegen::{Service, generate}; use rayon::prelude::*; /// Parses and generates variables used to construct a User-Agent. /// /// This is used to create a Us...
}
{ println!("cargo:rerun-if-changed=codegen"); }
conditional_block
build.rs
extern crate rustc_version; extern crate rusoto_codegen; extern crate rayon; use std::env; use std::path::Path; use std::io::Write; use std::fs::File; use rusoto_codegen::{Service, generate}; use rayon::prelude::*; /// Parses and generates variables used to construct a User-Agent. /// /// This is used to create a Us...
(output_path: &Path) { let rust_version = rustc_version::version(); let mut f = File::create(&output_path.join("user_agent_vars.rs")) .expect("Could not create user agent file"); f.write_all(format!("static RUST_VERSION: &'static str = \"{}\";", rust_version).as_bytes()) .expect("Una...
generate_user_agent_vars
identifier_name
jquery.slideshow.js
/* * Source: http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/ */ $(document).ready(function(){ var currentPosition = 0; var slideWidth = 560; var slides = $('.slide'); var numberOfSlides = slides.length; // Remove scrollbar in JS $('#...
});
{ // Hide left arrow if position is first slide if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() } // Hide right arrow if position is last slide if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() } }
identifier_body
jquery.slideshow.js
/* * Source: http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/ */ $(document).ready(function(){ var currentPosition = 0; var slideWidth = 560; var slides = $('.slide'); var numberOfSlides = slides.length; // Remove scrollbar in JS $('#...
(position){ // Hide left arrow if position is first slide if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() } // Hide right arrow if position is last slide if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() } } });
manageControls
identifier_name
jquery.slideshow.js
/* * Source: http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/ */ $(document).ready(function(){ var currentPosition = 0; var slideWidth = 560; var slides = $('.slide'); var numberOfSlides = slides.length; // Remove scrollbar in JS $('#...
else{ $('#rightControl').show() } } });
{ $('#rightControl').hide() }
conditional_block
jquery.slideshow.js
/* * Source: http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/ */ $(document).ready(function(){ var currentPosition = 0; var slideWidth = 560; var slides = $('.slide'); var numberOfSlides = slides.length; // Remove scrollbar in JS $('#...
$('#slideInner').css('width', slideWidth * numberOfSlides); // Insert left and right arrow controls in the DOM $('#slideshow') .prepend('<span class="control" id="leftControl">Move left</span>') .append('<span class="control" id="rightControl">Move right</span>'); // Hide left arrow control on ...
// Set #slideInner width equal to total width of all slides
random_line_split
p041.rs
//! [Problem 41](https://projecteuler.net/problem=41) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use integer::Integer; use iter::Permutations; use prime::PrimeSet; // 1 + 2 + ... + 9 = 45 (dividable by 9 => 9-pandig...
() -> String { compute().to_string() } common::problem!("7652413", solve);
solve
identifier_name
p041.rs
//! [Problem 41](https://projecteuler.net/problem=41) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use integer::Integer; use iter::Permutations; use prime::PrimeSet; // 1 + 2 + ... + 9 = 45 (dividable by 9 => 9-pandig...
} unreachable!() } fn solve() -> String { compute().to_string() } common::problem!("7652413", solve);
{ return n; }
conditional_block
p041.rs
//! [Problem 41](https://projecteuler.net/problem=41) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use integer::Integer; use iter::Permutations; use prime::PrimeSet; // 1 + 2 + ... + 9 = 45 (dividable by 9 => 9-pandig...
fn solve() -> String { compute().to_string() } common::problem!("7652413", solve);
{ let radix = 10; let ps = PrimeSet::new(); for (perm, _) in Permutations::new(&[7, 6, 5, 4, 3, 2, 1], 7) { let n = Integer::from_digits(perm.iter().rev().copied(), radix); if ps.contains(n) { return n; } } unreachable!() }
identifier_body
CP.py
#!/usr/bin/env python3 import os import sys thispath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper")) from MiscFxns import * from StandardModules import * import pulsar_psi4 def ApplyBasis(syst,bsname,bslabel="primary"): return psr.system.apply_si...
return AllGood def Run(mm): try: tester = psr.testing.Tester("Testing Boys and Bernardi CP") tester.print_header() pulsar_psi4.pulsar_psi4_setup(mm) LoadDefaultModules(mm) mm.change_option("PSI4_SCF","BASIS_SET","sto-3g") mm.change_option("PSR_CP","METHOD","PSI4_...
AllGood=AllGood and CorrectGrad[i]-GradIn[i]<0.00001
conditional_block
CP.py
#!/usr/bin/env python3 import os import sys thispath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper")) from MiscFxns import * from StandardModules import * import pulsar_psi4 def ApplyBasis(syst,bsname,bslabel="primary"):
def CompareEgy(EgyIn): return abs(EgyIn+224.89287653924677)<0.00001 def CompareGrad(GradIn): CorrectGrad=[ -0.000988976949000001, 0.0004443157829999993, 0.05238342271999999, 0.018237358511, -0.002547005771, -0.030731839919000005, -0.02344281975, -0.0062568701740000005, -0.025360880303, -0.0...
return psr.system.apply_single_basis(bslabel,bsname,syst)
identifier_body
CP.py
#!/usr/bin/env python3 import os import sys thispath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper")) from MiscFxns import * from StandardModules import * import pulsar_psi4 def ApplyBasis(syst,bsname,bslabel="primary"): return psr.system.apply_si...
NewWfn,Egy=MyMod.deriv(0,wfn) tester.test("Testing CP Energy via Deriv(0)", True, CompareEgy, Egy[0]) NewWfn,Egy=MyMod.energy(wfn) tester.test("Testing CP Energy via Energy()", True, CompareEgy, Egy) NewWfn,Egy=MyMod.deriv(1,wfn) tester.test("Testing CP Gradient via Deriv...
wfn=psr.datastore.Wavefunction() wfn.system=mol MyMod=mm.get_module("PSR_CP",0)
random_line_split
CP.py
#!/usr/bin/env python3 import os import sys thispath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper")) from MiscFxns import * from StandardModules import * import pulsar_psi4 def
(syst,bsname,bslabel="primary"): return psr.system.apply_single_basis(bslabel,bsname,syst) def CompareEgy(EgyIn): return abs(EgyIn+224.89287653924677)<0.00001 def CompareGrad(GradIn): CorrectGrad=[ -0.000988976949000001, 0.0004443157829999993, 0.05238342271999999, 0.018237358511, -0.002547005771, ...
ApplyBasis
identifier_name
gear.controller.js
(function() { 'use strict'; angular.module('character-tracker.charactersheet') .controller('GearController', GearController); GearController.$inject =['GearService', 'InventoryService', '$scope']; function GearController(GearService, InventoryService, $scope)
}());
{ var vm = this; var currentItem = ''; vm.inventory = InventoryService.getItems(); vm.gearSlots = GearService.getGearSlots(); vm.equipItem = function (item, slot){ if (item.equipped) { vm.unequipItem(item); } for (i = 0; i < vm.gearSlots.length; i++) {...
identifier_body
gear.controller.js
(function() { 'use strict'; angular.module('character-tracker.charactersheet') .controller('GearController', GearController); GearController.$inject =['GearService', 'InventoryService', '$scope']; function GearController(GearService, InventoryService, $scope) { var vm = this; var currentItem ...
InventoryService.equipItem(item); } vm.unequipItem = function(item) { for (i = 0; i < vm.gearSlots.length; i++) { if (vm.gearSlots[i].equippedItem == item) { vm.gearSlots[i].equippedItem = {}; } InventoryService.unequipItem(item); } } vm.get...
{ if (vm.gearSlots[i].slot === slot) { vm.gearSlots[i].equipped = true; vm.gearSlots[i].equippedItem = item; } }
conditional_block
gear.controller.js
(function() { 'use strict'; angular.module('character-tracker.charactersheet') .controller('GearController', GearController); GearController.$inject =['GearService', 'InventoryService', '$scope']; function
(GearService, InventoryService, $scope) { var vm = this; var currentItem = ''; vm.inventory = InventoryService.getItems(); vm.gearSlots = GearService.getGearSlots(); vm.equipItem = function (item, slot){ if (item.equipped) { vm.unequipItem(item); } for...
GearController
identifier_name
gear.controller.js
(function() { 'use strict'; angular.module('character-tracker.charactersheet') .controller('GearController', GearController); GearController.$inject =['GearService', 'InventoryService', '$scope']; function GearController(GearService, InventoryService, $scope) { var vm = this; var currentItem ...
if (vm.gearSlots[i].slot === slot) { vm.gearSlots[i].equipped = true; vm.gearSlots[i].equippedItem = item; } } InventoryService.equipItem(item); } vm.unequipItem = function(item) { for (i = 0; i < vm.gearSlots.length; i++) { if (vm.gearSlots[i]....
vm.unequipItem(item); } for (i = 0; i < vm.gearSlots.length; i++) {
random_line_split
line.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
impl Extend<String> for LineCollection { fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) { for item in iter { self.add(item); } self.clear_excess(); } } pub struct ParserState<'a, I> where I: DoubleEndedIterator<Item = &'a Line> { iterator: I, pa...
random_line_split
line.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later ve...
{ pub content_without_ansi: String, pub components: Option<ComponentCollection>, pub width: usize, } impl Line { pub fn new(content: String) -> Line { let has_ansi = content.has_ansi_escape_sequence(); let (content_without_ansi, components) = if has_ansi { (content.strip_a...
Line
identifier_name