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
ZI_PQSC.py
""" Driver for PQSC V1 Author: Michael Kerschbaum Date: 2019/09 """ import time import sys import os import logging import numpy as np import pycqed import json import copy import pycqed.instrument_drivers.physical_instruments.ZurichInstruments.ZI_base_instrument as zibase log = logging.getLogger(__name__) ########...
(self): if self.devtype != 'PQSC': raise zibase.ziDeviceError('Device {} of type {} is not a PQSC \ instrument!'.format(self.devname, self.devtype)) def _check_options(self): """ Checks that the correct options are installed on the instrument. """ ...
_check_devtype
identifier_name
ZI_PQSC.py
""" Driver for PQSC V1 Author: Michael Kerschbaum Date: 2019/09 """ import time import sys import os import logging import numpy as np import pycqed import json import copy import pycqed.instrument_drivers.physical_instruments.ZurichInstruments.ZI_base_instrument as zibase log = logging.getLogger(__name__) ########...
**kw) -> None: """ Input arguments: name: (str) name of the instrument device (str) the name of the device e.g., "dev8008" interface (str) the name of the interface to use ('1GbE' or 'USB') ...
""" This is the frist version of the PycQED driver for the Zurich Instruments PQSC. """ # Put in correct minimum required revisions #FIXME: put correct version MIN_FWREVISION = 63210 MIN_FPGAREVISION = 63133 ########################################################################## ...
identifier_body
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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 ap...
{ /** * Exponential distribution constructor. * * @param lambda - rate parameter * @throws `lambda` must be a positive number * @returns distribution instance * * @example * var exponential = new Exponential( 1.0 ); * * var y = exponential.cdf( 0.8 ); * // returns ~0.551 * * var v = exponential.mode; * ...
Exponential
identifier_name
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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 ap...
} // EXPORTS // export = Exponential;
quantile( p: number ): number;
random_line_split
inverse.rs
use num::{Zero, One, Signed}; use bigint::{BigUint, BigInt, Sign}; pub trait Inverse { type Output; fn inverse(self, modulo: Self) -> Option<Self::Output>; } impl<'a> Inverse for &'a BigUint { type Output = BigUint; fn inverse(self, modulo: Self) -> Option<Self::Output> { BigInt::from_biguin...
(self, modulo: Self) -> Option<Self::Output> { let (mut t, mut new_t): (BigInt, BigInt) = (Zero::zero(), One::one()); let (mut r, mut new_r): (BigInt, BigInt) = (modulo.clone(), self.clone()); while !new_r.is_zero() { let quo = &r / &new_r; let tmp = &r - &quo * &new_r; ...
inverse
identifier_name
inverse.rs
use num::{Zero, One, Signed}; use bigint::{BigUint, BigInt, Sign}; pub trait Inverse { type Output; fn inverse(self, modulo: Self) -> Option<Self::Output>; } impl<'a> Inverse for &'a BigUint { type Output = BigUint; fn inverse(self, modulo: Self) -> Option<Self::Output> { BigInt::from_biguin...
impl<'a> Inverse for &'a BigInt { type Output = BigInt; fn inverse(self, modulo: Self) -> Option<Self::Output> { let (mut t, mut new_t): (BigInt, BigInt) = (Zero::zero(), One::one()); let (mut r, mut new_r): (BigInt, BigInt) = (modulo.clone(), self.clone()); while !new_r.is_zero() { ...
}
random_line_split
inverse.rs
use num::{Zero, One, Signed}; use bigint::{BigUint, BigInt, Sign}; pub trait Inverse { type Output; fn inverse(self, modulo: Self) -> Option<Self::Output>; } impl<'a> Inverse for &'a BigUint { type Output = BigUint; fn inverse(self, modulo: Self) -> Option<Self::Output> { BigInt::from_biguin...
} }
{ Some(t) }
conditional_block
inverse.rs
use num::{Zero, One, Signed}; use bigint::{BigUint, BigInt, Sign}; pub trait Inverse { type Output; fn inverse(self, modulo: Self) -> Option<Self::Output>; } impl<'a> Inverse for &'a BigUint { type Output = BigUint; fn inverse(self, modulo: Self) -> Option<Self::Output> { BigInt::from_biguin...
Some(t) } } }
{ let (mut t, mut new_t): (BigInt, BigInt) = (Zero::zero(), One::one()); let (mut r, mut new_r): (BigInt, BigInt) = (modulo.clone(), self.clone()); while !new_r.is_zero() { let quo = &r / &new_r; let tmp = &r - &quo * &new_r; r = new_r; new_r = tm...
identifier_body
i686_unknown_linux_gnu.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 mut base = super::linux_base::opts(); base.pre_link_args.push("-m32".to_string()); Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), target_word_...
identifier_body
i686_unknown_linux_gnu.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 ...
() -> Target { let mut base = super::linux_base::opts(); base.pre_link_args.push("-m32".to_string()); Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), ...
target
identifier_name
i686_unknown_linux_gnu.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target;...
random_line_split
index.tsx
import React, { MouseEvent, ReactNode } from 'react' interface Props { 'aria-describedby'?: string
children?: ReactNode className?: string nodeType?: 'button' | 'input' onClick?: (event?: MouseEvent<HTMLButtonElement | HTMLInputElement>) => void outline?: boolean overrideClassName?: boolean style?: object type?: 'button' | 'reset' | 'submit' } /** * Button * @prop {string} [aria-describedby] aria-...
'aria-label'?: string 'aria-labelledby'?: string
random_line_split
index.tsx
import React, { MouseEvent, ReactNode } from 'react' interface Props { 'aria-describedby'?: string 'aria-label'?: string 'aria-labelledby'?: string children?: ReactNode className?: string nodeType?: 'button' | 'input' onClick?: (event?: MouseEvent<HTMLButtonElement | HTMLInputElement>) => void outline?...
} let t = type || 'button' // Apply type attribute // Apply CSS class names let classNames = [] if (!overrideClassName) { classNames.push('btn') if (outline) classNames.push('outline') } if (className) classNames.push(className) // Render component return ( <Node aria-describedby...
{ // eslint-disable-next-line no-console console.warn( 'Attempted to set unsupported node type. Setting node type as "button".' ) }
conditional_block
inboxFinancialFacts.js
import { createBackendModule } from './backendModule' import { SUCCESS_CREATE as JOURNAL_ENTRY_SUCCESS_CREATE } from './journalEntryCreatedEvents' import { BASE_PATH, objectToQueryParams } from 'modules/http' const path = 'journal-entry-proposals' const SUCCESS_FETCH_JEP = '@@' + path + '/SUCCESS_FETCH' const START_FE...
const module = createBackendModule('inboxFinancialFacts') export const fetchInboxFinancialFacts = module.fetchActionCreator module.ACTION_HANDLERS[JOURNAL_ENTRY_SUCCESS_CREATE] = (state, action) => { const financialFactId = action.json.financialFactId return { ...state, data: state.data.filter(iff => iff...
} }
random_line_split
mongoCursorSnippets.ts
///<reference path='typings/node/node.d.ts'/> var mongoForEachTemplates = [ { caption: "forEach", snippet: `forEach((it)=> { $1 });`, comment: 'Iterates the cursor to apply a JavaScript function to each document from the cursor.', example: `db.users.find()...
snippet: `limit(\${2:5})`, comment: 'Use the limit() method on a cursor to specify the maximum number of documents the cursor will return. limit() is analogous to the LIMIT statement in a SQL database.', example: `db.orders.find().limit(5)`, score:1000 }, ] var m...
var mongoLimitTemplates = [ { caption: "limit",
random_line_split
from_list.rs
use crate::*; // List used for calling from_list tests. fn get_list<'a>() -> &'a [(i16, i16); 8] { &[ (0, 0), // Default test, (100, 100), // Two positive values test, (50, -50), // One positive one negative test. (-9999, 9999), // Larger values test. (0, 1...
#[test] fn node() { let result = Node::from_list(get_list()); assert_eq!(result.len(), 8); } #[test] fn group() { let result = Group::from_list(get_list()); assert_eq!(result.len(), 8); }
{ let result = Coordinate::from_list(get_list()); assert_eq!(result.len(), 8); }
identifier_body
from_list.rs
use crate::*; // List used for calling from_list tests. fn get_list<'a>() -> &'a [(i16, i16); 8] { &[ (0, 0), // Default test, (100, 100), // Two positive values test, (50, -50), // One positive one negative test. (-9999, 9999), // Larger values test. (0, 1...
() { let result = Group::from_list(get_list()); assert_eq!(result.len(), 8); }
group
identifier_name
from_list.rs
use crate::*; // List used for calling from_list tests. fn get_list<'a>() -> &'a [(i16, i16); 8] { &[ (0, 0), // Default test, (100, 100), // Two positive values test, (50, -50), // One positive one negative test. (-9999, 9999), // Larger values test. (0, 1...
#[test] fn group() { let result = Group::from_list(get_list()); assert_eq!(result.len(), 8); }
#[test] fn node() { let result = Node::from_list(get_list()); assert_eq!(result.len(), 8); }
random_line_split
urls.py
"""srt URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/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='home') Class-based ...
1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin urlpatterns =...
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf
random_line_split
urls.py
"""srt URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/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='home') Class-based ...
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
conditional_block
wavetx2.py
import sys import os import time import serial #DTR0 - blue DATA #RTS0 - purple STB RX #DTR1 - (blue on 232 side) then green CLK #CTS0 - black LD #RTS1 - purple STB TX delay=0.001 def getserials(): s0 = serial.Serial("/dev/ttyUSB0") s1 = serial.Serial("/dev/ttyUSB1") return (s0,s1) def test(): per...
if __name__=="__main__": os.system("/usr/bin/chrt -r -p 99 %s"%os.getpid()) (s0,s1)=getserials() # set up reference divider # r=[1,0,0,0,0,0,0,0,0,0,0,1] r=[1,1,1,1,1,1,1,1,1,1,1,0] r=[0,0,1,1,1,1,0,0,0,0,1,0] # good r=[1,1,1,1,1,1,1,0,0,0,1,0] # good 1 jan r=[1,0,1,1,1,1,0,0,0,0,1,0...
d=[1,0,1,1] for x in d: outbit(s0,s1,x) latch(s0) return
identifier_body
wavetx2.py
import sys import os import time import serial #DTR0 - blue DATA #RTS0 - purple STB RX #DTR1 - (blue on 232 side) then green CLK #CTS0 - black LD #RTS1 - purple STB TX delay=0.001 def getserials(): s0 = serial.Serial("/dev/ttyUSB0") s1 = serial.Serial("/dev/ttyUSB1") return (s0,s1) def test(): per...
s1.setRTS(val) # tx strobe return def enable_outputs(s0,s1): d=[1,0,1,1] for x in d: outbit(s0,s1,x) latch(s0) return if __name__=="__main__": os.system("/usr/bin/chrt -r -p 99 %s"%os.getpid()) (s0,s1)=getserials() # set up reference divider # r=[1,0,0,0,0,0,0,0,0,...
random_line_split
wavetx2.py
import sys import os import time import serial #DTR0 - blue DATA #RTS0 - purple STB RX #DTR1 - (blue on 232 side) then green CLK #CTS0 - black LD #RTS1 - purple STB TX delay=0.001 def getserials(): s0 = serial.Serial("/dev/ttyUSB0") s1 = serial.Serial("/dev/ttyUSB1") return (s0,s1) def test(): per...
s.setDTR(False) #s.setRTS(False) time.sleep(period) def outbit(s0,s1,valn): clk=True if valn==0: val=True else: val=False print valn s0.setDTR(val) # rx strobe time.sleep(delay/10) s1.setDTR(clk) time.sleep(delay) s1.setDTR(not clk) tim...
print s.getCTS()
conditional_block
wavetx2.py
import sys import os import time import serial #DTR0 - blue DATA #RTS0 - purple STB RX #DTR1 - (blue on 232 side) then green CLK #CTS0 - black LD #RTS1 - purple STB TX delay=0.001 def
(): s0 = serial.Serial("/dev/ttyUSB0") s1 = serial.Serial("/dev/ttyUSB1") return (s0,s1) def test(): period=0.001 i = 0 s=serial.Serial("/dev/ttyUSB1") while True: s.setDTR(True) #s.setRTS(True) time.sleep(period) i = i + 1 if i % 10 == 0: pri...
getserials
identifier_name
choose_format_device_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yc/code/calibre/calibre/src/calibre/gui2/dialogs/choose_format_device.ui' # # Created: Thu Oct 25 16:54:55 2012 # by: PyQt4 UI code generator 4.8.5 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore...
def retranslateUi(self, ChooseFormatDeviceDialog): pass
random_line_split
choose_format_device_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yc/code/calibre/calibre/src/calibre/gui2/dialogs/choose_format_device.ui' # # Created: Thu Oct 25 16:54:55 2012 # by: PyQt4 UI code generator 4.8.5 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore...
pass
identifier_body
choose_format_device_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yc/code/calibre/calibre/src/calibre/gui2/dialogs/choose_format_device.ui' # # Created: Thu Oct 25 16:54:55 2012 # by: PyQt4 UI code generator 4.8.5 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore...
(self, ChooseFormatDeviceDialog): ChooseFormatDeviceDialog.setObjectName(_fromUtf8("ChooseFormatDeviceDialog")) ChooseFormatDeviceDialog.resize(507, 377) ChooseFormatDeviceDialog.setWindowTitle(_("Choose Format")) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(I("mim...
setupUi
identifier_name
FontWarnings.js
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/fi/FontWarnings.js * * Copyright (c) 2009-2013 The MathJax Consortium * * Licensed under the Apache License, Versi...
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the Lic...
*
random_line_split
mod.rs
2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITI...
let vec0 = unwrap!(generate_random_vector::<u8>(SIZE)); let vec1 = unwrap!(generate_random_vector::<u8>(SIZE)); let vec2 = unwrap!(generate_random_vector::<u8>(SIZE)); assert_ne!(vec0, vec1); assert_ne!(vec0, vec2); assert_ne!(vec1, vec2); assert_eq!(vec0.len(),...
// Test `generate_random_vector` and that the results are not repeated. #[test] fn random_vector() {
random_line_split
mod.rs
2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITI...
(length: usize) -> Result<String, CoreError> { let mut os_rng = OsRng::new().map_err(|error| { error!("{:?}", error); CoreError::RandomDataGenerationFailure })?; Ok(generate_readable_string_rng(&mut os_rng, length)) } /// Generates a readable `String` using provided `length` and `rng. pub ...
generate_readable_string
identifier_name
mod.rs
018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIO...
/// Generate a random vector of given length. pub fn generate_random_vector<T>(length: usize) -> Result<Vec<T>, CoreError> where Standard: Distribution<T>, { let mut os_rng = OsRng::new().map_err(|error| { error!("{:?}", error); CoreError::RandomDataGenerationFailure })?; Ok(generate_...
{ ::std::iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .take(length) .collect() }
identifier_body
32-bridge-in.py
# This example is designed to be paired with example file 31-bridge-out.py # Run the two with DIFFERENT DEVICE TOKENS. # (They can be either in same "project" or separate projects as set at phone. Just use different tokens.) # This "in" bridge receives data directly from other RPi. # Our display shows incoming messag...
# set up the RPi LED or other outputs and connect to generic gpioOut function above ledR = GPIO.LED(21) # gpiozero led objects blynk.add_digital_hw_pin(21, None, gpioOut_h, ledR) #----------------------------------------- # Listen for anything coming in V61. Just print it def virt_in_h(val, pin, st): print("I...
gpioObj.value = val # control the LED print("Incoming GPIO OUT command:", pin, val)
identifier_body
32-bridge-in.py
# This example is designed to be paired with example file 31-bridge-out.py # Run the two with DIFFERENT DEVICE TOKENS. # (They can be either in same "project" or separate projects as set at phone. Just use different tokens.) # This "in" bridge receives data directly from other RPi. # Our display shows incoming messag...
(val, pin, gpioObj): gpioObj.value = val # control the LED print("Incoming GPIO OUT command:", pin, val) # set up the RPi LED or other outputs and connect to generic gpioOut function above ledR = GPIO.LED(21) # gpiozero led objects blynk.add_digital_hw_pin(21, None, gpioOut_h, ledR) #---------------------...
gpioOut_h
identifier_name
32-bridge-in.py
# This example is designed to be paired with example file 31-bridge-out.py
# This "in" bridge receives data directly from other RPi. # Our display shows incoming messages. # Our LED on gpio 21 is controlled by button at other end. import gpiozero as GPIO from PiBlynk import Blynk from mytoken import * blynk = Blynk(token2) # <<<<<<<<<<<<<<<<<<<< USE DIFFERENT TOKED FROM OTHER END !!...
# Run the two with DIFFERENT DEVICE TOKENS. # (They can be either in same "project" or separate projects as set at phone. Just use different tokens.)
random_line_split
test_sigchld.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet._sigchld}, an alternate, superior SIGCHLD monitoring API. """ import os, signal, errno from twisted.python.log import msg from twisted.trial.unittest import TestCase from twisted.internet.fdesc import setNonBlock...
else: self.signalModuleHandler = None self.oldFD = self.installHandler(-1) if self.signalModuleHandler is not None and self.oldFD != -1: msg("SIGCHLD setup issue: %r %r" % (self.signalModuleHandler, self.oldFD)) raise RuntimeError("You used some signal APIs...
self.signalModuleHandler = handler signal.signal(signal.SIGCHLD, signal.SIG_DFL)
conditional_block
test_sigchld.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet._sigchld}, an alternate, superior SIGCHLD monitoring API. """ import os, signal, errno from twisted.python.log import msg from twisted.trial.unittest import TestCase from twisted.internet.fdesc import setNonBlock...
def test_uninstallHandler(self): """ C{installHandler(-1)} removes the SIGCHLD handler completely. """ read, write = self.pipe() self.assertTrue(self.isDefaultHandler()) self.installHandler(write) self.assertFalse(self.isDefaultHandler()) self.insta...
""" L{installHandler} returns the previously registered file descriptor. """ read, write = self.pipe() oldFD = self.installHandler(write) self.assertEqual(self.installHandler(oldFD), write)
identifier_body
test_sigchld.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet._sigchld}, an alternate, superior SIGCHLD monitoring API. """ import os, signal, errno from twisted.python.log import msg from twisted.trial.unittest import TestCase from twisted.internet.fdesc import setNonBlock...
(self): """ C{installHandler(-1)} removes the SIGCHLD handler completely. """ read, write = self.pipe() self.assertTrue(self.isDefaultHandler()) self.installHandler(write) self.assertFalse(self.isDefaultHandler()) self.installHandler(-1) self.asser...
test_uninstallHandler
identifier_name
test_sigchld.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet._sigchld}, an alternate, superior SIGCHLD monitoring API. """ import os, signal, errno from twisted.python.log import msg from twisted.trial.unittest import TestCase
from twisted.internet.fdesc import setNonBlocking from twisted.internet._signals import installHandler, isDefaultHandler from twisted.internet._signals import _extInstallHandler, _extIsDefaultHandler from twisted.internet._signals import _installHandlerUsingSetWakeup, \ _installHandlerUsingSignal, _isDefaultHandler...
random_line_split
pointer_constants.rs
// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // ...
else { "" }; Ok(Branch(vec![ Line(format!("{}static {}: [capnp::Word; {}] = [", vis, name, words.len() / 8)), Indent(Box::new(Branch(words_lines))), Line("];".to_string()) ])) } pub fn generate_pointer_constant( gen: &GeneratorContext, styled_name: &str, typ: type_::Reader,...
{ "pub " }
conditional_block
pointer_constants.rs
// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy
// furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO TH...
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is
random_line_split
pointer_constants.rs
// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // ...
{ pub public: bool, pub omit_first_word: bool, } pub fn word_array_declaration(name: &str, value: any_pointer::Reader, options: WordArrayDeclarationOptions) -> ::capnp::Result<FormattedText> { let allocator = message::HeapAllocator::new() ...
WordArrayDeclarationOptions
identifier_name
pointer_constants.rs
// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // ...
{ Ok(Branch(vec![ Line(format!("pub static {}: ::capnp::constant::Reader<{}> = {{", styled_name, typ.type_string(gen, Leaf::Owned)?)), Indent(Box::new(Branch(vec![ word_array_declaration("WORDS", value, WordArrayDeclarationOptions { public: false, omit_first_word: fa...
identifier_body
utils.py
import re def get_subset(a, keys): return dict((k, a[k]) for k in keys if k in a) def find(array, properties): keys = properties.keys() for a in array: dict_a = a if hasattr(a, '__dict__'): dict_a = a.__dict__ subset = get_subset(dict_a, keys) if subset == pro...
def extract_version(event): """ Parses the output from docker --version for the version, e.g. >>> extract_version("Docker version 0.11.1, build fb99f99") "0.11.1" """ match = re.search(r'Docker version ([0-9\.]+),', event) if match: version = match.group(1) return version
""" Get the element at the index of the list or return None >>> example = [1, 2] >>> get_index(example, 1) 1 >>> get_index(example, 7) None """ if len(x) > index: return x[index]
identifier_body
utils.py
import re def get_subset(a, keys): return dict((k, a[k]) for k in keys if k in a) def find(array, properties): keys = properties.keys() for a in array: dict_a = a if hasattr(a, '__dict__'): dict_a = a.__dict__ subset = get_subset(dict_a, keys) if subset == pro...
match = re.search(r'Docker version ([0-9\.]+),', event) if match: version = match.group(1) return version
random_line_split
utils.py
import re def get_subset(a, keys): return dict((k, a[k]) for k in keys if k in a) def
(array, properties): keys = properties.keys() for a in array: dict_a = a if hasattr(a, '__dict__'): dict_a = a.__dict__ subset = get_subset(dict_a, keys) if subset == properties: return a return None def missing_keys(a, b): return [k for k in a.k...
find
identifier_name
utils.py
import re def get_subset(a, keys): return dict((k, a[k]) for k in keys if k in a) def find(array, properties): keys = properties.keys() for a in array: dict_a = a if hasattr(a, '__dict__'):
subset = get_subset(dict_a, keys) if subset == properties: return a return None def missing_keys(a, b): return [k for k in a.keys() if k not in b.keys()] def get_index(x, index): """ Get the element at the index of the list or return None >>> example = [1, 2] >>>...
dict_a = a.__dict__
conditional_block
database.js
intelli.database = []; $(function() { if ($('#query_out').text()) { setTimeout( (function(){ $('#query_out').height(window.screen.height - $('#query_out').offset().top - 300) }), 1000); } $('a', '.js-selecting').on('click', function(e) { e.preventDefault(); var $ctl = $('#tbl option'); switch ($(this)....
} else if (query.selectionStart || query.selectionStart == '0') { var startPos = query.selectionStart; var endPos = query.selectionEnd; var flag = false; if(query.value.length == startPos) flag = true; query.value = query.value.substring(0, startPos) + text + query.value.substring(endPos, query.va...
sel.text = text;
random_line_split
database.js
intelli.database = []; $(function() { if ($('#query_out').text()) { setTimeout( (function(){ $('#query_out').height(window.screen.height - $('#query_out').offset().top - 300) }), 1000); } $('a', '.js-selecting').on('click', function(e) { e.preventDefault(); var $ctl = $('#tbl option'); switch ($(this)....
(item) { var value = $('#' + item).val(); if (value) { addText('`' + value + '`'); } else { intelli.admin.alert( { title: _t('error'), type: 'error', msg: 'Please choose any ' + item + '.' }); } } // add text to query function addText(text) { text = ' ' + text + ' '; ...
addData
identifier_name
database.js
intelli.database = []; $(function() { if ($('#query_out').text()) { setTimeout( (function(){ $('#query_out').height(window.screen.height - $('#query_out').offset().top - 300) }), 1000); } $('a', '.js-selecting').on('click', function(e) { e.preventDefault(); var $ctl = $('#tbl option'); switch ($(this)....
} else { query.val(query.val() + text); } focusCampo('query'); } // sql template click $('a', '#sqlButtons').on('click', function(e) { e.preventDefault(); addText($(this).text()); }); // reset tables $('#js-reset-all, #js-reset').on('click', function(e) { if ($(this).attr('id') == 'js-res...
{ text = ' ' + text + ' '; var query = $('#query'); if (document.selection) { query.focus(); sel = document.selection.createRange(); sel.text = text; } else if (query.selectionStart || query.selectionStart == '0') { var startPos = query.selectionStart; var endPos = query.selectionEnd; ...
identifier_body
database.js
intelli.database = []; $(function() { if ($('#query_out').text()) { setTimeout( (function(){ $('#query_out').height(window.screen.height - $('#query_out').offset().top - 300) }), 1000); } $('a', '.js-selecting').on('click', function(e) { e.preventDefault(); var $ctl = $('#tbl option'); switch ($(this)....
}); function focusCampo(id) { var inputField = document.getElementById(id); if (inputField != null && inputField.value.length != 0){ if (inputField.createTextRange){ var FieldRange = inputField.createTextRange(); FieldRange.moveStart('character',inputField.value.length); FieldRange.collapse(); FieldRa...
{ focusCampo('query'); }
conditional_block
animation.rs
extern crate sdl2; use std::path::Path; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sdl2::rect::Point; use std::time::Duration; fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("...
renderer.set_draw_color(sdl2::pixels::Color::RGBA(0,0,0,255)); let mut timer = sdl_context.timer().unwrap(); let mut event_pump = sdl_context.event_pump().unwrap(); let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/animate.bmp")).unwrap(); let texture = renderer.create_texture...
let mut renderer = window.renderer() .accelerated().build().unwrap();
random_line_split
animation.rs
extern crate sdl2; use std::path::Path; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sdl2::rect::Point; use std::time::Duration; fn main()
let mut source_rect = Rect::new(0, 0, 128, 82); let mut dest_rect = Rect::new(0,0, 128, 82); dest_rect.center_on(center); let mut running = true; while running { for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::KeyDown {keycode: Some(...
{ let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("SDL2", 640, 480) .position_centered().build().unwrap(); let mut renderer = window.renderer() .accelerated().build().unwrap(); renderer.set_draw_color...
identifier_body
animation.rs
extern crate sdl2; use std::path::Path; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sdl2::rect::Point; use std::time::Duration; fn
() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("SDL2", 640, 480) .position_centered().build().unwrap(); let mut renderer = window.renderer() .accelerated().build().unwrap(); renderer.set_draw_co...
main
identifier_name
animation.rs
extern crate sdl2; use std::path::Path; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sdl2::rect::Point; use std::time::Duration; fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window("...
} } let ticks = timer.ticks(); source_rect.set_x((128 * ((ticks / 100) % 6) ) as i32); renderer.clear(); renderer.copy_ex(&texture, Some(source_rect), Some(dest_rect), 10.0, None, true, false).unwrap(); renderer.present(); std::thread::sleep(Durati...
{}
conditional_block
utilities.py
""" Utilities for plotting various figures and animations in EEG101. """ # Author: Hubert Banville <hubert@neurotechx.com> # # License: TBD import numpy as np import matplotlib.pylab as plt import collections from scipy import signal def dot_plot(x, labels, step=1, figsize=(12,8)): """ Make a 1D dot plot. ...
ax.set_ylabel('Power (dB)') ylim = ax.get_ylim() for i, [bkey, bfreq] in enumerate(bands.iteritems()): ind = (f>=bfreq[0]) & (f<=bfreq[1]) f1 = f[ind] y1 = psd[ind] ax.fill_between(f1, y1, ylim[0], facecolor=[(0.7, i/5., 0.7)], alpha=0.5) ax.text(np.mean(f1),...
""" Plot a static PSD. INPUTS f : 1D array containing frequencies of the PSD psd : 1D array containing the power at each frequency in f figsize : figure size """ bands = collections.OrderedDict() bands[r'$\delta$'] = (0,4) bands[r'$\theta$'] = (4,8) b...
identifier_body
utilities.py
""" Utilities for plotting various figures and animations in EEG101. """ # Author: Hubert Banville <hubert@neurotechx.com> # # License: TBD import numpy as np import matplotlib.pylab as plt import collections from scipy import signal def dot_plot(x, labels, step=1, figsize=(12,8)): """ Make a 1D dot plot. ...
Inputs x : 1D array containing the points to plot labels : 1D array containing the label for each point in x step : vertical space between two points """ # Get the histogram for each class classes = np.unique(labels) hist = [np.histogram(x[labels==c], density=True) f...
random_line_split
utilities.py
""" Utilities for plotting various figures and animations in EEG101. """ # Author: Hubert Banville <hubert@neurotechx.com> # # License: TBD import numpy as np import matplotlib.pylab as plt import collections from scipy import signal def dot_plot(x, labels, step=1, figsize=(12,8)): """ Make a 1D dot plot. ...
nb_points = 10*10 relax_data = np.random.normal(0.01, 0.01, size=(nb_points,)) focus_data = np.random.normal(0.03, 0.01, size=(nb_points,)) dot_plot(x=np.concatenate((relax_data, focus_data)), labels=np.concatenate((np.zeros((nb_points,)), np.ones((nb_points,)))), step=4) ...
conditional_block
utilities.py
""" Utilities for plotting various figures and animations in EEG101. """ # Author: Hubert Banville <hubert@neurotechx.com> # # License: TBD import numpy as np import matplotlib.pylab as plt import collections from scipy import signal def dot_plot(x, labels, step=1, figsize=(12,8)): """ Make a 1D dot plot. ...
(f, psd, figsize=(12,8)): """ Plot a static PSD. INPUTS f : 1D array containing frequencies of the PSD psd : 1D array containing the power at each frequency in f figsize : figure size """ bands = collections.OrderedDict() bands[r'$\delta$'] = (0,4) ba...
psd_with_bands_plot
identifier_name
main.js
const express = require('express'); const app = express(); // var server = require('http').Server(app); var server = require('http').createServer(app); var io = require('socket.io')(server); var SerialPort = require('serialport'); var fs = require('fs'); /****** Setup Variables ******/ var userConfig = fs.readFile...
{ leaderList.sort(function(a,b){ return b.point - a.point; }); }
identifier_body
main.js
const express = require('express'); const app = express(); // var server = require('http').Server(app); var server = require('http').createServer(app); var io = require('socket.io')(server); var SerialPort = require('serialport'); var fs = require('fs'); /****** Setup Variables ******/ var userConfig = fs.readFile...
(){ leaderList.sort(function(a,b){ return b.point - a.point; }); }
leaderListSort
identifier_name
main.js
const express = require('express'); const app = express(); // var server = require('http').Server(app); var server = require('http').createServer(app); var io = require('socket.io')(server); var SerialPort = require('serialport'); var fs = require('fs'); /****** Setup Variables ******/ var userConfig = fs.readFile...
leaderListSort(); // sort after placing new leader socket.emit("currentPoints",{"name":currentPlayer,"point":gamePoint}); socket.emit("getLeaders",leaderList); // limit leader list if ( leaderList.length >7){ leaderList.pop(); // remove the lowest score console.log(JSON.stringif...
{ leaderList.push({"name":currentPlayer,"point":gamePoint}) }
conditional_block
main.js
const express = require('express'); const app = express(); // var server = require('http').Server(app); var server = require('http').createServer(app);
/****** Setup Variables ******/ var userConfig = fs.readFileSync('../CONFIG.json').toString(); userConfig = JSON.parse(userConfig); const totalGameTime = userConfig["GAMETIME"]; // in milliseconds console.log("game time:"+totalGameTime); /****** Game Variables ******/ var prevColor = 1; var gamePoint = 0; var currentP...
var io = require('socket.io')(server); var SerialPort = require('serialport'); var fs = require('fs');
random_line_split
__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
logging.basicConfig(filename=config.get_logger(), level=config.get_level(), format=config.get_format())
from cs.CsConfig import CsConfig config = CsConfig()
random_line_split
Album.py
from PIL import Image import os.path,os #import pickle #import sqlite3 import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Ver...
def set_thumbnail(self, location): if self.thumbnail : self.scheduler.remove_file(self.thumbnail) if not isinstance(location, str) or check_ext(location, img_exts): #fichier ouvert self.thumbnail = make_thumbnail(self.scheduler, location ) else: ...
album.lock_files()
random_line_split
Album.py
from PIL import Image import os.path,os #import pickle #import sqlite3 import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Ver...
if not isinstance(location, str) or check_ext(location, img_exts): #fichier ouvert self.thumbnail = make_thumbnail(self.scheduler, location ) else: self.thumbnail = self.scheduler.add_file(location_album_default) #size and md5 ought to be combute once for all ...
self.scheduler.remove_file(self.thumbnail)
conditional_block
Album.py
from PIL import Image import os.path,os #import pickle #import sqlite3 import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Ver...
@recursion_protect() def lock_files(self): for _file in self.files: _file.io_lock.acquire() for album in self.subalbums: album.lock_files() def set_thumbnail(self, location): if self.thumbnail : self.scheduler.remove_...
location = os.path.join(path, self.name) if not os.path.isdir(location): os.makedirs( location ) for _file in self.files: _file.export_to(location) for album in self.subalbums: album.export_to( location )
identifier_body
Album.py
from PIL import Image import os.path,os #import pickle #import sqlite3 import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Ver...
(self, new_id): alb = self.__deepcopy__(None) alb.inner_keys.clear() alb.id = new_id return alb def pseudo_clone(self): new = Album(self.id, self.scheduler, self.name, self.datetime) if self.thumbnail: self.scheduler.duplicate(se...
clone
identifier_name
ruta3.d.ts
declare module 'ruta3' { export interface RouteMatch<T> { /** The action passed to `addRoute`. Using a function is recommended. */ action: T /** Fall through to the next route, pass it as the `startAt` parameter to match. */ next: number /** The route passed to `addRoute` as the first argument. */...
}
} export default function ruta3<T>(): Router<T>
random_line_split
models.py
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
context['invoice'] = context.get('invoice_html', None) return Template(body).render(context) def __unicode__(self): return self.subject
body = self.body
conditional_block
models.py
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
('user', 'User'), ('attendee', 'Attendee') ) # template subject = models.CharField(max_length=128) body = models.TextField() body_format = models.CharField(max_length=32, choices=BODY_FORMAT_CHOICES, default='markdown') # context template_context = models.CharField(max_len...
CONTEXT_CHOICES = (
random_line_split
models.py
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
(self, user, attendee=None): # lazy import, prevent circular import in core.events from selvbetjening.core.events.options.dynamic_selections import SCOPE, dynamic_selections context = { # user context 'username': user.username, 'full_name': ('%s %s' % (user.f...
_get_context
identifier_name
models.py
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
def render_attendee(self, attendee): """ Renders the e-mail template using a user object as source. """ return self._render(self._get_context(attendee.user, attendee=attendee)) def render_dummy(self): context = { # user context 'username': 'jo...
""" Renders the e-mail template using a user object as source. An error is thrown if the template context is Attendee. """ if self.template_context == 'attendee': raise ValueError return self._render(self._get_context(user))
identifier_body
setup.py
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), "README.md")) as readme: README = readme.read() with open(os.path.join(os.path.dirname(__file__), "requirements.in")) as requirements: REQUIREMENTS = [ req.split("#egg=")[1] if "#egg=" in req else req for...
"License :: OSI Approved :: GPL License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], )
author_email="webmaster@saurel.me", classifiers=[ "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers",
random_line_split
auth.py
"""Authentication for HTTP component.""" import base64 import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeass...
"""Validate a signed request.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( s...
async def async_validate_signed_request(request):
random_line_split
auth.py
"""Authentication for HTTP component.""" import base64 import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeass...
async def async_validate_legacy_api_password(request, password): """Validate api_password.""" user = await legacy_api_password.async_validate_password(hass, password) if user is None: return False request[KEY_HASS_USER] = user return True @middleware a...
"""Test if request is from a trusted ip.""" ip_addr = request[KEY_REAL_IP] if not any(ip_addr in trusted_network for trusted_network in trusted_networks): return False user = await hass.auth.async_get_owner() if user is None: return False request[KEY_HA...
identifier_body
auth.py
"""Authentication for HTTP component.""" import base64 import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeass...
if hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header( request ): # it included both use_auth and api_password Basic auth authenticated = True # We first start with a string check to avoid parsing query params # for every req...
_LOGGER.log( logging.INFO if support_legacy else logging.WARNING, "api_password is going to deprecate. You need to use a" " bearer token to access %s from %s", request.path, request[KEY_REAL_IP], ) ...
conditional_block
auth.py
"""Authentication for HTTP component.""" import base64 import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeass...
(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = generate_secret() now = dt_util.utcnow() return "{}?{}={}".format( path, ...
async_sign_path
identifier_name
runtime_compiler.ts
import {Compiler, Compiler_, internalCreateProtoView} from 'angular2/src/core/linker/compiler'; import {ProtoViewRef} from 'angular2/src/core/linker/view_ref'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {TemplateCompiler} from './template_compiler'; import {Injectable} from 'a...
super(_protoViewFactory); } compileInHost(componentType: Type): Promise<ProtoViewRef> { return this._templateCompiler.compileHostComponentRuntime(componentType) .then(compiledHostTemplate => internalCreateProtoView(this, compiledHostTemplate)); } clearCache() { super.clearCache(); this...
export abstract class RuntimeCompiler extends Compiler {} @Injectable() export class RuntimeCompiler_ extends Compiler_ implements RuntimeCompiler { constructor(_protoViewFactory: ProtoViewFactory, private _templateCompiler: TemplateCompiler) {
random_line_split
runtime_compiler.ts
import {Compiler, Compiler_, internalCreateProtoView} from 'angular2/src/core/linker/compiler'; import {ProtoViewRef} from 'angular2/src/core/linker/view_ref'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {TemplateCompiler} from './template_compiler'; import {Injectable} from 'a...
extends Compiler_ implements RuntimeCompiler { constructor(_protoViewFactory: ProtoViewFactory, private _templateCompiler: TemplateCompiler) { super(_protoViewFactory); } compileInHost(componentType: Type): Promise<ProtoViewRef> { return this._templateCompiler.compileHostComponentRuntime(componentType) ...
RuntimeCompiler_
identifier_name
runtime_compiler.ts
import {Compiler, Compiler_, internalCreateProtoView} from 'angular2/src/core/linker/compiler'; import {ProtoViewRef} from 'angular2/src/core/linker/view_ref'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {TemplateCompiler} from './template_compiler'; import {Injectable} from 'a...
clearCache() { super.clearCache(); this._templateCompiler.clearCache(); } }
{ return this._templateCompiler.compileHostComponentRuntime(componentType) .then(compiledHostTemplate => internalCreateProtoView(this, compiledHostTemplate)); }
identifier_body
cache_tests.py
# -*- coding: utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals
__version__ = '$Id$' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir from tests.aspects import unittest, TestCase class RequestCacheTests(TestCase): """Validate cache entries.""" net = False def _check_cache_entry(self, entry): """...
random_line_split
cache_tests.py
# -*- coding: utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id$' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir fro...
unittest.main()
conditional_block
cache_tests.py
# -*- coding: utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id$' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir fro...
if __name__ == '__main__': unittest.main()
"""Validate cache entries.""" net = False def _check_cache_entry(self, entry): """Assert validity of the cache entry.""" self.assertIsInstance(entry.site, BaseSite) self.assertIsInstance(entry.site._loginstatus, int) self.assertIsInstance(entry.site._username, list) if ...
identifier_body
cache_tests.py
# -*- coding: utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id$' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir fro...
(TestCase): """Validate cache entries.""" net = False def _check_cache_entry(self, entry): """Assert validity of the cache entry.""" self.assertIsInstance(entry.site, BaseSite) self.assertIsInstance(entry.site._loginstatus, int) self.assertIsInstance(entry.site._username, ...
RequestCacheTests
identifier_name
firewalls_utils.py
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
(allowed, message_classes): """Parses protocol:port mappings from --allow command line.""" allowed_value_list = [] for spec in allowed or []: match = LEGAL_SPECS.match(spec) if not match: raise calliope_exceptions.ToolException( 'Firewall rules must be of the form {0}; received [{1}].' ...
ParseAllowed
identifier_name
firewalls_utils.py
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
return allowed_value_list
match = LEGAL_SPECS.match(spec) if not match: raise calliope_exceptions.ToolException( 'Firewall rules must be of the form {0}; received [{1}].' .format(ALLOWED_METAVAR, spec)) if match.group('ports'): ports = [match.group('ports')] else: ports = [] allowed_value_li...
conditional_block
firewalls_utils.py
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
parser.add_argument( 'name', help='The name of the firewall rule to {0}'.format( 'update.' if for_update else 'create.')) def ParseAllowed(allowed, message_classes): """Parses protocol:port mappings from --allow command line.""" allowed_value_list = [] for spec in allowed or []: mat...
"""
random_line_split
firewalls_utils.py
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
A port or port range can be specified after PROTOCOL to allow traffic through specific ports. If no port or port range is specified, connections through all ranges are allowed. For example, the following will create a rule that allows TCP traffic through port 80 and allows ICMP traffic: ...
"""Adds common arguments for firewall create or update subcommands.""" min_length = 0 if for_update else 1 switch = [] if min_length == 0 else None allow = parser.add_argument( '--allow', metavar=ALLOWED_METAVAR, type=arg_parsers.ArgList(min_length=min_length), action=arg_parsers.Floatin...
identifier_body
demo-set.module.ts
import {NgModule} from "@angular/core"; import {RouterModule} from "@angular/router"; import { SelectGroupDemoComponent } from './select-group/demo.component'; import { SelectGroupDemoModule } from './select-group/demo.module'; import { SelectGroupEditResultDemoComponent } from './edit-selected-items/demo.component'; i...
{ }
SelectGroupDemoSetModule
identifier_name
demo-set.module.ts
import {NgModule} from "@angular/core"; import {RouterModule} from "@angular/router"; import { SelectGroupDemoComponent } from './select-group/demo.component'; import { SelectGroupDemoModule } from './select-group/demo.module'; import { SelectGroupEditResultDemoComponent } from './edit-selected-items/demo.component'; i...
export class SelectGroupDemoSetModule { }
SelectGroupValidDemoModule ] })
random_line_split
fuzz.py
from random import randint overflowstrings = ["A" * 255, "A" * 256, "A" * 257, "A" * 420, "A" * 511, "A" * 512, "A" * 1023, "A" * 1024, "A" * 2047, "A" * 2048, "A" * 4096, "A" * 4097, "A" * 5000, "A" * 10000, "A" * 20000, "A" * 32762, "A" * 32763, "A" * 32764, "A" * 32765, "A" * 32766, "A" * 32767, "A" * 32768, "A" * ...
def bofinjection(data): l = len(data) r = randint(0,len(overflowstrings)-1) data = data[0:r] + overflowstrings[r] + data[r-l:] return data def fuzz(data, bit_flip_percentage = 20, bof_injection_percentage = 20, bit_flip_density = 7): #print "Fuzz:" #print " bfp:" + str(bit_flip_perce...
l = len(data) n = int(l*mangle_percentage/100) # 7% of the bytes to be modified for i in range(0,n): # We change the bytes r = randint(0,l-1) data = data[0:r] + chr(randint(0,255)) + data[r+1:] return data
identifier_body
fuzz.py
from random import randint overflowstrings = ["A" * 255, "A" * 256, "A" * 257, "A" * 420, "A" * 511, "A" * 512, "A" * 1023, "A" * 1024, "A" * 2047, "A" * 2048, "A" * 4096, "A" * 4097, "A" * 5000, "A" * 10000, "A" * 20000, "A" * 32762, "A" * 32763, "A" * 32764, "A" * 32765, "A" * 32766, "A" * 32767, "A" * 32768, "A" * ...
(data): l = len(data) r = randint(0,len(overflowstrings)-1) data = data[0:r] + overflowstrings[r] + data[r-l:] return data def fuzz(data, bit_flip_percentage = 20, bof_injection_percentage = 20, bit_flip_density = 7): #print "Fuzz:" #print " bfp:" + str(bit_flip_percentage) #print ...
bofinjection
identifier_name
fuzz.py
from random import randint overflowstrings = ["A" * 255, "A" * 256, "A" * 257, "A" * 420, "A" * 511, "A" * 512, "A" * 1023, "A" * 1024, "A" * 2047, "A" * 2048, "A" * 4096, "A" * 4097, "A" * 5000, "A" * 10000, "A" * 20000, "A" * 32762, "A" * 32763, "A" * 32764, "A" * 32765, "A" * 32766, "A" * 32767, "A" * 32768, "A" * ...
#print " second r:" + str(r) r = randint(0,100) if r<=bof_injection_percentage: was_fuzzed = True data = bofinjection(data) return was_fuzzed, data
random_line_split
fuzz.py
from random import randint overflowstrings = ["A" * 255, "A" * 256, "A" * 257, "A" * 420, "A" * 511, "A" * 512, "A" * 1023, "A" * 1024, "A" * 2047, "A" * 2048, "A" * 4096, "A" * 4097, "A" * 5000, "A" * 10000, "A" * 20000, "A" * 32762, "A" * 32763, "A" * 32764, "A" * 32765, "A" * 32766, "A" * 32767, "A" * 32768, "A" * ...
#print " second r:" + str(r) r = randint(0,100) if r<=bof_injection_percentage: was_fuzzed = True data = bofinjection(data) return was_fuzzed, data
was_fuzzed = True data = bitflipping(data, bit_flip_density)
conditional_block
graph.spec.ts
import {Task, Graph, RootGraph, Workspace} from '@openmicrostep/msbuildsystem.core'; import {assert} from 'chai'; function simple_graph()
export const tests = [ { name: "simple graph", test: simple_graph }, ];
{ var r = new RootGraph(new Workspace()); var g = new Graph({ name: "root", type: "test" }, r); var t1 = new Task({ name: 't1', type: "test" }, g); var t2 = new Task({ name: 't2', type: "test" }, g); var t3 = new Task({ name: 't3', type: "test" }, g); t2.addDependency(t1); t3.addDependency(t1); var task...
identifier_body
graph.spec.ts
import {Task, Graph, RootGraph, Workspace} from '@openmicrostep/msbuildsystem.core'; import {assert} from 'chai'; function simple_graph() { var r = new RootGraph(new Workspace()); var g = new Graph({ name: "root", type: "test" }, r); var t1 = new Task({ name: 't1', type: "test" }, g); var t2 = new Task({ name:...
];
} export const tests = [ { name: "simple graph", test: simple_graph },
random_line_split
graph.spec.ts
import {Task, Graph, RootGraph, Workspace} from '@openmicrostep/msbuildsystem.core'; import {assert} from 'chai'; function
() { var r = new RootGraph(new Workspace()); var g = new Graph({ name: "root", type: "test" }, r); var t1 = new Task({ name: 't1', type: "test" }, g); var t2 = new Task({ name: 't2', type: "test" }, g); var t3 = new Task({ name: 't3', type: "test" }, g); t2.addDependency(t1); t3.addDependency(t1); var t...
simple_graph
identifier_name
opengl_info.py
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2020-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
app = QGuiApplication([]) surface = QOffscreenSurface() surface.create() ctx = QOpenGLContext() ok = ctx.create() assert ok ok = ctx.makeCurrent(surface) assert ok print(f"GLES: {ctx.isOpenGLES()}") vp = QOpenGLVersionProfile() vp.setVersion(2, 0) vf = ctx.versionFunctions(vp) print(f"Vendor: {vf.glGetString(vf.G...
QOffscreenSurface, QGuiApplication)
random_line_split
GetJobDocumentsResponse.py
#!/usr/bin/env python """ Copyright 2012 GroupDocs. 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...
} self.result = None # GetJobDocumentsResult self.status = None # str self.error_message = None # str self.composedOn = None # int
random_line_split
GetJobDocumentsResponse.py
#!/usr/bin/env python """ Copyright 2012 GroupDocs. 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...
(self): self.swaggerTypes = { 'result': 'GetJobDocumentsResult', 'status': 'str', 'error_message': 'str', 'composedOn': 'int' } self.result = None # GetJobDocumentsResult self.status = None # str self.error_message = None # str ...
__init__
identifier_name