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 |
|---|---|---|---|---|
insert-module-globals-tests.ts | import insert = require('insert-module-globals');
import { VarsOption } from 'insert-module-globals';
function example() {
function inserter(file: string) {
return insert(file, { basedir: __dirname + '/files' });
}
return inserter;
}
function insert_custom_globals() {
const customProcessConte... | function disable_select_globals() {
const insertGlobalVars: VarsOption = {};
const wantedGlobalVars = ['__filename', '__dirname'];
Object.keys(insert.vars).forEach((x) => {
if (wantedGlobalVars.indexOf(x) === -1) {
insertGlobalVars[x] = undefined;
}
});
return insert('in... | return inserter;
}
| random_line_split |
insert-module-globals-tests.ts | import insert = require('insert-module-globals');
import { VarsOption } from 'insert-module-globals';
function example() {
function inserter(file: string) {
return insert(file, { basedir: __dirname + '/files' });
}
return inserter;
}
function | () {
const customProcessContent = 'customProcessContent';
const files: string[] = [];
const vars: VarsOption = {
process(file, basedir) {
return {
id: "path/to/custom_process.js",
source: customProcessContent
};
},
Buffer(file,... | insert_custom_globals | identifier_name |
script.js | 'use strict';
const { spawn } = require('child_process');
const path = require('path');
const Promise = require('bluebird');
function newProcessor(context, opConfig) {
const { args, options } = opConfig;
const contextLogger = context.logger;
let command = '';
return new Promise(((resolve, reject) =>... | () {
return {
command: {
doc: 'what command to run',
default: 'echo',
format: 'required_String'
},
args: {
doc: 'arguments to pass along with the command',
default: [],
format(val) {
if (!Array.isArray(va... | schema | identifier_name |
script.js | 'use strict';
const { spawn } = require('child_process');
const path = require('path');
const Promise = require('bluebird');
function newProcessor(context, opConfig) {
const { args, options } = opConfig;
const contextLogger = context.logger;
let command = '';
return new Promise(((resolve, reject) =>... |
});
childProcess.stderr.on('data', (outError) => {
outErrors += outError;
});
childProcess.on('close', (code) => {
if (code > 1) {
const errorMsg = 'child process non-zero exit';
logger.error(errorM... | {
try {
const final = JSON.parse(outData);
resolve(final);
} catch (error) {
const errorMsg = 'processing script stdout pipe';
logger.error(errorMsg, error);
re... | conditional_block |
script.js | 'use strict';
const { spawn } = require('child_process');
const path = require('path');
const Promise = require('bluebird');
function newProcessor(context, opConfig) {
const { args, options } = opConfig;
const contextLogger = context.logger;
let command = '';
return new Promise(((resolve, reject) =>... | asset: {
doc: 'name of asset to use for op',
default: 'echo',
format: 'optional_String'
}
};
}
module.exports = {
newProcessor,
schema
};
| {
return {
command: {
doc: 'what command to run',
default: 'echo',
format: 'required_String'
},
args: {
doc: 'arguments to pass along with the command',
default: [],
format(val) {
if (!Array.isArray(val))... | identifier_body |
script.js | 'use strict';
const { spawn } = require('child_process');
const path = require('path');
const Promise = require('bluebird');
function newProcessor(context, opConfig) {
const { args, options } = opConfig;
const contextLogger = context.logger;
let command = '';
return new Promise(((resolve, reject) =>... | reject(err);
});
}));
}
}
function schema() {
return {
command: {
doc: 'what command to run',
default: 'echo',
format: 'required_String'
},
args: {
doc: 'arguments to pass along with the command',
... | }
});
childProcess.on('error', (err) => {
logger.error(err); | random_line_split |
Pool.js | = opt || {};
if (!opt.create) {
throw new Error('Tarn: opt.create function most be provided');
}
if (!opt.destroy) {
throw new Error('Tarn: opt.destroy function most be provided');
}
if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) {
throw new ... | () {
return this.used.length;
}
numFree() {
return this.free.length;
}
numPendingAcquires() {
return this.pendingAcquires.length;
}
numPendingCreates() {
return this.pendingCreates.length;
}
acquire() {
const pendingAcquire = new PendingOperation(this.acquireTimeoutMillis);
t... | numUsed | identifier_name |
Pool.js | = opt || {};
if (!opt.create) {
throw new Error('Tarn: opt.create function most be provided');
}
if (!opt.destroy) {
throw new Error('Tarn: opt.destroy function most be provided');
}
if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) {
throw new ... | this.propagateCreateError = !!opt.propagateCreateError;
this.min = opt.min;
this.max = opt.max;
this.used = [];
this.free = [];
this.pendingCreates = [];
this.pendingAcquires = [];
this.destroyed = false;
this.interval = null;
}
numUsed() {
return this.used.length;
}
... | this.idleTimeoutMillis = opt.idleTimeoutMillis || 30000;
this.reapIntervalMillis = opt.reapIntervalMillis || 1000;
this.createRetryIntervalMillis = opt.createRetryIntervalMillis || 200; | random_line_split |
Pool.js | opt || {};
if (!opt.create) {
throw new Error('Tarn: opt.create function most be provided');
}
if (!opt.destroy) {
throw new Error('Tarn: opt.destroy function most be provided');
}
if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) {
throw new Er... |
if (!checkOptionalTime(opt.createTimeoutMillis)) {
throw new Error(
'Tarn: invalid opt.createTimeoutMillis ' + JSON.stringify(opt.createTimeoutMillis)
);
}
if (!checkOptionalTime(opt.idleTimeoutMillis)) {
throw new Error(
'Tarn: invalid opt.idleTimeoutMillis ' + JSON.str... | {
throw new Error(
'Tarn: invalid opt.acquireTimeoutMillis ' + JSON.stringify(opt.acquireTimeoutMillis)
);
} | conditional_block |
Pool.js | opt || {};
if (!opt.create) {
throw new Error('Tarn: opt.create function most be provided');
}
if (!opt.destroy) {
throw new Error('Tarn: opt.destroy function most be provided');
}
if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) {
throw new Er... |
numFree() {
return this.free.length;
}
numPendingAcquires() {
return this.pendingAcquires.length;
}
numPendingCreates() {
return this.pendingCreates.length;
}
acquire() {
const pendingAcquire = new PendingOperation(this.acquireTimeoutMillis);
this.pendingAcquires.push(pendingAcqui... | {
return this.used.length;
} | identifier_body |
function_call.rs | use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
| use gluon::{
new_vm,
vm::{
api::{primitive, FunctionRef, Primitive},
thread::{Status, Thread},
},
ThreadExt,
};
// Benchmarks function calls
fn identity(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let id x = x
id
"#;
vm.load_script("id", text).unwrap();... | random_line_split | |
function_call.rs | use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
use gluon::{
new_vm,
vm::{
api::{primitive, FunctionRef, Primitive},
thread::{Status, Thread},
},
ThreadExt,
};
// Benchmarks function calls
fn identity(b: &mut Bencher) |
fn factorial(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial n =
if n < 2
then 1
else n * factorial (n - 1)
factorial
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwra... | {
let vm = new_vm();
let text = r#"
let id x = x
id
"#;
vm.load_script("id", text).unwrap();
let mut id: FunctionRef<fn(i32) -> i32> = vm.get_global("id").unwrap();
b.iter(|| {
let result = id.call(20).unwrap();
black_box(result)
})
} | identifier_body |
function_call.rs | use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
use gluon::{
new_vm,
vm::{
api::{primitive, FunctionRef, Primitive},
thread::{Status, Thread},
},
ThreadExt,
};
// Benchmarks function calls
fn identity(b: &mut Bencher) {
let vm = new_vm();
let t... | (b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial a n =
if n < 2
then a
else factorial (a * n) (n - 1)
factorial 1
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
... | factorial_tail_call | identifier_name |
index.ts | import styled from 'styled-components'
import type { TTestable } from '@/spec'
import Img from '@/Img'
import { theme } from '@/utils/themes'
import css from '@/utils/css'
import SiteLogo from '@/icons/CPLogo'
export const Wrapper = styled.div.attrs(({ testid }: TTestable) => ({
'data-test-id': testid,
}))<TTestabl... | `
export const HomeLogo = styled(SiteLogo)`
${css.size(32)};
fill: #007fa8;
`
export const Icon = styled(Img)`
${css.size(32)};
fill: ${theme('thread.articleDigest')};
`
export const Name = styled.a`
text-decoration: none;
color: ${theme('thread.articleTitle')};
font-size: 14px;
margin-top: 12px;
marg... | ${css.flexColumn('align-both')};
position: relative; | random_line_split |
mod.rs | to
//! the DOM object in the reflector, and initializes the pointer to the reflector
//! in the `Reflector` field.
//!
//! The `DomObject` trait provides a `reflector()` method that returns the
//! DOM object's `Reflector`. It is implemented automatically for DOM structs
//! through the `#[dom_struct]` attribute.
//!
... | pub mod mouseevent; | random_line_split | |
FreeProxyParser.py | import logging
import requests
from bs4 import BeautifulSoup
from http_request_randomizer.requests.parsers.UrlParser import UrlParser
from http_request_randomizer.requests.proxy.ProxyObject import ProxyObject, AnonymityLevel, Protocol
logger = logging.getLogger(__name__)
__author__ = 'pgaref'
class FreeProxyParser... | for dataset in datasets:
proxy_obj = self.create_proxy_object(dataset)
# Make sure it is a Valid Proxy Address
if proxy_obj is not None and UrlParser.valid_ip_port(proxy_obj.get_address()):
curr_proxy_list.append(proxy_obj)
... | curr_proxy_list = []
try:
response = requests.get(self.get_url(), timeout=self.timeout)
if not response.ok:
logger.warning("Proxy Provider url failed: {}".format(self.get_url()))
return []
content = response.content
soup = Beautifu... | identifier_body |
FreeProxyParser.py | import logging
import requests
from bs4 import BeautifulSoup
from http_request_randomizer.requests.parsers.UrlParser import UrlParser
from http_request_randomizer.requests.proxy.ProxyObject import ProxyObject, AnonymityLevel, Protocol
logger = logging.getLogger(__name__)
__author__ = 'pgaref'
class FreeProxyParser... | if field[0] == 'IP Address':
# Make sure it is a Valid IP
ip = field[1].strip() # String strip()
# Make sure it is a Valid IP
if not UrlParser.valid_ip(ip):
logger.debug("IP with Invalid format: {}".format(ip))
... | country = None
protocols = []
for field in dataset: | random_line_split |
FreeProxyParser.py | import logging
import requests
from bs4 import BeautifulSoup
from http_request_randomizer.requests.parsers.UrlParser import UrlParser
from http_request_randomizer.requests.proxy.ProxyObject import ProxyObject, AnonymityLevel, Protocol
logger = logging.getLogger(__name__)
__author__ = 'pgaref'
class FreeProxyParser... |
return ProxyObject(source=self.id, ip=ip, port=port, anonymity_level=anonymity, country=country, protocols=protocols)
def __str__(self):
return "{0} parser of '{1}' with required bandwidth: '{2}' KBs" \
.format(self.id, self.url, self.minimum_bandwidth_in_KBs)
| protocols.append(Protocol.HTTP) | conditional_block |
FreeProxyParser.py | import logging
import requests
from bs4 import BeautifulSoup
from http_request_randomizer.requests.parsers.UrlParser import UrlParser
from http_request_randomizer.requests.proxy.ProxyObject import ProxyObject, AnonymityLevel, Protocol
logger = logging.getLogger(__name__)
__author__ = 'pgaref'
class FreeProxyParser... | (self):
return "{0} parser of '{1}' with required bandwidth: '{2}' KBs" \
.format(self.id, self.url, self.minimum_bandwidth_in_KBs)
| __str__ | identifier_name |
index.d.ts | // Type definitions for react-sticky 6.0
// Project: https://github.com/captivationsoftware/react-sticky
// Definitions by: Matej Lednicky <http://www.thinkcreatix.com/>, Curtis Warren <https://github.com/curtisw0>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import * a... | className?: string;
style?: any;
stickyClassName?: string;
stickyStyle?: any;
topOffset?: number;
bottomOffset?: number;
onStickyStateChange?(isSticky: boolean): void;
disableCompensation?: boolean;
disableHardwareAcceleration?: boolean;
}
export const Sticky: React.ComponentClass<S... | export const StickyContainer: React.ComponentClass<React.HTMLAttributes<HTMLDivElement>>;
export interface StickyProps {
relative?: boolean;
isActive?: boolean; | random_line_split |
failure.py | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza import StreamFeatures
from sleekxmpp.xmlstream import ElementBase, StanzaBase, ET
from sleekxmpp.xmlstream import register... |
def del_condition(self):
"""Remove the condition element."""
for child in self.xml.getchildren():
if "{%s}" % self.condition_ns in child.tag:
tag = child.tag.split('}', 1)[-1]
if tag in self.conditions:
self.xml.remove(child)
... | """
Set the tag name of the condition element.
Arguments:
value -- The tag name of the condition element.
"""
if value in self.conditions:
del self['condition']
self.xml.append(ET.Element("{%s}%s" % (self.namespace, value)))
return self | identifier_body |
failure.py | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza import StreamFeatures
from sleekxmpp.xmlstream import ElementBase, StanzaBase, ET
from sleekxmpp.xmlstream import register... | interfaces = set(('condition', 'text'))
plugin_attrib = name
sub_interfaces = set(('text',))
conditions = set(('aborted', 'account-disabled', 'credentials-expired',
'encryption-required', 'incorrect-encoding', 'invalid-authzid',
'invalid-mechanism', 'malformed-request', 'mechansism-too-w... | namespace = 'urn:ietf:params:xml:ns:xmpp-sasl' | random_line_split |
failure.py | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza import StreamFeatures
from sleekxmpp.xmlstream import ElementBase, StanzaBase, ET
from sleekxmpp.xmlstream import register... |
return self
| self.xml.remove(child) | conditional_block |
failure.py | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza import StreamFeatures
from sleekxmpp.xmlstream import ElementBase, StanzaBase, ET
from sleekxmpp.xmlstream import register... | (self):
"""Return the condition element's name."""
for child in self.xml.getchildren():
if "{%s}" % self.namespace in child.tag:
cond = child.tag.split('}', 1)[-1]
if cond in self.conditions:
return cond
return 'not-authorized'
... | get_condition | identifier_name |
fixture.js | } else {
return AJAX(settings);
}
}
}
var typeTest = /^(script|json|text|jsonp)$/,
// a list of 'overwrite' settings object
overwrites = [],
// returns the index of an overwrite function
find = function (settings, exact) {
for (var i = 0; i < overwrites.length; i++) {
if ($fixture._similar(set... | })
return data;
},
/**
* @description Make a store of objects to use when making requests against fixtures.
* @function can.fixture.store store
* @parent can.fixture
*
* @signature `can.fixture.store(count, make[, filter])`
*
* @param {Number} count The number of items to create.
*
... | return null;
}
res.shift();
can.each(order, function (name) {
data[name] = res.shift() | random_line_split |
fixture.js |
// if we get response(200, RESPONSES, HEADERS)
if(typeof statusText != "string"){
headers = responses;
responses = statusText;
statusText = "success";
}
if ( status >= 400 && status <= 599 ) {
this.dataType = "text"
}
return [status, statusText, extractResponses(this, responses), head... | {
headers = statusText;
responses = status;
statusText = "success"
status = 200;
} | conditional_block | |
Augur Installer.py | import os
import sys
import shutil
import binascii
import traceback
import subprocess
from win32com.client import Dispatch
LAUNCHER_PATH = "C:\\Program Files\\Augur"
DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur")
PASSFILE = os.path.join(DATA_PATH, "password.txt")
if getattr(sys, 'fro... |
if __name__ == '__main__':
try:
if len(sys.argv) == 2 and sys.argv[1] == 'uninstall':
uninstall()
elif len(sys.argv) == 1:
main()
else:
assert len(sys.argv) <= 2, "wrong number of arguements!"
except Exception as exc:
traceback.print_exc()
... | paths = LAUNCHER_PATH, DATA_PATH
for p in paths:
print("Deleting", p, "...", end=" ", flush=True)
shutil.rmtree(p)
print("Success!")
print("Removing desktop shortcut...", end=" ", flush=True)
desktop = os.path.join(os.path.expanduser('~'), 'Desktop')
shortcut_path = os.path.join(... | identifier_body |
Augur Installer.py | import os
import sys
import shutil
import binascii
import traceback
import subprocess
from win32com.client import Dispatch
LAUNCHER_PATH = "C:\\Program Files\\Augur"
DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur")
PASSFILE = os.path.join(DATA_PATH, "password.txt")
if getattr(sys, 'fro... | ():
# first make all the appropriate directories
print("Making directories...")
for d in LAUNCHER_PATH, DATA_PATH:
print("Creating", d, end=" ", flush=True)
os.mkdir(d)
print("Success!")
print("Generating random password file...", end=" ", flush=True)
# then generate the pas... | main | identifier_name |
Augur Installer.py | import os
import sys
import shutil
import binascii
import traceback
import subprocess
from win32com.client import Dispatch
LAUNCHER_PATH = "C:\\Program Files\\Augur"
DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur")
PASSFILE = os.path.join(DATA_PATH, "password.txt")
if getattr(sys, 'fro... |
else:
# we are running in a normal Python environment
BASEDIR = os.path.dirname(os.path.abspath(__file__))
GETH_EXE = os.path.join(BASEDIR, 'geth.exe')
LAUNCHER_EXE = os.path.join(BASEDIR, 'augurlauncher.exe')
def main():
# first make all the appropriate directories
print("Making directories...")
... | BASEDIR = sys._MEIPASS | conditional_block |
Augur Installer.py | import os
import sys
import shutil
import binascii
import traceback | import subprocess
from win32com.client import Dispatch
LAUNCHER_PATH = "C:\\Program Files\\Augur"
DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur")
PASSFILE = os.path.join(DATA_PATH, "password.txt")
if getattr(sys, 'frozen', False):
# we are running in a |PyInstaller| bundle
BAS... | random_line_split | |
clone.rs | //! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not hav... | ///
/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
/// must not rely on it to ensure m... | /// }
/// ```
///
/// ## How can I implement `Clone`? | random_line_split |
clone.rs | //! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not hav... |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Clone for *const T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Clone for *mut T {
#[inline]
fn clone(&self) -> ... | {
*self
} | identifier_body |
clone.rs | //! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not hav... | <T: Clone + ?Sized> {
_field: crate::marker::PhantomData<T>,
}
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct AssertParamIsCopy<T: Copy + ?Sized> {
_field: crate::marker::P... | AssertParamIsClone | identifier_name |
issue-53548.rs | // Regression test for #53548. The `Box<dyn Trait>` type below is
// expanded to `Box<dyn Trait + 'static>`, but the generator "witness"
// that results is `for<'r> { Box<dyn Trait + 'r> }`. The WF code was
// encountering an ICE (when debug-assertions were enabled) and an
// unexpected compilation error (without debug... | Box::new(static move || {
let store = Store::<Box<dyn Trait>> {
inner: Default::default(),
};
yield ();
});
} | random_line_split | |
issue-53548.rs | // Regression test for #53548. The `Box<dyn Trait>` type below is
// expanded to `Box<dyn Trait + 'static>`, but the generator "witness"
// that results is `for<'r> { Box<dyn Trait + 'r> }`. The WF code was
// encountering an ICE (when debug-assertions were enabled) and an
// unexpected compilation error (without debug... | () {
Box::new(static move || {
let store = Store::<Box<dyn Trait>> {
inner: Default::default(),
};
yield ();
});
}
| main | identifier_name |
issue-53548.rs | // Regression test for #53548. The `Box<dyn Trait>` type below is
// expanded to `Box<dyn Trait + 'static>`, but the generator "witness"
// that results is `for<'r> { Box<dyn Trait + 'r> }`. The WF code was
// encountering an ICE (when debug-assertions were enabled) and an
// unexpected compilation error (without debug... | {
Box::new(static move || {
let store = Store::<Box<dyn Trait>> {
inner: Default::default(),
};
yield ();
});
} | identifier_body | |
contact.js | // Generated by CoffeeScript 1.4.0
(function() {
$('document').ready(function() {
var init, pendulumswing, rotation, swingtime;
rotation = 3;
swingtime = 700;
init = function() {
return $('#get_in_touch_pivot').stop().animate({
rotate: rotation
}, 0, function() {
$('#get_i... |
}, {
offset: 500
});
});
}).call(this);
| {
rotation = 3;
swingtime = 700;
return init();
} | conditional_block |
contact.js | // Generated by CoffeeScript 1.4.0
(function() {
$('document').ready(function() {
var init, pendulumswing, rotation, swingtime;
rotation = 3;
swingtime = 700; | return pendulumswing();
});
};
pendulumswing = function() {
return $('#get_in_touch_pivot').animate({
rotate: rotation
}, swingtime, "swing", function() {
if (rotation === 0) {
return;
}
if (rotation > 0) {
rotation -= 0.5;
} ... | init = function() {
return $('#get_in_touch_pivot').stop().animate({
rotate: rotation
}, 0, function() {
$('#get_in_touch_pivot').css("display", "block"); | random_line_split |
user.py | from __future__ import absolute_import
import six
from collections import defaultdict
from django.conf import settings
from sentry.app import env
from sentry.api.serializers import Serializer, register
from sentry.models import AuthIdentity, Authenticator, User, UserAvatar, UserOption
from sentry.utils.avatar import... |
return results
def get_attrs(self, item_list, user):
avatars = {
a.user_id: a
for a in UserAvatar.objects.filter(
user__in=item_list
)
}
identities = self._get_identities(item_list, user)
authenticators = Authenticator.ob... | results[item.user_id].append(item) | conditional_block |
user.py | from __future__ import absolute_import
import six
from collections import defaultdict
from django.conf import settings
from sentry.app import env
from sentry.api.serializers import Serializer, register
from sentry.models import AuthIdentity, Authenticator, User, UserAvatar, UserOption
from sentry.utils.avatar import... | (self, item_list, user):
avatars = {
a.user_id: a
for a in UserAvatar.objects.filter(
user__in=item_list
)
}
identities = self._get_identities(item_list, user)
authenticators = Authenticator.objects.bulk_users_have_2fa([i.id for i in i... | get_attrs | identifier_name |
user.py | from __future__ import absolute_import
import six
from collections import defaultdict
from django.conf import settings
from sentry.app import env
from sentry.api.serializers import Serializer, register
from sentry.models import AuthIdentity, Authenticator, User, UserAvatar, UserOption
from sentry.utils.avatar import... | def get_attrs(self, item_list, user):
avatars = {
a.user_id: a
for a in UserAvatar.objects.filter(
user__in=item_list
)
}
identities = self._get_identities(item_list, user)
authenticators = Authenticator.objects.bulk_users_have_2fa... | results = {i.id: [] for i in item_list}
for item in queryset:
results[item.user_id].append(item)
return results
| random_line_split |
user.py | from __future__ import absolute_import
import six
from collections import defaultdict
from django.conf import settings
from sentry.app import env
from sentry.api.serializers import Serializer, register
from sentry.models import AuthIdentity, Authenticator, User, UserAvatar, UserOption
from sentry.utils.avatar import... |
def serialize(self, obj, attrs, user):
d = {
'id': six.text_type(obj.id),
'name': obj.get_display_name(),
'username': obj.username,
'email': obj.email,
'avatarUrl': get_gravatar_url(obj.email, size=32),
'isActive': obj.is_active,
... | avatars = {
a.user_id: a
for a in UserAvatar.objects.filter(
user__in=item_list
)
}
identities = self._get_identities(item_list, user)
authenticators = Authenticator.objects.bulk_users_have_2fa([i.id for i in item_list])
data = {}
... | identifier_body |
chip-list.d.ts | import { AfterContentInit, ElementRef, QueryList } from '@angular/core';
import { MdChip } from './chip';
import { FocusKeyManager } from '../core/a11y/focus-key-manager';
/**
* A material design chips component (named ChipList for it's similarity to the List component).
*
* Example:
*
* <md-chip-list>
* ... | implements AfterContentInit {
private _elementRef;
/** Track which chips we're listening to for focus/destruction. */
private _subscribed;
/** Whether or not the chip is selectable. */
protected _selectable: boolean;
/** The FocusKeyManager which handles focus. */
_keyManager: FocusKeyManag... | MdChipList | identifier_name |
chip-list.d.ts | import { AfterContentInit, ElementRef, QueryList } from '@angular/core';
import { MdChip } from './chip';
import { FocusKeyManager } from '../core/a11y/focus-key-manager';
/**
* A material design chips component (named ChipList for it's similarity to the List component).
*
* Example:
*
* <md-chip-list>
* ... | } | random_line_split | |
carousel_lite.js | (function ($) {
$.fn.jCarouselLite = function (o) {
o = $.extend({
btnPrev: null,
btnNext: null,
btnGo: null,
mouseWheel: false,
auto: null,
speed: 200,
easing: null,
vertical: false,
circular: true,
visible: 5,
start: 0,
scroll: 1,
beforeStart: null,
afterEn... | });
if (o.btnGo) $.each(o.btnGo, function (i, a) {
$(a).click(function () {
return go(o.circular ? o.visible + i: i)
})
});
if (o.mouseWheel && c.mousewheel) c.mousewheel(function (e, d) {
return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll)
});
if (o.auto) setInterval(fu... | if (o.btnNext) $(o.btnNext).click(function () {
return go(curr + o.scroll)
| random_line_split |
carousel_lite.js | (function ($) {
$.fn.jCarouselLite = function (o) {
o = $.extend({
btnPrev: null,
btnNext: null,
btnGo: null,
mouseWheel: false,
auto: null,
speed: 200,
easing: null,
vertical: false,
circular: true,
visible: 5,
start: 0,
scroll: 1,
beforeStart: null,
afterEn... |
})(jQuery); | {
return a[0].offsetHeight + css(a, 'marginTop') + css(a, 'marginBottom')
} | identifier_body |
carousel_lite.js | (function ($) {
$.fn.jCarouselLite = function (o) {
o = $.extend({
btnPrev: null,
btnNext: null,
btnGo: null,
mouseWheel: false,
auto: null,
speed: 200,
easing: null,
vertical: false,
circular: true,
visible: 5,
start: 0,
scroll: 1,
beforeStart: null,
afterEn... | (a) {
return a[0].offsetWidth + css(a, 'marginLeft') + css(a, 'marginRight')
};
function height(a) {
return a[0].offsetHeight + css(a, 'marginTop') + css(a, 'marginBottom')
}
})(jQuery); | width | identifier_name |
aws_kms.py | committer'
}
DOCUMENTATION = '''
---
module: aws_kms
short_description: Perform various KMS management tasks.
description:
- Manage role/user access to a KMS key. Not designed for encrypting/decrypting.
version_added: "2.3"
options:
mode:
description:
- Grant or deny access.
required: true
defau... | role_name: "prod-appServerRole-1R5AQG2BSEL6L"
'''
RETURN = '''
changes_needed:
description: grant types that would be changed/were changed.
type: dict
returned: always
sample: { "role": "add", "role grant": "add" }
had_invalid_entries:
description: there are invalid (non-ARN) entries in the KMS entry. Th... | key_alias: "alias/my_production_secrets" | random_line_split |
aws_kms.py | mitter'
}
DOCUMENTATION = '''
---
module: aws_kms
short_description: Perform various KMS management tasks.
description:
- Manage role/user access to a KMS key. Not designed for encrypting/decrypting.
version_added: "2.3"
options:
mode:
description:
- Grant or deny access.
required: true
default:... |
elif mode == 'deny' and statement['Sid'] == statement_label[granttype] and role_arn in statement['Principal']['AWS']:
# we don't selectively deny. that's a grant with a
# smaller list. so deny=remove all of this arn.
changes_needed[granttype] = 'remove'
... | statement['Principal']['AWS'].remove(role_arn) | conditional_block |
aws_kms.py | mitter'
}
DOCUMENTATION = '''
---
module: aws_kms
short_description: Perform various KMS management tasks.
description:
- Manage role/user access to a KMS key. Not designed for encrypting/decrypting.
version_added: "2.3"
options:
mode:
description:
- Grant or deny access.
required: true
default:... | ():
argument_spec = ansible.module_utils.ec2.ec2_argument_spec()
argument_spec.update(dict(
mode = dict(choices=['grant', 'deny'], default='grant'),
key_alias = dict(required=False, type='str'),
key_arn = dict(required=False, type='str'),
role_name = dict(required=False, type='st... | main | identifier_name |
aws_kms.py | mitter'
}
DOCUMENTATION = '''
---
module: aws_kms
short_description: Perform various KMS management tasks.
description:
- Manage role/user access to a KMS key. Not designed for encrypting/decrypting.
version_added: "2.3"
options:
mode:
description:
- Grant or deny access.
required: true
default:... |
result = {}
mode = module.params['mode']
try:
region, ec2_url, aws_connect_kwargs = | argument_spec = ansible.module_utils.ec2.ec2_argument_spec()
argument_spec.update(dict(
mode = dict(choices=['grant', 'deny'], default='grant'),
key_alias = dict(required=False, type='str'),
key_arn = dict(required=False, type='str'),
role_name = dict(required=False, type='str'),
... | identifier_body |
file.rs | use std::path::Path;
use std::fs::File;
use std::fs::OpenOptions;
use std::error::Error;
use std::io::prelude::*;
use std::io::BufReader;
use regex::Regex;
#[allow(unused_variables)]
pub fn write(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file = match File::create(&path)... | {
let path = Path::new(pathstring);
let mut file;
if path.exists() {
file = match OpenOptions::new().write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
} else {
file = match OpenOption... | identifier_body | |
file.rs | use std::path::Path;
use std::fs::File;
use std::fs::OpenOptions;
use std::error::Error;
use std::io::prelude::*;
use std::io::BufReader;
use regex::Regex;
#[allow(unused_variables)]
pub fn write(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file = match File::create(&path)... | (path: &Path) -> String {
let mut content: String = String::new();
let mut file = match File::open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
file.read_to_string(&mut content);
content
}
#[allow(unused_must_use)]
pub f... | read | identifier_name |
file.rs | use std::path::Path;
use std::fs::File;
use std::fs::OpenOptions;
use std::error::Error;
use std::io::prelude::*;
use std::io::BufReader; | pub fn write(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file = match File::create(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
match file.write_all(content.as_bytes()) {
Err(_) ... | use regex::Regex;
#[allow(unused_variables)] | random_line_split |
markstress.py | ### This program intends to combine same GSHF in citation tree, and sort them according to the first letter of title;
### Author: Ye Gao
### Date: 2017-11-7
import csv
file = open('NodeCheckList.csv', 'rb')
reader = csv.reader(file)
NodeCheckList = list(reader)
file.close()
#print NodeCheckList
FirstRow = NodeChec... |
print SortYear
NodeStressList = []
for element in NodeCheckList:
if (int(element[7]) == 0) or (int(element[7]) == 1) or (int(element[7]) == 2):
NodeStressList.append(element)
SortTitle = sorted(NodeStressList, key=lambda l:l[4], reverse=False)
SortTitle = [FirstRow] + SortTitle
title = ""
CombineTitle = []
for... | element[2] = int(element[2])
SortYear = sorted(NodeCheckList, key=lambda l:l[3], reverse=True)
SortCiteTimes = sorted(NodeCheckList, key=lambda l:l[2], reverse=True) | random_line_split |
markstress.py | ### This program intends to combine same GSHF in citation tree, and sort them according to the first letter of title;
### Author: Ye Gao
### Date: 2017-11-7
import csv
file = open('NodeCheckList.csv', 'rb')
reader = csv.reader(file)
NodeCheckList = list(reader)
file.close()
#print NodeCheckList
FirstRow = NodeChec... |
SortYear = sorted(NodeCheckList, key=lambda l:l[3], reverse=True)
SortCiteTimes = sorted(NodeCheckList, key=lambda l:l[2], reverse=True)
print SortYear
NodeStressList = []
for element in NodeCheckList:
if (int(element[7]) == 0) or (int(element[7]) == 1) or (int(element[7]) == 2):
NodeStressList.append(element)
... | element[2] = int(element[2]) | conditional_block |
take_picture_state.py | #!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from sensor_msgs.msg import PointCloud2
class TakePictureState(EventState):
'''
Stores the pic... | '''
def __init__(self):
super(TakePictureState, self).__init__(outcomes = ['done'], output_keys = ['Image'])
self._topic = '/head_xtion/rgb/image_rect_color'
self._sub = ProxySubscriberCached({self._topic:Image})
def execute(self, userdata):
if self._sub.has_msg(self._topic):
userdata.Image = self... |
<= done The picture has been received and stored.
| random_line_split |
take_picture_state.py | #!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from sensor_msgs.msg import PointCloud2
class TakePictureState(EventState):
'''
Stores the pic... | if self._sub.has_msg(self._topic):
userdata.Image = self._sub.get_last_msg(self._topic)
print 'take_picture_state: took a picture'
return 'done' | identifier_body | |
take_picture_state.py | #!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from sensor_msgs.msg import PointCloud2
class TakePictureState(EventState):
'''
Stores the pic... |
print 'take_picture_state: took a picture'
return 'done'
| userdata.Image = self._sub.get_last_msg(self._topic) | conditional_block |
take_picture_state.py | #!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from sensor_msgs.msg import PointCloud2
class | (EventState):
'''
Stores the picture of the given topic.
#> Image Image The received pointcloud.
<= done The picture has been received and stored.
'''
def __init__(self):
super(TakePictureState, self).__init__(outcomes = ['done'], output_keys = ['Image'])
self._topic = '/head_xt... | TakePictureState | identifier_name |
isRegExp.js | var isObject = require('./isObject');
/** `Object#toString` result references. */
var regexpTag = '[object RegExp]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype... | function isRegExp(value) {
return isObject(value) && objectToString.call(value) == regexpTag;
}
module.exports = isRegExp; | * // => false
*/
| random_line_split |
isRegExp.js | var isObject = require('./isObject');
/** `Object#toString` result references. */
var regexpTag = '[object RegExp]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype... |
module.exports = isRegExp;
| {
return isObject(value) && objectToString.call(value) == regexpTag;
} | identifier_body |
isRegExp.js | var isObject = require('./isObject');
/** `Object#toString` result references. */
var regexpTag = '[object RegExp]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype... | (value) {
return isObject(value) && objectToString.call(value) == regexpTag;
}
module.exports = isRegExp;
| isRegExp | identifier_name |
pyrpo.py | if not self.remote_url:
output.append('#')
output.extend([
self.label,
self.clone_cmd,
repr(self.remote_url), # TODO: shell quote?
repr(self.relpath)
])
yield ' '.join(output)
def pip_report(self):
comment = '#' i... | yield pprint.pformat(self.to_dict())
def sh_report(self):
output = [] | random_line_split | |
pyrpo.py | .field_trans.get(attr, attr), value)
else:
raise Exception()
if bufname is not None:
if len(buf):
buf.pop()
len(buf) > 1 and buf.popleft()
yield (bufname, '\n'.join(buf))
return
... | path = l.rstrip()
_path, _prefix = os.path.dirname(path), os.path.basename(path)
repo = REPO_PREFIXES.get(_prefix)
if repo is None:
log.error("repo for path %r and prefix %r is None" %
(path, _prefix))
if repo:
yield repo(_path)
# yie... | conditional_block | |
pyrpo.py | vid
)
return
def status_report(self):
yield '######'
yield self.sh_report().next()
yield self.last_commit
yield self.status
yield ""
def hgsub_report(self):
if self.relpath == '.':
return
yield "%s = [%s]%s" % (
... |
@cached_property
def branch(self):
return self.sh('hg branch')
def log(self, n=None, **kwargs):
# TODO: nested generator
return self.sh(' '.join((
'hg log',
('-l%d' % n) if n else '',
' '.join(
('--%s=%s' % (k, v)) for (k, v) in ... | return self.sh('hg id -i').rstrip().rstrip('+') # TODO | identifier_body |
pyrpo.py | vid
)
return
def status_report(self):
yield '######'
yield self.sh_report().next()
yield self.last_commit
yield self.status
yield ""
def hgsub_report(self):
if self.relpath == '.':
return
yield "%s = [%s]%s" % (
... | ():
output = sh("hg showconfig | grep '^schemes.'").split('\n')
log.debug(output)
schemes = (
l.split('.', 1)[1].split('=') for l in output if '=' in l)
regexes = sorted(
((k, v, re.compile(v.replace('{1}', '(.*)')+'(.*)'))
for k, v in schemes),
... | _get_url_scheme_regexes | identifier_name |
cstore.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > {
&self.used_link_args
}
pub fn add_extern_mod_stmt_cnum(&self,
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
self.extern_mod_crate_map.borrow_mut().in... | {
for s in args.split(' ') {
self.used_link_args.borrow_mut().push(s.to_owned());
}
} | identifier_body |
cstore.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self) -> ast::CrateNum {
self.metas.borrow().len() as ast::CrateNum + 1
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
self.metas.borrow().get(&cnum).clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
let cdata = self.get_crate_d... | next_crate_num | identifier_name |
cstore.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
-> Option<ast::CrateNum> {
self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x)
}
}
impl crate_metadata {
pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
pub fn crate_id(&... | emod_id: ast::NodeId,
cnum: ast::CrateNum) {
self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
} | random_line_split |
utils.py | # -*- coding: utf-8 -*-
import os
from future.moves.urllib.parse import quote
import uuid
import ssl
from pymongo import MongoClient
import requests
from django.apps import apps
from addons.wiki import settings as wiki_settings
from addons.wiki.exceptions import InvalidVersionError
from osf.utils.permissions import A... |
def migrate_uuid(node, wname):
"""Migrates uuid to new namespace."""
db = share_db()
old_sharejs_uuid = get_sharejs_uuid(node, wname)
broadcast_to_sharejs('lock', old_sharejs_uuid)
generate_private_uuid(node, wname)
new_sharejs_uuid = get_sharejs_uuid(node, wname)
doc_item = db['docs'... | """Deletes share document and removes namespace from model."""
db = share_db()
sharejs_uuid = get_sharejs_uuid(node, wname)
db['docs'].remove({'_id': sharejs_uuid})
db['docs_ops'].remove({'name': sharejs_uuid})
wiki_key = to_mongo_key(wname)
del node.wiki_private_uuids[wiki_key]
node.save... | identifier_body |
utils.py | # -*- coding: utf-8 -*-
import os
from future.moves.urllib.parse import quote
import uuid
import ssl
from pymongo import MongoClient
import requests
from django.apps import apps
from addons.wiki import settings as wiki_settings
from addons.wiki.exceptions import InvalidVersionError
from osf.utils.permissions import A... | """Deletes share document and removes namespace from model."""
db = share_db()
sharejs_uuid = get_sharejs_uuid(node, wname)
db['docs'].remove({'_id': sharejs_uuid})
db['docs_ops'].remove({'name': sharejs_uuid})
wiki_key = to_mongo_key(wname)
del node.wiki_private_uuids[wiki_key]
node.... | def delete_share_doc(node, wname): | random_line_split |
utils.py | # -*- coding: utf-8 -*-
import os
from future.moves.urllib.parse import quote
import uuid
import ssl
from pymongo import MongoClient
import requests
from django.apps import apps
from addons.wiki import settings as wiki_settings
from addons.wiki.exceptions import InvalidVersionError
from osf.utils.permissions import A... |
write_contributors = [
user._id for user in node.contributors
if node.has_permission(user, WRITE)
]
broadcast_to_sharejs('unlock', old_sharejs_uuid, data=write_contributors)
def share_db():
"""Generate db client for sharejs db"""
client = MongoClient(wiki_settings.SHAREJS_DB_URL,... | for item in ops_items:
item['_id'] = item['_id'].replace(old_sharejs_uuid, new_sharejs_uuid)
item['name'] = new_sharejs_uuid
db['docs_ops'].insert(ops_items)
db['docs_ops'].remove({'name': old_sharejs_uuid}) | conditional_block |
utils.py | # -*- coding: utf-8 -*-
import os
from future.moves.urllib.parse import quote
import uuid
import ssl
from pymongo import MongoClient
import requests
from django.apps import apps
from addons.wiki import settings as wiki_settings
from addons.wiki.exceptions import InvalidVersionError
from osf.utils.permissions import A... | (node, wname):
"""Deletes share document and removes namespace from model."""
db = share_db()
sharejs_uuid = get_sharejs_uuid(node, wname)
db['docs'].remove({'_id': sharejs_uuid})
db['docs_ops'].remove({'name': sharejs_uuid})
wiki_key = to_mongo_key(wname)
del node.wiki_private_uuids[wiki... | delete_share_doc | identifier_name |
__init__.py | RFXtrx."""
rfx_object.close_connection()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown_rfxtrx)
hass.data[DATA_RFXOBJECT] = rfx_object
return True
def get_rfx_object(packetid):
"""Return the RFXObject with the packetid."""
try:
binarypacket = bytearray.fromhex(packetid... |
if command == "turn_on":
for _ in range(self.signal_repetitions):
self._event.device.send_on(rfx_object.transport)
self._state = True | random_line_split | |
__init__.py | , Pkt_id: %s)",
slugify(event.device.id_string.lower()),
event.device.__class__.__name__,
event.device.subtype,
"".join(f"{x:02x}" for x in event.data),
)
# Callback to HA registered components.
for subscriber in RECEIVED_EVT_SUBSCRIBERS:
... | should_poll | identifier_name | |
__init__.py | not event.device.id_string:
return
_LOGGER.debug(
"Receive RFXCOM event from "
"(Device_id: %s Class: %s Sub: %s, Pkt_id: %s)",
slugify(event.device.id_string.lower()),
event.device.__class__.__name__,
event.device.subtype,
"".... | """Initialize the device."""
self.signal_repetitions = signal_repetitions
self._name = name
self._event = event
self._state = datas[ATTR_STATE]
self._should_fire_event = datas[ATTR_FIRE_EVENT]
self._brightness = 0
self._unique_id = f"{slugify(self._event.device.ty... | identifier_body | |
__init__.py | Humidity status", ""),
("Forecast", ""),
("Forecast numeric", ""),
("Rain total", ""),
("Wind average speed", ""),
("Wind gust", ""),
("Chill", ""),
("Total usage", ""),
("Count", ""),
("Current Ch. 1", ""),
("Current Ch. 2", ""),
(... |
else:
obj = rfxtrxmod.ControlEvent(pkt)
return obj
def get_pt2262_deviceid(device_id, nb_data_bits):
"""Extract and return the address bits from a Lighting4/PT2262 packet."""
if nb_data_bits is None:
return
try:
data = bytearray.fromhex(device_id)
except ValueError:
... | obj = rfxtrxmod.StatusEvent(pkt) | conditional_block |
declareQueries.test.tsx | import * as React from 'react';
import { render, waitForElement, cleanup } from 'react-testing-library';
import { queryStrict, refetch, invalidate } from '../src/DSL';
import { taskEither } from 'fp-ts/lib/TaskEither';
import { declareQueries } from '../src/react';
import * as QR from '../src/QueryResult';
import { pip... | props.queries,
QR.map(q => q.foo),
QR.fold(whenLoading, () => 'failure', whenSuccess)
);
});
const { getByText } = await render(<Foo />);
await waitForElement(() => getByText('foos'));
expect(whenLoading).toHaveBeenCalledTimes(
1 + 1 /* because we subscribe in compon... | }, []);
return pipe( | random_line_split |
test_context.py | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... | (self):
ctxt = context.DesignateContext(
user_id='12345', project_id='54321'
)
admin_ctxt = ctxt.elevated(show_deleted=True)
self.assertTrue(admin_ctxt.show_deleted)
def test_all_tenants(self):
ctxt = context.DesignateContext(
user_id='12345', projec... | test_elevated_with_show_deleted | identifier_name |
test_context.py | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... |
def test_elevated_with_show_deleted(self):
ctxt = context.DesignateContext(
user_id='12345', project_id='54321'
)
admin_ctxt = ctxt.elevated(show_deleted=True)
self.assertTrue(admin_ctxt.show_deleted)
def test_all_tenants(self):
ctxt = context.DesignateCont... |
self.assertFalse(ctxt.is_admin)
self.assertTrue(admin_ctxt.is_admin)
self.assertEqual(0, len(ctxt.roles)) | random_line_split |
test_context.py | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... |
def test_edit_managed_records(self):
ctxt = context.DesignateContext(
user_id='12345', project_id='54321'
)
admin_ctxt = ctxt.elevated()
admin_ctxt.edit_managed_records = True
self.assertFalse(ctxt.is_admin)
self.assertTrue(admin_ctxt.is_admin)
... | ctxt = context.DesignateContext(
user_id='12345', project_id='54321'
)
with testtools.ExpectedException(exceptions.Forbidden):
ctxt.all_tenants = True | identifier_body |
notparallel_chain_fit.py | # Copied from LMC documentation
# Modified to use MPI (but not enable parallelization), to increase the parameter degeneracy, and to disperse the start points
# Here is a simple example. As shown it will run in non-parallel mode; comments indicate what to do for parallelization.
from lmc import *
## for MPI
from mpi4... | (self, x, y):
self.x = x
self.y = y
thing = Thing(x, y)
### The log-posterior function. Here we just assume a bivariate Gaussian posterior with marginal standard deviations s(x)=2 and s(y)=3, correlation coefficient 0.75, and means <x>=-1, <y>=1.
def post(thing):
r = 0.99
sx = 2.0
sy = 3.0
... | __init__ | identifier_name |
notparallel_chain_fit.py | # Copied from LMC documentation
# Modified to use MPI (but not enable parallelization), to increase the parameter degeneracy, and to disperse the start points
# Here is a simple example. As shown it will run in non-parallel mode; comments indicate what to do for parallelization.
from lmc import *
## for MPI
from mpi4... | return -0.5/(1.0-r**2)*( (thing.x()-mx)**2/sx**2 + (thing.y()-my)**2/sy**2 - 2.0*r*(thing.x()-mx)/sx*(thing.y()-my)/sy )
### Create a parameter space consisting of x and y, and associate the log-posterior function with it.
space = ParameterSpace([thing.x, thing.y], post)
### If we'd bothered to define a DerivedPa... | random_line_split | |
notparallel_chain_fit.py | # Copied from LMC documentation
# Modified to use MPI (but not enable parallelization), to increase the parameter degeneracy, and to disperse the start points
# Here is a simple example. As shown it will run in non-parallel mode; comments indicate what to do for parallelization.
from lmc import *
## for MPI
from mpi4... |
thing = Thing(x, y)
### The log-posterior function. Here we just assume a bivariate Gaussian posterior with marginal standard deviations s(x)=2 and s(y)=3, correlation coefficient 0.75, and means <x>=-1, <y>=1.
def post(thing):
r = 0.99
sx = 2.0
sy = 3.0
mx = -1.0
my = 1.0
return -0.5/(1.0-r**... | def __init__(self, x, y):
self.x = x
self.y = y | identifier_body |
test_serving.py | # Copyright 2013 Donald Stufft
#
# 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, so... | (monkeypatch):
_log = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(serving, "_log", _log)
monkeypatch.setattr(WSGIRequestHandler, "__init__", lambda *a, **kw: None)
handler = WSGIRequestHandler()
handler.address_string = pretend.call_recorder(lambda: "127.0.0.1")
handler.l... | test_request_handler_log | identifier_name |
test_serving.py | # Copyright 2013 Donald Stufft
#
# 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, so... | _log = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(serving, "_log", _log)
monkeypatch.setattr(WSGIRequestHandler, "__init__", lambda *a, **kw: None)
handler = WSGIRequestHandler()
handler.address_string = pretend.call_recorder(lambda: "127.0.0.1")
handler.log("info", "test me... | identifier_body | |
test_serving.py | # Copyright 2013 Donald Stufft
#
# 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, so... | # limitations under the License.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import pretend
from warehouse import serving
from warehouse.serving import WSGIRequestHandler
def test_request_handler_log(monkeypatch):
_log = pretend.call_recorder(lambda *... | # See the License for the specific language governing permissions and | random_line_split |
01_starttime_duration.py | #!/usr/bin/env python
# encoding: utf-8
"""
Show how to use `dur` and `delay` parameters of play() and out()
methods to sequence events over time.
"""
from pyo import *
import random
s = Server(duplex=0).boot()
num = 70
freqs = [random.uniform(100, 1000) for i in range(num)]
start1 = [i * 0.5 for i in range(num)]
fa... | tabs = SndTable(snds)
fade2 = Fader(0.05, 10, dur2, mul=0.7).play(dur=dur2, delay=start2)
b = Beat(time=0.125, w1=[90, 30, 30, 20], w2=[30, 90, 50, 40], w3=[0, 30, 30, 40], poly=1).play(dur=dur2, delay=start2)
out = TrigEnv(b, tabs, b["dur"], mul=b["amp"] * fade2).out(dur=dur2, delay=start2)
start3 = 45
dur3 = 30
fade... | "../snds/alum3.wav",
"../snds/alum4.wav",
] | random_line_split |
preserve.rs | Bindings are these kind of weird implicit pointers (cc
// #2329). We require (in gather_loans) that they be
// rooted in an immutable location.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
... | attempt_root | identifier_name | |
preserve.rs | if we are
// preserving an expression like a.b where the field `b`
// has @ type, then it will recurse to ensure that the `a`
// is stable to try and avoid rooting the value `a.b`. In
// this case, root_managed_data will be false.
if self.root_managed_data {... | {
if self.bccx.is_subregion_of(self.scope_region, scope_ub) {
Ok(PcOk)
} else {
Err(bckerr {
cmt:cmt,
code:err_out_of_scope(scope_ub, self.scope_region)
})
}
} | identifier_body | |
preserve.rs | the memory
scope_region: ty::Region,
// the scope for the body of the enclosing fn/method item
item_ub: ast::node_id,
// the upper bound on how long we can root an @T pointer
root_ub: ast::node_id,
// if false, do not attempt to root managed data
root_managed_data: bool
}
pub impl<'self... | // the corner case.
//
// Nonetheless, if you decide to optimize this case in the
// future, you need only adjust where the cat_discr()
// node appears | random_line_split | |
preserve.rs | memory
scope_region: ty::Region,
// the scope for the body of the enclosing fn/method item
item_ub: ast::node_id,
// the upper bound on how long we can root an @T pointer
root_ub: ast::node_id,
// if false, do not attempt to root managed data
root_managed_data: bool
}
pub impl<'self> Pr... | else {
self.attempt_root(cmt, base, derefs)
}
}
cat_discr(base, match_id) => {
// Subtle: in a match, we must ensure that each binding
// variable remains valid for the duration of the arm in
// which it appears, presuming that this ar... | {
let non_rooting_ctxt = PreserveCtxt {
root_managed_data: false,
..*self
};
match non_rooting_ctxt.preserve(base) {
Ok(PcOk) => {
Ok(PcOk)
}
Ok(PcIfPure(_)) ... | conditional_block |
CamIcon.tsx | import React from "react"
import Svg, { Circle, G, Path } from "react-native-svg"
export const CamIcon = props => (
<Svg width={40} height={35} viewBox="0 0 37 30" {...props}>
<G fill="#000" fillRule="evenodd">
<Path
d="M32.625 0h-14.25v3.733H0V30h37V3.733h-4.375V0zm-2 2v3.733H35v22.266H2V5.733h18.... | </G>
</Svg>
) | <Path
d="M18.375 10.333a6 6 0 110 12 6 6 0 010-12zm0 1.83a4.171 4.171 0 100 8.342 4.171 4.171 0 000-8.343z"
fillRule="nonzero"
/>
<Circle cx={7.375} cy={10.467} r={2} /> | random_line_split |
gtest_env_var_test.py | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
return gtest_test_utils.Subprocess(args, env=environ).output
def TestFlag(flag, test_val, default_val):
"""Verifies that the given flag is affected by the corresponding env var."""
env_var = 'GTEST_' + flag.upper()
SetEnvVar(env_var, test_val)
AssertEq(test_val, GetFlag(flag))
SetEnvVar(env_var, None)
... | args += [flag] | conditional_block |
gtest_env_var_test.py | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... | (self):
"""Tests that environment variable should affect the corresponding flag."""
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
TestFlag('filter', 'FooTest.Bar', '*')
SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
TestFlag('output', 'xml:tmp/foo.xml', '')
... | testEnvVarAffectsFlag | identifier_name |
gtest_env_var_test.py | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... | SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
TestFlag('output', 'xml:tmp/foo.xml', '')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
TestFlag('death_test_style', 'threadsafe', 'fast')
TestFlag('catch_exceptions', '0', '1')
... | TestFlag('filter', 'FooTest.Bar', '*') | random_line_split |
gtest_env_var_test.py | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
if __name__ == '__main__':
gtest_test_utils.Main()
| """Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT"""
SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml')
SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')
AssertEq('xml:tmp/foo.xml', GetFlag('output')) | identifier_body |
sparkline.rs | use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
} | Self {
min,
max,
data,
step,
}
}
}
impl fmt::Display for Ascii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇'];
let ticks_len = (ticks.len() - 1) as f64;
let spar... |
impl Ascii {
pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self { | random_line_split |
sparkline.rs | use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
}
impl Ascii {
pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self {
Self {
min,
max,
data,
step,
}
}
}
impl fmt::Display for Ascii... | ticks[i as usize]
})
.collect();
write!(f, "{}", sparkline)
}
}
#[test]
fn test_display() {
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
ma... | i = (i / self.max).round();
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.