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 |
|---|---|---|---|---|
feedback.ts | egrityService private integrityService: IIntegrityService,
@IThemeService private themeService: IThemeService,
@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService
) {
super(container, {
contextViewProvider: options.contextViewProvider,
labelRenderer: (container: HTM... | {
element.on('click', callback);
element.on('keypress', (e) => {
if (e instanceof KeyboardEvent) {
const keyboardEvent = <KeyboardEvent>e;
if (keyboardEvent.keyCode === 13 || keyboardEvent.keyCode === 32) { // Enter or Spacebar
callback();
}
}
});
return element;
} | identifier_body | |
feedback.ts | }
export interface IFeedbackDropdownOptions {
contextViewProvider: IContextViewService;
feedbackService?: IFeedbackService;
}
enum FormEvent {
SENDING,
SENT,
SEND_ERROR
}
export class FeedbackDropdown extends Dropdown {
private maxFeedbackCharacters: number;
private feedback: string;
private sentiment: numb... |
this.feedbackForm = <HTMLFormElement>$form.getHTMLElement();
$('h2.title').text(nls.localize("label.sendASmile", "Tweet us your feedback.")).appendTo($form);
this.invoke($('div.cancel').attr('tabindex', '0'), () => {
this.hide();
}).appendTo($form);
const $content = $('div.content').appendTo($form);
... | action: 'javascript:void(0);',
tabIndex: '-1'
}).appendTo(container);
$(container).addClass('monaco-menu-container'); | random_line_split |
feedback.ts | }
export interface IFeedbackDropdownOptions {
contextViewProvider: IContextViewService;
feedbackService?: IFeedbackService;
}
enum FormEvent {
SENDING,
SENT,
SEND_ERROR
}
export class FeedbackDropdown extends Dropdown {
private maxFeedbackCharacters: number;
private feedback: string;
private sentiment: numb... | (
container: HTMLElement,
options: IFeedbackDropdownOptions,
@ICommandService private commandService: ICommandService,
@ITelemetryService private telemetryService: ITelemetryService,
@IIntegrityService private integrityService: IIntegrityService,
@IThemeService private themeService: IThemeService,
@IWorks... | constructor | identifier_name |
feedback.ts | .")).appendTo($sentimentContainer);
$('br').appendTo($sentimentContainer);
}
$('span').text(nls.localize("sentiment", "How was your experience?")).appendTo($sentimentContainer);
const $feedbackSentiment = $('div.feedback-sentiment').appendTo($sentimentContainer);
this.smileyInput = $('div').addClass('senti... | {
this.feedbackDescriptionInput.value = '';
} | conditional_block | |
manifest.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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... | {
/// The identifier of the Habitat package
pub pkg_ident: PackageIdent,
/// Name of the Kubernetes resource.
pub metadata_name: String,
/// The docker image.
pub image: String,
/// The number of desired instances in the service group.
pub count: u64,
/// The relationship of a servi... | Manifest | identifier_name |
manifest.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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... | }
#[test]
fn test_manifest_generation_binds() {
let mut m = Manifest {
pkg_ident: PackageIdent::from_str("core/nginx").unwrap(),
metadata_name: "nginx-latest".to_owned(),
image: "core/nginx:latest".to_owned(),
count: 3,
service_topology: D... | assert_eq!(out, expected); | random_line_split |
manifest.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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... | };
let version_suffix = match pkg_ident.version {
Some(ref v) => {
pkg_ident
.release
.as_ref()
.map(|r| format!("{}-{}", v, r))
.unwrap_or(v.to_string())
}
None => "lates... | {
let count = matches.value_of("COUNT").unwrap_or("1").parse()?;
let topology: Topology = matches
.value_of("TOPOLOGY")
.unwrap_or("standalone")
.parse()
.unwrap_or(Default::default());
let group = matches.value_of("GROUP").map(|s| s.to_string());
... | identifier_body |
test_zip.py | import io
import zipfile
from tornado import testing
from waterbutler.core import streams
from waterbutler.core.utils import AsyncIterator
from tests import utils
class TestZipHandler(utils.HandlerTestCase):
| assert zip.open('file.txt').read() == data
| HOOK_PATH = 'waterbutler.server.api.v0.zip.ZipHandler._send_hook'
@testing.gen_test
def test_download_stream(self):
data = b'freddie brian john roger'
stream = streams.StringStream(data)
stream.content_type = 'application/octet-stream'
zipstream = streams.ZipStreamReader(AsyncI... | identifier_body |
test_zip.py | import io
import zipfile
from tornado import testing
from waterbutler.core import streams
from waterbutler.core.utils import AsyncIterator
from tests import utils
class | (utils.HandlerTestCase):
HOOK_PATH = 'waterbutler.server.api.v0.zip.ZipHandler._send_hook'
@testing.gen_test
def test_download_stream(self):
data = b'freddie brian john roger'
stream = streams.StringStream(data)
stream.content_type = 'application/octet-stream'
zipstream = ... | TestZipHandler | identifier_name |
test_zip.py | import io
import zipfile
from tornado import testing
from waterbutler.core import streams
from waterbutler.core.utils import AsyncIterator
from tests import utils
class TestZipHandler(utils.HandlerTestCase):
HOOK_PATH = 'waterbutler.server.api.v0.zip.ZipHandler._send_hook'
@testing.gen_test
def test_... | resp = yield self.http_client.fetch(
self.get_url('/zip?provider=queenhub&path=/freddie.png'),
)
zip = zipfile.ZipFile(io.BytesIO(resp.body))
assert zip.testzip() is None
assert zip.open('file.txt').read() == data | random_line_split | |
struct.rs | // First attempt: No explicit lifetimes
// Error! Compiler needs explicit lifetime
//struct Singleton {
//one: &mut i32,
//}
// TODO ^ Try uncommenting this struct
// Second attempt: Add lifetimes to all the references
struct | <'a, 'b> {
one: &'a mut i32,
two: &'b mut i32,
}
fn main() {
// Let's say that `one` has lifetime `o`
let mut one = 1;
{
// And that `two` has lifetime `t`
// `two` has a shorter (and different) lifetime than `one` (`'t < 'o`)
let mut two = 2;
println!("Before: ({}... | Pair | identifier_name |
struct.rs | // First attempt: No explicit lifetimes
// Error! Compiler needs explicit lifetime
//struct Singleton {
//one: &mut i32,
//}
// TODO ^ Try uncommenting this struct
// Second attempt: Add lifetimes to all the references
struct Pair<'a, 'b> {
one: &'a mut i32,
two: &'b mut i32,
}
fn main() {
// Let's sa... | } | random_line_split | |
mo.py | from cookiecutter.main import cookiecutter
import click
import requests
import sys
@click.group()
def cli():
'''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()... | (framework, user):
'''initialize a new cookiecutter template'''
# Check that cookiecutter template exists for requested framework
git_url = 'https://github.com/'
framework = framework.lower().replace(' ', '-')
mo_url = git_url+user+'/mo-'+framework
try:
response = requests.head(mo_url)
... | init | identifier_name |
mo.py | from cookiecutter.main import cookiecutter
import click
import requests
import sys
@click.group()
def cli():
'''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()... | try:
cookiecutter(mo_url+'.git')
except:
sys.exit("Problem encounted while cloning '{0}'.git"
.format(mo_url)) | conditional_block | |
mo.py | from cookiecutter.main import cookiecutter
import click
import requests
import sys
@click.group()
def cli():
'''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()... | 'Do you want to continue?'.format(mo_url)):
try:
cookiecutter(mo_url+'.git')
except:
sys.exit("Problem encounted while cloning '{0}'.git"
.format(mo_url))
| '''initialize a new cookiecutter template'''
# Check that cookiecutter template exists for requested framework
git_url = 'https://github.com/'
framework = framework.lower().replace(' ', '-')
mo_url = git_url+user+'/mo-'+framework
try:
response = requests.head(mo_url)
status = respon... | identifier_body |
mo.py | from cookiecutter.main import cookiecutter
import click
import requests
import sys
| '''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()
@click.argument('framework', type=click.STRING)
@click.option('--user', '-u',
help='Specify git ... | @click.group()
def cli(): | random_line_split |
styleguide.py | ##
# Copyright (C) 2017 Jessica Tallon, Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | from django.contrib.messages.utils import get_level_tags
from django.template.response import TemplateResponse
from django.utils import timezone
from django.views.decorators.http import require_GET
from inboxen.forms.inbox import InboxEditForm
from inboxen.tickets.models import Question
class Form(forms.Form):
t... | from django.contrib.messages.constants import DEFAULT_LEVELS | random_line_split |
styleguide.py | ##
# Copyright (C) 2017 Jessica Tallon, Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | (forms.Form):
text = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Placeholder'}))
checkbox = forms.BooleanField()
dropdown = forms.ChoiceField(choices=((0, "Thing"), (1, "Other thing")))
radio = forms.ChoiceField(widget=forms.RadioSelect, choices=((0, "Thing"), (1, "Other thing")))
@r... | Form | identifier_name |
styleguide.py | ##
# Copyright (C) 2017 Jessica Tallon, Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | inbox="qwerty",
domain=domain,
get_bools_for_labels=(("new", True), ("pinned", True)),
last_activity=now,
form=False,
),
]
# emails
emails = [
mock.Mock(
inbox=inboxes[0],
get_bools_for_labels=(("important",... | now = timezone.now() + timedelta(-1)
domain = mock.Mock(domain="example.com")
# create a bunch of mocked inboxes
inboxes = [
mock.Mock(
inbox="qwerty",
domain=domain,
get_bools_for_labels=(("new", False),),
last_activity=now,
form=InboxEdi... | identifier_body |
Compositor.styles.tsx | import {Layer} from '@sanity/ui'
import styled, {css} from 'styled-components'
import {focusRingBorderStyle, focusRingStyle} from '../../components/withFocusRing/helpers'
export const Root = styled.div(({theme}) => {
const {focusRing, input} = theme.sanity
const base = theme.sanity.color.base
const color = theme... | // This element only wraps the input when in "fullscreen" mode
export const ExpandedLayer = styled(Layer)`
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
` | })};
}
`
})
| random_line_split |
configuration.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/configuration.py
#
# 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, th... | (self, item_name, item_value):
"""
Sets the value of an option in the configuration.
:param str item_name: The name of the option to set.
:param item_value: The value of the option to set.
"""
if self.prefix:
item_name = self.prefix + self.seperator + item_name
item_names = item_name.split(self.sepera... | set | identifier_name |
configuration.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/configuration.py
#
# 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, th... |
return isinstance(self.get(section_name), dict)
def set(self, item_name, item_value):
"""
Sets the value of an option in the configuration.
:param str item_name: The name of the option to set.
:param item_value: The value of the option to set.
"""
if self.prefix:
item_name = self.prefix + self.sepe... | return False | conditional_block |
configuration.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/configuration.py
#
# 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, th... | """
if not self.has_option(section_name):
return False
return isinstance(self.get(section_name), dict)
def set(self, item_name, item_value):
"""
Sets the value of an option in the configuration.
:param str item_name: The name of the option to set.
:param item_value: The value of the option to set.
... | :return: True if the section exists.
:rtype: dict | random_line_split |
configuration.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/configuration.py
#
# 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, th... |
def has_option(self, option_name):
"""
Check that an option exists.
:param str option_name: The name of the option to check.
:return: True of the option exists in the configuration.
:rtype: bool
"""
if self.prefix:
option_name = self.prefix + self.seperator + option_name
item_names = option_name.... | """
Use a verification configuration which has a list of required options
and their respective types. This information is used to identify missing
and incompatbile options in the loaded configuration.
:param str verify_file: The file to load for verification data.
:return: A dictionary of missing and incompa... | identifier_body |
index.js |
"use strict";
module.exports = (function() {
function LocalDNS(args) {
var dbPath = args.db;
var parentDNS = args.parent;
var domain = args.domain || "";
var http = require("http");
var nativeDNS = require("native-dns");
var nativeDNSComposer = require("native-dns-composer");
var Promi... |
var indexPromise = Promise.all([
this.registry.ensureIndexAsync({fieldName: "ip"}),
this.registry.ensureIndexAsync({fieldName: "name"})
]);
this.parentDNS = parentDNS;
var onRequest = function onRequest(req, res) {
var requestPromise = (Promise.map(req.question, function(que... | {
return (self.registry.findAsync({ ip:ip, name:name })
.then(function(list) { return (list.length <= 0); })
.then(function(doInsert) {
var result = true;
if(doInsert) {
console.log("received new A record:", name, "->", ip);
result = self... | identifier_body |
index.js |
"use strict";
module.exports = (function() {
function LocalDNS(args) {
var dbPath = args.db;
var parentDNS = args.parent;
var domain = args.domain || "";
var http = require("http");
var nativeDNS = require("native-dns");
var nativeDNSComposer = require("native-dns-composer");
var Promi... | else if(type === nativeDNS.consts.NAME_TO_QTYPE.PTR) {
var ip = name.split(".").slice(0, 4).reverse().join(".");
lookupPromise = (self.registry.findAsync({ip:ip})
.map(function(answer) {
return nativeDNS.PTR({
name: name, data... | {
lookupPromise = (self.registry.findAsync({name:name})
.map(function(answer) {
return nativeDNS.A({
name: name, address: answer.ip, ttl: 600});
})
.map(function(aRecord) {
res.answer.push(a... | conditional_block |
index.js |
"use strict";
module.exports = (function() {
function | (args) {
var dbPath = args.db;
var parentDNS = args.parent;
var domain = args.domain || "";
var http = require("http");
var nativeDNS = require("native-dns");
var nativeDNSComposer = require("native-dns-composer");
var Promise = require("bluebird");
var nedb = require("./promisified-ne... | LocalDNS | identifier_name |
index.js | "use strict";
module.exports = (function() {
function LocalDNS(args) {
var dbPath = args.db;
var parentDNS = args.parent;
var domain = args.domain || "";
var http = require("http");
var nativeDNS = require("native-dns");
var nativeDNSComposer = require("native-dns-composer");
var Promis... | res.answer.push(ptrRecord);
return true;
})
.then(function(list) {
return (list.length > 0);
}));
}
lookupPromise = lookupPromise.then(function(questionAnswered) {
var re... | .map(function(ptrRecord) { | random_line_split |
asyncGeneratorsTest.js | const assert = require("assert");
describe("chain of iterators", function() {
it("should conform to ES", function() {
let finallyCalledSrc = 0;
let finallyCalled1 = 0;
let finallyCalled2 = 0;
let cb;
let p1 = new Promise(i => (cb = i));
let tasks = [];
let cbtask;
let p2 = {
the... | finallyCalled2 = true;
}
}
async function* a3() {
const v = a2();
try {
for (let i; !(i = await v.next()).done; ) {
yield `a3:${i.value}`;
}
assert.fail("never");
} finally {
await v.return();
}
return 2;
}
async funct... | } finally { | random_line_split |
asyncGeneratorsTest.js | const assert = require("assert");
describe("chain of iterators", function() {
it("should conform to ES", function() {
let finallyCalledSrc = 0;
let finallyCalled1 = 0;
let finallyCalled2 = 0;
let cb;
let p1 = new Promise(i => (cb = i));
let tasks = [];
let cbtask;
let p2 = {
the... | () {
await new Promise(i => (cbtask = i));
tasks.pop()("t1");
}
scheduler();
async function* src() {
try {
yield await p1;
yield await p2;
assert.fail("never");
} finally {
finallyCalledSrc++;
}
}
async function* a1() {
try {
... | scheduler | identifier_name |
asyncGeneratorsTest.js | const assert = require("assert");
describe("chain of iterators", function() {
it("should conform to ES", function() {
let finallyCalledSrc = 0;
let finallyCalled1 = 0;
let finallyCalled2 = 0;
let cb;
let p1 = new Promise(i => (cb = i));
let tasks = [];
let cbtask;
let p2 = {
the... |
assert.fail("never");
} finally {
await v.return();
}
return 2;
}
async function a4() {
const v = a3();
const i1 = await v.next();
assert.ok(!i1.done);
assert.equal(i1.value, "a3:a1:hi");
const n = v.next();
const i2 = await n;
assert.... | {
yield `a3:${i.value}`;
} | conditional_block |
asyncGeneratorsTest.js | const assert = require("assert");
describe("chain of iterators", function() {
it("should conform to ES", function() {
let finallyCalledSrc = 0;
let finallyCalled1 = 0;
let finallyCalled2 = 0;
let cb;
let p1 = new Promise(i => (cb = i));
let tasks = [];
let cbtask;
let p2 = {
the... |
};
async function scheduler() {
await new Promise(i => (cbtask = i));
tasks.pop()("t1");
}
scheduler();
async function* src() {
try {
yield await p1;
yield await p2;
assert.fail("never");
} finally {
finallyCalledSrc++;
}
}
async... | {
tasks.push(next);
cbtask();
} | identifier_body |
core_selectors.ts | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
export const getCoreDataLoadedState = createSelector(
selectCoreState,
(state: CoreState): DataLoadState => {
return state.coreDataLoadState.state;
}
);
/**
* Returns last _successful_ loaded time of the applicational state where an
* applicational state is defined as combinations of plugins listing, runs,... | ); | random_line_split |
utils.js |
// Pretty dumb name for a function, just wraps callback calls so we dont
// to if (callback) callback() everywhere
exports.call = exports.getArguments(function (args) {
if (!args.length) {
return;
}
var fun = args.shift();
if (typeof fun === 'function') {
fun.apply(this, args);
}
});
exports.isLoca... | {
return (typeof chrome !== "undefined" &&
typeof chrome.storage !== "undefined" &&
typeof chrome.storage.local !== "undefined");
} | identifier_body | |
utils.js | 1], 10),
ids: [revInfo[2], {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = parseInt(revInfo[1], 10) + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = [... | {
reject(failed);
} | conditional_block | |
utils.js | dumb name for a function, just wraps callback calls so we dont
// to if (callback) callback() everywhere
exports.call = exports.getArguments(function (args) {
if (!args.length) {
return;
}
var fun = args.shift();
if (typeof fun === 'function') {
fun.apply(this, args);
}
});
exports.isLocalId = funct... | () {
if (!(this instanceof Changes)) {
return new Changes();
}
var self = this;
EventEmitter.call(this);
this.isChrome = isChromeApp();
this.listeners = {};
this.hasLocal = false;
if (!this.isChrome) {
this.hasLocal = exports.hasLocalStorage();
}
if (this.isChrome) {
chrome.storage.onCha... | Changes | identifier_name |
utils.js | dumb name for a function, just wraps callback calls so we dont
// to if (callback) callback() everywhere
exports.call = exports.getArguments(function (args) {
if (!args.length) {
return;
}
var fun = args.shift();
if (typeof fun === 'function') {
fun.apply(this, args);
}
});
exports.isLocalId = funct... | doc._id = exports.uuid();
}
newRevId = exports.uuid(32, 16).toLowerCase();
if (doc._rev) {
revInfo = /^(\d+)-(.+)$/.exec(doc._rev);
if (!revInfo) {
var err = new TypeError("invalid value for property '_rev'");
err.status = 400;
}
doc._rev_tree = [{
pos: ... | if (!doc._id) { | random_line_split |
tools.py | import time
def dumps(s):
if not console.json:
die('dumps requries lib', 'console-json')
console.json(s)
def out(prefix, *a):
p = [prefix]
for obj in a:
if obj.__repr__:
p.append(obj.__repr__())
else:
p.append(obj)
console.log.apply(console, p)
de... |
del r['constructor']
del r['__class__']
return r
def name_value_pairs(l):
return [{'name': k, 'value': v} for k, v in l]
def camelize(s):
''' kendo wants camelCase, we want snake_case '''
s = s.split('_')
r = s[0]
for part in s[1:]:
r += part.capitalize()
return r
def... | __pragma__('js', '{}', 'return {}') | conditional_block |
tools.py | import time
def dumps(s):
if not console.json:
die('dumps requries lib', 'console-json')
console.json(s)
def out(prefix, *a):
p = [prefix]
for obj in a:
if obj.__repr__:
p.append(obj.__repr__())
else:
p.append(obj)
console.log.apply(console, p)
de... | (cls, func, dfunc):
"""
class : a Transcrypt class
func : name of method to decorate
dfunc : decorator function
Example:
e.g. dfunc =
def mydeco(obj, func, *a): return func(obj, *a)
class A:
i = 2
def foo(self, j, k): return self.i * int(j) * int... | decorate | identifier_name |
tools.py | import time
def dumps(s):
if not console.json:
die('dumps requries lib', 'console-json')
console.json(s)
def out(prefix, *a):
p = [prefix]
for obj in a:
if obj.__repr__:
p.append(obj.__repr__())
else:
p.append(obj)
console.log.apply(console, p)
de... |
def jstype(obj, typ):
__pragma__('js', '{}', '''
var t = typeof(obj)''')
if t == typ:
return True
return False
class PyDate:
'''
Descendants get a self.value property, which is always in sync
with an internal self.ts = unixtime'''
_value = ts = None
_mod_time = time
def g... | ''' kendo wants camelCase, we want snake_case '''
s = s.split('_')
r = s[0]
for part in s[1:]:
r += part.capitalize()
return r | identifier_body |
tools.py | import time
def dumps(s):
if not console.json:
die('dumps requries lib', 'console-json')
console.json(s)
def out(prefix, *a):
p = [prefix]
for obj in a:
if obj.__repr__:
p.append(obj.__repr__())
else:
p.append(obj)
console.log.apply(console, p)
de... | def mydeco(obj, func, *a): return func(obj, *a)
class A:
i = 2
def foo(self, j, k): return self.i * int(j) * int(k)
decorate(A, 'foo', dfunc)
A().foo(4, 5) -> will pass the args and the result through the mydeco
"""
def d3(*a):
# stage 3: cal... | dfunc : decorator function
Example:
e.g. dfunc = | random_line_split |
stream_tests.py | import json
import threading
import time
import traceback
import urllib
from vtdb import cursor
from vtdb import dbexceptions
import environment
import framework
class TestStream(framework.TestCase):
def tearDown(self):
self.env.conn.begin()
self.env.execute("delete from vtocc_big")
self.env.conn.commi... |
def test_streaming_error(self):
with self.assertRaises(dbexceptions.DatabaseError):
cu = self.env.execute("select count(abcd) from vtocc_big b1",
cursorclass=cursor.StreamCursor)
def check_row_10(self, row):
# null the dates so they match
row = list(row)
row[6] ... | for i in xrange(loop_count):
cu = cursor.StreamCursor(self.env.conn)
cu.execute("select * from vtocc_big b1, vtocc_big b2", {})
count = 0
while True:
row = cu.fetchone()
if row is None:
break
if count == 10:
self.check_row_10(row)
... | conditional_block |
stream_tests.py | import json
import threading
import time
import traceback
import urllib
from vtdb import cursor
from vtdb import dbexceptions
import environment
import framework
class TestStream(framework.TestCase):
def tearDown(self):
self.env.conn.begin()
self.env.execute("delete from vtocc_big")
self.env.conn.commi... | break
if count == 10:
self.check_row_10(row)
count += 1
self.assertEqual(count, 10000)
def test_streaming_error(self):
with self.assertRaises(dbexceptions.DatabaseError):
cu = self.env.execute("select count(abcd) from vtocc_big b1",
... | count = 0
while True:
row = cu.fetchone()
if row is None: | random_line_split |
stream_tests.py | import json
import threading
import time
import traceback
import urllib
from vtdb import cursor
from vtdb import dbexceptions
import environment
import framework
class TestStream(framework.TestCase):
def tearDown(self):
self.env.conn.begin()
self.env.execute("delete from vtocc_big")
self.env.conn.commi... | (self):
cu = self.env.execute("select 1 from dual union select 1 from dual",
cursorclass=cursor.StreamCursor)
count = 0
while True:
row = cu.fetchone()
if row is None:
break
count += 1
self.assertEqual(count, 1)
def test_customrules(self):
bv = ... | test_union | identifier_name |
stream_tests.py | import json
import threading
import time
import traceback
import urllib
from vtdb import cursor
from vtdb import dbexceptions
import environment
import framework
class TestStream(framework.TestCase):
def tearDown(self):
self.env.conn.begin()
self.env.execute("delete from vtocc_big")
self.env.conn.commi... |
def check_row_10(self, row):
# null the dates so they match
row = list(row)
row[6] = None
row[11] = None
row[20] = None
row[25] = None
self.assertEqual(row, [10L, 'AAAAAAAAAAAAAAAAAA 10', 'BBBBBBBBBBBBBBBBBB 10', 'C', 'DDDDDDDDDDDDDDDDDD 10', 'EEEEEEEEEEEEEEEEEE 10', None, 'FF 10', 'GGGG... | with self.assertRaises(dbexceptions.DatabaseError):
cu = self.env.execute("select count(abcd) from vtocc_big b1",
cursorclass=cursor.StreamCursor) | identifier_body |
index.ts | messages to be displayed in the badge iOS or message count in the notification shade in Android.
* For windows, it represents the value in the badge notification which could be a number or a status glyph.
*/
count: string;
/**
* The name of the sound file to be played upon receipt of the notification.
... | * sound.
*/
sound?: boolean | string;
/**
* If true the device vibrates on receipt of notification.
*/
vibrate?: boolean | string;
/**
* If true the icon badge will be cleared on init and before push messages are processed.
*/
clearBadge?: boolean | string;
/**
* If true the app clea... | random_line_split | |
index.ts | messages to be displayed in the badge iOS or message count in the notification shade in Android.
* For windows, it represents the value in the badge notification which could be a number or a status glyph.
*/
count: string;
/**
* The name of the sound file to be played upon receipt of the notification.
... | (): Promise<{ isEnabled: boolean }> { return; }
}
/**
* @hidden
*/
@Plugin({
pluginName: 'Push',
plugin: 'phonegap-plugin-push',
pluginRef: 'PushNotification'
})
export class PushObject {
private _objectInstance: any;
constructor(options: PushOptions) {
if (checkAvailability('PushNotification', 'ini... | hasPermission | identifier_name |
index.ts | to be displayed in the badge iOS or message count in the notification shade in Android.
* For windows, it represents the value in the badge notification which could be a number or a status glyph.
*/
count: string;
/**
* The name of the sound file to be played upon receipt of the notification.
*/
soun... |
}
/**
* Adds an event listener
* @param event {string}
* @return {Observable<EventResponse>}
*/
@CordovaInstance({
observable: true,
clearFunction: 'off',
clearWithArgs: true
})
on(event: PushEvent): Observable<EventResponse> { return; }
/**
* The unregister method is used when... | {
this._objectInstance = window.PushNotification.init(options);
} | conditional_block |
downloadActions.js | import {action} from "mobx";
import MainStore from "../common/MainStore";
import ToastStore from "../toast/ToastStore";
import commonActions from "../common/commonActions";
import "whatwg-fetch";
// TODO: ES2015
module.exports = {
saveDownloadList: action(saveDownloadList),
hideDownloadCard: action(hideDown... | MainStore.isDownloadCardVisible = false;
} | random_line_split | |
downloadActions.js | import {action} from "mobx";
import MainStore from "../common/MainStore";
import ToastStore from "../toast/ToastStore";
import commonActions from "../common/commonActions";
import "whatwg-fetch";
// TODO: ES2015
module.exports = {
saveDownloadList: action(saveDownloadList),
hideDownloadCard: action(hideDown... | () {
MainStore.isDownloadCardVisible = false;
}
| hideDownloadCard | identifier_name |
downloadActions.js | import {action} from "mobx";
import MainStore from "../common/MainStore";
import ToastStore from "../toast/ToastStore";
import commonActions from "../common/commonActions";
import "whatwg-fetch";
// TODO: ES2015
module.exports = {
saveDownloadList: action(saveDownloadList),
hideDownloadCard: action(hideDown... |
const tagArr = commonActions.tagStringToArray(data.list.tags);
if (commonActions.isInvalidTags(tagArr)) {
// Ideally should never happen, as tags on website should be valid
return;
}
commonActions.addNewList(title, tagArr);
hideDownloadCard();
});
}
function hideDownloadCard() {
Ma... | {
ToastStore.isMissingList = true;
return;
} | conditional_block |
downloadActions.js | import {action} from "mobx";
import MainStore from "../common/MainStore";
import ToastStore from "../toast/ToastStore";
import commonActions from "../common/commonActions";
import "whatwg-fetch";
// TODO: ES2015
module.exports = {
saveDownloadList: action(saveDownloadList),
hideDownloadCard: action(hideDown... | {
MainStore.isDownloadCardVisible = false;
} | identifier_body | |
render.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::{CardTemplate, NoteType, NoteTypeKind};
use crate::{
card::{Card, CardID},
collection::Collection,
err::{AnkiError, Result},
i18n::{I18n, TR},
notes::{Note, No... |
fn render_card_inner(
&mut self,
note: &Note,
card: &Card,
nt: &NoteType,
template: &CardTemplate,
browser: bool,
) -> Result<RenderCardOutput> {
let mut field_map = note.fields_map(&nt.fields);
let card_num;
self.add_special_fields(&mut... | {
// fetch existing card
if let Some(ord) = template_ord {
if let Some(card) = self.storage.get_card_by_ordinal(nid, ord as u16)? {
return Ok(card);
}
}
// no existing card; synthesize one
Ok(Card {
template_idx: card_ord,
... | identifier_body |
render.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::{CardTemplate, NoteType, NoteTypeKind};
use crate::{
card::{Card, CardID},
collection::Collection,
err::{AnkiError, Result},
i18n::{I18n, TR},
notes::{Note, No... |
}
}
}
}
| {
*val = format!("({})", field.name);
} | conditional_block |
render.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::{CardTemplate, NoteType, NoteTypeKind};
use crate::{
card::{Card, CardID},
collection::Collection,
err::{AnkiError, Result},
i18n::{I18n, TR},
notes::{Note, No... | if let Some(ord) = template_ord {
if let Some(card) = self.storage.get_card_by_ordinal(nid, ord as u16)? {
return Ok(card);
}
}
// no existing card; synthesize one
Ok(Card {
template_idx: card_ord,
..Default::default()
... | template_ord: Option<u32>,
card_ord: u16,
) -> Result<Card> {
// fetch existing card | random_line_split |
render.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::{CardTemplate, NoteType, NoteTypeKind};
use crate::{
card::{Card, CardID},
collection::Collection,
err::{AnkiError, Result},
i18n::{I18n, TR},
notes::{Note, No... | (n: u8) -> &'static str {
match n {
1 => "flag1",
2 => "flag2",
3 => "flag3",
4 => "flag4",
_ => "",
}
}
fn fill_empty_fields(note: &mut Note, qfmt: &str, nt: &NoteType, i18n: &I18n) {
if let Ok(tmpl) = ParsedTemplate::from_text(qfmt) {
let cloze_fields = tmp... | flag_name | identifier_name |
mod.rs | = crate::RegisteredLabel<iana::KeyOperation>;
/// A collection of [`CoseKey`] objects.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CoseKeySet(pub Vec<CoseKey>);
impl crate::CborSerializable for CoseKeySet {}
impl AsCborValue for CoseKeySet {
fn from_cbor_value(value: Value) -> Result<Self> {
... | {
if iana::KeyParameter::from_i64(label).is_some() {
panic!("param() method used to set KeyParameter"); // safe: invalid input
}
self.0.params.push((Label::Int(label), value));
self
} | identifier_body | |
mod.rs | 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 License.
//
/////////////////////////////////////////////////////////... | cbor::value::Value,
common::AsCborValue,
iana,
iana::EnumI64,
util::{to_cbor_array, ValueTryAs},
Algorithm, CoseError, Label, Result,
};
use alloc::{collections::BTreeSet, vec, vec::Vec};
#[cfg(test)]
mod tests;
/// Key type.
pub type KeyType = crate::RegisteredLabel<iana::KeyType>;
impl Defa... | //! COSE_Key functionality.
use crate::{ | random_line_split |
mod.rs | 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 License.
//
/////////////////////////////////////////////////////////... | (self) -> Result<Value> {
let mut map: Vec<(Value, Value)> = vec![(KTY.to_cbor_value()?, self.kty.to_cbor_value()?)];
if !self.key_id.is_empty() {
map.push((KID.to_cbor_value()?, Value::Bytes(self.key_id)));
}
if let Some(alg) = self.alg {
map.push((ALG.to_cbor_va... | to_cbor_value | identifier_name |
documents.ts | // Node.js bindings for ../../rust/src/documents.rs, see there for more documentation.
import { JSONSchema7 } from 'json-schema'
import { fromJSON } from './prelude'
import * as pubsub from './pubsub'
import { Document, DocumentEvent } from './types'
const addon = require('../index.node')
/**
* Get the JSON Schemas... | (path?: string, format?: string): Document {
return fromJSON<Document>(addon.documentsCreate(path ?? '', format ?? ''))
}
/**
* Open an existing document, optionally specifying its format.
*
* @param path Path to the document's file
* @param format Format of the document. If `undefined` will be inferred from
* ... | create | identifier_name |
documents.ts | // Node.js bindings for ../../rust/src/documents.rs, see there for more documentation.
import { JSONSchema7 } from 'json-schema'
import { fromJSON } from './prelude'
import * as pubsub from './pubsub'
import { Document, DocumentEvent } from './types'
const addon = require('../index.node')
/**
* Get the JSON Schemas... |
/**
* Alter properties of a document.
*
* If a `path` is provided then the document's `name`, `format`, `status` and `temporary`
* flag will be updated (`temporary` will be set to `false` and `status` to `unwritten`
* immediately after the call).
*
* If `format` is provided, only the `format` property of the d... | {
return fromJSON<Document>(addon.documentsGet(id))
} | identifier_body |
documents.ts | // Node.js bindings for ../../rust/src/documents.rs, see there for more documentation.
import { JSONSchema7 } from 'json-schema'
import { fromJSON } from './prelude'
import * as pubsub from './pubsub'
import { Document, DocumentEvent } from './types'
const addon = require('../index.node')
/**
* Get the JSON Schemas... |
/**
* Close a document.
*
* This will drop the document from memory and stop any
* associated file watching thread.
*
* @param id Id of the document
*/
export function close(id: string): void {
addon.documentsClose(id)
} | for (const topic of topics) {
addon.documentsUnsubscribe(id, topic)
pubsub.unsubscribe(`documents:${id}:${topic}`)
}
} | random_line_split |
Germany.tsx | // Based on https://github.com/lipis/flag-icon-css/blob/master/flags/4x3/de.svg
// Copyright (c) 2013 Panayiotis Lipiridis
import * as React from 'react';
import SvgIcon from 'material-ui/lib/svg-icon';
const Germany = (props) => (
<SvgIcon viewBox="0 0 640 480" {...props}>
<g fill-rule="evenodd" stroke-width=... | <path fill="#f00" d="M0 160h640v160H0z"/>
</g>
</SvgIcon>
)
export default Germany; | random_line_split | |
keyframes.rs | is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
write!(dest, "{}%", self.0 * 100.0)
}
}
impl KeyframePercentage {
/// Trivially... | },
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only... | random_line_split | |
keyframes.rs | is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
write!(dest, "{}%", self.0 * 100.0)
}
}
impl KeyframePercentage {
/// Trivially... | panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_at... | {
if !self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read();
let &(ref declaration, _) =
guard.get(PropertyDeclarationId::Longhand(... | identifier_body |
keyframes.rs | KeyframePercentage::new(1.)
} else {
let percentage = try!(input.expect_percentage());
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(());
}
};
Ok(perce... | Void | identifier_name | |
doctab.ts | <!DOCTYPE TS><TS>
<defaultcodec>iso8859-1</defaultcodec>
<context>
<name>DocTabSettingsBase</name>
<message>
<source>DocTab Settings</source>
<translation>Paramètres de l'onglet Documents</translation>
</message>
<message>
<source>Enable the DocTab</source>
<translat... | <source>No, thanks.</source>
<translation>Non.</translation>
</message>
<message>
<source><b>Do you want a Documents Tab?</b><p>
(Note that such a tab scans <i>all</i> documents
on <i>all</i> external media, which can be quite
slow and annoying..... | <message> | random_line_split |
somModels.js | Template.somModels.events({
'click .load-model':function(event) {
FlowRouter.go('learn', {id: FlowRouter.getParam("id")}, {m: event.target.id});
},
'click .del-model': function(event) {
Meteor.call('SOM:delete', event.target.id);
},
'submit .compute-som': function(event, instance) {
console.log('called subm... |
},
})
Template.somModels.helpers({
'isDisabled': function(status) {
if (status === 100) {
return '';
}
return 'disabled';
},
'labels': function() {
project = Projects.findOne({_id: FlowRouter.getParam("id"), uid: Meteor.userId()});
return project.labels;
},
'models':function() {
return SOM.fi... | {
Meteor.call('SOM:compute', projectId, props, balance);
M.toast({html: 'Model building', displayLength: 2000});
} | conditional_block |
somModels.js | Template.somModels.events({
'click .load-model':function(event) {
FlowRouter.go('learn', {id: FlowRouter.getParam("id")}, {m: event.target.id});
},
'click .del-model': function(event) {
Meteor.call('SOM:delete', event.target.id);
},
'submit .compute-som': function(event, instance) {
console.log('called subm... | M.toast({html: 'Model building', displayLength: 2000});
}
},
})
Template.somModels.helpers({
'isDisabled': function(status) {
if (status === 100) {
return '';
}
return 'disabled';
},
'labels': function() {
project = Projects.findOne({_id: FlowRouter.getParam("id"), uid: Meteor.userId()});
r... | M.toast({html: 'Running cross validation', displayLength: 2000});
} else {
Meteor.call('SOM:compute', projectId, props, balance); | random_line_split |
MetaStore.js | var _ = require('lodash');
var GraphQL = require('./GraphQL');
var GraphQLFilter = require('./GraphQLFilter');
var Util = require('./Util');
var MetaStore = function() { | };
MetaStore.prototype.export = function () {
return JSON.stringify(this._rawData, null, 2);
}
MetaStore.prototype.import = function (data) {
this._rawData = JSON.parse(data);
this._resetCompile();
}
MetaStore.prototype.addData = function (extractorName, fileName, data) {
if (this._rawData[extractorN... | this._rawData = {}; | random_line_split |
GeometryFactory.py | #!/usr/bin/python
import Colors
import Shapes
from abc import ABCMeta, abstractmethod
class AbstractFactory(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_color(self, color):
pass
@abstractmethod
def get_shape(self, shape):
pass
class ShapeFactory(AbstractFactory):
... |
class FactoryProducer(object):
@staticmethod
def get_factory(factory_name):
factory_name = factory_name.lower()
if factory_name == 'shape':
return ShapeFactory()
elif factory_name == 'color':
return ColorFactory()
else:
raise InvalidFactoryE... | raise 'use shape factory' | identifier_body |
GeometryFactory.py | #!/usr/bin/python
import Colors
import Shapes
from abc import ABCMeta, abstractmethod
class AbstractFactory(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_color(self, color):
pass
@abstractmethod
def get_shape(self, shape):
pass
class ShapeFactory(AbstractFactory):
... | (self, color):
color = color.lower()
if color == 'red':
return Colors.Red()
elif color == 'green':
return Colors.Green()
elif color == 'blue':
return Colors.Blue()
else:
raise InvalidColorException('unknown color: {0}'.format(color)... | get_color | identifier_name |
GeometryFactory.py | #!/usr/bin/python
import Colors
import Shapes
from abc import ABCMeta, abstractmethod
class AbstractFactory(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_color(self, color):
pass
@abstractmethod
def get_shape(self, shape):
pass
class ShapeFactory(AbstractFactory):
... | else:
raise InvalidFactoryException('unknown factory specified')
class InvalidFactoryException(Exception):
pass
class InvalidColorException(Exception):
pass
class InvalidShapeException(Exception):
pass | return ShapeFactory()
elif factory_name == 'color':
return ColorFactory() | random_line_split |
GeometryFactory.py | #!/usr/bin/python
import Colors
import Shapes
from abc import ABCMeta, abstractmethod
class AbstractFactory(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_color(self, color):
pass
@abstractmethod
def get_shape(self, shape):
pass
class ShapeFactory(AbstractFactory):
... |
else:
raise InvalidFactoryException('unknown factory specified')
class InvalidFactoryException(Exception):
pass
class InvalidColorException(Exception):
pass
class InvalidShapeException(Exception):
pass
| return ColorFactory() | conditional_block |
play_context.py | may have been
# templated based on the loop variable, so we try and locate
# the host name in the delegated variable dictionary here
delegated_host_name = templar.template(task.delegate_to)
delegated_vars = variables.get('ansible_delegated_vars', dict()).get(delegated_ho... | elif self.become_method == 'ksu':
def detect_ksu_prompt(b_data):
return | conditional_block | |
play_context.py | # become legacy updates -- from inventory file (inventory overrides
# commandline)
for become_pass_name in MAGIC_VARIABLE_MAPPING.get('become_pass'):
if become_pass_name in variables:
break
else: # This is a for-else
if new_info.become_method == '... | _type = None
| identifier_name | |
play_context.py | (isa='string', default=C.ANSIBLE_SSH_EXECUTABLE)
_ssh_args = FieldAttribute(isa='string', default=C.ANSIBLE_SSH_ARGS)
_ssh_common_args = FieldAttribute(isa='string')
_sftp_extra_args = FieldAttribute(isa='string')
_scp_extra_args = FieldAttribute(isa='string')
_ssh_extra_args = FieldAttribute(isa='s... | attrs_considered.append(attr)
elif variable_name in variables: | random_line_split | |
play_context.py | new_info.port = int(C.DEFAULT_REMOTE_PORT)
# special overrides for the connection setting
if len(delegated_vars) > 0:
# in the event that we were using local before make sure to reset the
# connection type to the default transport for the delegated-to host,
# if not... | utes['connection'] == 'smart':
conn_type = 'ssh'
if sys.platform.startswith('darwin') and self.password:
# due to a current bug in sshpass on OSX, which can trigger
# a kernel panic even for non-privileged users, we revert to
# paramiko on that OS ... | identifier_body | |
__init__.py | ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.co... | (self, argv=None):
self.argv = argv or sys.argv[:]
self.prog_name = os.path.basename(self.argv[0])
def main_help_text(self):
"""
Returns the script's main help text, as a string.
"""
usage = ['',"Type '%s help <subcommand>' for help on a specific subcommand." % self.... | __init__ | identifier_name |
__init__.py | installed apps
try:
from google.appengine._internal.django.conf import settings
apps = settings.INSTALLED_APPS
except (AttributeError, EnvironmentError, ImportError):
apps = []
# Find the project directory
try:
from google.appengine._inte... | opt_label = option[0]
# append '=' to options which require args
if option[1]:
opt_label += '='
print opt_label | conditional_block | |
__init__.py | ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.co... |
def main_help_text(self):
"""
Returns the script's main help text, as a string.
"""
usage = ['',"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,'']
usage.append('Available subcommands:')
commands = get_commands().keys()
comm... | self.argv = argv or sys.argv[:]
self.prog_name = os.path.basename(self.argv[0]) | identifier_body |
__init__.py | ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.co... | # If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def autocomplete(self):
"""
Output completion suggestions for BASH.
The output of this function is p... | if isinstance(app_name, BaseCommand): | random_line_split |
main.py | #!/usr/bin/env python
"""rds-create-cpu-alarms
Script used to create CPUUtilization alarms in AWS CloudWatch
for all RDS instances.
A upper-limit threshold needs to be defined.
Usage:
rds-create-cpu-alarms [options] <threshold> <sns_topic_arn> <region>
rds-create-cpu-alarms -h | --help
Options:
-h --help... | (rds_instances,
threshold,
aws_cw_connect,
sns_topic_arn):
"""
Creates a CPUUtilization alarm for all RDS instances
Args:
rds_instances (list) List of all RDS instances
th... | get_cpuutilization_alarms_to_create | identifier_name |
main.py | #!/usr/bin/env python
"""rds-create-cpu-alarms
Script used to create CPUUtilization alarms in AWS CloudWatch
for all RDS instances.
A upper-limit threshold needs to be defined.
Usage:
rds-create-cpu-alarms [options] <threshold> <sns_topic_arn> <region>
rds-create-cpu-alarms -h | --help
Options:
-h --help... |
return alarms_to_create
def main():
args = docopt(__doc__, version=VERSION)
global DEBUG
if args['--debug']:
DEBUG = True
region = args['<region>']
sns_topic_arn = args['<sns_topic_arn>']
rds_instances = get_rds_instances(region)
aws_cw_connect = boto.ec2.cloudwatch.conn... | cpu_utilization_alarm = MetricAlarm(
name=u'RDS-{}-High-CPUUtilization'.format(
instance[u'DBInstanceIdentifier']
),
namespace=u'AWS/RDS',
metric=u'CPUUtilization', statistic='Average',
comparison=u'>',
threshold=threshold,
... | conditional_block |
main.py | #!/usr/bin/env python
"""rds-create-cpu-alarms
Script used to create CPUUtilization alarms in AWS CloudWatch
for all RDS instances.
A upper-limit threshold needs to be defined.
Usage:
rds-create-cpu-alarms [options] <threshold> <sns_topic_arn> <region>
rds-create-cpu-alarms -h | --help
Options:
-h --help... |
main() | random_line_split | |
main.py | #!/usr/bin/env python
"""rds-create-cpu-alarms
Script used to create CPUUtilization alarms in AWS CloudWatch
for all RDS instances.
A upper-limit threshold needs to be defined.
Usage:
rds-create-cpu-alarms [options] <threshold> <sns_topic_arn> <region>
rds-create-cpu-alarms -h | --help
Options:
-h --help... |
for instance in rds_instances:
# initiate a CPUUtilization MetricAlarm object for each RDS instance
cpu_utilization_alarm = MetricAlarm(
name=u'RDS-{}-High-CPUUtilization'.format(
instance[u'DBInstanceIdentifier']
),
namespace=u'AWS/RDS',
... | """
Creates a CPUUtilization alarm for all RDS instances
Args:
rds_instances (list) List of all RDS instances
threshold (int) The upper limit after which alarm activates
aws_cw_connect (CloudWatchConnection)
sns_topic_arn (str)
Returns:
(set) All CPUUtilization alar... | identifier_body |
plugins.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private readonly _onDidUpdatePlugins = this._register(new vscode.EventEmitter<this>());
public readonly onDidChangePlugins = this._onDidUpdatePlugins.event;
private readonly _onDidUpdateConfig = this._register(new vscode.EventEmitter<{ pluginId: string; config: {} }>());
public readonly onDidUpdateConfig = this.... | {
if (!this._plugins) {
this._plugins = this.readPlugins();
}
return Array.from(this._plugins.values()).flat();
} | identifier_body |
plugins.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): ReadonlyArray<TypeScriptServerPlugin> {
if (!this._plugins) {
this._plugins = this.readPlugins();
}
return Array.from(this._plugins.values()).flat();
}
private readonly _onDidUpdatePlugins = this._register(new vscode.EventEmitter<this>());
public readonly onDidChangePlugins = this._onDidUpdatePlugins.e... | plugins | identifier_name |
plugins.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | public readonly onDidUpdateConfig = this._onDidUpdateConfig.event;
public setConfiguration(pluginId: string, config: {}) {
this._pluginConfigurations.set(pluginId, config);
this._onDidUpdateConfig.fire({ pluginId, config });
}
public configurations(): IterableIterator<[string, {}]> {
return this._pluginConf... |
private readonly _onDidUpdatePlugins = this._register(new vscode.EventEmitter<this>());
public readonly onDidChangePlugins = this._onDidUpdatePlugins.event;
private readonly _onDidUpdateConfig = this._register(new vscode.EventEmitter<{ pluginId: string; config: {} }>()); | random_line_split |
plugins.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
}
return pluginMap;
}
}
| {
pluginMap.set(extension.id, plugins);
} | conditional_block |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use QueryExt;
use draw_parameters::TimeElapsedQuery;
use Api;
use version::Version;
use gl;
pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f... | }
}
if let Some(stencil) = stencil {
let stencil = stencil as gl::types::GLint;
flags |= gl::STENCIL_BUFFER_BIT;
if ctxt.state.clear_stencil != stencil {
ctxt.gl.ClearStencil(stencil);
ctxt.state.clear_stencil = stencil;... | {
let depth = depth as gl::types::GLclampf;
flags |= gl::DEPTH_BUFFER_BIT;
if ctxt.state.clear_depth != depth {
if ctxt.version >= &Version(Api::Gl, 1, 0) {
ctxt.gl.ClearDepth(depth as gl::types::GLclampd);
} else if ctxt.version ... | conditional_block |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use QueryExt;
use draw_parameters::TimeElapsedQuery;
use Api;
use version::Version;
use gl;
pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f... |
flags |= gl::STENCIL_BUFFER_BIT;
if ctxt.state.clear_stencil != stencil {
ctxt.gl.ClearStencil(stencil);
ctxt.state.clear_stencil = stencil;
}
}
ctxt.gl.Clear(flags);
}
} |
if let Some(stencil) = stencil {
let stencil = stencil as gl::types::GLint; | random_line_split |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use QueryExt;
use draw_parameters::TimeElapsedQuery;
use Api;
use version::Version;
use gl;
pub fn | (context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, color_srgb: bool,
depth: Option<f32>, stencil: Option<i32>)
{
unsafe {
let mut ctxt = context.make_current();
let fbo_id = fbo::FramebuffersContainer::... | clear | identifier_name |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use QueryExt;
use draw_parameters::TimeElapsedQuery;
use Api;
use version::Version;
use gl;
pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f... | if !color_srgb && !ctxt.state.enabled_framebuffer_srgb {
ctxt.gl.Enable(gl::FRAMEBUFFER_SRGB);
ctxt.state.enabled_framebuffer_srgb = true;
} else if color_srgb && ctxt.state.enabled_framebuffer_srgb {
ctxt.gl.Disable(gl::FRAMEBUFFER_SRGB);
... | {
unsafe {
let mut ctxt = context.make_current();
let fbo_id = fbo::FramebuffersContainer::get_framebuffer_for_drawing(&mut ctxt, framebuffer);
fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false);
if ctxt.state.enabled_rasterizer_discard {
ctxt.gl.Disable(gl::RASTERIZ... | identifier_body |
markov.py | import argparse
from collections import defaultdict, Counter, deque
import random
import json
import time
from tqdm import tqdm
import wikipedia
class MarkovModel(object):
def __init__(self):
self.states = defaultdict(lambda: Counter())
self.totals = Counter()
def add_sample(self, state, foll... |
def remove_single_newlines(story):
paragraphs = [[]]
for line in story.splitlines():
if len(line.strip()) == 0:
paragraphs.append([])
else:
paragraphs[-1].append(line)
return '\n'.join(' '.join(x for x in p) for p in paragraphs)
def load_wikipedia(num_articles):
... | random_line_split | |
markov.py | import argparse
from collections import defaultdict, Counter, deque
import random
import json
import time
from tqdm import tqdm
import wikipedia
class MarkovModel(object):
def __init__(self):
self.states = defaultdict(lambda: Counter())
self.totals = Counter()
def add_sample(self, state, foll... | um_articles):
lines = []
while num_articles > 0:
chunk = min(10, num_articles)
num_articles -= 10
for article in wikipedia.random(chunk):
try:
page = wikipedia.page(article)
except wikipedia.DisambiguationError as ex:
page = wikiped... | ad_wikipedia(n | identifier_name |
markov.py | import argparse
from collections import defaultdict, Counter, deque
import random
import json
import time
from tqdm import tqdm
import wikipedia
class MarkovModel(object):
def __init__(self):
self.states = defaultdict(lambda: Counter())
self.totals = Counter()
def add_sample(self, state, foll... |
def eat_one_token(story):
while len(story) > 0 and isinvalid(story[0]):
story.popleft()
if len(story) == 0:
return None
if isalnum(story[0]):
return eat_word(story)
if ispunctuation(story[0]):
return eat_punctuation(story)
if isnewline(story[0]):
return eat... | yield token | conditional_block |
markov.py | import argparse
from collections import defaultdict, Counter, deque
import random
import json
import time
from tqdm import tqdm
import wikipedia
class MarkovModel(object):
def __init__(self):
self.states = defaultdict(lambda: Counter())
self.totals = Counter()
def add_sample(self, state, foll... |
def ispunctuation(char):
return char in ",.-!?:&"
def isnewline(char):
return char == '\n'
def eat_word(story):
word = [story.popleft()]
while len(story) > 0 and isalnum(story[0]):
word.append(story.popleft())
return ''.join(word)
def eat_punctuation(story):
token = [story.popleft... | return char.isalnum() or char == "'" or char == "’"
| identifier_body |
TickModel.js | // # **TickModel**
// A Backbone.Model that represents the data required to build a CMapTickView. The model contains
// a data object that has keys for each row to display in the view and array values for each tick
// to display in each row. An example data object might look like this: |
// {PC3: [.23,-.28], MCF7: [-0.6]}
// example usage
// tick_model = new TickModel();
Barista.Models.TickModel = Backbone.Model.extend({
// ### defaults
// set up defaults for model values
// 1. {String} **title** the title to use in the plot, defaults to *""*
// 2. {Object} **data_object** the data ob... | random_line_split | |
account_db.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&self, key: &H256) -> Option<DBValue> {
if key == &SHA3_NULL_RLP {
return Some(DBValue::from_slice(&NULL_RLP_STATIC));
}
self.0.get(key)
}
fn contains(&self, key: &H256) -> bool {
if key == &SHA3_NULL_RLP {
return true;
}
self.0.contains(key)
}
fn insert(&mut self, value: &[u8]) -> H256 {
if ... | get | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.