file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
node_item.py
__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(s...
if self.material == 'wood': return 0 elif self.material == 'clay': return 1 elif self.material == 'stone': return 2 def describe(self): return u"\u25A1" # white square (unicode) class StableItem(FieldNodeItem): """ A stable on the play...
""" A single room on a player's field board """ MATERIAL_CHOICES = frozenset(['wood', 'stone', 'clay']) def __init__(self, material='wood'): super(RoomItem, self).__init__() if material not in self.MATERIAL_CHOICES: raise ValueError('Invalid material %s not in %s' % (materia...
identifier_body
elision.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 ...
} fn main() { }
{ unimplemented!() }
identifier_body
elision.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 ...
() { }
main
identifier_name
elision.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 ...
fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>; } impl UnicodeStr for str { #[inline] fn split_whitespace(&self) -> SplitWhitespace { unimplemented!() } } fn main() { }
pub trait UnicodeStr {
random_line_split
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
} #[cfg(target_os = "macos")] mod inner { use std::ffi::OsString; use crate::common::ui::{UIWriter, UI}; use crate::error::{Error, Result}; pub async fn start(ui: &mut UI, _args: &[OsString], export_cmd...
{ crypto::init()?; let ident = match henv::var(export_pkg_ident_envvar) { Ok(ref ident_str) => PackageIdent::from_str(ident_str)?, Err(_) => { let version: Vec<&str> = VERSION.split('/').collect(); PackageIdent::from_str(&format!("{}/{}", export_pk...
identifier_body
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
pub async fn start(ui: &mut UI, _args: &[OsString], export_cmd: &str, _export_pkg_ident: &str, _export_pkg_ident_envvar: &str) -> Result<()> { let cmd = export_cmd.replace("hab", "").replace("-...
UI}; use crate::error::{Error, Result};
random_line_split
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
(ui: &mut UI, _args: &[OsString], export_cmd: &str, _export_pkg_ident: &str, _export_pkg_ident_envvar: &str) -> Result<()> { let cmd = export_cmd.replace("hab", "").replace("-", " "); ui.wa...
start
identifier_name
export_common.rs
use std::ffi::OsString; use crate::common::ui::UI; use crate::error::Result; pub async fn start(ui: &mut UI, args: &[OsString], export_cmd: &str, export_pkg_ident: &str, export_pkg_ident_envvar: &str) -> Result<()> { i...
else { Err(Error::ExecCommandNotFound(command)) } } } #[cfg(target_os = "macos")] mod inner { use std::ffi::OsString; use crate::common::ui::{UIWriter, UI}; use crate::error::{Error, Result}; pub async fn start(ui: &mut UI, ...
{ command::pkg::exec::start(&ident, cmd, args) }
conditional_block
dutch.py
from .features import Dictionary, RegexMatches, Stemmed, Stopwords name = "dutch" try: import enchant dictionary = enchant.Dict("nl") except enchant.errors.DictNotFoundError: raise ImportError("No enchant-compatible dictionary found for 'nl'. " + "Consider installing 'myspell-nl'.")...
r"aap(jes)?", r"banaan", r"bent", r"boe(it)?", r"doei" r"dombo", r"domme", r"eigelijk", r"godverdomme", r"groetjes", r"gwn", r"hoi", r"hal+o+", r"heb", r"hee+[jyl]", r"heee+?l", r"houd?", r"(?:hoi+)+", r"hoor", r"izan", r"jij", r"jou", ...
informal_regexes = [
random_line_split
translate_test.py
"""Translate generators test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tarfile import tensorflow as tf from data_generators import text_problems from data_generators import translate class TranslateTest(tf.test.Te...
self.assertEqual(count, len(self.data)) if __name__ == "__main__": tf.test.main()
expected = self.data[i] self.assertEqual(list(expected), [example["inputs"], example["targets"]]) count += 1
conditional_block
translate_test.py
"""Translate generators test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tarfile import tensorflow as tf from data_generators import text_problems from data_generators import translate class TranslateTest(tf.test.Te...
with tf.gfile.Open(de_file, "w") as de_f: start = i * 10 end = start + 10 for en_line, de_line in data[start:end]: en_f.write(en_line) en_f.write("\n") de_f.write(de_line) de_f.write("\n") with tarfile.open(os.path.join(tmp_dir...
random_line_split
translate_test.py
"""Translate generators test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tarfile import tensorflow as tf from data_generators import text_problems from data_generators import translate class TranslateTest(tf.test.Te...
(self): filename = "out" filepath = os.path.join(self.tmp_dir, filename) translate.compile_data(self.tmp_dir, self.DATASETS, filename) count = 0 for i, example in enumerate( text_problems.text2text_txt_iterator(filepath + ".lang1", filepath + ".l...
testCompileData
identifier_name
translate_test.py
"""Translate generators test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tarfile import tensorflow as tf from data_generators import text_problems from data_generators import translate class TranslateTest(tf.test.Te...
if __name__ == "__main__": tf.test.main()
filename = "out" filepath = os.path.join(self.tmp_dir, filename) translate.compile_data(self.tmp_dir, self.DATASETS, filename) count = 0 for i, example in enumerate( text_problems.text2text_txt_iterator(filepath + ".lang1", filepath + ".lang2")): ...
identifier_body
lookup.ts
import {Injectable} from 'angular2/core'; import {Http, Response, Headers} from 'angular2/http'; import {Logger} from "../logger/logger"; import 'rxjs/add/operator/map'; import {Observable} from 'rxjs'; export class LookupData { name: string; isItem: boolean = false; path: string; url: string; uui...
} return this.http.get(this.root + this.domainRoot + path) .map((resp: Response) => { var json : any = resp.json(); let result : Array<LookupData> = []; for (var key in json) { var data : LookupData = new LookupData(''); ...
if(json != null) { this.logger.debug("LookupService.getDomainChildren() - path '"+this.domainRoot+path+"' was found in sessionStorage"); //Observable.from(JSON.parse(json));
random_line_split
lookup.ts
import {Injectable} from 'angular2/core'; import {Http, Response, Headers} from 'angular2/http'; import {Logger} from "../logger/logger"; import 'rxjs/add/operator/map'; import {Observable} from 'rxjs'; export class LookupData { name: string; isItem: boolean = false; path: string; url: string; uui...
var i = data.url.indexOf('item'); if (i != -1) { data.isItem = true; data.uuid = data.url.substr(i+5); } this.logger.debug('LookupService.getDomainChildren() - '+JSON.stringify(data)); ...
{ let json = sessionStorage.getItem(this.domainRoot + path); if(json != null) { this.logger.debug("LookupService.getDomainChildren() - path '"+this.domainRoot+path+"' was found in sessionStorage"); //Observable.from(JSON.parse(json)); } return this.http.get(this....
identifier_body
lookup.ts
import {Injectable} from 'angular2/core'; import {Http, Response, Headers} from 'angular2/http'; import {Logger} from "../logger/logger"; import 'rxjs/add/operator/map'; import {Observable} from 'rxjs'; export class LookupData { name: string; isItem: boolean = false; path: string; url: string; uui...
(path: string) { return this.http.get(this.root + path) .map((resp: Response) => { var json : any = resp.json(); let result : Array<LookupData> = []; for (var key in json) { var data : LookupData = new LookupData(''); ...
getRoleChildren
identifier_name
concept.js
app.Drag.prototype.handleUpEvent }); /** * @type {ol.Pixel} * @private */ this.coordinate_ = null; /** * @type {string|undefined} * @private */ this.cursor_ = 'pointer'; /** * @type {ol.Feature} * @private */ this.feature_ = null; /** * @type {string|undefined} * @p...
this.coordinate_[1] = evt.coordinate[1]; }; /** * @param {ol.MapBrowserEvent} evt Event. */ app.Drag.prototype.handleMoveEvent = function(evt) { if (this.cursor_) { var map = evt.map; var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) { return feature; ...
this.coordinate_[0] = evt.coordinate[0];
random_line_split
concept.js
@private */ this.cursor_ = 'pointer'; /** * @type {ol.Feature} * @private */ this.feature_ = null; /** * @type {string|undefined} * @private */ this.previousCursor_ = undefined; }; ol.inherits(app.Drag, ol.interaction.Pointer); /** * @param {ol.MapBrowserEvent} evt Map browser even...
{ layers.remove(found); }
conditional_block
openscap.py
import logging from ..openscap import OSCAPScanner log = logging.getLogger(__package__) def init(app): app.hooks.connect("pre-arg-parse", add_argparse) app.hooks.connect("post-arg-parse", post_argparse) def add_argparse(app, parser, subparsers):
def post_argparse(app, args): if args.command == "openscap": os = OSCAPScanner() if args.list: print("Registered profile: %s" % os.profile) elif args.all: for id_, desc in os.profiles().items(): print("Id: %s\n %s\n" % (id_, desc)) elif a...
s = subparsers.add_parser("openscap", help="Security management") s.add_argument("--all", action="store_true", help="List all available profiles") s.add_argument("--list", action="store_true", help="List registered profile") s.add_argument("--configure", action="store_t...
identifier_body
openscap.py
import logging from ..openscap import OSCAPScanner log = logging.getLogger(__package__) def init(app): app.hooks.connect("pre-arg-parse", add_argparse) app.hooks.connect("post-arg-parse", post_argparse) def add_argparse(app, parser, subparsers): s = subparsers.add_parser("openscap", help="Security man...
(app, args): if args.command == "openscap": os = OSCAPScanner() if args.list: print("Registered profile: %s" % os.profile) elif args.all: for id_, desc in os.profiles().items(): print("Id: %s\n %s\n" % (id_, desc)) elif args.configure: ...
post_argparse
identifier_name
openscap.py
import logging from ..openscap import OSCAPScanner log = logging.getLogger(__package__) def init(app): app.hooks.connect("pre-arg-parse", add_argparse) app.hooks.connect("post-arg-parse", post_argparse) def add_argparse(app, parser, subparsers): s = subparsers.add_parser("openscap", help="Security man...
for id_, desc in os.profiles().items(): print("Id: %s\n %s\n" % (id_, desc)) elif args.configure: os.configure() elif args.register: datastream, profile = args.register os.register(datastream, profile) elif args.unregister: ...
if args.command == "openscap": os = OSCAPScanner() if args.list: print("Registered profile: %s" % os.profile) elif args.all:
random_line_split
openscap.py
import logging from ..openscap import OSCAPScanner log = logging.getLogger(__package__) def init(app): app.hooks.connect("pre-arg-parse", add_argparse) app.hooks.connect("post-arg-parse", post_argparse) def add_argparse(app, parser, subparsers): s = subparsers.add_parser("openscap", help="Security man...
elif args.scan: os.scan(remediate=False, path=args.scan) elif args.remediate: os.scan(remediate=True, path=args.remediate)
os.unregister(args.unregister)
conditional_block
adapter.rs
use api::{ Error, Operation, User }; use channel::Channel; use io::*; use services::*; use values::*; use transformable_channels::mpsc::*; use std::collections::HashMap; use std::sync::Arc; pub type ResultMap<K, T, E> = HashMap<K, Result<T, E>>; /// A witness that we are currently watching for a value. /// Watching...
/// Signal the adapter that it is time to stop. /// /// Ideally, the adapter should not return until all its threads have been stopped. fn stop(&self) { // By default, do nothing. } } /// API that adapters must implement. /// /// # Requirements /// /// Channels and Services are expected...
{ target.drain(..).map(|(id, _, _, _)| { (id.clone(), Err(Error::OperationNotSupported(Operation::Watch, id))) }).collect() }
identifier_body
adapter.rs
use api::{ Error, Operation, User }; use channel::Channel; use io::*; use services::*; use values::*; use transformable_channels::mpsc::*; use std::collections::HashMap; use std::sync::Arc; pub type ResultMap<K, T, E> = HashMap<K, Result<T, E>>; /// A witness that we are currently watching for a value. /// Watching...
(&self) { // By default, do nothing. } } pub type RawWatchTarget = (Id<Channel>, /*condition*/Option<(Payload, Type)>, /*values*/Type, Box<ExtSender<WatchEvent</*result*/(Payload, Type)>>>); pub type WatchTarget = (Id<Channel>, /*condition*/Option<Value>, Box<ExtSender<WatchEvent</*result*/Value>>>); pub ...
stop
identifier_name
adapter.rs
use api::{ Error, Operation, User }; use channel::Channel; use io::*; use services::*; use values::*; use transformable_channels::mpsc::*; use std::collections::HashMap; use std::sync::Arc; pub type ResultMap<K, T, E> = HashMap<K, Result<T, E>>; /// A witness that we are currently watching for a value. /// Watching...
pub type WatchResult = Vec<(Id<Channel>, Result<Box<AdapterWatchGuard>, Error>)>;
random_line_split
urls.py
"""pint_journal_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='hom...
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^user/', include('pints_user.urls')), url(r'^/?', include('pints_main.urls')), ]
"""
random_line_split
hooks.py
_msg_regex.search(text) time = int(match.group(1)) def clear_ban(userdata): chan.areWeBanned = False chan.emit_print('Server Text', "You are (hopefully) no longer banned") hexchat.hook_timer(time * 1000, clear_ban) else: action = word[3][1:] param = word[4:] if action...
elif nick == 'twitchnotify': twitch.channel.get(chan).emit_print('Server Text', text[1:]) return hexchat.EAT_ALL else: twitch.user.get(nick).joinChannel(chan) return hexchat.EAT_NONE except: log.exception("Unhandled exception in twitch.privmsg_cb") return hexchat.EAT_NONE # handle Twitch WHI...
ctxt = twitch.channel.get(chan).getContext() twitch.channel.get(chan).emit_print('Server Text', text[1:]) return hexchat.EAT_ALL
conditional_block
hooks.py
_msg_regex.search(text) time = int(match.group(1)) def clear_ban(userdata): chan.areWeBanned = False chan.emit_print('Server Text', "You are (hopefully) no longer banned") hexchat.hook_timer(time * 1000, clear_ban) else: action = word[3][1:] param = word[4:] if action...
# try: # log.debug("Got raw msg: %s", word) # except: # log.exception("Unhandled exception in twitch.rawmsg_cb") # finally: # return hexchat.EAT_NONE # message hook to format user messages nicely. message_cb_recurse = False def message_cb(word, word_eol, msgtype): # avoid infinite loop global message_cb_recurse ...
log.exception("Unhandled exception in twitch.clearchat_cb") finally: return hexchat.EAT_ALL #def rawmsg_cb(word, word_eol, msgtype, attributes):
random_line_split
hooks.py
(word, word_eol, userdata): hexchat.command('CAP REQ :twitch.tv/tags twitch.tv/commands') # Ignore various "unknown command" errors unknowncommands = ('WHO', 'WHOIS') def servererr_cb(word, word_eol, userdata): if word[3] in unknowncommands: return hexchat.EAT_ALL return hexchat.EAT_NONE # PRIVMSG hook to ha...
endofmotd_cb
identifier_name
hooks.py
_msg_regex.search(text) time = int(match.group(1)) def clear_ban(userdata): chan.areWeBanned = False chan.emit_print('Server Text', "You are (hopefully) no longer banned") hexchat.hook_timer(time * 1000, clear_ban) else: action = word[3][1:] param = word[4:] if action...
# When we join a channel, set up the user info and get stream status def youjoin_cb(word, word_eol, msgtype): try: chan = twitch.channel.get(word[1]) chan.join() hexchat.command("CAP REQ :twitch.tv/membership") # automatically set up some users jtv = twitch.user.get('jtv') jtv.joinChannel(chan) jtv...
try: chan = word[2] mode = word[3] whom = word[4] user = twitch.user.get(whom) what = '+' for char in mode: if char == '+' or char == '-': what = char elif what == '+': user.setChannelMode(chan, char, True) elif what == '-': user.setChannelMode(chan, char, False) except: log.excep...
identifier_body
wx.d.ts
* 触发事件的源组件 */ type BaseEventTarget = { id: string; tagName: string; dataset: object; } /** * 基础事件对象属性 */ interface BaseEvent { type: string; timeStamp: number; target: BaseEventTarget; currentTarget: BaseEventTarget; } /** * Touch 对象 */ type WxmlEventHandleTou...
rotate(deg: number/**degrees * Math.PI/180;degrees范围为0~360;旋转角度,以弧度计 */): void; /** * 对坐标原点进行缩放 */ translate(x: number/**水平坐标平移量 */, y: number/**竖直坐标平移量 */): void; /** * 从原始画布中剪切任意形状和尺寸 */ clip(): void; /** * 在画布上绘制被填充的文本 */ fillText(text: string, x: number, y: ...
* 对坐标轴进行顺时针旋转 */
random_line_split
app.js
We need to tell jshint which are our global variables */ /* global $:false, Rickshaw: false, moment: false, navigator: false, theme: false */ (function() { 'use strict'; var app = angular.module('winderfulApp', [ 'turbine-directives', 'winderful-filters', 'ngBootstrap', ...
_this.loaded = true; if (typeof (theme) !== 'undefined' && typeof (theme.onStart) !== 'undefined') { theme.onStart(); } }); } }.bind(this); $scope.$watch(function() { return this.daterange; }.bind(this), function() { $sc...
{ if (!firstLoad) { dateChanged(this.daterange.startDate.unix(), this.daterange.endDate.unix()); } firstLoad = false; var _this = this; var startDate = this.daterange.startDate.unix(); var endDate = this.daterange.endDate.unix(); $scope.delta = endDat...
conditional_block
app.js
We need to tell jshint which are our global variables */ /* global $:false, Rickshaw: false, moment: false, navigator: false, theme: false */ (function() { 'use strict'; var app = angular.module('winderfulApp', [ 'turbine-directives', 'winderful-filters', 'ngBootstrap', ...
(start, end) { var dateRange = moment.unix(start).format('Do MMMM YYYY') + ' - ' + moment.unix(end).format('Do MMMM YYYY'); var dateChangedEvent = { hitType: 'event', eventCategory: 'dates', eventAction: 'change', eventLabel: dateRange }; if (typeof ga !== 'undef...
dateChanged
identifier_name
app.js
need to tell jshint which are our global variables */ /* global $:false, Rickshaw: false, moment: false, navigator: false, theme: false */ (function() { 'use strict'; var app = angular.module('winderfulApp', [ 'turbine-directives', 'winderful-filters', 'ngBootstrap', 'a...
$scope.loadInData = function() { if (typeof (this.daterange) !== 'undefined') { if (!firstLoad) { dateChanged(this.daterange.startDate.unix(), this.daterange.endDate.unix()); } firstLoad = false; var _this = this; var startDate = this.daterange.startDate.u...
{ var dateRange = moment.unix(start).format('Do MMMM YYYY') + ' - ' + moment.unix(end).format('Do MMMM YYYY'); var dateChangedEvent = { hitType: 'event', eventCategory: 'dates', eventAction: 'change', eventLabel: dateRange }; if (typeof ga !== 'undefined') { ...
identifier_body
app.js
We need to tell jshint which are our global variables */ /* global $:false, Rickshaw: false, moment: false, navigator: false, theme: false */ (function() { 'use strict'; var app = angular.module('winderfulApp', [ 'turbine-directives', 'winderful-filters', 'ngBootstrap', ...
this.speed = 0; $scope.wattage = 0; this.displayDate = new Date(); this.loaded = false; this.hoverDeets = {}; this.iosSafari = /(iPhone|iPod|iPad).*AppleWebKit/i.test(navigator.userAgent); this.usageExamples = [ { action: 'Powering', consumption: (0.000483 * 26400000) / 100, object:...
$scope.rotationSpeed = 10; this.graph = {}; this.percentage = 0;
random_line_split
banning_queue.rs
uingInstant; use error::{Error, TransactionError}; use util::{Uint, U256, H256, Address, Hashable}; type Count = u16; /// Auto-Banning threshold pub enum Threshold { /// Should ban after given number of misbehaves reported. BanAfter(Count), /// Should never ban anything NeverBan } impl Default for Threshold { f...
#[test] fn should_not_accept_transactions_from_banned_sender() { // given let tx = transaction(Action::Create); let mut txq = queue(); // Banlist once (threshold not reached) let ban
{ // given let tx = transaction(Action::Create); let mut txq = queue(); // when txq.queue().add(tx, TransactionOrigin::External, 0, None, &default_tx_provider()).unwrap(); // then // should also deref to queue assert_eq!(txq.status().pending, 1); }
identifier_body
banning_queue.rs
uingInstant; use error::{Error, TransactionError}; use util::{Uint, U256, H256, Address, Hashable}; type Count = u16; /// Auto-Banning threshold pub enum Threshold { /// Should ban after given number of misbehaves reported. BanAfter(Count), /// Should never ban anything NeverBan } impl Default for Threshold { f...
} impl DerefMut for BanningTransactionQueue { fn deref_mut(&mut self) -> &mut Self::Target { self.queue() } } #[cfg(test)] mod tests { use std::time::Duration; use super::{BanningTransactionQueue, Threshold}; use ethkey::{Random, Generator}; use transaction::{Transaction, SignedTransaction, Action}; use error...
fn deref(&self) -> &Self::Target { &self.queue }
random_line_split
banning_queue.rs
uingInstant; use error::{Error, TransactionError}; use util::{Uint, U256, H256, Address, Hashable}; type Count = u16; /// Auto-Banning threshold pub enum Threshold { /// Should ban after given number of misbehaves reported. BanAfter(Count), /// Should never ban anything NeverBan } impl Default for Threshold { f...
(&mut self) -> &mut TransactionQueue { &mut self.queue } /// Add to the queue taking bans into consideration. /// May reject transaction because of the banlist. pub fn add_with_banlist( &mut self, transaction: SignedTransaction, time: QueuingInstant, details_provider: &TransactionQueueDetailsProvider, )...
queue
identifier_name
internal_crypto.rs
// internal_crypto.rs - internal cryptographic functions // Copyright (C) 2018 David Anthony Stainton. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the Licen...
(input: &[u8; KEY_SIZE]) -> PacketKeys { let mut output = [0u8; KDF_OUTPUT_SIZE]; let hk = Hkdf::<Sha256>::extract(None, &input[..]); hk.expand(String::from(KDF_INFO_STR).into_bytes().as_slice(), &mut output).unwrap(); let (a1,a2,a3,a4,a5,a6) = array_refs![&output,MAC_KEY_SIZE,STREAM_KEY_SIZE,STREAM_IV...
kdf
identifier_name
internal_crypto.rs
// internal_crypto.rs - internal cryptographic functions // Copyright (C) 2018 David Anthony Stainton. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the Licen...
pub const SPRP_IV_SIZE: usize = AEZ_NONCE_SIZE; /// the size of the DH group element in bytes. pub const GROUP_ELEMENT_SIZE: usize = KEY_SIZE; const KDF_OUTPUT_SIZE: usize = MAC_KEY_SIZE + STREAM_KEY_SIZE + STREAM_IV_SIZE + SPRP_KEY_SIZE + SPRP_IV_SIZE + KEY_SIZE; const KDF_INFO_STR: &str = "panoramix-kdf-v0-hkdf-sh...
/// the key size of the SPRP in bytes. pub const SPRP_KEY_SIZE: usize = AEZ_KEY_SIZE; /// the IV size of the SPRP in bytes.
random_line_split
main.rs
extern crate serde_json; use serde_json::Value; use std::path::Path; use std::io::prelude::*; use std::fs::File; use serde_json::Value::*; fn add_up_numbers_part1(json: &Value) -> isize { match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Ar...
fn parse_and_add_up_numbers_part2(input: &str) -> isize { serde_json::from_str::<Value>(input).map(|json| add_up_numbers_part2(&json)).unwrap_or(0) } fn read_file(path: &Path) -> String { let mut input = String::new(); let mut file = File::open(path).expect("File could not be found"); file.read_to_st...
{ serde_json::from_str::<Value>(input).map(|json| add_up_numbers_part1(&json)).unwrap_or(0) }
identifier_body
main.rs
extern crate serde_json; use serde_json::Value; use std::path::Path; use std::io::prelude::*; use std::fs::File; use serde_json::Value::*; fn add_up_numbers_part1(json: &Value) -> isize { match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Ar...
match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Array(ref vec) => vec.into_iter().fold(0, |a, i| a + add_up_numbers_part2(i)), Object(ref map) => { if map.values().any(|v| { match *v { ...
fn add_up_numbers_part2(json: &Value) -> isize {
random_line_split
main.rs
extern crate serde_json; use serde_json::Value; use std::path::Path; use std::io::prelude::*; use std::fs::File; use serde_json::Value::*; fn add_up_numbers_part1(json: &Value) -> isize { match *json { I64(num) => num as isize, U64(num) => num as isize, F64(num) => num as isize, Ar...
(path: &Path) -> String { let mut input = String::new(); let mut file = File::open(path).expect("File could not be found"); file.read_to_string(&mut input).expect("File could not be read"); input } fn main() { let input = read_file(Path::new("input.txt")); let number_part1 = parse_and_add_up_n...
read_file
identifier_name
condition.rs
use num::FromPrimitive; enum_from_primitive! { #[derive(Debug)] pub enum Cond{ Equal = 0b0000, NotEqual = 0b0001, UnsignedHigherOrSame = 0b0010, UnsignedLower = 0b0011, Negative = 0b0100, PositiveOrZero = 0b0101, Overflow...
(insn: u32) -> Cond { Cond::from_u8((insn >> 28) as u8).unwrap() } }
from
identifier_name
condition.rs
use num::FromPrimitive; enum_from_primitive! { #[derive(Debug)] pub enum Cond{ Equal = 0b0000, NotEqual = 0b0001, UnsignedHigherOrSame = 0b0010, UnsignedLower = 0b0011, Negative = 0b0100, PositiveOrZero = 0b0101, Overflow...
}
{ Cond::from_u8((insn >> 28) as u8).unwrap() }
identifier_body
condition.rs
use num::FromPrimitive; enum_from_primitive! { #[derive(Debug)] pub enum Cond{ Equal = 0b0000, NotEqual = 0b0001, UnsignedHigherOrSame = 0b0010, UnsignedLower = 0b0011, Negative = 0b0100, PositiveOrZero = 0b0101,
LessThan = 0b1011, GreaterThan = 0b1100, LessThanOrEqual = 0b1101, Always = 0b1110, Undefined = 0b1111 } } impl From<u32> for Cond { fn from (insn: u32) -> Cond { Cond::from_u8((insn >> 28) as u8).unwrap() } }
Overflow = 0b0110, NoOverflow = 0b0111, UnsignedHigher = 0b1000, UnsignedLowerOrSame = 0b1001, GreaterOrEqual = 0b1010,
random_line_split
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= e...
if pivot != 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot { swa...
let pivot = partition(nums, start, end);
random_line_split
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= e...
println!("{:?}", quick_sort(nums)); }
];
identifier_name
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; }
i32>, start: usize, end: usize) { if start >= end { return; } // 分区点 let pivot = partition(nums, start, end); if pivot != 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize...
let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<
identifier_body
quick_sort.rs
/// 快排 /// 时间复杂度:O(nlogn), 空间复杂度: O(1), 不稳定排序 // 快排 pub fn quick_sort(mut nums: Vec<i32>) -> Vec<i32> { if nums.is_empty() { return nums; } let n = nums.len() - 1; quick_sort_internally(&mut nums, 0, n); nums } fn quick_sort_internally(nums: &mut Vec<i32>, start: usize, end: usize) { if start >= e...
s, start, end); if pivot != 0 { quick_sort_internally(nums, start, pivot-1); } quick_sort_internally(nums, pivot+1, end); } fn partition(nums: &mut Vec<i32>, start: usize, end: usize) -> usize { let pivot = nums[end]; let mut i = start; for j in start..end { if nums[j] < pivot {...
rtition(num
conditional_block
dynamic_lib.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 ...
<T>(&self, symbol: &str) -> Result<T, ~str> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let maybe_symbol_value = dl::check_for_errors_in(|| { symbol.with_c_str(|raw_string| { dl::symbol(self.handle, raw_s...
symbol
identifier_name
dynamic_lib.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 ...
let maybe_symbol_value = dl::check_for_errors_in(|| { symbol.with_c_str(|raw_string| { dl::symbol(self.handle, raw_string) }) }); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symb...
random_line_split
dynamic_lib.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 ...
pub unsafe fn open_internal() -> *u8 { dlopen(ptr::null(), Lazy as libc::c_int) as *u8 } pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT; unsa...
{ filename.with_c_str(|raw_name| { dlopen(raw_name, Lazy as libc::c_int) as *u8 }) }
identifier_body
lib.rs
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/. */ #![feature(custom_derive, plugin)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![crate_name = "gfx_traits"] #![crate_type = "rlib"] #![deny(unsafe_code)]
extern crate azure; extern crate euclid; extern crate heapsize; extern crate layers; extern crate msg; extern crate serde; pub mod color; mod paint_listener; pub use paint_listener::PaintListener; use azure::azure_hl::Color; use euclid::Matrix4D; use euclid::rect::Rect; use msg::constellation_msg::PipelineId; use std...
random_line_split
lib.rs
. 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/. */ #![feature(custom_derive, plugin)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![crate_name = "gfx_traits"] #![crate_type = "rlib"] #![deny(unsafe_code)] extern crate azure; extern crate ...
{ /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. ...
LayerType
identifier_name
ssh.py
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
sent_bytes = session.send(data_to_send) # LOG.debug("sent: %s" % data_to_send[:sent_bytes]) data_to_send = data_to_send[sent_bytes:] if session.exit_status_ready(): break if timeout and (time.time() - timeout) > start...
data_to_send = stdin.read(4096) if not data_to_send: stdin.close() session.shutdown_write() writes = [] continue
conditional_block
ssh.py
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
def close(self): self._client.close() self._client = False def run(self, cmd, stdin=None, stdout=None, stderr=None, raise_on_error=True, timeout=3600): """Execute specified command on the server. :param cmd: Command to be executed. :param stdin...
if self._client: return self._client try: self._client = paramiko.SSHClient() self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self._client.connect(self.host, username=self.user, port=self.port, pkey=self.pkey, ...
identifier_body
ssh.py
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
exit_status = self.run(cmd, stderr=stderr, stdout=stdout, stdin=stdin, timeout=timeout, raise_on_error=False) stdout.seek(0) stderr.seek(0) return (exit_status, stdout.read(), stderr.read()) def wait(self, timeout=120, in...
""" stdout = six.moves.StringIO() stderr = six.moves.StringIO()
random_line_split
ssh.py
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
(self, client, cmd, stdin=None, stdout=None, stderr=None, raise_on_error=True, timeout=3600): transport = client.get_transport() session = transport.open_session() session.exec_command(cmd) start_time = time.time() data_to_send = "" stderr_data = None ...
_run
identifier_name
web.rs
use actix::Addr; use actix_web::{http, middleware}; use actix_web::{web, App, HttpServer}; use diesel::r2d2::{self, ConnectionManager}; use diesel::PgConnection; use crate::database::DbExecutor; use badge::handlers::badge_handler; // use run::handlers::run_handler; use status::handlers::status_handler; pub type Poo...
{ use actix_web::middleware::cors::Cors; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middleware::Logger::default()) .wrap( Cors::new() // <- Construct CORS middleware builder .allowed_methods(vec!["GET", "POST", ...
identifier_body
web.rs
use actix::Addr; use actix_web::{http, middleware}; use actix_web::{web, App, HttpServer}; use diesel::r2d2::{self, ConnectionManager}; use diesel::PgConnection; use crate::database::DbExecutor; use badge::handlers::badge_handler; // use run::handlers::run_handler; use status::handlers::status_handler; pub type Poo...
(state: WebState, http_bind: String, http_port: String) { use actix_web::middleware::cors::Cors; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middleware::Logger::default()) .wrap( Cors::new() // <- Construct CORS middleware builder ...
http_server
identifier_name
web.rs
use actix::Addr; use actix_web::{http, middleware}; use actix_web::{web, App, HttpServer}; use diesel::r2d2::{self, ConnectionManager}; use diesel::PgConnection; use crate::database::DbExecutor; use badge::handlers::badge_handler; // use run::handlers::run_handler;
#[derive(Clone)] pub struct WebState { pub db: Pool, pub db_actor: Addr<DbExecutor>, } pub fn http_server(state: WebState, http_bind: String, http_port: String) { use actix_web::middleware::cors::Cors; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middl...
use status::handlers::status_handler; pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
random_line_split
cell.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 dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; use servo_util::task_state; use servo_util::tas...
<'a>(&'a self) -> &'a T { debug_assert!(task_state::get().contains(SCRIPT | IN_GC)); &*self.value.as_unsafe_cell().get() } /// Is the cell mutably borrowed? /// /// For safety checks in debug builds only. pub fn is_mutably_borrowed(&self) -> bool { self.value.try_borrow().is...
borrow_for_gc_trace
identifier_name
cell.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 dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; use servo_util::task_state; use servo_util::tas...
pub fn unwrap(self) -> T { self.value.unwrap() } pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("DOMRefCell<T> already mutably borrowed") } } pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {...
{ DOMRefCell { value: RefCell::new(value), } }
identifier_body
cell.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 dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; use servo_util::task_state; use servo_util::tas...
value: RefCell::new(value), } } pub fn unwrap(self) -> T { self.value.unwrap() } pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("DOMRefCell<T> already mutably borrowed") } } ...
impl<T> DOMRefCell<T> { pub fn new(value: T) -> DOMRefCell<T> { DOMRefCell {
random_line_split
custom-validators.ts
import { AbstractControl } from "@angular/forms"; import { PhoneNumberUtil } from "google-libphonenumber"; interface ValidationResult { [key: string]: boolean; } export class CustomValidators { private static phoneNumberUtil: any = PhoneNumberUtil.getInstance(); private static defaultRegion = "GB"; /** *...
if ( CustomValidators.phoneNumberUtil.isPossibleNumber(parsed) && CustomValidators.phoneNumberUtil.isValidNumber(parsed) ) { return null; } else { return { phoneNumber: true }; } } catch (ex) { return { phoneNumber: true }; } ...
const parsed = CustomValidators.phoneNumberUtil.parse( numToTest, CustomValidators.defaultRegion );
random_line_split
custom-validators.ts
import { AbstractControl } from "@angular/forms"; import { PhoneNumberUtil } from "google-libphonenumber"; interface ValidationResult { [key: string]: boolean; } export class CustomValidators { private static phoneNumberUtil: any = PhoneNumberUtil.getInstance(); private static defaultRegion = "GB"; /** *...
/** * Use Google's libphonenumber library to validate phone numbers. */ static phoneNumber(control: AbstractControl): ValidationResult { const numToTest: string = control.value; if (numToTest !== undefined && numToTest !== "") { try { const parsed = CustomValidators.phoneNumberUtil.pa...
{ if ( control.value === undefined || control.value === "" || !/.+\@.+\..+/.test(control.value) ) { return { email: true }; } else { return null; } }
identifier_body
custom-validators.ts
import { AbstractControl } from "@angular/forms"; import { PhoneNumberUtil } from "google-libphonenumber"; interface ValidationResult { [key: string]: boolean; } export class
{ private static phoneNumberUtil: any = PhoneNumberUtil.getInstance(); private static defaultRegion = "GB"; /** * Perform a basic sanity check on an e-mail address. */ static email(control: AbstractControl): ValidationResult { if ( control.value === undefined || control.value === "" || ...
CustomValidators
identifier_name
custom-validators.ts
import { AbstractControl } from "@angular/forms"; import { PhoneNumberUtil } from "google-libphonenumber"; interface ValidationResult { [key: string]: boolean; } export class CustomValidators { private static phoneNumberUtil: any = PhoneNumberUtil.getInstance(); private static defaultRegion = "GB"; /** *...
else { return { phoneNumber: true }; } } catch (ex) { return { phoneNumber: true }; } } else { return { phoneNumber: true }; } } }
{ return null; }
conditional_block
Transactions.js
'use strict' const _ = require('lodash') const util = require('../util') const crypto = require('tendermint-crypto') /** * Transactions component * @see {@link https://monax.io/docs/documentation/db/latest/specifications/api/#broadcast-tx} * @type {ErisDB.Transactions} */ module.exports = class Transactions { ...
/** * Call a given (contract) account to execute its code with the given in-data. * @param {String} address * @param {String} data * @return {Promise} */ call (address, data) { if (!address || !util.isAddress(address)) return Promise.reject(new Error('Address is required parameter')) ...
{ return this._eris.request .call('getUnconfirmedTxs') .then((data) => { if (!data || !data.txs) return Promise.reject(new Error('Wrong response received from RPC')) return data.txs }) }
identifier_body
Transactions.js
'use strict' const _ = require('lodash') const util = require('../util') const crypto = require('tendermint-crypto') /** * Transactions component * @see {@link https://monax.io/docs/documentation/db/latest/specifications/api/#broadcast-tx} * @type {ErisDB.Transactions} */ module.exports = class Transactions { ...
}) .catch(reject) }, 500) }) } let subId return this._eris .events .eventSubscribe(`Acc/${result.contract_addr}/Call`) .then((newSubId) => { subId = newSubId return checkEvents(subId) }) .then((data) => { // unsubs...
{ if (events[i].tx_id == result.tx_hash && _.isObject(events[i].call_data)) return resolve(events[i]) // handle error if (events[i].tx_id == result.tx_hash && events[i].exception.length > 0) return reject(new Error(events[i].exception))...
conditional_block
Transactions.js
'use strict' const _ = require('lodash') const util = require('../util') const crypto = require('tendermint-crypto') /** * Transactions component * @see {@link https://monax.io/docs/documentation/db/latest/specifications/api/#broadcast-tx}
constructor (eris) { this._eris = eris } /** * Sign helper for transactions * @param {Object} tx * @param {String} privKey private key in hex format * @return {Promise} */ sign (tx, privKey) { if (!_.isObject(tx)) return Promise.reject(new Error('Transaction is required parameter')...
* @type {ErisDB.Transactions} */ module.exports = class Transactions {
random_line_split
Transactions.js
'use strict' const _ = require('lodash') const util = require('../util') const crypto = require('tendermint-crypto') /** * Transactions component * @see {@link https://monax.io/docs/documentation/db/latest/specifications/api/#broadcast-tx} * @type {ErisDB.Transactions} */ module.exports = class Transactions {
(eris) { this._eris = eris } /** * Sign helper for transactions * @param {Object} tx * @param {String} privKey private key in hex format * @return {Promise} */ sign (tx, privKey) { if (!_.isObject(tx)) return Promise.reject(new Error('Transaction is required parameter')) if (!u...
constructor
identifier_name
rt.rs
// This file is part of rgtk. // // rgtk 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 // (at your option) any later version. // // rgtk is distributed in the hop...
pub fn events_pending() -> bool { unsafe { ffi::to_bool(ffi::gtk_events_pending()) } } pub fn get_major_version() -> u32 { unsafe { ffi::gtk_get_major_version() as u32 } } pub fn get_minor_version() -> u32 { unsafe { ffi::gtk_get_minor_version() as u32 } } pub fn ge...
{ let c_blocking = if blocking { ffi::GTRUE } else { ffi::GFALSE }; match unsafe { ffi::gtk_main_iteration_do(c_blocking) } { ffi::GFALSE => false, _ => true } }
identifier_body
rt.rs
// This file is part of rgtk. // // rgtk 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 // (at your option) any later version. // // rgtk is distributed in the hop...
() -> u32 { unsafe { ffi::gtk_get_major_version() as u32 } } pub fn get_minor_version() -> u32 { unsafe { ffi::gtk_get_minor_version() as u32 } } pub fn get_micro_version() -> u32 { unsafe { ffi::gtk_get_micro_version() as u32 } } pub fn get_binary_age() -> u32 { u...
get_major_version
identifier_name
rt.rs
// This file is part of rgtk. // // rgtk 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 // (at your option) any later version. // // rgtk is distributed in the hop...
unsafe { ffi::gtk_get_interface_age() as u32 } } pub fn check_version(required_major: u32, required_minor: u32, required_micro: u32) -> Option<String> { let c_str = unsafe { ffi::gtk_check_version(required_major as c_uint, required_mino...
} } pub fn get_interface_age() -> u32 {
random_line_split
middleware.py
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from mezgrman.utils.classes import ExtendedTemplateResponse from django.template import RequestContext, Template from .models import StaticPage, StaticPageGroup from django.conf import settings from django.db.models import Q impo...
potential_groups = StaticPageGroup.objects.filter(Q(site = request.site) | Q(site = None)) if not potential_groups: raise ValueError # Filter out groups with no matching base path potential_groups = [group for group in potential_groups if ...
if response.status_code != 404: # Only look for static pages when no view could be found return response try: try: # First look for standalone pages only (no group members) # Only get pages for the current site or universal pages (with...
identifier_body
middleware.py
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from mezgrman.utils.classes import ExtendedTemplateResponse from django.template import RequestContext, Template from .models import StaticPage, StaticPageGroup from django.conf import settings from django.db.models import Q impo...
(object): """ This middleware adds support for database-managed, static pages. """ def process_response(self, request, response): if response.status_code != 404: # Only look for static pages when no view could be found return response try: ...
StaticPagesMiddleware
identifier_name
middleware.py
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from mezgrman.utils.classes import ExtendedTemplateResponse from django.template import RequestContext, Template from .models import StaticPage, StaticPageGroup from django.conf import settings from django.db.models import Q impo...
# Filter out groups with no matching base path potential_groups = [group for group in potential_groups if re.match(group.base_path_regex, request.path)] if not potential_groups: raise ValueError # Filter out groups with n...
raise ValueError
conditional_block
middleware.py
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from mezgrman.utils.classes import ExtendedTemplateResponse from django.template import RequestContext, Template from .models import StaticPage, StaticPageGroup from django.conf import settings from django.db.models import Q impo...
if page.redirect_permanent: return HttpResponsePermanentRedirect(page.redirect_url) else: return HttpResponseRedirect(page.redirect_url) if not page.template: # Return a bare HttpResponse return HttpResponse(page.content, c...
# We have a copied page page = page.copy_of if page.redirect_url: # We have a redirect
random_line_split
app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {HttpModule} from '@angular/http'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FlexLayoutModule, MediaQueriesModule} from '@angular/flex-layout'; import {FormsModule, Reactiv...
@NgModule({ declarations: [ AppComponent, NavbarComponent, FooterComponent, HomepageComponent, TimetableComponent, StudentIdValidatorDirective, TimetableColumnComponent, LessonInfoDialogComponent, ], entryComponents: [LessonInfoDialogComponent], imports: [ BrowserModule, ...
{ return client; }
identifier_body
app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {HttpModule} from '@angular/http'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FlexLayoutModule, MediaQueriesModule} from '@angular/flex-layout'; import {FormsModule, Reactiv...
import 'hammerjs'; import {MaterialModule} from './material.module'; import {routing} from './routes.module'; import {AppComponent} from './app.component'; import {NavbarComponent} from './components/navbar/navbar.component'; import {FooterComponent} from './components/footer/footer.component'; import {HomepageCompon...
import {ApolloModule} from 'apollo-angular';
random_line_split
app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {HttpModule} from '@angular/http'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FlexLayoutModule, MediaQueriesModule} from '@angular/flex-layout'; import {FormsModule, Reactiv...
(): ApolloClient { return client; } @NgModule({ declarations: [ AppComponent, NavbarComponent, FooterComponent, HomepageComponent, TimetableComponent, StudentIdValidatorDirective, TimetableColumnComponent, LessonInfoDialogComponent, ], entryComponents: [LessonInfoDialogComponent...
provideClient
identifier_name
kendo.culture.kok.js
/* * Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial licen...
y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "-", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
random_line_split
extract.ts
import {normalize, schema} from 'normalizr' import {mergeEntities} from '../utils' const praise = new schema.Entity('praises') const message = new schema.Entity('messages', { praise: praise }) const thread = new schema.Entity('threads', { messages: [message] }) const feed = { threads: [thread] } export default...
} return memo }, {} ) // Add ID to result. result.id = request.id // Merge extracted fields into entities. mergeEntities(entities, references, { tags: tags || {}, urls: urls || {} }) // Merge `messages`, `replied_to_messages`, and `shared_messages`. entities.messages = mer...
random_line_split
extract.ts
import {normalize, schema} from 'normalizr' import {mergeEntities} from '../utils' const praise = new schema.Entity('praises') const message = new schema.Entity('messages', { praise: praise }) const thread = new schema.Entity('threads', { messages: [message] }) const feed = { threads: [thread] } export default...
return memo }, {} ) // Add ID to result. result.id = request.id // Merge extracted fields into entities. mergeEntities(entities, references, { tags: tags || {}, urls: urls || {} }) // Merge `messages`, `replied_to_messages`, and `shared_messages`. entities.messages = mergeEntit...
{ memo[tagId] = { id: tagId, network_id: topic.network_id, topic_id: topic.id } }
conditional_block
karma.conf.js
// Karma configuration // Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/ka...
sourceMap: 'inline', presets: [ 'es2015', 'stage-1'], plugins: [ 'transform-decorators-legacy', ['babel-plugin-transform-builtin-extend', {globals: ['Set']}] ] } }, // test results reporter to use // possible values: 'dots', 'progress' // availa...
'test/**/*.js': ['babel'], 'src/**/*.js': ['babel'] }, 'babelPreprocessor': { options: {
random_line_split
Storage.js
|0)); }); }.bind(this); fs.readdir(this.dir, function(err, files) { if(files) fileStat(files, 0); }); }, isInitialized: function() { return this._initialized && this.usedSize !== null; }, //---------- Abstract ------------- getRingSize: ...
httpCommandData: function(conn) { throw 'Abstract method' }, /** * process GET-request: * /-/<seg>/listen/<uid> */ httpCommandListen: function(conn) { conn.response400('Method Not Allowed'); }, notifyListeners: function() { // abstract method ...
}.bind(this)); },
random_line_split
c10t-tk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4 sw=4 et import re import os.path import subprocess from mainwindow import MainWindow def default_c10t_executable(): return "./c10t" def default_minecraft_world(): return "~/.minecraft/saves/World1" def default_output_image(): return os.path.abspat...
(self): self.win = MainWindow() self.args = [] # Files self.win.ui.exepath = default_c10t_executable() self.win.ui.world = default_minecraft_world() self.win.ui.output = default_output_image() self.update_ui_commandline() self.win.update_button_callback...
__init__
identifier_name
c10t-tk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4 sw=4 et import re import os.path import subprocess from mainwindow import MainWindow def default_c10t_executable():
def default_minecraft_world(): return "~/.minecraft/saves/World1" def default_output_image(): return os.path.abspath("out.png") def quote_arg_if_needed(arg): """Add quotes if the argument has 'weird' characters. This function is extremely simple, and it is not fool-proof. Improvements are quit...
return "./c10t"
identifier_body
c10t-tk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4 sw=4 et import re import os.path import subprocess from mainwindow import MainWindow def default_c10t_executable(): return "./c10t" def default_minecraft_world(): return "~/.minecraft/saves/World1" def default_output_image(): return os.path.abspat...
args = [os.path.expanduser(ui.exepath)] # Filtering if ui.topcheck : args.extend(["--top" , str(ui.top )]) if ui.bottomcheck: args.extend(["--bottom", str(ui.bottom)]) if ui.limitscheck: args.extend([ "--limits", ",".join(str(x)...
def build_commandline(self): ui = self.win.ui
random_line_split
c10t-tk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4 sw=4 et import re import os.path import subprocess from mainwindow import MainWindow def default_c10t_executable(): return "./c10t" def default_minecraft_world(): return "~/.minecraft/saves/World1" def default_output_image(): return os.path.abspat...
# Adding the "Files" section to the end for readability reasons args.extend([ "-w", os.path.expanduser(ui.world), "-o", os.path.expanduser(ui.output), ]) self.args = args def main(self): self.win.mainloop() if __name__ == "__main__": p = Prog...
args.extend(["--coordinate-color", str(ui.coordcolor)])
conditional_block
lv.rs
name: String, /// The UUID. pub id: String, /// The status. pub status: Vec<String>, /// Flags. pub flags: Vec<String>, /// Created by this host. pub creation_host: String, /// Created at this Unix time. pub creation_time: i64, /// A list of the segments comprising the LV. ...
/// Construct an LV from an LvmTextMap. pub fn from_textmap( name: &str, vg_name: &str, map: &LvmTextMap, pvs: &BTreeMap<String, PV>, ) -> Result<LV> { let err = || Error::Io(io::Error::new(Other, "lv textmap parsing error")); let id = map.string_from_textmap("id").ok_or_else(err)?; let c...
{ let mut v = Vec::new(); for seg in &lv.segments { v.extend(seg.used_areas()) } v }
identifier_body
lv.rs
name: String, /// The UUID. pub id: String, /// The status. pub status: Vec<String>, /// Flags. pub flags: Vec<String>, /// Created by this host. pub creation_host: String, /// Created at this Unix time. pub creation_time: i64, /// A list of the segments comprising the LV. ...
(map: &LvmTextMap, pvs: &BTreeMap<String, PV>) -> Result<Box<dyn Segment>> { match map.string_from_textmap("type") { Some("striped") => StripedSegment::from_textmap(map, pvs), _ => unimplemented!(), } } /// A striped Logical Volume Segment. #[derive(Debug, PartialEq)...
from_textmap
identifier_name
lv.rs
name: String, /// The UUID. pub id: String,
pub creation_host: String, /// Created at this Unix time. pub creation_time: i64, /// A list of the segments comprising the LV. pub segments: Vec<Box<dyn segment::Segment>>, /// The major/minor number of the LV. pub device: LinearDev, } impl LV { /// The total number of extents used by ...
/// The status. pub status: Vec<String>, /// Flags. pub flags: Vec<String>, /// Created by this host.
random_line_split
lv.rs
name: String, /// The UUID. pub id: String, /// The status. pub status: Vec<String>, /// Flags. pub flags: Vec<String>, /// Created by this host. pub creation_host: String, /// Created at this Unix time. pub creation_time: i64, /// A list of the segments comprising the LV. ...
map.insert( "stripes".to_string(), Entry::List( self.stripes .iter() .map(|&(k, v)| { let name = format!("pv{}", dev_to_idx.get(&k).unwrap()); vec
{ map.insert("stripe_size".to_string(), Entry::Number(stripe_size as i64)); }
conditional_block
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
MySqlPool { type Value = MySqlPool; } pub struct RedisConfig { pub connect_string: String, pub expire: u64 } pub fn get_redis_config(config: &Config) -> RedisConfig { let table = config.value(); let redis_config = table.get("redis").unwrap().as_table().unwrap(); let protocol = redis_config....
0.clone() } } impl Key for
identifier_body
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
g { connect_string: connect_string, expire: max_age as u64 } }
ct_string = format!("{}://{}:{}@{}:{}", protocol, username, password, host, &*port) } RedisConfi
conditional_block
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
ct_string: String, pub expire: u64 } pub fn get_redis_config(config: &Config) -> RedisConfig { let table = config.value(); let redis_config = table.get("redis").unwrap().as_table().unwrap(); let protocol = redis_config.get("protocol").unwrap().as_str().unwrap(); let host = redis_config.get("host")...
pub conne
identifier_name
db.rs
use mysql; use iron::typemap::Key; use common::config::Config; pub struct MySqlPool(mysql::Pool); impl MySqlPool { pub fn new(config: &Config) -> MySqlPool { let table = config.value(); let mysql_config = table.get("mysql").unwrap().as_table().unwrap(); let username = mysql_config.get(...
let table = config.value(); let redis_config = table.get("redis").unwrap().as_table().unwrap(); let protocol = redis_config.get("protocol").unwrap().as_str().unwrap(); let host = redis_config.get("host").unwrap().as_str().unwrap(); let port = redis_config.get("port").unwrap().as_integer().unwrap().t...
} pub fn get_redis_config(config: &Config) -> RedisConfig {
random_line_split