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 |
|---|---|---|---|---|
__init__.py | Parser()
QUERY_PARSER.add_argument("filter", action="append", help="Filter")
QUERY_PARSER.add_argument("order", help="Ordering", default="id")
QUERY_PARSER.add_argument("page", type=int, default=1, help="Page #")
QUERY_PARSER.add_argument("count",
type=int,
default=10... | break
if success:
return func(*args, **kwargs)
else:
return "", 403
return decorated
def dynamic_query(model, query, expression):
"""
Construct query based on:
attribute.operation.expression
For example:
foo.eq.42
""... | auth_data = auth_response.json()
for endpoint in auth_data["endpoints"]:
if endpoint["name"] == PACKAGE:
success = True | random_line_split |
test_views.py | # -*- coding: utf-8 -*-
import mock
import pytest
from future.moves.urllib.parse import urlparse, urljoin
from addons.base.tests import views
from addons.base.tests.utils import MockFolder
from addons.mendeley.models import Mendeley
from addons.mendeley.tests.utils import MendeleyTestCase, mock_responses
from tests.b... | (self):
super(TestConfigViews, self).test_deauthorize_node()
| test_deauthorize_node | identifier_name |
test_views.py | # -*- coding: utf-8 -*-
import mock
import pytest
from future.moves.urllib.parse import urlparse, urljoin
from addons.base.tests import views
from addons.base.tests.utils import MockFolder
from addons.mendeley.models import Mendeley
from addons.mendeley.tests.utils import MendeleyTestCase, mock_responses
from tests.b... |
class TestConfigViews(MendeleyTestCase, views.OAuthCitationAddonConfigViewsTestCaseMixin, OsfTestCase):
folder = MockFolder()
Serializer = MendeleySerializer
client = Mendeley
citationsProvider = MendeleyCitationsProvider
foldersApiUrl = urljoin(API_URL, 'folders')
documentsApiUrl = urljoin(AP... | pass | identifier_body |
test_views.py | # -*- coding: utf-8 -*-
import mock
import pytest
from future.moves.urllib.parse import urlparse, urljoin
from addons.base.tests import views
from addons.base.tests.utils import MockFolder
from addons.mendeley.models import Mendeley
from addons.mendeley.tests.utils import MendeleyTestCase, mock_responses
from tests.b... | super(TestConfigViews, self).test_deauthorize_node() | random_line_split | |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
* | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing per... | * 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
* | random_line_split |
testing.py | import collections
import lxml.objectify
import mock
import zeit.cms.repository.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.tagging.tag
import zope.component
import zope.interface
NAMESPACE = "http://namespaces.zeit.de/CMS/tagging"
KEYWORD_PROPERTY = ('testtags', NAMESPACE)
class DummyTagger(objec... |
@property
def pinned(self):
return [x.code for x in self.values() if x.pinned]
@property
def links(self):
config = zope.app.appsetup.product.getProductConfiguration('zeit.cms')
live_prefix = config['live-prefix']
return {x.uniqueId: live_prefix + x.link
... | for tag in self.values():
tag.pinned = tag.code in keys | identifier_body |
testing.py | import collections
import lxml.objectify
import mock
import zeit.cms.repository.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.tagging.tag
import zope.component
import zope.interface
NAMESPACE = "http://namespaces.zeit.de/CMS/tagging"
KEYWORD_PROPERTY = ('testtags', NAMESPACE)
class DummyTagger(objec... |
def to_xml(self):
node = lxml.objectify.E.tags(*[
lxml.objectify.E.tag(x.label) for x in self.values()])
return node
class FakeTag(object):
"""Fake implementation of ITag for tests."""
zope.interface.implements(zeit.cms.tagging.interfaces.ITag)
def __init__(self, code, l... | random_line_split | |
testing.py | import collections
import lxml.objectify
import mock
import zeit.cms.repository.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.tagging.tag
import zope.component
import zope.interface
NAMESPACE = "http://namespaces.zeit.de/CMS/tagging"
KEYWORD_PROPERTY = ('testtags', NAMESPACE)
class DummyTagger(objec... |
return None
class FakeTags(collections.OrderedDict):
def __init__(self):
super(FakeTags, self).__init__()
self.updateOrder = mock.Mock()
self.update = mock.Mock()
def __contains__(self, key):
return key in list(self)
def set_pinned(self, keys):
for tag i... | return FakeTag(code=id, label=self.tags[id]) | conditional_block |
testing.py | import collections
import lxml.objectify
import mock
import zeit.cms.repository.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.tagging.tag
import zope.component
import zope.interface
NAMESPACE = "http://namespaces.zeit.de/CMS/tagging"
KEYWORD_PROPERTY = ('testtags', NAMESPACE)
class DummyTagger(objec... | (self, context):
self.context = context
@property
def whitelist(self):
return zope.component.getUtility(
zeit.cms.tagging.interfaces.IWhitelist)
@property
def dav_properties(self):
return zeit.connector.interfaces.IWebDAVProperties(self.context)
def __iter__(se... | __init__ | identifier_name |
quickOpenEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | this.codeEditor.addOverlayWidget(this);
}
public setInput(model: QuickOpenModel, focus: IAutoFocus): void {
this.quickOpenWidget.setInput(model, focus);
}
public getId(): string {
return QuickOpenEditorWidget.ID;
}
public getDomNode(): HTMLElement {
return this.domNode;
}
public destroy(): void {
... | random_line_split | |
quickOpenEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public destroy(): void {
this.codeEditor.removeOverlayWidget(this);
this.quickOpenWidget.dispose();
this.styler.dispose();
}
public isVisible(): boolean {
return this.visible;
}
public show(value: string): void {
this.visible = true;
var editorLayout = this.codeEditor.getLayoutInfo();
if (editor... | {
return this.domNode;
} | identifier_body |
quickOpenEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): void {
this.visible = false;
this.quickOpenWidget.hide();
this.codeEditor.layoutOverlayWidget(this);
}
public getPosition(): IOverlayWidgetPosition {
if (this.visible) {
return {
preference: OverlayWidgetPositionPreference.TOP_CENTER
};
}
return null;
}
} | hide | identifier_name |
quickOpenEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
this.quickOpenWidget.show(value);
this.codeEditor.layoutOverlayWidget(this);
}
public hide(): void {
this.visible = false;
this.quickOpenWidget.hide();
this.codeEditor.layoutOverlayWidget(this);
}
public getPosition(): IOverlayWidgetPosition {
if (this.visible) {
return {
preference: OverlayW... | {
this.quickOpenWidget.layout(new Dimension(editorLayout.width, editorLayout.height));
} | conditional_block |
sci_bdt_electron_DecisionTree.py | from array import array
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
from sklearn import tree
import cPickle
... |
#sk_y_predicted = dt.predict(X_test)
#sk_y_predicted = dt.predict_proba(X_test)[:, 1]
sk_y_predicted = dt.predict_proba(X_test)[:, 1]
predictions = dt.predict(X_test)
print predictions
print y_test
# Draw ROC curve
fpr, tpr, _ = roc_curve(y_test, sk_y_predicted)
plt.figure()
plt.plot(fpr, tpr, label='ROC curve of ... | print "Loading DecisionTree..."
# load it again
with open('electrons_toTMVA.pkl', 'rb') as fid:
dt = cPickle.load(fid) | conditional_block |
sci_bdt_electron_DecisionTree.py | from array import array
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
from sklearn import tree
import cPickle
... | cPickle.dump(dt, fid)
else:
print "Loading DecisionTree..."
# load it again
with open('electrons_toTMVA.pkl', 'rb') as fid:
dt = cPickle.load(fid)
#sk_y_predicted = dt.predict(X_test)
#sk_y_predicted = dt.predict_proba(X_test)[:, 1]
sk_y_predicted = dt.predict_proba(X_test)[:, 1]
prediction... | import cPickle
with open('electrons_toTMVA.pkl', 'wb') as fid: | random_line_split |
modeling-assessment.component.ts | } from 'ng-jhipster';
import interact from 'interactjs';
import { Feedback } from 'app/entities/feedback';
import { User } from 'app/core';
import * as $ from 'jquery';
@Component({
selector: 'jhi-modeling-assessment',
templateUrl: './modeling-assessment.component.html',
styleUrls: ['./modeling-assessment... | (newElementIDs: Set<string>) {
if (!newElementIDs) {
newElementIDs = new Set<string>();
}
if (this.apollonEditor !== null) {
const model: UMLModel = this.apollonEditor!.model;
for (const element of model.elements) {
if (newElementIDs.has(elemen... | updateHighlightedElements | identifier_name |
modeling-assessment.component.ts | } from 'ng-jhipster';
import interact from 'interactjs';
import { Feedback } from 'app/entities/feedback';
import { User } from 'app/core';
import * as $ from 'jquery';
@Component({
selector: 'jhi-modeling-assessment',
templateUrl: './modeling-assessment.component.html',
styleUrls: ['./modeling-assessment... | @ViewChild('resizeContainer', { static: false }) resizeContainer: ElementRef;
@Input() model: UMLModel;
@Input() highlightedElementIds: Set<string>;
@Input() highlightColor = 'rgba(219, 53, 69,0.6)';
@Input() centeredElementId: string;
@Input() feedbacks: Feedback[] = [];
@Input() diagramTyp... | totalScore = 0;
@ViewChild('editorContainer', { static: false }) editorContainer: ElementRef; | random_line_split |
modeling-assessment.component.ts | from 'ng-jhipster';
import interact from 'interactjs';
import { Feedback } from 'app/entities/feedback';
import { User } from 'app/core';
import * as $ from 'jquery';
@Component({
selector: 'jhi-modeling-assessment',
templateUrl: './modeling-assessment.component.html',
styleUrls: ['./modeling-assessment.c... |
let availableIds: string[] = this.model.elements.map(element => element.id);
if (this.model.relationships) {
availableIds = availableIds.concat(this.model.relationships.map(relationship => relationship.id));
}
return feedbacks.filter(feedback => availableIds.includes(feedba... | {
return [];
} | conditional_block |
modeling-assessment.component.ts | from 'ng-jhipster';
import interact from 'interactjs';
import { Feedback } from 'app/entities/feedback';
import { User } from 'app/core';
import * as $ from 'jquery';
@Component({
selector: 'jhi-modeling-assessment',
templateUrl: './modeling-assessment.component.html',
styleUrls: ['./modeling-assessment.c... |
/**
* Updates the mapping of elementIds to Feedback elements. This should be called after getting the
* (updated) Feedback list from the server.
*
* @param feedbacks new Feedback elements to insert
*/
private updateElementFeedbackMapping(feedbacks: Feedback[]) {
if (!this.elem... | {
if (!feedbacks) {
return feedbacks;
}
if (!this.model || !this.model.elements) {
return [];
}
let availableIds: string[] = this.model.elements.map(element => element.id);
if (this.model.relationships) {
availableIds = availableIds.co... | identifier_body |
shopkeeper.py | liquors = [
'Njezjin', 'Tsjernigof', 'Ossipewsk', 'Gorlowka',
'Gomel',
'Konosja', 'Weliki Oestjoeg', 'Syktywkar', 'Sablja',
'Narodnaja', 'Kyzyl',
'Walbrzych', 'Swidnica', 'Klodzko', 'Raciborz', 'Gliwice',
'Brzeg', 'Krnov', 'Hradec Kralove',
'Leuk', 'Brig', 'Brienz', 'Thun', 'Sarnen', 'Burgle... | foods + weapons + tools + light + general + special) | random_line_split | |
useDragLayer.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useDragLayer = useDragLayer;
var _react = require("react");
var _useDragDropManager = require("./useDragDropManager");
var _useCollector3 = require("./useCollector");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr)... | (collect) {
var dragDropManager = (0, _useDragDropManager.useDragDropManager)();
var monitor = dragDropManager.getMonitor();
var _useCollector = (0, _useCollector3.useCollector)(monitor, collect),
_useCollector2 = _slicedToArray(_useCollector, 2),
collected = _useCollector2[0],
updateCollected ... | useDragLayer | identifier_name |
useDragLayer.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useDragLayer = useDragLayer;
var _react = require("react");
var _useDragDropManager = require("./useDragDropManager");
var _useCollector3 = require("./useCollector");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr)... |
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Argume... | { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } | identifier_body |
useDragLayer.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useDragLayer = useDragLayer;
var _react = require("react");
var _useDragDropManager = require("./useDragDropManager");
var _useCollector3 = require("./useCollector");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr)... |
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
* useDragLayer Hook
* @param collector The property collector
*/
function useDragLayer(collect) {
var dragDropManager = (0, _useDragDropManager.useDragDropManager)();
var monitor = dragDropManager.getMonitor();
var _useCollector = (0,... | function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Argument... | random_line_split |
player_loop.rs | // Tunnul
// Copyright (c) 2015, Richard Lettich
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of... | {
// Packet(Packet),
TcpErr, // Packet already formed
KeepAlive,
// Fixme, Thread to thread transmission
}
const PLAYER_STREAM: Token = Token(0);
const RECIEVER: Token = Token(1);
struct MyHandler(TcpStream);
impl Handler for MyHandler {
type Timeout = ();
type Message = ();
fn ready(&mu... | ReceiverData | identifier_name |
player_loop.rs | // Tunnul
// Copyright (c) 2015, Richard Lettich
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of... |
struct MyHandler(TcpStream);
impl Handler for MyHandler {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) {
match token {
PLAYER_STREAM => {
println!("hi");
}
_ => panic... | const PLAYER_STREAM: Token = Token(0);
const RECIEVER: Token = Token(1); | random_line_split |
player_loop.rs | // Tunnul
// Copyright (c) 2015, Richard Lettich
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of... |
fn use_entity(player: &mut Player, packet: &mut Packet) -> Option<&'static str> {
let target_id = packet.get_varint();
let interact_type = packet.getas::<u8>();
if interact_type == 2 {
let interact_location = packet.get_location();
if player.location.distance(&interact_location) > 25.0 {
... | {
unimplemented!();
} | identifier_body |
mod.rs | // Copyright 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-MIT or ... | #[derive(Copy, Clone, PartialEq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Shutdown {
/// Indicates that the reading portion of this stream/socket should be shut
/// down. All currently blocked and future reads will return `Ok(0)`.
#[stable(feature = "rust1", since = "1.0.0")]
Read,... | random_line_split | |
mod.rs | // Copyright 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-MIT or ... | (&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() }
}
/// Resolve the host specified by `host` as a number of `SocketAddr` instances.
///
/// This method may perform a DNS query to resolve `host` and may also inspect
/// system configuration to resolve the specified hostname.
///
/// # Examples
///
/// ```... | next | identifier_name |
mod.rs | // Copyright 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-MIT or ... | {
net_imp::lookup_addr(addr)
} | identifier_body | |
repro_mixin.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... | with open(fullpath, 'r') as infile:
content = infile.read()
self.assertEqual(expected_content, content) | conditional_block | |
repro_mixin.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... | content = infile.read()
self.assertEqual(expected_content, content) | random_line_split | |
repro_mixin.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... |
def assert_not_exists(self, root, path):
"""Assert a file at relpath doesn't exist
:param str root: Root directory of path.
:param str path: Path relative to tar.gz.
:return: bool
"""
fullpath = os.path.join(root, path)
self.assertFalse(os.path.exists(fullpath))
def assert_file(self,... | """Add a file with specified contents
:param str root: Root directory for path.
:param str path: Path relative to root.
:param str content: Content to write to file.
"""
fullpath = os.path.join(root, path)
safe_mkdir_for(fullpath)
with open(fullpath, 'w') as outfile:
outfile.write(con... | identifier_body |
repro_mixin.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... | (object):
""" Additional helper methods for use in Repro tests"""
def add_file(self, root, path, content):
"""Add a file with specified contents
:param str root: Root directory for path.
:param str path: Path relative to root.
:param str content: Content to write to file.
"""
fullpath = os... | ReproMixin | identifier_name |
treemap_helper.js | var core = require('../../utils/core.js');
var ERROR = require('../../utils/errors.js');
var initOption = require('../option.js').initOption;
var TreeMap = require('./treemap.js');
var TreeMapHelper = function (os, dt) {
ERROR(!d3, '0001');
var defaultOptions = {};
var defaultData = [];
var option = initOption(d... | }
}._();
};
module.exports = TreeMapHelper; | },
redraw: function () {
return this; | random_line_split |
promise-test-open-close.js | var common = require("./common")
, ibmdb = require("../")
, db = new ibmdb.Database()
, assert = require("assert");
db.query("select * from " + common.tableName).then(null, function (err) {
assert.deepEqual(err, { message: 'Connection not open.' });
assert.equal(db.connected, false);
});
db.open(common.conn... | });
})
.catch(function(err){console.log(err);})
.done(); | random_line_split | |
issue-2735-3.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 ... | (&mut self) {
self.b.set(true);
}
}
fn defer(b: &Cell<bool>) -> defer {
defer {
b: b
}
}
pub fn main() {
let dtor_ran = &Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
}
| drop | identifier_name |
issue-2735-3.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 dtor_ran = &Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
}
| {
defer {
b: b
}
} | identifier_body |
issue-2735-3.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 ... | impl<'a> Drop for defer<'a> {
fn drop(&mut self) {
self.b.set(true);
}
}
fn defer(b: &Cell<bool>) -> defer {
defer {
b: b
}
}
pub fn main() {
let dtor_ran = &Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
} | struct defer<'a> {
b: &'a Cell<bool>,
}
| random_line_split |
index.test.tsx | import * as React from 'react'
import WithStyles, {createUseStyles} from '.'
const expectType = <T extends any>(x: T): T => x
interface Props {
testProp: string
}
class TestComponent extends React.Component<Props> {
static defaultProps: Props = {
testProp: 'hello'
}
state = {message: ''}
render() {
... | // component can accept innerRef prop
return (
<>
<TestComponentWitStyles />
<TestComponentWitStyles innerRef={ref} />
<TestComponentWitStyles innerRef={refFunction} />
</>
)
}
declare global {
namespace Jss {
export interface Theme {
themeColour: string
defaultFontSiz... | function refFunction(instance: TestComponent) {
instance.setState({message: 'From ref'})
}
// component shouldn't ask to pass `testProp` | random_line_split |
index.test.tsx | import * as React from 'react'
import WithStyles, {createUseStyles} from '.'
const expectType = <T extends any>(x: T): T => x
interface Props {
testProp: string
}
class TestComponent extends React.Component<Props> {
static defaultProps: Props = {
testProp: 'hello'
}
state = {message: ''}
render() {
... | () {
const ref = React.useRef<TestComponent>()
function refFunction(instance: TestComponent) {
instance.setState({message: 'From ref'})
}
// component shouldn't ask to pass `testProp`
// component can accept innerRef prop
return (
<>
<TestComponentWitStyles />
<TestComponentWitStyles i... | testRender | identifier_name |
index.test.tsx | import * as React from 'react'
import WithStyles, {createUseStyles} from '.'
const expectType = <T extends any>(x: T): T => x
interface Props {
testProp: string
}
class TestComponent extends React.Component<Props> {
static defaultProps: Props = {
testProp: 'hello'
}
state = {message: ''}
render() {
... |
declare global {
namespace Jss {
export interface Theme {
themeColour: string
defaultFontSize: number
}
}
}
const useStyles = createUseStyles(theme => {
expectType<string>(theme.themeColour)
expectType<number>(theme.defaultFontSize)
return {
myDiv: {
color: theme.themeColour,... | {
const ref = React.useRef<TestComponent>()
function refFunction(instance: TestComponent) {
instance.setState({message: 'From ref'})
}
// component shouldn't ask to pass `testProp`
// component can accept innerRef prop
return (
<>
<TestComponentWitStyles />
<TestComponentWitStyles inne... | identifier_body |
textobject.rs | use std::default::Default;
use editor::text_editor::buffer::Mark;
#[derive(Copy, Clone, Debug)]
pub enum Kind {
Char,
Line(Anchor),
Word(Anchor),
// Sentence(Anchor),
// Paragraph(Anchor),
// Expression(Anchor),
// Statement(Anchor),
// Block(Anchor),
}
impl Kind {
pub fn with_a... |
}
#[derive(Copy, Clone, Debug)]
pub enum Anchor {
Before, // Index just prior to TextObject
Start, // First index within TextObject
// Middle, // Middle index of TextObject
End, // Last index within TextObject
After, // First index after TextObject
Same, // Same as ... | {
Kind::Char
} | identifier_body |
textobject.rs | use std::default::Default;
use editor::text_editor::buffer::Mark;
#[derive(Copy, Clone, Debug)]
pub enum Kind {
Char,
Line(Anchor),
Word(Anchor),
// Sentence(Anchor),
// Paragraph(Anchor),
// Expression(Anchor),
// Statement(Anchor),
// Block(Anchor),
}
impl Kind {
pub fn with_a... | pub enum Anchor {
Before, // Index just prior to TextObject
Start, // First index within TextObject
// Middle, // Middle index of TextObject
End, // Last index within TextObject
After, // First index after TextObject
Same, // Same as index within current TextObject of... | random_line_split | |
textobject.rs | use std::default::Default;
use editor::text_editor::buffer::Mark;
#[derive(Copy, Clone, Debug)]
pub enum Kind {
Char,
Line(Anchor),
Word(Anchor),
// Sentence(Anchor),
// Paragraph(Anchor),
// Expression(Anchor),
// Statement(Anchor),
// Block(Anchor),
}
impl Kind {
pub fn with_a... | {
pub kind: Kind,
pub offset: Offset
}
impl Default for TextObject {
fn default() -> TextObject {
TextObject {
kind: Default::default(),
offset: Default::default()
}
}
}
| TextObject | identifier_name |
sistema.js | /**
*
* @author xedushx
*/
$(document).bind("touchmove", function (event) {
event.preventDefault();
});
/*
* Función que permite bloquear la pantalla mientras esta procesando
*/
$(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
});
/*
* Función que bloquea la tecla F5 y Enter de ... | {
var na = $(window).height();
var me = $('#formulario\\:menu').height();
var alto = na - me - 45;
alto = parseInt(alto);
document.getElementById('formulario:ith_alto').value = alto;
document.getElementById('formulario:alto').value = na;
var ancho = $(window).width();
document.getElement... | ensionesDisponibles() | identifier_name |
sistema.js | /**
*
* @author xedushx
*/
$(document).bind("touchmove", function (event) {
event.preventDefault();
});
/*
* Función que permite bloquear la pantalla mientras esta procesando
*/
$(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
});
/*
* Función que bloquea la tecla F5 y Enter de ... | w = window.open(dir, "", "width=" + screen.availWidth + ", height=" + screen.availHeight + ", screenX=0,screenY=0, top=0, left=0, status=0 , resizable=yes, scrollbars=yes");
w.focus();
}
| identifier_body | |
sistema.js | /**
*
* @author xedushx
*/
$(document).bind("touchmove", function (event) {
event.preventDefault();
});
/*
* Función que permite bloquear la pantalla mientras esta procesando
*/
$(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
});
/*
* Función que bloquea la tecla F5 y Enter de ... | if (code == 38) {
teclaArriba();
e.preventDefault();
}
}
});
});
/*
*Función Desabilitar el clik derecho
*/
//$(function() {
// $(document).ready(function(){
// $(document).bind("contextmenu",function(e){
// return false;
// ... | teclaAbajo();
e.preventDefault();
}
| conditional_block |
sistema.js | /**
*
* @author xedushx
*/
$(document).bind("touchmove", function (event) {
event.preventDefault();
});
/*
* Función que permite bloquear la pantalla mientras esta procesando
*/
$(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
});
/* | if ($('#formulario\\:menu').length) {
var code = (e.keyCode ? e.keyCode : e.which);
//if(code == 116 || code == 13) {
if (code == 13) {
e.preventDefault();
}
if (code == 40) {
teclaAbajo();
e.preventDefau... | * Función que bloquea la tecla F5 y Enter de la pagina y detectar tecla arriba y abajo
*/
$(function () {
$(document).keydown(function (e) { | random_line_split |
1strandbushinga002.py | = []
zpath = []
step = []
epath = []
xstart = 10.0
ystart = 10.0
zstart = 0.5
height = 0.0
LayerHeight = 0.3
ExtrusionWidth = 0.6
FilamentDiameter=3
FilamentArea = FilamentDiameter * FilamentDiameter * 3.14159 / 4.0
GooCoefficient = LayerHeight * ExtrusionWidth / FilamentArea
configlist = [LayerHeight, ExtrusionWidth,... | goutput.write("G1 X" );
goutput.write( str(xpath[x]) );
goutput.write( " Y" );
goutput.write( str(ypath[x]) );
goutput.write( " Z" );
goutput.write( str(zpath[x]) );
goutput.write( " E" );
goutput.write( str(epath[x]) );
goutput.write( " F2000 \n" ); | conditional_block | |
1strandbushinga002.py | print "This program is for printing the best possible circular bushings"
print "Printer config values are hardcoded for ease of use (for me)"
xpath = [] #These are initialized and default values
ypath = []
zpath = []
step = []
epath = []
xstart = 10.0
ystart = 10.0
zstart = 0.5
height = 0.0
LayerHeight = 0.3
Extrusion... | # xpath.append(centerx+radius*math.cos(i*anglestep))
# ypath.append(centery+radius*math.sin(i*anglestep))
# zpath.append(CurrentHeight)
##odd layers are outside to inside, to maintain strand continuity
#CurrentLayer=3
#CurrentHeight=LayerHeight*CurrentLayer
#j=0
#i=0
#radius = OuterDiameter/2 - ... | # while (i<N):
# i=i+1
# #print "i=", i, "j=", j, "radius=", radius | random_line_split |
reducer.py | #! /usr/bin/python
import sys
sys.path.append('../')
from toolbox.hreaders import token_readers as reader
from toolbox.hreducers import list_reducer as reducer
SOLO_FACTURA = False
def reduction(x,y):
v1 = x.split(',')
v2 = y.split(',')
r = x if int(v1[1])>=int(v2[1]) else y
return r
_reader = reader... |
else:
for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(K,V)
print '{}\t{}'.format(key,V) | for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(V.split(',')[0],V.split(',')[1])
V = _reducer.out.split(',')
print '{}\t{}'.format(V[0],V[1]) | conditional_block |
reducer.py | #! /usr/bin/python
import sys
sys.path.append('../')
from toolbox.hreaders import token_readers as reader
from toolbox.hreducers import list_reducer as reducer
SOLO_FACTURA = False
def | (x,y):
v1 = x.split(',')
v2 = y.split(',')
r = x if int(v1[1])>=int(v2[1]) else y
return r
_reader = reader.Token_reader("\t",1)
_reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element
if SOLO_FACTURA:
for line in sys.stdin:
key, value = _reader.read_all(l... | reduction | identifier_name |
reducer.py | #! /usr/bin/python
import sys
sys.path.append('../')
from toolbox.hreaders import token_readers as reader
from toolbox.hreducers import list_reducer as reducer
SOLO_FACTURA = False
def reduction(x,y):
v1 = x.split(',')
v2 = y.split(',')
r = x if int(v1[1])>=int(v2[1]) else y
return r
_reader = reader... | _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element
if SOLO_FACTURA:
for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(V.split(',')[0],V.split(',')[1])
V = _reducer.ou... | random_line_split | |
reducer.py | #! /usr/bin/python
import sys
sys.path.append('../')
from toolbox.hreaders import token_readers as reader
from toolbox.hreducers import list_reducer as reducer
SOLO_FACTURA = False
def reduction(x,y):
|
_reader = reader.Token_reader("\t",1)
_reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element
if SOLO_FACTURA:
for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(V.split(',')... | v1 = x.split(',')
v2 = y.split(',')
r = x if int(v1[1])>=int(v2[1]) else y
return r | identifier_body |
print.d.ts | *
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
export declare const printReceivedStringContainExpectedSubstring: (received: string, start: number, length: number) => string;
export declare const printReceivedStringContainExpectedRe... | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. | random_line_split | |
e05-atexit-type.rs | /// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit
/// handler. Redo the prototype for atexit using this data type.
///
/// $ e05-atexit-type
/// main is done
/// first exit handler
/// first exit handler
/// second exit handler
extern crate libc;
#[macro_use(cstr)]
extern c... | () {
unsafe { printf(cstr!("second exit handler\n")) };
}
fn main() {
my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno()));
my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno()));
my_atexit(my_exit1).expect(&format!("can't register my_exit1: {... | my_exit2 | identifier_name |
e05-atexit-type.rs | /// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit
/// handler. Redo the prototype for atexit using this data type.
///
/// $ e05-atexit-type
/// main is done
/// first exit handler
/// first exit handler
/// second exit handler
extern crate libc;
#[macro_use(cstr)]
extern c... |
extern "C" fn my_exit2() {
unsafe { printf(cstr!("second exit handler\n")) };
}
fn main() {
my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno()));
my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno()));
my_atexit(my_exit1).expect(&format!("ca... | {
unsafe { printf(cstr!("first exit handler\n")) };
} | identifier_body |
e05-atexit-type.rs | /// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit
/// handler. Redo the prototype for atexit using this data type.
///
/// $ e05-atexit-type
/// main is done
/// first exit handler
/// first exit handler
/// second exit handler
extern crate libc;
#[macro_use(cstr)]
extern c... | unsafe { atexit(f).check_not_negative() }
}
extern "C" fn my_exit1() {
unsafe { printf(cstr!("first exit handler\n")) };
}
extern "C" fn my_exit2() {
unsafe { printf(cstr!("second exit handler\n")) };
}
fn main() {
my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno()));
... | random_line_split | |
main.rs | extern crate iron;
extern crate logger;
extern crate router;
extern crate hyper;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate log;
extern crate env_logger;
use std::str::FromStr;
use std::io::Read;
use iron::prelude::*;
use router::Router;
... |
let mut body = Vec::new();
req.body.read_to_end(&mut body);
self.client.request(req.method.clone(), &url_base)
.headers(req.headers.clone())
.body(Body::BufBody(body.as_slice(), body.len()))
.send()
.unwrap();
}
fn new(protocol:... | {
url_base.push_str("?");
url_base.push_str(q);
} | conditional_block |
main.rs | extern crate iron;
extern crate logger;
extern crate router;
extern crate hyper;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate log;
extern crate env_logger;
use std::str::FromStr;
use std::io::Read;
use iron::prelude::*;
use router::Router;
... | }
let mut body = Vec::new();
req.body.read_to_end(&mut body);
self.client.request(req.method.clone(), &url_base)
.headers(req.headers.clone())
.body(Body::BufBody(body.as_slice(), body.len()))
.send()
.unwrap();
}
fn new(... | random_line_split | |
main.rs | extern crate iron;
extern crate logger;
extern crate router;
extern crate hyper;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate log;
extern crate env_logger;
use std::str::FromStr;
use std::io::Read;
use iron::prelude::*;
use router::Router;
... |
fn rate_handler(req: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Hello admin")))
}
fn buffer_handler(req: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Hello admin")))
}
fn get_target(req: &mut Request) -> IronResult<Response> {
Ok(Respons... | {
let stats = Stats {
requests_forwarded: 345242,
target_requests_per_second: 250.,
average_requests_per_second: 261.,
max_requests_per_second: 342.,
buffer_size_in_bytes: 5098231,
};
Ok(Response::with((iron::status::Ok,
serde_json::to_string(&stats).unwrap(... | identifier_body |
main.rs | extern crate iron;
extern crate logger;
extern crate router;
extern crate hyper;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate log;
extern crate env_logger;
use std::str::FromStr;
use std::io::Read;
use iron::prelude::*;
use router::Router;
... | () {
env_logger::init().unwrap();
let (logger_before, logger_after) = Logger::new(None);
let mut forward_chain = Chain::new(forward);
forward_chain.link_before(logger_before);
forward_chain.link_after(logger_after);
let forward_server = Iron::new(forward_chain).http("localhost:6666");
let ... | main | identifier_name |
macros.py | #Macros commonly used
_be = "(be|is|am|are|were|was|been|being)"
_intensadj1 = "( absolutely| absurdly| resoundingly | amazingly | awfully | extremely | completely | highly | incredibly | perfectly | quite | really | strikingly | surprisingly | terribly | totally | unbelievably | hugely | unnaturally | unusually | utte... | _emo1v= "(like| adore| want| prefer| love| enjoy)" | _GONNANEG= "( am not going to| are not going to| is not going to| am not gonna| are not gonna| is not gonna| ain\'t gonna| isn\'t gonna| aren\'t gonna)"
_GONNACL = "( i\'m going to| they\'re going to| she\'s going to| it\'s going to| we\'re going to| i\'m gonna| you\'re gonna| i\'m gonna| you\'re gonna| he\'s gonna| sh... | random_line_split |
roboclaw_simplepwm.py | import time
from roboclaw import Roboclaw
#Windows comport name
rc = Roboclaw("COM11",115200)
#Linux comport name
#rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
address = 0x80
while(1):
rc.ForwardM1(address,32) #1/4 power forward
rc.BackwardM2(address,32) #1/4 power backward
time.sleep(2)
rc.B... |
m1duty = 16
m2duty = -16
rc.ForwardBackwardM1(address,64+m1duty) #1/4 power forward
rc.ForwardBackwardM2(address,64+m2duty) #1/4 power backward
time.sleep(2)
m1duty = -16
m2duty = 16
rc.ForwardBackwardM1(address,64+m1duty) #1/4 power backward
rc.ForwardBackwardM2(address,64+m2duty) #1/4 power forw... | time.sleep(2)
rc.BackwardM1(address,0) #Stopped
rc.ForwardM2(address,0) #Stopped
time.sleep(2)
| random_line_split |
roboclaw_simplepwm.py | import time
from roboclaw import Roboclaw
#Windows comport name
rc = Roboclaw("COM11",115200)
#Linux comport name
#rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
address = 0x80
while(1):
| rc.ForwardBackwardM1(address,64+m1duty) #1/4 power backward
rc.ForwardBackwardM2(address,64+m2duty) #1/4 power forward
time.sleep(2)
rc.ForwardBackwardM1(address,64) #Stopped
rc.ForwardBackwardM2(address,64) #Stopped
time.sleep(2)
| rc.ForwardM1(address,32) #1/4 power forward
rc.BackwardM2(address,32) #1/4 power backward
time.sleep(2)
rc.BackwardM1(address,32) #1/4 power backward
rc.ForwardM2(address,32) #1/4 power forward
time.sleep(2)
rc.BackwardM1(address,0) #Stopped
rc.ForwardM2(address,0) #Stopped
time.sleep(2)
m1dut... | conditional_block |
2dEnv.js | //var socket = io.connect('http://localhost:8081');
//////////////////////////////////////////////////////////////Player design//////////////////////////////////////////////////////////////
//$("#player_detect").css({ 'position': 'absolute','z-index': '10', 'background-color': 'green','height': '1.5%', 'width': '1%'... | () {
// var socket = io.connect('http://localhost:8081');
var cene = $('#cene');
var playerdiv = $('#player_detect');
// var camera = $('#player_div');
var cene = $('#cene');
var x = cene.offset().left;
var y = cene.offset().top;
///////////////////////position feedback/////////////////////
//var cord = {... | terminal | identifier_name |
2dEnv.js | //var socket = io.connect('http://localhost:8081');
//////////////////////////////////////////////////////////////Player design//////////////////////////////////////////////////////////////
//$("#player_detect").css({ 'position': 'absolute','z-index': '10', 'background-color': 'green','height': '1.5%', 'width': '1%'... | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var player = $('#player_detect');
var camera = $('#player_div');
newPos = new Object();
newPos.left = -camera.offset().left;
newPos.top = -camera... | $("#container").css({ 'position': 'absolute','z-index':'-10', 'background-color': '','height': gameBGResCX, 'width': gameBGResCY,'left': '0%','top':'0%' });
$("#cenario").css({ 'opacity':'0.3','z-index':'3','position': 'absolute','background-image': 'url("'+floorbackimg+'")','background-size': '100% 100%','height': g... | random_line_split |
2dEnv.js | //var socket = io.connect('http://localhost:8081');
//////////////////////////////////////////////////////////////Player design//////////////////////////////////////////////////////////////
//$("#player_detect").css({ 'position': 'absolute','z-index': '10', 'background-color': 'green','height': '1.5%', 'width': '1%'... | ;
terminal();
}, refreshScreen);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| {
// var socket = io.connect('http://localhost:8081');
var cene = $('#cene');
var playerdiv = $('#player_detect');
// var camera = $('#player_div');
var cene = $('#cene');
var x = cene.offset().left;
var y = cene.offset().top;
///////////////////////position feedback/////////////////////
//var cord = {x, ... | identifier_body |
slushfile.js | /*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = req... |
var defaults = (function () {
var workingDirName = path.basename(process.cwd()),
homeDir, osUserName, configFile, user;
if (process.platform === 'win32') {
homeDir = process.env.USERPROFILE;
osUserName = process.env.USERNAME || path.basename(homeDir).toLowerCase();
}
else {
... | {
var username = string.toLowerCase();
return username.replace(/\s/g, '');
} | identifier_body |
slushfile.js | /*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = req... |
return {
appName: workingDirName,
userName: osUserName || format(user.name || ''),
authorName: user.name || '',
authorEmail: user.email || ''
};
})();
gulp.task('default', function (done) {
var prompts = [{
name: 'appName',
message: 'What is the name of you... | {
user = require('iniparser').parseSync(configFile).user;
} | conditional_block |
slushfile.js | /*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = req... | var workingDirName = path.basename(process.cwd()),
homeDir, osUserName, configFile, user;
if (process.platform === 'win32') {
homeDir = process.env.USERPROFILE;
osUserName = process.env.USERNAME || path.basename(homeDir).toLowerCase();
}
else {
homeDir = process.env.HOME |... | var defaults = (function () { | random_line_split |
slushfile.js | /*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = req... | (string) {
var username = string.toLowerCase();
return username.replace(/\s/g, '');
}
var defaults = (function () {
var workingDirName = path.basename(process.cwd()),
homeDir, osUserName, configFile, user;
if (process.platform === 'win32') {
homeDir = process.env.USERPROFILE;
osU... | format | identifier_name |
exc.py | """Exceptions used by basic support utilities."""
__author__ = "Ian Goodfellow"
import sys
from pylearn2.utils.common_strings import environment_variable_essay
from theano.compat import six
class EnvironmentVariableError(Exception):
"""
An exception raised when a required environment variable is not defined
... | --------
>>> try:
... do_something_crazy()
... except Exception:
... reraise_as(UnhandledException("Informative message"))
"""
orig_exc_type, orig_exc_value, orig_exc_traceback = sys.exc_info()
if isinstance(new_exc, six.string_types):
new_exc = orig_exc_type(new_exc)
... | """
Re-raise current exception as a new exception.
Parameters
----------
new_exc : Exception isinstance
The new error to be raised e.g. (ValueError("New message"))
or a string that will be prepended to the original exception
message
Notes
-----
Note that when rerais... | identifier_body |
exc.py | """Exceptions used by basic support utilities."""
__author__ = "Ian Goodfellow"
import sys
from pylearn2.utils.common_strings import environment_variable_essay
from theano.compat import six
class EnvironmentVariableError(Exception):
"""
An exception raised when a required environment variable is not defined
... |
new_exc.args = (new_message,) + new_exc.args[1:]
new_exc.__cause__ = orig_exc_value
new_exc.reraised = True
six.reraise(type(new_exc), new_exc, orig_exc_traceback)
| new_message += ': ' + ', '.join(str(arg)
for arg in orig_exc_value.args) | conditional_block |
exc.py | """Exceptions used by basic support utilities."""
__author__ = "Ian Goodfellow"
import sys
from pylearn2.utils.common_strings import environment_variable_essay
from theano.compat import six
class EnvironmentVariableError(Exception):
"""
An exception raised when a required environment variable is not defined
... | You need to define your PYLEARN2_DATA_PATH environment variable. If you are
using a computer at LISA, this should be set to /data/lisa/data.
"""
def reraise_as(new_exc):
"""
Re-raise current exception as a new exception.
Parameters
----------
new_exc : Exception isinstance
The new error t... | data_path_essay = """\ | random_line_split |
exc.py | """Exceptions used by basic support utilities."""
__author__ = "Ian Goodfellow"
import sys
from pylearn2.utils.common_strings import environment_variable_essay
from theano.compat import six
class EnvironmentVariableError(Exception):
"""
An exception raised when a required environment variable is not defined
... | (self):
super(NoDataPathError, self).__init__(data_path_essay +
environment_variable_essay)
data_path_essay = """\
You need to define your PYLEARN2_DATA_PATH environment variable. If you are
using a computer at LISA, this should be set to /data/lisa/data.
"""
def... | __init__ | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | #
##############################################################################
from . import test_rule_rounding
from . import test_rule_currency | # GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
test_variable.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | (unittest.TestCase):
def setUp(self):
crypto._fernet = None
def tearDown(self):
crypto._fernet = None
@conf_vars({('core', 'fernet_key'): ''})
def test_variable_no_encryption(self):
"""
Test variables without encryption
"""
Variable.set('key', 'value')
... | TestVariable | identifier_name |
test_variable.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
def test_var_with_encryption_rotate_fernet_key(self):
"""
Tests rotating encrypted variables.
"""
key1 = Fernet.generate_key()
key2 = Fernet.generate_key()
with conf_vars({('core', 'fernet_key'): key1.decode()}):
Variable.set('key', 'value')
... | """
Test variables with encryption
"""
Variable.set('key', 'value')
session = settings.Session()
test_var = session.query(Variable).filter(Variable.key == 'key').one()
self.assertTrue(test_var.is_encrypted)
self.assertEqual(test_var.val, 'value') | identifier_body |
test_variable.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | self.assertTrue(test_var.is_encrypted)
self.assertEqual(test_var.val, 'value')
def test_var_with_encryption_rotate_fernet_key(self):
"""
Tests rotating encrypted variables.
"""
key1 = Fernet.generate_key()
key2 = Fernet.generate_key()
with conf_vars(... | """
Variable.set('key', 'value')
session = settings.Session()
test_var = session.query(Variable).filter(Variable.key == 'key').one() | random_line_split |
interfaces.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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... |
class SubflowPlaceable(BasePlaceable):
pass
class Delimiter(object):
pass
class PairedDelimiter(object):
pass
| pass | identifier_body |
interfaces.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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... | This file contains abstract (semantic) interfaces for placeable
implementations.
"""
from translate.storage.placeables.strelem import StringElem
class BasePlaceable(StringElem):
"""Base class for all placeables."""
parse = None
class InvisiblePlaceable(BasePlaceable):
pass
class MaskingPlaceable(Bas... | random_line_split | |
interfaces.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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... | (BasePlaceable):
pass
class Delimiter(object):
pass
class PairedDelimiter(object):
pass
| SubflowPlaceable | identifier_name |
core.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... | (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _immutable = require('immutable');
var _immutable2 = _interopRequireDefault(_immutable);
var _action = require('./action');
var _action2 = _interopRequireDefault(_action);
var _rx =... | _classCallCheck | identifier_name |
core.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... |
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call ... | { return obj && obj.__esModule ? obj : { 'default': obj }; } | identifier_body |
core.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... |
var newActions = _immutable2['default'].Map({});
actionNames.forEach(function (name) {
return newActions = newActions.set(name, new _action2['default']());
});
this._actions = newActions.merge(this._actions);
return this._actions.toObject();
}
}, {
key: 'createStores',
... | {
actionNames[_key] = arguments[_key];
} | conditional_block |
core.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... |
return (_Rx$Observable = _rx2['default'].Observable).merge.apply(_Rx$Observable, _toConsumableArray(this._getObservables('_stores', stores))).map(function () {
return stores.map(function (name) {
return _this2.get(name);
});
});
}
}, {
key: 'waitForStores',
value: fu... | stores[_key2] = arguments[_key2];
} | random_line_split |
volumeEditor.py | ; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more d... |
def closeEvent(self, event):
event.accept()
def setLabelSink(self, labelsink):
self.brushingController.setDataSink(labelsink)
##
## private
##
def _initImagePumps( self ):
alongTXC = SliceProjection( abscissa = 2, ordinate = 3, along = [0,1,4] )
alongTYC = Sli... | QApplication.processEvents()
for scene in self._imageViews:
scene.close()
scene.deleteLater()
self._imageViews = []
QApplication.processEvents() | identifier_body |
volumeEditor.py | Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License... | self.posModel = PositionModel()
self.brushingModel = BrushingModel()
self.cropModel = CropExtentsModel( self )
self.imageScenes = [ImageScene2D(self.posModel, (0,1,4), swapped_default=True),
ImageScene2D(self.posModel, (0,2,4)),
Im... | random_line_split | |
volumeEditor.py | ; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more d... | (self, show):
for s in self.imageScenes:
s.showTileProgress = show
self._showTileProgress = show
@property
def cacheSize(self):
return self._cacheSize
@cacheSize.setter
def cacheSize(self, cache_size):
self._cacheSize = cache_size
for s in self.imageS... | showTileProgress | identifier_name |
volumeEditor.py | Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License... |
self._showTileProgress = show
@property
def cacheSize(self):
return self._cacheSize
@cacheSize.setter
def cacheSize(self, cache_size):
self._cacheSize = cache_size
for s in self.imageScenes:
s.setCacheSize(cache_size)
@property
def navigationInterpr... | s.showTileProgress = show | conditional_block |
fc_scan.py | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import re
from waflib import Utils,Task,TaskGen,Logs
from waflib.TaskGen import feature,before_method,after_method,extension
from waflib.Configure import conf
INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)... | uses=[]
mods=[]
for line in txt.splitlines():
m=re_inc.search(line)
if m:
incs.append(m.group(1))
m=re_use.search(line)
if m:
uses.append(m.group(1))
m=re_mod.search(line)
if m:
mods.append(m.group(1))
return(incs,uses,mods)
def start(self,node):
self.waiting=[node]
while self... | def find_deps(self,node):
txt=node.read()
incs=[] | random_line_split |
fc_scan.py | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import re
from waflib import Utils,Task,TaskGen,Logs
from waflib.TaskGen import feature,before_method,after_method,extension
from waflib.Configure import conf
INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)... |
def iter(self,node):
path=node.abspath()
incs,uses,mods=self.find_deps(node)
for x in incs:
if x in self.seen:
continue
self.seen.append(x)
self.tryfind_header(x)
for x in uses:
name="USE@%s"%x
if not name in self.names:
self.names.append(name)
for x in mods:
name="MOD@%s"%x
if ... | self.waiting=[node]
while self.waiting:
nd=self.waiting.pop(0)
self.iter(nd) | identifier_body |
fc_scan.py | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import re
from waflib import Utils,Task,TaskGen,Logs
from waflib.TaskGen import feature,before_method,after_method,extension
from waflib.Configure import conf
INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)... |
for x in mods:
name="MOD@%s"%x
if not name in self.names:
self.names.append(name)
def tryfind_header(self,filename):
found=None
for n in self.incpaths:
found=n.find_resource(filename)
if found:
self.nodes.append(found)
self.waiting.append(found)
break
if not found:
if not filena... | name="USE@%s"%x
if not name in self.names:
self.names.append(name) | conditional_block |
fc_scan.py | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import re
from waflib import Utils,Task,TaskGen,Logs
from waflib.TaskGen import feature,before_method,after_method,extension
from waflib.Configure import conf
INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)... | (self,filename):
found=None
for n in self.incpaths:
found=n.find_resource(filename)
if found:
self.nodes.append(found)
self.waiting.append(found)
break
if not found:
if not filename in self.names:
self.names.append(filename)
| tryfind_header | identifier_name |
ViewingRoomApp_viewingRoom.graphql.ts | /* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ViewingRoomApp_viewingRoom = {
readonly partner: {
readonly internalID: string;
} | null; | readonly " $refType": "ViewingRoomApp_viewingRoom";
};
export type ViewingRoomApp_viewingRoom$data = ViewingRoomApp_viewingRoom;
export type ViewingRoomApp_viewingRoom$key = {
readonly " $data"?: ViewingRoomApp_viewingRoom$data;
readonly " $fragmentRefs": FragmentRefs<"ViewingRoomApp_viewingRoom">;
};
co... | readonly status: string;
readonly " $fragmentRefs": FragmentRefs<"ViewingRoomMeta_viewingRoom" | "ViewingRoomHeader_viewingRoom" | "ViewingRoomContentNotAccessible_viewingRoom">; | random_line_split |
worker.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::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe... | (address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.to_temporary().root();
let global = worker.r().global.root();
let error = UndefinedValue();
let target: JSRef<EventTarget> = EventTarge... | handle_error_message | identifier_name |
worker.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::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe... | }
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.to_temporary().root();
let global = worker.r().global.root();
let error = UndefinedValue();
let t... | let message = data.read(global.r());
MessageEvent::dispatch_jsval(target, global.r(), message); | random_line_split |
worker.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::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe... |
pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Temporary<Worker> {
reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
// http://www.whatwg.org/html/#dom-worker
... | {
Worker {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker),
refcount: Cell::new(0),
global: GlobalField::from_rooted(&global),
sender: sender,
}
} | identifier_body |
index.js | const path = require('path');
const consoleLogger = require('./logger'); | const _ = require('lodash');
module.exports = (config, logger, metrics, next) => {
if (!next) { next = metrics; metrics = { increment: _.noop }; }
if (!next) { next = logger; logger = consoleLogger; }
require('../db')(config, logger, (err, client) => {
if (err) { return next(err); }
const messaging = r... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.