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 |
|---|---|---|---|---|
properties.js | (function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', '../node_modules/skatejs/lib/index'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('../node_modules/skatejs/lib/index'));
} else {
var mod = {
exports: {}
};
... | (obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var props = _index2.default.properties;
var array = props.array;
var boolean = props.boolean;
var number = props.number;
var string = props.string;
exports.default = props;
exports.array = array;
exports.boolean = boolean;... | _interopRequireDefault | identifier_name |
properties.js | (function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', '../node_modules/skatejs/lib/index'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('../node_modules/skatejs/lib/index'));
} else {
var mod = {
exports: {}
};
... | exports.boolean = boolean;
exports.number = number;
exports.string = string;
}); | var string = props.string;
exports.default = props;
exports.array = array; | random_line_split |
properties.js | (function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', '../node_modules/skatejs/lib/index'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('../node_modules/skatejs/lib/index'));
} else {
var mod = {
exports: {}
};
... |
var props = _index2.default.properties;
var array = props.array;
var boolean = props.boolean;
var number = props.number;
var string = props.string;
exports.default = props;
exports.array = array;
exports.boolean = boolean;
exports.number = number;
exports.string = string;
}); | {
return obj && obj.__esModule ? obj : {
default: obj
};
} | identifier_body |
heap.rs | // Copyright 2014-2015 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... |
}
#[cfg(not(test))]
#[lang = "exchange_free"]
#[inline]
unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) {
deallocate(ptr, old_size, align);
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use boxed::Box;
use heap;
#[test]
fn basic_reallocate_in... | {
let ptr = allocate(size, align);
if ptr.is_null() {
::oom()
}
ptr
} | conditional_block |
heap.rs | // Copyright 2014-2015 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... | }
}
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
let _: Box<_> = box 10;
})
}
} | let ret = heap::reallocate_inplace(ptr, size, size, 8);
heap::deallocate(ptr, size, 8);
assert_eq!(ret, heap::usable_size(size, 8)); | random_line_split |
heap.rs | // Copyright 2014-2015 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... |
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// On failure, return a null pointer and leave the original allocation intact.
///
/// If the allocation was relocated, the memory at the passed-in pointer is
/// undefined after the call.
///
/// Behavior is undefined if the requested size is 0 or t... | {
check_size_and_alignment(size, align);
__rust_allocate(size, align)
} | identifier_body |
heap.rs | // Copyright 2014-2015 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... | () {
unsafe {
let size = 4000;
let ptr = heap::allocate(size, 8);
if ptr.is_null() {
::oom()
}
let ret = heap::reallocate_inplace(ptr, size, size, 8);
heap::deallocate(ptr, size, 8);
assert_eq!(ret, heap::usable_... | basic_reallocate_inplace_noop | identifier_name |
graphGroup.tsx | import * as React from "react";
import { MetricsDataProvider } from "../containers/metricsDataProvider";
/**
* GraphGroup is a stateless react component that wraps a group of graphs (the
* children of this component) in a MetricsDataProvider and some additional tags
* relevant to the layout of our graphs pages.
*... |
return <div>
{
React.Children.map(props.children, (child, idx) => {
let key = props.groupId + idx.toString();
// Special case h2 tags which are used as the graph group title.
if ((child as React.ReactElement<any>).type === "h2") {
return <div>{ child }</div>;
}
return <di... | {
return null;
} | conditional_block |
graphGroup.tsx | import * as React from "react";
import { MetricsDataProvider } from "../containers/metricsDataProvider";
/**
* GraphGroup is a stateless react component that wraps a group of graphs (the
* children of this component) in a MetricsDataProvider and some additional tags
* relevant to the layout of our graphs pages. | export default function (props: { groupId: string, hide: boolean, childClassName?: string, children?: any }) {
if (props.hide) {
return null;
}
return <div>
{
React.Children.map(props.children, (child, idx) => {
let key = props.groupId + idx.toString();
// Special case h2 tags which are use... | */ | random_line_split |
generic-struct.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5 };
let float_int = AGenericStruct { key: 4.5, value: 5 };
let float_int_float = AGenericStruct { key: 6.5, value: AGenericStruct { key:... | AGenericStruct | identifier_name |
generic-struct.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn zzz() {()}
| {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5 };
let float_int = AGenericStruct { key: 4.5, value: 5 };
let float_int_float = AGenericStruct { key: 6.5, value: AGenericStruct { key: 7, value: 8.5 } };
zzz();
} | identifier_body |
generic-struct.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print int_int
// check:$1 = {key = 0, value = 1}
// debugger:print int_float
// check:$2 = {key = 2, value = 3.5}
// debugger:print float_int
// check:$3 = {key = 4.5, value = 5}
// debugger:print float_int_floa... | // except according to those terms. | random_line_split |
flows_backgrid_view.js | nmeta.FlowsBackGridView = Backbone.View.extend({
initialize:function (options) {
// Specify columns that will be displayed in Backgrid:
var columns = [{
name: "timestamp",
label: "Timestamp",
editable: false,
// Extend UriCell to have timestamp custo... | this.pageableGrid = new Backgrid.Grid({
columns: columns,
collection: this.model
});
// Display a loading indication whenever the Collection is fetching.
this.model.on("request", function() {
this.$el.html("Loading...");
}, this);
this.m... | cell: "string"
}];
// Set up a Backgrid grid to use the pageable collection | random_line_split |
widget-form.component.ts | import { Component, Input, Output, EventEmitter } from "@angular/core";
import { Widget } from "../../../models/widget";
interface SelectItem {
value: string;
label: string;
}
@Component({
selector: "widget-form",
template: require("./widget-form.component.html"),
styles: [require("./widget-form.... | {
@Input()
public widget: Widget = {} as Widget;
@Output()
public saveWidget: EventEmitter<Widget> = new EventEmitter<Widget>();
@Output()
public deleteWidget: EventEmitter<Widget> = new EventEmitter<Widget>();
@Output()
public cancelWidget: EventEmitter<Widget> = new EventEmitter<W... | WidgetFormComponent | identifier_name |
widget-form.component.ts | import { Component, Input, Output, EventEmitter } from "@angular/core";
import { Widget } from "../../../models/widget";
interface SelectItem {
value: string;
label: string;
}
@Component({ | })
export class WidgetFormComponent {
@Input()
public widget: Widget = {} as Widget;
@Output()
public saveWidget: EventEmitter<Widget> = new EventEmitter<Widget>();
@Output()
public deleteWidget: EventEmitter<Widget> = new EventEmitter<Widget>();
@Output()
public cancelWidget: EventE... | selector: "widget-form",
template: require("./widget-form.component.html"),
styles: [require("./widget-form.component.scss")] | random_line_split |
any.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for dyna... |
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
use owned::Box;
use realstd::str::StrAllocating;
#[deriving(Eq, Show)]
struct Test;
static TEST: &'static str = "Test";
#[test]
fn any_referenced() {
let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
... | {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Prevent destructor on self being run
intrinsics::forget(self);
// Extract the data pointe... | identifier_body |
any.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for dyna... | TypeId::of::<T>()
}
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
// Implemented as three extension traits so that the methods can be generic.
///////////////////////////////////////////////////////////////////////////////
///... |
impl<T: 'static> Any for T {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId { | random_line_split |
any.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for dyna... | { }
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// The `Any` trait is implemented by all types, and can be used as a trait object
/// for dynamic typing
pub trait Any {
/// Get the `T... | Void | identifier_name |
subresource.py | _value = {"Owner": acl.owner.id}
grants = []
for grant in acl.grants:
grant = {"Permission": grant.permission,
"Grantee": str(grant.grantee)}
grants.append(grant)
header_value.update({"Grant": grants})
headers = {}
key = sysmeta_header(resource, 'acl')
headers[ke... |
class LogDelivery(Group):
"""
WRITE and READ_ACP permissions on a bucket enables this group to write
server access logs to the bucket.
"""
uri = 'http://acs.amazonaws.com/groups/s3/LogDelivery'
def __contains__(self, key):
if ':' in key:
tenant, user = key.split(':', 1)
... | """
Access permission to this group allows anyone to access the resource. The
requests can be signed (authenticated) or unsigned (anonymous). Unsigned
requests omit the Authentication header in the request.
Note: Swift3 regards unsigned requests as Swift API accesses, and bypasses
them to Swift. ... | identifier_body |
subresource.py | _value = {"Owner": acl.owner.id}
grants = []
for grant in acl.grants:
grant = {"Permission": grant.permission,
"Grantee": str(grant.grantee)}
grants.append(grant)
header_value.update({"Grant": grants})
headers = {}
key = sysmeta_header(resource, 'acl')
headers[ke... | (cls, elem):
"""
Convert an ElementTree to an ACL instance
"""
grantee = Grantee.from_elem(elem.find('./Grantee'))
permission = elem.find('./Permission').text
return cls(grantee, permission)
def elem(self):
"""
Create an etree element.
"""
... | from_elem | identifier_name |
subresource.py | text
return User(value)
elif type == 'Group':
value = elem.find('./URI').text
subclass = get_group_subclass_from_uri(value)
return subclass()
elif type == 'AmazonCustomerByEmail':
raise S3NotImplemented()
else:
raise Malform... | if key.lower().startswith('x-amz-grant-'):
permission = key[len('x-amz-grant-'):]
permission = permission.upper().replace('-', '_')
if permission not in PERMISSIONS:
continue
for grantee in value.split(','):
... | conditional_block | |
subresource.py | _value = {"Owner": acl.owner.id}
grants = []
for grant in acl.grants:
grant = {"Permission": grant.permission,
"Grantee": str(grant.grantee)}
grants.append(grant) | headers = {}
key = sysmeta_header(resource, 'acl')
headers[key] = json.dumps(header_value, separators=(',', ':'))
return headers
def decode_acl(resource, headers):
"""
Decode Swift metadata to an ACL instance.
Given a resource type and HTTP headers, this method returns an ACL
instanc... | header_value.update({"Grant": grants}) | random_line_split |
ex_synchronize.py | #
# A test file for the `processing` package
#
import time, sys, random
from Queue import Empty
import processing # may get overwritten
#### TEST_VALUE
def value_func(running, mutex):
random.seed()
time.sleep(random.random()*4)
mutex.acquire()
print '\n\t\t\t' + ... |
elif sys.argv[1] == 'threads':
print ' Using threads '.center(79, '-')
import processing.dummy as namespace
else:
print 'Usage:\n\t%s [processes | manager | threads]' % sys.argv[0]
raise SystemExit, 2
test(namespace)
| print ' Using processes and a manager '.center(79, '-')
namespace = processing.Manager()
namespace.Process = processing.Process
namespace.currentProcess = processing.currentProcess
namespace.activeChildren = processing.activeChildren | conditional_block |
ex_synchronize.py | #
# A test file for the `processing` package
#
import time, sys, random
from Queue import Empty
import processing # may get overwritten
#### TEST_VALUE
def value_func(running, mutex):
random.seed()
time.sleep(random.random()*4)
mutex.acquire()
print '\n\t\t\t' + ... | (namespace=processing):
global processing
processing = namespace
for func in [ test_value, test_queue, test_condition,
test_semaphore, test_join_timeout, test_event,
test_sharedvalues ]:
print '\n\t######## %s\n' % func.__name__
func()... | test | identifier_name |
ex_synchronize.py | #
# A test file for the `processing` package
#
import time, sys, random
from Queue import Empty
import processing # may get overwritten
#### TEST_VALUE
def value_func(running, mutex):
random.seed()
time.sleep(random.random()*4)
mutex.acquire()
print '\n\t\t\t' + ... | assert v == sv
for i in range(len(values)):
a = arrays[i][1]
sa = list(shared_arrays[i][:])
assert a == sa
print 'Tests passed'
def test_sharedvalues():
values = [
('i', 10),
('h', -2),
('d', 1.25)
]
arrays = [
('... | def sharedvalues_func(values, arrays, shared_values, shared_arrays):
for i in range(len(values)):
v = values[i][1]
sv = shared_values[i].value
| random_line_split |
ex_synchronize.py | #
# A test file for the `processing` package
#
import time, sys, random
from Queue import Empty
import processing # may get overwritten
#### TEST_VALUE
def value_func(running, mutex):
random.seed()
time.sleep(random.random()*4)
mutex.acquire()
print '\n\t\t\t' + ... |
#### TEST_JOIN_TIMEOUT
def join_timeout_func():
print '\tchild sleeping'
time.sleep(5.5)
print '\n\tchild terminating'
def test_join_timeout():
p = processing.Process(target=join_timeout_func)
p.start()
print 'waiting for process to finish'
while 1:
p.join(tim... | sema = processing.Semaphore(3)
mutex = processing.RLock()
running = processing.Value('i', 0)
processes = [
processing.Process(target=semaphore_func, args=(sema, mutex, running))
for i in range(10)
]
for p in processes:
p.start()
for p in processes:
... | identifier_body |
exam.js | ---
layout: null
---
$(document).ready(function(){
console.log("exam.js: document is ready");
$('.template').each(function(i) {
$(this).css('display','none');
});
// Use with <div class="copy-of" data-id="foo"></div> | // The class="copy-of" data-id="foo" signals that you want a copy of foo inserted here.
$('.copy-of').each(function(i) {
var id = $(this).data('id')
$(this).html($(document.getElementById(id)).clone().html());
});
$('.page-break-before').each(function(i) {
var pageNum = i+1;
var prev =... | // Use <div id="foo" class="template"></div> on the stuff you want to copy
// The class="template" will hide it the first time. | random_line_split |
exam.js | ---
layout: null
---
$(document).ready(function(){
console.log("exam.js: document is ready");
$('.template').each(function(i) {
$(this).css('display','none');
});
// Use with <div class="copy-of" data-id="foo"></div>
// Use <div id="foo" class="template"></div> on the stuff you want to cop... |
});
console.log("exam.js: done");
});
| {
$(this).parents(".pagebreak").removeClass("even-page");
$(this).parents(".pagebreak").addClass("odd-page");
} | conditional_block |
foreach-put-structured.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } | assert_eq!(j, 45); | random_line_split |
foreach-put-structured.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut i: int = 10;
let mut j: int = 0;
do pairs() |p| {
let (_0, _1) = p;
info!(_0);
info!(_1);
assert_eq!(_0 + 10, i);
i += 1;
j = _1;
};
assert_eq!(j, 45);
}
| main | identifier_name |
foreach-put-structured.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let mut i: int = 10;
let mut j: int = 0;
do pairs() |p| {
let (_0, _1) = p;
info!(_0);
info!(_1);
assert_eq!(_0 + 10, i);
i += 1;
j = _1;
};
assert_eq!(j, 45);
}
| {
let mut i: int = 0;
let mut j: int = 0;
while i < 10 { it((i, j)); i += 1; j += i; }
} | identifier_body |
ReadOnlyStoryNodeObjectFactorySpec.ts | // Copyright 2018 The Oppia 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 ap... | * @fileoverview Tests for ReadOnlyStoryNodeObjectFactory.
*/
require('domain/story_viewer/ReadOnlyStoryNodeObjectFactory.ts');
describe('Read only story node object factory', function() {
var ReadOnlyStoryNodeObjectFactory = null;
var _sampleSubtopic = null;
var _sampleStoryNode = null;
beforeEach(angular.... | // See the License for the specific language governing permissions and
// limitations under the License.
/** | random_line_split |
Button.test.js | import Button from '../Button';
import React from 'react';
import ReactTestUtils from 'react-dom/test-utils';
import renderer from 'react-test-renderer';
test('render button with correct label', () => {
const mockCallback = jest.fn();
const button = renderer.create(
<Button onClick={mockCallback} className="b... |
}
const button = ReactTestUtils.renderIntoDocument(
<Wrapper />
);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(button, 'button');
ReactTestUtils.Simulate.click(buttonNode);
expect(mockCallback.mock.calls.length).toBe(1);
});
| {
return (
<div>
<Button onClick={mockCallback} className="btn btn-default btn-xs">Export</Button>
</div>
);
} | identifier_body |
Button.test.js | import Button from '../Button';
import React from 'react';
import ReactTestUtils from 'react-dom/test-utils';
import renderer from 'react-test-renderer';
test('render button with correct label', () => {
const mockCallback = jest.fn();
const button = renderer.create(
<Button onClick={mockCallback} className="b... | () {
return (
<div>
<Button onClick={mockCallback} className="btn btn-default btn-xs">Export</Button>
</div>
);
}
}
const button = ReactTestUtils.renderIntoDocument(
<Wrapper />
);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(button, 'button')... | render | identifier_name |
Button.test.js | import Button from '../Button';
import React from 'react';
import ReactTestUtils from 'react-dom/test-utils';
import renderer from 'react-test-renderer';
test('render button with correct label', () => {
const mockCallback = jest.fn();
const button = renderer.create(
<Button onClick={mockCallback} className="b... |
const button = renderer.create(
<Button glyph="export" onClick={mockCallback} className="btn btn-default btn-xs">Export</Button>
);
expect(button).toMatchSnapshot();
});
test('should call click handler callback when clicked', () => {
const mockCallback = jest.fn();
// Must wrap `Button` in a Composite... | });
test('render button with correct label and glyphicon', () => {
const mockCallback = jest.fn(); | random_line_split |
string-length.js | /*# STRING LENGTH
You will often need to know how many characters are in a string.
For this you will use the .length property. Here's an example:
var example = 'example string';
example.length
# NOTE
Make sure there is a period between example and length.
The above code will return a number for the total numb... | In that file, create a variable named example.
Assign the string 'example string' to the variable example.
Use console.log to print the length of the string to the terminal.
Check to see if your program is correct by running this command:
javascripting verify string-length.js
-------------------
» To print thes... | random_line_split | |
gl.py | from glad.lang.common.loader import BaseLoader
from glad.lang.d.loader import LOAD_OPENGL_DLL
_OPENGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'private', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
bool gladLoadGL() {
bool status = false;
if(open_gl()) {
s... | (self, fobj):
fobj.write(_OPENGL_HAS_EXT)
| write_has_ext | identifier_name |
gl.py | from glad.lang.common.loader import BaseLoader
from glad.lang.d.loader import LOAD_OPENGL_DLL
_OPENGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'private', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
bool gladLoadGL() {
bool status = false;
if(open_gl()) {
s... |
def write_begin_load(self, fobj):
fobj.write('\tglGetString = cast(typeof(glGetString))load("glGetString");\n')
fobj.write('\tif(glGetString is null) { return false; }\n')
fobj.write('\tif(glGetString(GL_VERSION) is null) { return false; }\n\n')
def write_end_load(self, fobj):
... | fobj.write(_OPENGL_LOADER) | conditional_block |
gl.py | from glad.lang.common.loader import BaseLoader
from glad.lang.d.loader import LOAD_OPENGL_DLL
_OPENGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'private', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
bool gladLoadGL() {
bool status = false;
if(open_gl()) {
s... | // https://github.com/glfw/glfw/blob/master/src/context.c#L36
int i;
const(char)* glversion;
const(char)*[] prefixes = [
"OpenGL ES-CM ".ptr,
"OpenGL ES-CL ".ptr,
"OpenGL ES ".ptr,
];
glversion = cast(const(char)*)glGetString(GL_VERSION);
if (glversion is null) retur... | random_line_split | |
gl.py | from glad.lang.common.loader import BaseLoader
from glad.lang.d.loader import LOAD_OPENGL_DLL
_OPENGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'private', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
bool gladLoadGL() {
bool status = false;
if(open_gl()) {
s... |
def write_begin_load(self, fobj):
fobj.write('\tglGetString = cast(typeof(glGetString))load("glGetString");\n')
fobj.write('\tif(glGetString is null) { return false; }\n')
fobj.write('\tif(glGetString(GL_VERSION) is null) { return false; }\n\n')
def write_end_load(self, fobj):
... | fobj.write('alias Loader = void* delegate(const(char)*);\n')
if not self.disabled and 'gl' in self.apis:
fobj.write(_OPENGL_LOADER) | identifier_body |
doc-web.py | #!/usr/bin/env python
#
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
| def GET(self, path):
if path == '':
path = 'index.html'
f = open('_build/html/'+path)
return f.read() | identifier_body |
doc-web.py | #!/usr/bin/env python
#
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | app = web.application(urls, globals())
app.run() | conditional_block | |
doc-web.py | #!/usr/bin/env python
#
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | app.run() |
if __name__ == "__main__":
app = web.application(urls, globals()) | random_line_split |
doc-web.py | #!/usr/bin/env python
#
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | :
def GET(self, path):
if path == '':
path = 'index.html'
f = open('_build/html/'+path)
return f.read()
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
| router | identifier_name |
operator.rs | use super::graph::{Graph, IndexType};
use super::EdgeType;
use crate::visit::IntoNodeReferences;
/// \[Generic\] complement of the graph
///
/// Computes the graph complement of the input Graphand stores it
/// in the provided empty output Graph.
///
/// The function does not create self-loops.
///
/// Computes in **O... |
}
}
}
| {
output.add_edge(x, y, weight.clone());
} | conditional_block |
operator.rs | use super::graph::{Graph, IndexType};
use super::EdgeType;
use crate::visit::IntoNodeReferences;
/// \[Generic\] complement of the graph
///
/// Computes the graph complement of the input Graphand stores it
/// in the provided empty output Graph.
///
/// The function does not create self-loops.
///
/// Computes in **O... | /// (a, c),
/// (a, d),
/// (b, a),
/// (b, d),
/// (c, a),
/// (c, b),
/// (d, a),
/// (d, b),
/// (d, c),
/// ]);
///
/// for x in graph.node_indices() {
/// for y in graph.node_indices() {
/// assert_eq!(output.contains_edge(x, y), expected_res.contains_edge(x, y));
//... | /// let c = expected_res.add_node(());
/// let d = expected_res.add_node(());
/// expected_res.extend_with_edges(&[ | random_line_split |
operator.rs | use super::graph::{Graph, IndexType};
use super::EdgeType;
use crate::visit::IntoNodeReferences;
/// \[Generic\] complement of the graph
///
/// Computes the graph complement of the input Graphand stores it
/// in the provided empty output Graph.
///
/// The function does not create self-loops.
///
/// Computes in **O... | <N, E, Ty, Ix>(
input: &Graph<N, E, Ty, Ix>,
output: &mut Graph<N, E, Ty, Ix>,
weight: E,
) where
Ty: EdgeType,
Ix: IndexType,
E: Clone,
N: Clone,
{
for (_node, weight) in input.node_references() {
output.add_node(weight.clone());
}
for x in input.node_indices() {
... | complement | identifier_name |
operator.rs | use super::graph::{Graph, IndexType};
use super::EdgeType;
use crate::visit::IntoNodeReferences;
/// \[Generic\] complement of the graph
///
/// Computes the graph complement of the input Graphand stores it
/// in the provided empty output Graph.
///
/// The function does not create self-loops.
///
/// Computes in **O... | {
for (_node, weight) in input.node_references() {
output.add_node(weight.clone());
}
for x in input.node_indices() {
for y in input.node_indices() {
if x != y && !input.contains_edge(x, y) {
output.add_edge(x, y, weight.clone());
}
}
}
} | identifier_body | |
n_queens.py | #!/usr/bin/env python
# encoding: utf-8
"""
n_queens.py
Created by Shengwei on 2014-07-23.
"""
# https://oj.leetcode.com/problems/n-queens/
# tags: medim / hard, matrix, bit manipulation, generator, dfs, edge cases, bitmap
"""
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no t... |
return list(search([], n, 0, 0, 0))
| os = availables & (-availables) # get the rightmost bit that is 1
availables -= pos # remove current pos from availables
index = int(math.log(pos, 2)) # comput the index where to put queen
# note: remember the recursive call is an iterater and yield ag... | conditional_block |
n_queens.py | #!/usr/bin/env python
# encoding: utf-8
"""
n_queens.py
Created by Shengwei on 2014-07-23.
"""
# https://oj.leetcode.com/problems/n-queens/
# tags: medim / hard, matrix, bit manipulation, generator, dfs, edge cases, bitmap
"""
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no t... | self, n):
positions = (1 << n) - 1
def search(board, depth, vertical_taken, left_taken, right_taken):
if depth == 0:
yield board
return
line = ['.'] * n
# it must be & with positions, otherwise it's a nega... | olveNQueens( | identifier_name |
n_queens.py | #!/usr/bin/env python
# encoding: utf-8
"""
n_queens.py
Created by Shengwei on 2014-07-23.
"""
# https://oj.leetcode.com/problems/n-queens/
# tags: medim / hard, matrix, bit manipulation, generator, dfs, edge cases, bitmap
"""
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no t... | # note: remember the recursive call is an iterater and yield again
line[index] = 'Q'
for each in search(
board + [''.join(line)], depth - 1, vertical_taken + pos,
left_taken + pos << 1, right_taken + pos >> 1):
... | ef solveNQueens(self, n):
positions = (1 << n) - 1
def search(board, depth, vertical_taken, left_taken, right_taken):
if depth == 0:
yield board
return
line = ['.'] * n
# it must be & with positions, other... | identifier_body |
n_queens.py | #!/usr/bin/env python
# encoding: utf-8
"""
n_queens.py
Created by Shengwei on 2014-07-23.
"""
# https://oj.leetcode.com/problems/n-queens/
# tags: medim / hard, matrix, bit manipulation, generator, dfs, edge cases, bitmap
"""
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no t... | for each in search(
board + [''.join(line)], depth - 1, vertical_taken + pos,
left_taken + pos << 1, right_taken + pos >> 1):
yield each
line[index] = '.'
return list(search([], n, 0, 0, 0)) | # note: remember the recursive call is an iterater and yield again
line[index] = 'Q' | random_line_split |
test_chart_data_labels11.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest): | def setUp(self):
self.maxDiff = None
filename = 'chart_data_labels11.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore... | """
Test file created by XlsxWriter against a file created by Excel.
"""
| random_line_split |
test_chart_data_labels11.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class | (ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_data_labels11.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
... | TestCompareXLSXFiles | identifier_name |
test_chart_data_labels11.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | 'data_labels': {'value': 1, 'leader_lines': 1, 'position': 'best_fit'},
})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
| """Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'pie'})
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
... | identifier_body |
comment.ts | import { debug } from '../utils/debug'
import {
GET_COMMENT_LIST_ERROR,
GET_COMMENT_LIST_PENDING,
GET_COMMENT_LIST_SUCCESS,
POST_COMMENT_ERROR,
POST_COMMENT_SUCCESS,
POST_COMMENT_PENDING,
} from '../constants/comment.action.types'
import { fromJS, List, Map } from 'immutable'
const INITIAL_STATE = fromJ... |
const postId = comments[0].postId.toString()
const oldComments: List<CommentPayload>
= state.getIn(['comments', postId.toString()])
const newComments = oldComments
? oldComments.concat(comments)
: List(comments) as any
const oldTable = state.get('comments') as Map<string, List<any>>
const new... | {
return state
} | conditional_block |
comment.ts | import { debug } from '../utils/debug'
import {
GET_COMMENT_LIST_ERROR,
GET_COMMENT_LIST_PENDING,
GET_COMMENT_LIST_SUCCESS,
POST_COMMENT_ERROR,
POST_COMMENT_SUCCESS,
POST_COMMENT_PENDING,
} from '../constants/comment.action.types'
import { fromJS, List, Map } from 'immutable'
const INITIAL_STATE = fromJ... | {
const comment = action.payload as CommentPayload
const oldTable = state.get('comments') as Map<string, List<any>>
const oldComments = state
.get('comments')
.get(comment.postId.toString())
const newComments = oldComments
? oldComments.push(comment)
: List().push(comment)
const newTable = o... | identifier_body | |
comment.ts | import { debug } from '../utils/debug'
import {
GET_COMMENT_LIST_ERROR,
GET_COMMENT_LIST_PENDING,
GET_COMMENT_LIST_SUCCESS,
POST_COMMENT_ERROR,
POST_COMMENT_SUCCESS,
POST_COMMENT_PENDING,
} from '../constants/comment.action.types'
import { fromJS, List, Map } from 'immutable'
const INITIAL_STATE = fromJ... |
export default commentReducer
function processGetCommetList(state, action) {
const comments = action.payload as CommentPayload[]
if (comments.length === 0) {
return state
}
const postId = comments[0].postId.toString()
const oldComments: List<CommentPayload>
= state.getIn(['comments', postId.toStri... | }
} | random_line_split |
comment.ts | import { debug } from '../utils/debug'
import {
GET_COMMENT_LIST_ERROR,
GET_COMMENT_LIST_PENDING,
GET_COMMENT_LIST_SUCCESS,
POST_COMMENT_ERROR,
POST_COMMENT_SUCCESS,
POST_COMMENT_PENDING,
} from '../constants/comment.action.types'
import { fromJS, List, Map } from 'immutable'
const INITIAL_STATE = fromJ... | (state, action) {
const comments = action.payload as CommentPayload[]
if (comments.length === 0) {
return state
}
const postId = comments[0].postId.toString()
const oldComments: List<CommentPayload>
= state.getIn(['comments', postId.toString()])
const newComments = oldComments
? oldComments.c... | processGetCommetList | identifier_name |
removeUselessStrokeAndFill.js | 'use strict';
exports.type = 'perItem';
exports.active = true;
exports.description = 'removes useless stroke and fill attributes';
exports.params = {
stroke: true,
fill: true
};
var shape = require('./_collections').elemsGroups.shape,
regStrokeProps = /^stroke/,
regFillProps = /^fill-/,
styleOr... | (!fill || item.computedAttr('fill-opacity', '0'))
) {
item.eachAttr(function(attr) {
if (regFillProps.test(attr.name)) {
item.removeAttr(attr.name);
}
});
if (fill) {
if (item.hasAttr('fill'))
... |
// remove fill*
if (
params.fill && | random_line_split |
insn_assert_lt.py | # -*- coding: utf-8 -*-
#
# AWL simulator - instructions
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
... |
s.NER = 0
| raise AwlSimError("Assertion failed") | conditional_block |
insn_assert_lt.py | #
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# ... | # -*- coding: utf-8 -*-
#
# AWL simulator - instructions
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch> | random_line_split | |
insn_assert_lt.py | # -*- coding: utf-8 -*-
#
# AWL simulator - instructions
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
... | (AwlInsn): #+cdef
__slots__ = ()
def __init__(self, cpu, rawInsn):
AwlInsn.__init__(self, cpu, AwlInsn.TYPE_ASSERT_LT, rawInsn)
self.assertOpCount(2)
def run(self):
#@cy cdef S7StatusWord s
s = self.cpu.statusWord
val0 = self.cpu.fetch(self.ops[0])
val1 = self.cpu.fetch(self.ops[1])
if not (val0 < v... | AwlInsn_ASSERT_LT | identifier_name |
insn_assert_lt.py | # -*- coding: utf-8 -*-
#
# AWL simulator - instructions
#
# Copyright 2012-2014 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
... | s = self.cpu.statusWord
val0 = self.cpu.fetch(self.ops[0])
val1 = self.cpu.fetch(self.ops[1])
if not (val0 < val1):
raise AwlSimError("Assertion failed")
s.NER = 0 | identifier_body | |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use... | Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
}
impl<'a> HTMLSelectElementMethods for &'a HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(self) -> Root<ValidityState> {
let window = window_from_node(self);
Val... | #[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document); | random_line_split |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use... |
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited(H... | {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)))
} | identifier_body |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use... | (&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(*self);
node.set_disabled_state(true);
node.set_enabl... | after_set_attr | identifier_name |
gcp_iam_role.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | (module, link):
auth = GcpSession(module, 'iam')
return return_if_object(module, auth.post(link, resource_to_create(module)))
def update(module, link, fetch):
auth = GcpSession(module, 'iam')
params = {'updateMask': updateMask(resource_to_request(module), response_to_hash(module, fetch))}
request ... | create | identifier_name |
gcp_iam_role.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | ---
module: gcp_iam_role
description:
- A role in the Identity and Access Management API .
short_description: Creates a GCP Role
version_added: 2.8
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
state:
description:
- Whether the gi... | ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = ''' | random_line_split |
gcp_iam_role.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
return GcpRequest(request_vals) != GcpRequest(response_vals)
# Remove unnecessary properties from the response.
# This is for doing comparisons with Ansible's current parameters.
def response_to_hash(module, response):
return {
u'name': response.get(u'name'),
u'title': response.get(u'title')... | if k in response:
request_vals[k] = v | conditional_block |
gcp_iam_role.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
def update(module, link, fetch):
auth = GcpSession(module, 'iam')
params = {'updateMask': updateMask(resource_to_request(module), response_to_hash(module, fetch))}
request = resource_to_request(module)
del request['name']
return return_if_object(module, auth.put(link, request, params=params))
d... | auth = GcpSession(module, 'iam')
return return_if_object(module, auth.post(link, resource_to_create(module))) | identifier_body |
drain.py | import os
import command
import serverinfo
import accounts
from google.appengine.ext.webapp import template
class Drain(command.Command):
def have_access(self):
account = accounts.account()
if not account or not account.DRAIN_ACCESS_RIGHT:
return False
return True
def fini... | (self, selected, template_values):
drain_command = None
if self.request.get('drain'):
drain_command = 'drain'
if self.request.get('undrain'):
drain_command = 'undrain'
errors = []
if len(selected) == 0:
errors.append('Must select at least one ... | finish_post | identifier_name |
drain.py | import os
import command
import serverinfo
import accounts
from google.appengine.ext.webapp import template
class Drain(command.Command):
def have_access(self):
account = accounts.account()
if not account or not account.DRAIN_ACCESS_RIGHT:
return False
return True
def fini... |
else:
for info in selected:
serverinfo.ServerInfo.send_command(info, '{"command": "%s"}' % drain_command)
errors.append('Server %s sent %s command.' % (info['name'], drain_command))
template_values['errors'] = errors
self.response.headers['Content-T... | errors.append('Must select drain or undrain.') | conditional_block |
drain.py | import os
import command | from google.appengine.ext.webapp import template
class Drain(command.Command):
def have_access(self):
account = accounts.account()
if not account or not account.DRAIN_ACCESS_RIGHT:
return False
return True
def finish_get(self, template_values):
self.response.headers... | import serverinfo
import accounts
| random_line_split |
drain.py | import os
import command
import serverinfo
import accounts
from google.appengine.ext.webapp import template
class Drain(command.Command):
def have_access(self):
account = accounts.account()
if not account or not account.DRAIN_ACCESS_RIGHT:
return False
return True
def fini... | self.response.out.write(template.render(path, template_values))
| drain_command = None
if self.request.get('drain'):
drain_command = 'drain'
if self.request.get('undrain'):
drain_command = 'undrain'
errors = []
if len(selected) == 0:
errors.append('Must select at least one server.')
if drain_command == None:... | identifier_body |
web_form.js | frappe.provide("frappe.ui");
frappe.provide("frappe.web_form");
import EventEmitterMixin from '../../frappe/event_emitter';
export default class WebForm extends frappe.ui.FieldGroup {
constructor(opts) {
super();
Object.assign(this, opts);
frappe.web_form = this;
frappe.web_form.events = {};
Object.assign(f... |
handle_success(data) {
if (this.accept_payment && !this.doc.paid) {
window.location.href = data;
}
const success_dialog = new frappe.ui.Dialog({
title: __("Saved Successfully"),
secondary_action: () => {
if (this.success_url) {
window.location.href = this.success_url;
} else if(this.logi... | {
window.location.href = window.location.pathname;
} | identifier_body |
web_form.js | frappe.provide("frappe.ui");
frappe.provide("frappe.web_form");
import EventEmitterMixin from '../../frappe/event_emitter';
export default class WebForm extends frappe.ui.FieldGroup {
constructor(opts) {
super();
Object.assign(this, opts);
frappe.web_form = this;
frappe.web_form.events = {};
Object.assign(f... | () {
this.add_button_to_header(
'<i class="fa fa-trash" aria-hidden="true"></i>',
"light",
() => this.delete()
);
}
setup_print_button() {
this.add_button_to_header(
'<i class="fa fa-print" aria-hidden="true"></i>',
"light",
() => this.print()
);
}
save() {
if (this.validate && !this.v... | setup_delete_button | identifier_name |
web_form.js | frappe.provide("frappe.ui");
frappe.provide("frappe.web_form");
import EventEmitterMixin from '../../frappe/event_emitter';
export default class WebForm extends frappe.ui.FieldGroup {
constructor(opts) {
super();
Object.assign(this, opts);
frappe.web_form = this;
frappe.web_form.events = {};
Object.assign(f... | }
const success_dialog = new frappe.ui.Dialog({
title: __("Saved Successfully"),
secondary_action: () => {
if (this.success_url) {
window.location.href = this.success_url;
} else if(this.login_required) {
window.location.href =
window.location.pathname + "?name=" + data.name;
}
... | handle_success(data) {
if (this.accept_payment && !this.doc.paid) {
window.location.href = data; | random_line_split |
mod.rs | // This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope tha... | <F: Fetch = FetchClient, R: URLHint + Send + Sync + 'static = URLHintContract> {
dapps_path: PathBuf,
resolver: R,
cache: Arc<Mutex<ContentCache>>,
sync: Arc<SyncStatus>,
embeddable_on: Option<(String, u16)>,
remote: Remote,
fetch: F,
}
impl<R: URLHint + Send + Sync + 'static, F: Fetch> Drop for ContentFetcher<... | ContentFetcher | identifier_name |
mod.rs | // This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope tha... |
}
fn to_async_handler(&self, path: EndpointPath, control: hyper::Control) -> Box<Handler> {
let mut cache = self.cache.lock();
let content_id = path.app_id.clone();
let (new_status, handler) = {
let status = cache.get(&content_id);
match status {
// Just serve the content
Some(&mut ContentStatu... | {
false
} | conditional_block |
mod.rs | // This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope tha... |
}
#[test]
fn should_true_if_contains_the_app() {
// given
let path = env::temp_dir();
let fetcher = ContentFetcher::new(FakeResolver, Arc::new(|| false), None, Remote::new_sync(), Client::new().unwrap());
let handler = LocalPageEndpoint::new(path, EndpointInfo {
name: "fake".into(),
description: "".i... | {
None
} | identifier_body |
mod.rs | .
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope t... | },
Some(URLHintResult::Dapp(dapp)) => {
let handler = ContentFetcherHandler::new(
dapp.url(),
path,
control,
installers::Dapp::new(
content_id.clone(),
self.dapps_path.clone(),
Box::new(on_done),
self.embeddable_on.clone(),
)... | (None, Self::still_syncing(self.embeddable_on.clone())) | random_line_split |
app.js | window.jQuery = window.$ = require('jquery');
require('bootstrap');
var angular = require('angular');
var uirouter = require('angular-ui-router');
var uibootstrap = require('angular-ui-bootstrap');
var fileupload = require('ng-file-upload');
//TODO pretify these uris
require('./css/main.css');
require('./css/theme.cs... | })
.state('submit', {
url: '/submit',
templateUrl: '/app/partials/submit.html',
controller: 'submitCtrl'
})
.state('apps', {
url: '/apps',
templateUrl: '/app/partials/apps.html',
controller: 'appsCtrl'
})
.state('app', {
url: '/app/:name',
... | url: '/docs',
templateUrl: '/app/partials/docs.html',
controller: 'docsCtrl' | random_line_split |
sw_config_backup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:set sw=4 ts=4 et:
import sys
import pexpect
import threading
import os
import shutil
import logging
import time
import configparser
import ast
import subprocess
def backup(switch, server):
if switch['type'].lower() == '3com':
return backup_3com(switch, server)
... | (app_cfg):
command = "cd %s; git add -A; git commit -a -m 'autocommit on change'" % (app_cfg['backup_dir_path'])
subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
def main():
app_cfg = load_app_cfg()
logging.basicConfig(filename=app_cfg['log_file'], level=logging.INFO, format='%(asctime)s %(levelname)s ... | git_autocommit | identifier_name |
sw_config_backup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:set sw=4 ts=4 et:
import sys
import pexpect
import threading
import os
import shutil
import logging
import time
import configparser
import ast
import subprocess
def backup(switch, server):
if switch['type'].lower() == '3com':
return backup_3com(switch, server)
... |
elif (end_time - os.stat(tmp_file_path).st_mtime) > file_expiration_timeout:
logging.error("Configuration of %s, file %s is older than %d s, file will be ignored" % (switch['name'],tmp_file_path, file_expiration_timeout))
else:
shutil.copy2(tmp_file_path, app_cfg['backup_dir_path'])
logging.info("Sav... | logging.warning("Fail to read %s, expected file %s" % (switch['name'],tmp_file_path)) | conditional_block |
sw_config_backup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:set sw=4 ts=4 et:
import sys
import pexpect
import threading
import os
import shutil
import logging
import time
import configparser
import ast
import subprocess | if switch['type'].lower() == '3com':
return backup_3com(switch, server)
elif switch['type'].lower() == 'hp':
return backup_hp(switch, server)
else:
logging.error("Unsupported type of switch (type: %s)" % (switch['type']))
return 4
def backup_3com(switch, server):
try:
ssh=pexpect.spawn('ssh -o StrictHost... |
def backup(switch, server): | random_line_split |
sw_config_backup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:set sw=4 ts=4 et:
import sys
import pexpect
import threading
import os
import shutil
import logging
import time
import configparser
import ast
import subprocess
def backup(switch, server):
if switch['type'].lower() == '3com':
return backup_3com(switch, server)
... |
def load_app_cfg():
app_cfg = configparser.ConfigParser()
app_cfg.read("%s/conf/app.cfg" % (sys.path[0]))
retval = dict(app_cfg.items('APP'))
app_cfg_check(retval)
retval['git_autocommit'] = retval['git_autocommit'].lower() in ['true', '1', 'yes', 'y']
return retval
def git_autocommit(app_cfg):
command = "cd ... | keys = {'backup_dir_path', 'backup_server', 'file_expiration_timeout', 'tftp_dir_path', 'log_file', 'git_autocommit'}
for key in keys:
if not key in app_cfg:
raise Exception("Key \'%s\' in application configuration file is missing" % (key)) | identifier_body |
urls.py | """m_play URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | url(r'^admin/', admin.site.urls),
] | url(r'^gnovel/', include('gnovel.urls')), | random_line_split |
webpack.config.js | var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimi... | {
// Resolve to source
module.exports.resolve = { alias: { 'remote-redux-devtools': src } };
// Compile from source
module.exports.module.loaders.push({
test: /\.js$/,
loaders: ['babel'],
include: src
});
} | conditional_block | |
webpack.config.js | var path = require('path');
var webpack = require('webpack');
| devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new w... | module.exports = { | random_line_split |
test_http.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import run_tests # set sys.path
import tempfile
import os
from kobo.http import *
class | (unittest.TestCase):
def setUp(self):
self.postt = POSTTransport()
def test_get_content_type(self):
tf0 = tempfile.mkstemp()[1]
tf1 = tempfile.mkstemp(suffix=".txt")[1]
tf2 = tempfile.mkstemp(suffix=".rtf")[1]
tf3 = tempfile.mkstemp(suffix=".avi")[1]
self.assertE... | TestPOSTTransport | identifier_name |
test_http.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import run_tests # set sys.path
import tempfile
import os
from kobo.http import *
class TestPOSTTransport(unittest.TestCase):
def setUp(self):
self.postt = POSTTransport()
def test_get_content_type(self):
tf0 = tempfile.mkstemp()[1... | self.assertRaises(TypeError, self.postt.add_file, "file", tf3)
if __name__ == '__main__':
unittest.main() | self.assertRaises(OSError, self.postt.add_file, "file", tf1)
self.assertEqual(self.postt.add_file("file", tf2), None) | random_line_split |
test_http.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import run_tests # set sys.path
import tempfile
import os
from kobo.http import *
class TestPOSTTransport(unittest.TestCase):
def setUp(self):
self.postt = POSTTransport()
def test_get_content_type(self):
tf0 = tempfile.mkstemp()[1... | unittest.main() | conditional_block | |
test_http.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import run_tests # set sys.path
import tempfile
import os
from kobo.http import *
class TestPOSTTransport(unittest.TestCase):
def setUp(self):
self.postt = POSTTransport()
def test_get_content_type(self):
tf0 = tempfile.mkstemp()[1... |
if __name__ == '__main__':
unittest.main()
| tf1 = tempfile.mkstemp()[1]
tf2 = tempfile.mkstemp()[1]
tf3 = open(tempfile.mkstemp()[1])
os.unlink(tf1)
self.assertRaises(OSError, self.postt.add_file, "file", tf1)
self.assertEqual(self.postt.add_file("file", tf2), None)
self.assertRaises(TypeError, self.postt.add_file,... | identifier_body |
GetScrollbarWidth.ts | // From: http://stackoverflow.com/a/13382873/342378
class Ge |
private static _Width: number;
public static get Width(): number {
if (typeof this._Width === 'undefined') {
var outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
// TODOX msOverflowStyle not defined o... | tScrollbarWidth { | identifier_name |
GetScrollbarWidth.ts |
public static get Width(): number {
if (typeof this._Width === 'undefined') {
var outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
// TODOX msOverflowStyle not defined outer.style.msOverflowStyle = 'scroll... | // From: http://stackoverflow.com/a/13382873/342378
class GetScrollbarWidth {
private static _Width: number; | random_line_split | |
GetScrollbarWidth.ts | // From: http://stackoverflow.com/a/13382873/342378
class GetScrollbarWidth {
private static _Width: number;
public static get Width(): number {
if (typeof this._Width === 'undefined') {
var outer = document.createElement('div');
outer.style.visibility = 'hidden';
o... | this._Width = widthNoScroll - widthWithScroll;
}
return this._Width;
}
}
| outer.parentNode.removeChild(outer);
}
| conditional_block |
media_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cs... |
}
impl ToCssWithGuard for MediaRule {
// Serialization of MediaRule is not specced.
// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSMediaRule
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
dest.write_str("@media ")?;
sel... | {
// Measurement of other fields may be added later.
self.rules.unconditional_shallow_size_of(ops) +
self.rules.read_with(guard).size_of(guard, ops)
} | identifier_body |
media_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cs... | {
/// The list of media queries used by this media rule.
pub media_queries: Arc<Locked<MediaList>>,
/// The nested rules to this media rule.
pub rules: Arc<Locked<CssRules>>,
/// The source position where this media rule was found.
pub source_location: SourceLocation,
}
impl MediaRule {
//... | MediaRule | identifier_name |
media_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cs... | /// [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
#[derive(Debug)]
pub struct MediaRule {
/// The list of media queries used by this media rule.
pub media_queries: Arc<Locked<MediaList>>,
/// The nested rules to this media rule.
pub rules: Arc<Locked<CssRules>>,
/// The source ... | /// An [`@media`][media] urle.
/// | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.