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
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /...
<E: Encodable> { pub version: String, pub event: String, pub data: E } #[cfg(test)] mod tests { use chan; use crossbeam; use rustc_serialize::json; use std::{fs, thread}; use std::io::{Read, Write}; use std::net::Shutdown; use std::time::Duration; use datatype::{Comma...
EventWrapper
identifier_name
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write};
use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /// The `Socket` gateway is used for communication via Unix Domain Sockets. pub struct Socket { pub commands_path: String, pub events_path: String, } ...
use std::net::Shutdown; use std::sync::{Arc, Mutex};
random_line_split
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /...
} fn handle_client(stream: &mut UnixStream, itx: Arc<Mutex<Sender<Interpret>>>) -> Result<Event, Error> { info!("New domain socket connection"); let mut reader = BufReader::new(stream); let mut input = String::new(); try!(reader.read_to_string(&mut input)); debug!("socket input: {}", input); ...
{ let output = match event { Event::DownloadComplete(dl) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadComplete".to_string(), data: dl }).expect("couldn't encode DownloadC...
identifier_body
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)]
pub protocol_version: String, #[serde(rename = "customDependencies")] pub custom_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "customDevDependencies")] pub custom_dev_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "baseTypeName")] p...
pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String, #[serde(rename = "protocolVersion")]
random_line_split
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)] pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String...
} impl Error for ConfigError { fn description(&self) -> &str { match *self { ConfigError::Io(ref e) => e.description(), ConfigError::Format(ref e) => e.description() } } fn cause(&self) -> Option<&Error> { match *self { ConfigError::Io(ref e) =>...
{ match *self { ConfigError::Io(ref e) => e.fmt(f), ConfigError::Format(ref e) => e.fmt(f) } }
identifier_body
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)] pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String...
(err: io::Error) -> Self { ConfigError::Io(err) } } impl From<serde_json::Error> for ConfigError { fn from(err: serde_json::Error) -> Self { ConfigError::Format(err) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ...
from
identifier_name
virtualscrollerdemo.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {FormsModule} from '@angular/forms'; import {VirtualScrollerDemo} from './virtualscrollerdemo'; import {VirtualScrollerDemoRoutingModule} from './virtualscrollerdemo-routing.module'; import {VirtualScrollerModule} from '../...
{}
VirtualScrollerDemoModule
identifier_name
virtualscrollerdemo.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {FormsModule} from '@angular/forms'; import {VirtualScrollerDemo} from './virtualscrollerdemo'; import {VirtualScrollerDemoRoutingModule} from './virtualscrollerdemo-routing.module'; import {VirtualScrollerModule} from '../...
] }) export class VirtualScrollerDemoModule {}
random_line_split
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
; } } } struct ErrorContext; impl glfw::ErrorCallback for ErrorContext { fn call(&self, _: glfw::Error, description: ~str) { println!("GLFW Error: {:s}", description); } } mod gl { use std::libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern {...
{ let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }
conditional_block
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern mod glfw; #[link(name="glfw")] extern {} #[start] fn start(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc...
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc, argv, main) } fn main() { glfw::set_error_callback(~ErrorContext); do glfw::start { glfw::window_hint::visible(true); let window = glfw::Window::create(640, 480, "Defaults", glfw::Windowed) .expect("Failed to...
start
identifier_name
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std:...
app.stdout.flush().expect("fail to flush the stdout"); }
random_line_split
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std:...
fn list_page(state_manager: &mut StateManager, tx_req: &Sender<ChannelItem>) -> String { let ci = ChannelItem { extra: Some(ChannelItemType::Index(Default::default())), result: Default::default() }; let status_message = match tx_req.send(ci) { Ok(()) => { state_manage...
{ // Initialize log4rs::init_file("config/log4rs.yaml", Default::default()).expect("fail to init log4rs"); info!("app start"); // Clear the screen. hkg::screen::common::clear_screen(); let _stdout = stdout(); // web background services let (tx_req, rx_req) = channel::<ChannelItem>()...
identifier_body
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std:...
(state_manager: &mut StateManager, tx_req: &Sender<ChannelItem>) -> String { let ci = ChannelItem { extra: Some(ChannelItemType::Index(Default::default())), result: Default::default() }; let status_message = match tx_req.send(ci) { Ok(()) => { state_manager.set_web_requ...
list_page
identifier_name
at-rule.test.ts
import { AtRule, parse } from '../lib/postcss.js' it('initializes with properties', () => { let rule = new AtRule({ name: 'encoding', params: '"utf-8"' }) expect(rule.name).toEqual('encoding') expect(rule.params).toEqual('"utf-8"') expect(rule.toString()).toEqual('@encoding "utf-8"') }) it('does not fall on...
expect(rule.nodes).toHaveLength(1) }) it('creates nodes property on append()', () => { let rule = new AtRule() expect(rule.nodes).not.toBeDefined() rule.append('color: black') expect(rule.nodes).toHaveLength(1) }) it('inserts default spaces', () => { let rule = new AtRule({ name: 'page', params: 1, nodes...
it('creates nodes property on prepend()', () => { let rule = new AtRule() expect(rule.nodes).not.toBeDefined() rule.prepend('color: black')
random_line_split
angular-locale_ro-ro.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function
(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.m.", "p.m." ...
getVF
identifier_name
angular-locale_ro-ro.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n...
"a.m.", "p.m." ], "DAY": [ "duminic\u0103", "luni", "mar\u021bi", "miercuri", "joi", "vineri", "s\u00e2mb\u0103t\u0103" ], "ERANAMES": [ "\u00eenainte de Hristos", "dup\u0103 Hristos" ], "ERAS": [ "\u00ee.Hr...
random_line_split
angular-locale_ro-ro.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n...
return PLURAL_CATEGORY.OTHER;} }); }]);
{ return PLURAL_CATEGORY.FEW; }
conditional_block
angular-locale_ro-ro.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n...
$provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.m.", "p.m." ], "DAY": [ "duminic\u0103", "luni", "mar\u021bi", "miercuri", "joi", "vineri", "s\u00e2mb\u0103t\u0103" ], "ERANAMES": [ "\u00eenainte de Hri...
{ var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; }
identifier_body
basemap.js
function myelement(name) { return document.getElementById(name); } function show_validation() { myelement("contenu").innerHTML=" Contenu Validé "; } function make_url(type,data) { switch (type) { case "url_osm": url="http://nominatim.openstreetmap.org/search?"; key="email=" + data["key"] ;
format="format=" + data["format"]; base= url + key + "&" + format + "&q=" + data["address"]; break; case "url_gmap": url="https://maps.googleapis.com/maps/api/geocode/"; key="key=" + data["key"]; format=data["format"] + "?"; base= url + format + key + "&address=" + data["address"]; break; ca...
random_line_split
basemap.js
function myelement(name) { return document.getElementById(name); } function show_validation() { myelement("contenu").innerHTML=" Contenu Validé "; } function m
type,data) { switch (type) { case "url_osm": url="http://nominatim.openstreetmap.org/search?"; key="email=" + data["key"] ; format="format=" + data["format"]; base= url + key + "&" + format + "&q=" + data["address"]; break; case "url_gmap": url="https://maps.googleapis.com/maps/api/geocode/"; ...
ake_url(
identifier_name
basemap.js
function myelement(name) { return document.getElementById(name); } function show_validation()
function make_url(type,data) { switch (type) { case "url_osm": url="http://nominatim.openstreetmap.org/search?"; key="email=" + data["key"] ; format="format=" + data["format"]; base= url + key + "&" + format + "&q=" + data["address"]; break; case "url_gmap": url="https://maps.googleapis.com/maps/...
{ myelement("contenu").innerHTML=" Contenu Validé "; }
identifier_body
auth.js
/* Open Chord Charts -- Database of free chord charts By: Christophe Benz <contact@openchordcharts.org> Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz https://github.com/openchordcharts/ This file is part of Open Chord Charts. Open Chord Charts is free software; you can redistribute it and/or modify it under t...
module.exports = {login, logout};
{ // TODO simplify promises construct return webservices.logout().catch(() => { forgetCredentials(); }).then(() => { forgetCredentials(); }); }
identifier_body
auth.js
/* Open Chord Charts -- Database of free chord charts By: Christophe Benz <contact@openchordcharts.org> Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz https://github.com/openchordcharts/ This file is part of Open Chord Charts. Open Chord Charts is free software; you can redistribute it and/or modify it under t...
() { return webservices.login().then((res) => { if (res.login === "ok") { sessionStorage.loggedInUsername = res.username; global.authEvents.emit("loggedIn"); return true; } else { forgetCredentials(); return false; } }); } function logout() { // TODO simplify promises c...
login
identifier_name
auth.js
/* Open Chord Charts -- Database of free chord charts By: Christophe Benz <contact@openchordcharts.org> Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz https://github.com/openchordcharts/ This file is part of Open Chord Charts. Open Chord Charts is free software; you can redistribute it and/or modify it under t...
}); } function logout() { // TODO simplify promises construct return webservices.logout().catch(() => { forgetCredentials(); }).then(() => { forgetCredentials(); }); } module.exports = {login, logout};
{ forgetCredentials(); return false; }
conditional_block
auth.js
/* Open Chord Charts -- Database of free chord charts By: Christophe Benz <contact@openchordcharts.org> Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz https://github.com/openchordcharts/ This file is part of Open Chord Charts. Open Chord Charts is free software; you can redistribute it and/or modify it under t...
module.exports = {login, logout};
}
random_line_split
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(()) ...
if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; }
random_line_split
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(())...
{ if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; }
conditional_block
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
/// Get address balance at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn balance(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address balance at the latest block's state. f...
{ self.code(address, BlockID::Latest) .expect("code will return Some if given BlockID::Latest; qed") }
identifier_body
traits.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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....
(&self, address: &Address, position: &H256) -> H256 { self.storage_at(address, position, BlockID::Latest) .expect("storage_at will return Some if given BlockID::Latest. storage_at was given BlockID::Latest. \ Therefore storage_at has returned Some; qed") } /// Get a list of all accounts in the block `id`, if...
latest_storage_at
identifier_name
routes.js
// Controller for post digest PostsSingledayController = RouteController.extend({ template: getTemplate('singleDay'), onBeforeAction: function () { this.render(getTemplate('postListTop'), {to: 'postListTop'}); this.next(); }, data: function() { var currentDate = this.params.day ? new Date(this...
}); Router.route('/day', { name: 'postsSingleDayDefault', controller: PostsSingledayController }); });
name: 'postsSingleDay', controller: PostsSingledayController
random_line_split
repl.nls.js
/*!-------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ /*--------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. *---------------...
"Read Eval Print Loop Panel" ], "vs/workbench/parts/debug/electron-browser/replViewer": [ "Object state is captured from first evaluation", "Click to follow (Cmd + click opens to the side)", "Click to follow (Ctrl + click opens to the side)", "Variable {0} has value {1}, read eval print loop, debug", "Exp...
define("vs/workbench/parts/debug/electron-browser/repl.nls", { "vs/workbench/parts/debug/electron-browser/repl": [
random_line_split
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for Cust...
(&self) -> &str { self.0.as_str() } } fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), ...
description
identifier_name
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for Cust...
use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_description_with_key_value_pairs() { use std::error::Error; let error = throws_error_with_description_and_key_value_pairs().unwrap_err(); assert_eq!...
random_line_split
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for Cust...
} fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), "key" => "value" ); Ok(()) } #[te...
{ self.0.as_str() }
identifier_body
latest_blessed_model_strategy_test.py
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
tf.test.main()
conditional_block
latest_blessed_model_strategy_test.py
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
(self): # Model with id 1, will be blessed. model_one = standard_artifacts.Model() model_one.uri = 'model_one' model_one.id = 1 # Model with id 2, will be blessed. model_two = standard_artifacts.Model() model_two.uri = 'model_two' model_two.id = 2 # Model with id 3, will not be bless...
testStrategy
identifier_name
latest_blessed_model_strategy_test.py
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
class LatestBlessedModelStrategyTest(test_case_utils.TfxTest): def setUp(self): super().setUp() self._connection_config = metadata_store_pb2.ConnectionConfig() self._connection_config.sqlite.SetInParent() self._metadata = self.enter_context( metadata.Metadata(connection_config=self._connect...
from ml_metadata.proto import metadata_store_pb2
random_line_split
latest_blessed_model_strategy_test.py
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
if __name__ == '__main__': tf.test.main()
model_one = standard_artifacts.Model() model_one.uri = 'model_one' model_one.id = 1 # Model with id 2, will be blessed. model_two = standard_artifacts.Model() model_two.uri = 'model_two' model_two.id = 2 # Model with id 3, will not be blessed. model_three = standard_artifacts.Model() ...
identifier_body
updateImageSize.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const widthAttr = getAttribute(node, 'width'); const heightAttr = getAttribute(node, 'height'); const quote = getAttributeQuote(editor, srcAttr); const endOfAttributes = node.attributes[node.attributes.length - 1].end; let edits: TextEdit[] = []; let textToAdd = ''; if (!widthAttr) { textToAdd += ` width=${q...
random_line_split
updateImageSize.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
tmlNode): string | undefined { const srcAttr = getAttribute(node, 'src'); if (!srcAttr) { return; } return (<HtmlToken>srcAttr.value).value; } /** * Returns image source from given `url()` token */ function getImageSrcCSS(node: Property | undefined, position: Position): string | undefined { if (!node) { re...
SrcHTML(node: H
identifier_name
updateImageSize.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
Returns image source from given `url()` token */ function getImageSrcCSS(node: Property | undefined, position: Position): string | undefined { if (!node) { return; } const urlToken = findUrlToken(node, position); if (!urlToken) { return; } // A stylesheet token may contain either quoted ('string') or unquo...
srcAttr = getAttribute(node, 'src'); if (!srcAttr) { return; } return (<HtmlToken>srcAttr.value).value; } /** *
identifier_body
updateImageSize.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
xtToAdd) { edits.push(new TextEdit(new Range(endOfAttributes, endOfAttributes), textToAdd)); } return edits; } /** * Updates size of given CSS rule */ function updateCSSNode(editor: TextEditor, srcProp: Property, width: number, height: number): TextEdit[] { const rule = srcProp.parent; const widthProp = getCs...
s.push(new TextEdit(new Range(heightAttr.value.start, heightAttr.value.end), String(height))); } if (te
conditional_block
main_make_SWS_scalar_product.py
#!/usr/bin/env python ''' File name: main_ripp_mod.py Author: Guillaume Viejo Date created: 16/08/2017 Python Version: 3.5.2 ''' import sys import numpy as np import pandas as pd import scipy.io from functions import * # from pylab import * from multiprocessing import Pool import os import neurose...
spikeshd = {k:spikes[k] for k in np.where(hd_info_neuron==1)[0] if k not in []} spikesnohd = {k:spikes[k] for k in np.where(hd_info_neuron==0)[0] if k not in []} hdneurons = np.sort(list(spikeshd.keys())) nohdneurons = np.sort(list(spikesnohd.keys())) bin_size = 40 n_ex = 2000 rnd_tsd = nts.Ts(t = np.so...
# binning data ####################################################################################################################
random_line_split
main_make_SWS_scalar_product.py
#!/usr/bin/env python ''' File name: main_ripp_mod.py Author: Guillaume Viejo Date created: 16/08/2017 Python Version: 3.5.2 ''' import sys import numpy as np import pandas as pd import scipy.io from functions import * # from pylab import * from multiprocessing import Pool import os import neurose...
(r): tmp = np.sqrt(np.power(r, 2).sum(1)) denom = tmp[0:-1] * tmp[1:] num = np.sum(r[0:-1]*r[1:], 1) return num/(denom) @jit(nopython=True) def quickBin(spikelist, ts, bins, index): rates = np.zeros((len(ts), len(bins)-1, len(index))) for i, t in enumerate(ts): tbins = t + bins for j in range(len(spikelist)...
scalarProduct
identifier_name
main_make_SWS_scalar_product.py
#!/usr/bin/env python ''' File name: main_ripp_mod.py Author: Guillaume Viejo Date created: 16/08/2017 Python Version: 3.5.2 ''' import sys import numpy as np import pandas as pd import scipy.io from functions import * # from pylab import * from multiprocessing import Pool import os import neurose...
title("Radius") subplot(232) for i in velocity.columns: plot(velocity[i]) title("Ang velocity") subplot(233) for i in stability.columns: plot(stability[i]) title("Stability") subplot(234) for i in radius.columns: scatter(radius[i], stability[i]) xlabel("Radius") ylabel("Stability") subplot(235) for i in radius.co...
plot(radius[i])
conditional_block
main_make_SWS_scalar_product.py
#!/usr/bin/env python ''' File name: main_ripp_mod.py Author: Guillaume Viejo Date created: 16/08/2017 Python Version: 3.5.2 ''' import sys import numpy as np import pandas as pd import scipy.io from functions import * # from pylab import * from multiprocessing import Pool import os import neurose...
data_directory = '/mnt/DataGuillaume/MergedData/' datasets = np.loadtxt(data_directory+'datasets_ThalHpc.list', delimiter = '\n', dtype = str, comments = '#') anglehd = {} anglenohd = {} zanglehd = {} zanglenohd = {} for session in datasets: print(session) generalinfo = scipy.io.loadmat(data_directory+session+...
rates = np.zeros((len(ts), len(bins)-1, len(index))) for i, t in enumerate(ts): tbins = t + bins for j in range(len(spikelist)): a, _ = np.histogram(spikelist[j], tbins) rates[i,:,j] = a return rates
identifier_body
mod.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 base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{Byt...
/// Sets a byte in the slice to a value. /// /// [argument, idx] /// The index of the byte to be set. /// /// [argument, val] /// The value of the byte. /// /// = Remarks /// /// If `val == 0`, the process is aborted. pub fn set(&mut self, idx: usize, val: u8) { a...
impl NoNullStr {
random_line_split
mod.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 base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{Byt...
<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
fmt
identifier_name
mod.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 base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{Byt...
} impl Debug for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
{ self.as_ref() }
identifier_body
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SI...
#[cfg(target_os = "macos")] const numname: [(&str, c_int); 27] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ...
("POLL", libc::SIGPOLL), ("PWR", libc::SIGPWR), ("SYS", libc::SIGSYS), ];
random_line_split
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SI...
{ let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s { *signum = num; ...
identifier_body
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SI...
(signame: *const c_char, signum: *mut c_int) -> c_int { let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s...
str2sig
identifier_name
analyse_check_q_boundary_condition.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
# nproc = 1 # Number of processors to use from boututils import shell, launch, plotdata from boutdata import collect import numpy as np from sys import argv from math import sqrt, log10, log, pi from matplotlib import pyplot gamma = 3. if len(argv)>1: data_path = str(argv[1]) else: data_path = "data" electron...
# # Runs the conduction example, produces some output
random_line_split
analyse_check_q_boundary_condition.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Runs the conduction example, produces some output # nproc = 1 # Number of processors to use from boututils import shell, launch, plotdata from boutdata import collect import numpy as np from sys import argv from math import sqrt, log10, log, pi from matplotlib impo...
electron_mass = 9.10938291e-31 ion_mass = 3.34358348e-27 # Collect the data Te = collect("T_electron", path=data_path, info=True, yguards=True) Ti = collect("T_ion", path=data_path, info=True, yguards=True) n = collect("n_ion", path=data_path, info=True, yguards=True) V = collect("Vpar_ion", path=data_path, info=Tr...
data_path = "data"
conditional_block
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self...
fn clone(&self) -> Reshape<T> { Reshape{ base: self.base.clone(), nrow: self.nrow, ncol: self.ncol } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Reshape<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result { write_mat(buf, self) } }
random_line_split
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self...
}
{ write_mat(buf, self) }
identifier_body
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self...
(&self, r: usize, c: usize, val: f64) { self.base.unsafe_set(r * self.ncol() + c, val) } } impl<T> MatrixShape for Reshape<T> { fn nrow(&self) -> usize { self.nrow } fn ncol(&self) -> usize { self.ncol } } impl<T: MatrixShape> SameShape for Reshape<T> { fn same_shape(&self, nrow: usize, ncol: usize) ->...
raw_set
identifier_name
ifOptIn.tsx
// import * as React from 'react' // import { Optionalize } from 'src/util/types' // import { UserFeatureOptIn, UserFeatureOptInMap } from 'src/feature-opt-in/background/feature-opt-ins' // // // interface NavigationDependencies { userOptInFeatures: UserFeatureOptInMap} // export type NavigationDisplayChecker = (info: ...
// currentUser: await auth.getCurrentUser(), // authorizedFeatures: await auth.getAuthorizedFeatures(), // }) // const authEvents = getRemoteEventEmitter('auth') // authEvents.addListener( // 'onAuthStateChanged', // thi...
// } // // componentDidMount = async () => { // this.setState({
random_line_split
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _...
} impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value != 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) -> bool { self.value == 0 } } ...
impl<E> QFlags<E> { pub fn to_int(self) -> c_int { self.value }
random_line_split
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _...
} impl<E> From<QFlags<E>> for c_int { fn from(flags: QFlags<E>) -> Self { flags.value } } impl<E> QFlags<E> { pub fn to_int(self) -> c_int { self.value } } impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) ...
{ Self { value, _phantom_data: PhantomData, } }
identifier_body
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _...
(self) -> c_int { self.value } } impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value != 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) ...
to_int
identifier_name
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { ...
=> { rest.iter().fold(first, |acc, &item| { let &(op, factor) = &item; match op { "*" => acc * factor, "/" => acc / factor, _ => unreachable!() } }) } ); rule!(factor:i32 ...
rest:(ws op:(["*"] / ["/"]) ws factor:factor => {(op, factor)})*
random_line_split
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str>
rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, term)})* => { rest.iter().fold(first, |acc, &item| { let &(op, term) = &item; match op { "+" => acc + term, "-" => acc - term...
{ let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if !char.is_digit(10) { end = index; break; } }, None => { ...
identifier_body
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { ...
, None => { end = input.len(); break; } } } if end > 0 { Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, ...
{ if !char.is_digit(10) { end = index; break; } }
conditional_block
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn
(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if !char.is_digit(10) { end = index; break; } ...
digits
identifier_name
data.py
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license import re from dadict import DADict from error import log_loading ############ ## Consts ## ############ ETHER_ANY = "\...
except Exception,e: log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e)) f.close() except IOError: log_loading.info("Can't open /etc/services file") return tdct,udct TCP_SERVICES,UDP_SERVICES=load_services("/etc/services") class ManufDA(DADict...
udct[lt[0]] = int(lt[1].split('/')[0])
conditional_block
data.py
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license import re from dadict import DADict from error import log_loading ############ ## Consts ## ############ ETHER_ANY = "\...
def _get_manuf(self, mac): return self._get_manuf_couple(mac)[1] def _get_short_manuf(self, mac): return self._get_manuf_couple(mac)[0] def _resolve_MAC(self, mac): oui = ":".join(mac.split(":")[:3]).upper() if oui in self: return ":".join([self[oui][0]]+ mac.spl...
oui = ":".join(mac.split(":")[:3]).upper() return self.__dict__.get(oui,(mac,mac))
identifier_body
data.py
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license import re from dadict import DADict from error import log_loading ############ ## Consts ## ############ ETHER_ANY = "\...
l = l.strip() if not l: continue lt = tuple(re.split(spaces, l)) if len(lt) < 2 or not lt[0]: continue dct[lt[0]] = int(lt[1]) except Exception,e: log_loading.info("Couldn'...
l = l[:shrp]
random_line_split
data.py
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license import re from dadict import DADict from error import log_loading ############ ## Consts ## ############ ETHER_ANY = "\...
(filename): try: manufdb=ManufDA(_name=filename) for l in open(filename): try: l = l.strip() if not l or l.startswith("#"): continue oui,shrt=l.split()[:2] i = l.find("#") if i < 0: ...
load_manuf
identifier_name
preprocessed_dataset.py
import numpy as np import os import random import threading import time import traceback from util import cmudict, textinput from util.infolog import log import chainer _batches_per_group = 32 _p_cmudict = 0.5 _pad = 0 # https://github.com/chainer/chainer/blob/1ad6355f8bfe4ccfcf0efcfdb5bd048787069806/examples/imagene...
(self, word): pron = self._cmudict.lookup(word) return '{%s}' % pron[0] if pron is not None and random.random() < 0.5 else word def _prepare_batch(batch, outputs_per_step): random.shuffle(batch) inputs = _prepare_inputs([x[0] for x in batch]) input_lengths = np.asarray([len(...
_maybe_get_arpabet
identifier_name
preprocessed_dataset.py
import numpy as np import os import random import threading import time import traceback from util import cmudict, textinput from util.infolog import log import chainer _batches_per_group = 32 _p_cmudict = 0.5 _pad = 0 # https://github.com/chainer/chainer/blob/1ad6355f8bfe4ccfcf0efcfdb5bd048787069806/examples/imagene...
self._metadata = [line.strip().split('|') for line in f] hours = sum((int(x[2]) for x in self._metadata)) * \ hparams.frame_shift_ms / (3600 * 1000) log('Loaded metadata for %d examples (%.2f hours)' % (len(self._metadata), hours)) # Load CMUD...
# Load metadata: self._datadir = os.path.dirname(metadata_filename) # with open(metadata_filename) as f: with open(metadata_filename, encoding="utf-8_sig") as f:
random_line_split
preprocessed_dataset.py
import numpy as np import os import random import threading import time import traceback from util import cmudict, textinput from util.infolog import log import chainer _batches_per_group = 32 _p_cmudict = 0.5 _pad = 0 # https://github.com/chainer/chainer/blob/1ad6355f8bfe4ccfcf0efcfdb5bd048787069806/examples/imagene...
def _round_up(x, multiple): remainder = x % multiple return x if remainder == 0 else x + multiple - remainder # implimentation of DatasetMixin? def __len__(self): return len(self._metadata) # implimentation of DatasetMixin def get_example(self, i): input, mel, lin...
return np.pad(t, [(0, length - t.shape[0]), (0, 0)], mode='constant', constant_values=_pad)
identifier_body
preprocessed_dataset.py
import numpy as np import os import random import threading import time import traceback from util import cmudict, textinput from util.infolog import log import chainer _batches_per_group = 32 _p_cmudict = 0.5 _pad = 0 # https://github.com/chainer/chainer/blob/1ad6355f8bfe4ccfcf0efcfdb5bd048787069806/examples/imagene...
def _get_next_example(self, offset): '''Loads a single example (input, mel_target, linear_target, cost) from disk''' meta = self._metadata[offset] text = meta[3] if self._cmudict and random.random() < _p_cmudict: text = ' '.join([self._maybe_get_arpabet(word) ...
self._cmudict = None
conditional_block
purchase-requisition.component.ts
import { Component, OnInit } from '@angular/core'; import { purchaseService } from '../services/purchase.service'; import { Router } from '@angular/router'; export class PrItem{ itemNo: string; itemDes: string; qty:string; unitPrice:string; exCost:string } @Component({ selector: 'purchase-req...
implements OnInit { itemEntered:PrItem; items:PrItem[]=[]; items1:any=[]; constructor(private purchase_requisition:purchaseService,private router:Router) { this.purchase_requisition.getPR1().subscribe(ss=>{ this.items1=ss console.log(this.items1); }); this.purchase_requisition...
purchaseRequisitionComponent
identifier_name
purchase-requisition.component.ts
import { Component, OnInit } from '@angular/core'; import { purchaseService } from '../services/purchase.service'; import { Router } from '@angular/router'; export class PrItem{ itemNo: string; itemDes: string; qty:string; unitPrice:string; exCost:string } @Component({ selector: 'purchase-req...
}
random_line_split
34b18e18775c_add_last_totp_value_to_user.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
def downgrade(): op.drop_column("users", "last_totp_value")
op.add_column("users", sa.Column("last_totp_value", sa.String(), nullable=True))
identifier_body
34b18e18775c_add_last_totp_value_to_user.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
(): op.drop_column("users", "last_totp_value")
downgrade
identifier_name
34b18e18775c_add_last_totp_value_to_user.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
def downgrade(): op.drop_column("users", "last_totp_value")
random_line_split
select_multiple_control_value_accessor.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Provider, Renderer2, forwardRef, ɵlooseIdentical as...
implements ControlValueAccessor { value: any; /** @internal */ _optionMap: Map<string, NgSelectMultipleOption> = new Map<string, NgSelectMultipleOption>(); /** @internal */ _idCounter: number = 0; onChange = (_: any) => {}; onTouched = () => {}; @Input() set compareWith(fn: (o1: any, o2: any) => boo...
electMultipleControlValueAccessor
identifier_name
select_multiple_control_value_accessor.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Provider, Renderer2, forwardRef, ɵlooseIdentical as...
constructor(private _renderer: Renderer2, private _elementRef: ElementRef) {} writeValue(value: any): void { this.value = value; let optionSelectedStateSetter: (opt: NgSelectMultipleOption, o: any) => void; if (Array.isArray(value)) { // convert values to ids const ids = value.map((v) => t...
} this._compareWith = fn; } private _compareWith: (o1: any, o2: any) => boolean = looseIdentical;
random_line_split
select_multiple_control_value_accessor.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Provider, Renderer2, forwardRef, ɵlooseIdentical as...
else { this._setElementValue(value); } } /** @internal */ _setElementValue(value: string): void { this._renderer.setProperty(this._element.nativeElement, 'value', value); } /** @internal */ _setSelected(selected: boolean) { this._renderer.setProperty(this._element.nativeElement, 'selecte...
this._value = value; this._setElementValue(_buildValueString(this.id, value)); this._select.writeValue(this._select.value); }
conditional_block
bounds.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 ...
(cx: &mut ExtCtxt, span: Span, _: &MetaItem, _: &Annotatable, _: &mut dyn FnMut(Annotatable)) { cx.span_err(span, "this unsafe trait should be implemented explicitly"); } ...
expand_deriving_unsafe_bound
identifier_name
bounds.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 ...
{ let trait_def = TraitDef { span, attributes: Vec::new(), path: path_std!(cx, marker::Copy), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: true, methods: Vec::new(), associated_types: Vec:...
identifier_body
bounds.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
use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::MetaItem; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; pub fn expand_deriving_unsafe_bound(cx: &mut ExtCtxt, span: Span, _: &MetaItem, ...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use deriving::path_std;
random_line_split
gui_helper.py
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # gui_helper.py - # Copyright 2013 Tomas Hozza <thozza@gmail.com> # # 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 Lic...
(message="Error", buttons=Gtk.ButtonsType.CLOSE, parent=None, sec_message=None): return GuiHelper.show_msg_dialog(GuiHelper.DIALOG_TYPE_ERROR, message, buttons, parent, ...
show_error_dialog
identifier_name
gui_helper.py
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # gui_helper.py - # Copyright 2013 Tomas Hozza <thozza@gmail.com> # # 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 Lic...
@staticmethod def enable_item(widget, enable=True): widget.set_sensitive(enable) @staticmethod def calendar_get_date(calendar): year, month, day = calendar.get_date() return date(year, month + 1, day) @staticmethod def create_msg_dialog(type=DIALOG_TYPE_INFO, ...
random_line_split
gui_helper.py
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # gui_helper.py - # Copyright 2013 Tomas Hozza <thozza@gmail.com> # # 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 Lic...
@staticmethod def replace_widget2(cur, replace): """replace cur widget with another in a container keeping child properties""" con = cur.get_parent() pos = con.child_get_property(cur, "position", "") pak = con.query_child_packing(cur) con.remove(cur) if replace....
""" Replace one widget with another. 'current' has to be inside a container (e.g. gtk.VBox). """ container = current.get_parent() assert container # is "current" inside a container widget? # stolen from gazpacho code (widgets/base/base.py): props = {} for...
identifier_body
gui_helper.py
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # gui_helper.py - # Copyright 2013 Tomas Hozza <thozza@gmail.com> # # 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 Lic...
return None @staticmethod def widget_override_color(widget, color_string=None): if color_string: widget.override_color(Gtk.StateFlags.NORMAL, GuiHelper.get_RGBA_color(color_string)) else: widget.override_color(Gtk.StateFlags.NOR...
return color
conditional_block
MemUsageTimeseries.py
#!/usr/bin/env python """ Timeseries generator module """ from supremm.plugin import Plugin from supremm.subsample import TimeseriesAccumulator import numpy from collections import Counter class MemUsageTimeseries(Plugin): """ Generate the CPU usage as a timeseries data """ name = property(lambda x: "memused...
if nodemeta.nodeindex not in self._hostdata: self._hostdata[hostidx] = numpy.empty((TimeseriesAccumulator.MAX_DATAPOINTS, len(data[0]))) self._hostdevnames[hostidx] = dict((str(k), "numa " + v) for k, v in zip(description[0][0], description[0][1])) nodemem_kb = numpy.sum(data[...
return True
conditional_block
MemUsageTimeseries.py
#!/usr/bin/env python """ Timeseries generator module """ from supremm.plugin import Plugin from supremm.subsample import TimeseriesAccumulator import numpy from collections import Counter class MemUsageTimeseries(Plugin): """ Generate the CPU usage as a timeseries data """ name = property(lambda x: "memused...
def results(self): values = self._data.get() if len(self._hostdata) > 64: # Compute min, max & median data and only save the host data # for these hosts memdata = values[:, :, 1] sortarr = numpy.argsort(memdata.T, axis=1) retdata = { ...
return True
random_line_split
MemUsageTimeseries.py
#!/usr/bin/env python """ Timeseries generator module """ from supremm.plugin import Plugin from supremm.subsample import TimeseriesAccumulator import numpy from collections import Counter class MemUsageTimeseries(Plugin):
""" Generate the CPU usage as a timeseries data """ name = property(lambda x: "memused_minus_diskcache") mode = property(lambda x: "timeseries") requiredMetrics = property(lambda x: ["mem.numa.util.used", "mem.numa.util.filePages", "mem.numa.util.slab"]) optionalMetrics = property(lambda x: []) der...
identifier_body
MemUsageTimeseries.py
#!/usr/bin/env python """ Timeseries generator module """ from supremm.plugin import Plugin from supremm.subsample import TimeseriesAccumulator import numpy from collections import Counter class MemUsageTimeseries(Plugin): """ Generate the CPU usage as a timeseries data """ name = property(lambda x: "memused...
(self, nodemeta, timestamp, data, description): hostidx = nodemeta.nodeindex if len(data[0]) == 0: # Skip data point with no data return True if nodemeta.nodeindex not in self._hostdata: self._hostdata[hostidx] = numpy.empty((TimeseriesAccumulator.MAX_DATAP...
process
identifier_name
lib.rs
//! A wrapper for the Strava API //! //! # Organization //! //! The module layout in this crate mirrors the [Strava API documentation][]. All functions //! interacting with the strava servers will return a //! [`strava::error::Result`](error/type.Result.html) for which the `E` parameter is curried to //! [`strava::erro...
//! // Get the athlete associated with the given token //! let athlete = Athlete::get_current(&token).unwrap(); //! //! // All of the strava types implement Debug and can be printed like so: //! println!("{:?}", athlete); //! ``` //! //! [Strava API Documentation]: http://strava.github.io/api/ extern crate hyper; exte...
//!
random_line_split
aggregator.py
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N):
return data_binned class LatLonAggregator(object): """A class for aggregating L2 data into a gridded dataset.""" def __init__(self, dlon=1., dlat=1., lonlim=(-180,180), latlim=(-90,90)): self.dlon = dlon self.dlat = dlat self.lonmin = lonlim[0] self.lonmax = lonlim[1] ...
data_binned[j[n],i[n]] += data[n]
conditional_block
aggregator.py
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N): data_binned[j[n],i[n]] += data[n] return data_binn...
(self, data, lon, lat): """Bin the data into the lat-lon grid. Returns gridded dataset.""" i = np.digitize(lon.ravel(), self.lon) j = np.digitize(lat.ravel(), self.lat) return binsum2D(data.ravel(), i, j, self.Nx, self.Ny) def zeros(self, dtype=np.dtype('f4')): retur...
binsum
identifier_name
aggregator.py
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N): data_binned[j[n],i[n]] += data[n] return data_binn...
"""A class for aggregating L2 data into a gridded dataset.""" def __init__(self, dlon=1., dlat=1., lonlim=(-180,180), latlim=(-90,90)): self.dlon = dlon self.dlat = dlat self.lonmin = lonlim[0] self.lonmax = lonlim[1] self.latmin = latlim[0] self.latmax = latlim[1] ...
identifier_body
aggregator.py
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N): data_binned[j[n],i[n]] += data[n] return data_binn...
i = np.digitize(lon.ravel(), self.lon) j = np.digitize(lat.ravel(), self.lat) return binsum2D(data.ravel(), i, j, self.Nx, self.Ny) def zeros(self, dtype=np.dtype('f4')): return np.zeros((self.Ny, self.Nx), dtype=dtype)
def binsum(self, data, lon, lat): """Bin the data into the lat-lon grid. Returns gridded dataset."""
random_line_split
validators.py
PROJECT_DEFAULTS = 'Project Defaults' PATHS = 'Paths' _from_config = { 'author': None, 'email': None, 'license': None, 'language': None, 'type': None, 'parent': None, 'vcs': None, 'footprints': None } _from_args = { 'name': None, 'author': None, 'email': None, 'license'...
return from_args def load_config(config): from_config = _from_config.copy() keys = _from_config.keys() if config: if config.has_section(PROJECT_DEFAULTS): for key in keys: if config.has_option(PROJECT_DEFAULTS, key): from_config[key] = config.ge...
from_args[key] = args.__getattribute__(key)
conditional_block
validators.py
PROJECT_DEFAULTS = 'Project Defaults' PATHS = 'Paths' _from_config = { 'author': None, 'email': None, 'license': None, 'language': None, 'type': None, 'parent': None, 'vcs': None, 'footprints': None } _from_args = { 'name': None, 'author': None, 'email': None, 'license'...
(configged, argged): merged = configged.copy() for key in argged.keys(): if True in [key == k for k in configged.keys()]: # We only care about a None val if the key exists in configged # this will overwrite the config so that args take percedence if argged[key] is not...
merge_configged_argged
identifier_name