file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
accessibilityHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
@editorAction
class ShowAccessibilityHelpAction extends EditorAction {
constructor() {
super({
id: 'editor.action.showAccessibilityHelp',
label: nls.localize("ShowAccessibilityHelpAction", "Show Accessibility Help"),
alias: 'Show Accessibility Help',
precondition: null,
kbOpts: {
kbExpr: Editor... | this._domNode.setLeft(left);
} | random_line_split |
lexer.py | try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... | BASE_NAME = r"[a-zA-Z_][a-zA-Z0-9_]*"
class XPythonLexer(PythonLexer):
tokens = PythonLexer.tokens.copy()
tokens["classname"] = [
("'?[a-zA-Z_][a-zA-Z0-9_.]*'?", Name.Class, "#pop")
]
# Marker __repr__
ref = "(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)(... | conditional_block | |
lexer.py | try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... | (PythonTracebackLexer):
tokens = {
"root": [
include("entry"),
include("exception"),
(r"^.*\n", Generic.Error),
],
"entry": [
(r"^Traceback \(most recent call last\):\n",
Generic.Error,
... | PythonXTracebackLexer | identifier_name |
lexer.py | try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... | bygroups(Generic.Error, Name.Builtin, Operator.Word,
Generic.Error, Number, Generic.Error, Name.Function,
Text),
"frame"),
],
"exception": [
(r"^(AssertionError: )(.+\n)", bygroups(Generic.Error,
... | "frame"),
# file - path is colored differently if under working directory
(r'^( File )((?:"[./<][^"]+")?)((?:"[^"]+")?)' \
'(, line )(\d+)((?:, in )?)(.*)(\n)', | random_line_split |
lexer.py | try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... | tokens = {
"root": [
include("entry"),
include("exception"),
(r"^.*\n", Generic.Error),
],
"entry": [
(r"^Traceback \(most recent call last\):\n",
Generic.Error,
"frame"),
... | identifier_body | |
searchService.js | /*
* ***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
* ***************************************************
*/
angular.module(
'de.cismet.sip-html5-resource-registration.services'
).factory('de.cismet.sip-html5-resourc... | console.error("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ... | var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) { | random_line_split |
angular-file-upload-shim.js | /**!
* AngularJS file upload shim for HTML5 FormData
* @author Danial <danial.farid@gmail.com>
* @version <%= pkg.version %>
*/
(function() {
var hasFlash = function() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch(e) {
if (navigator.mimeTypes["applic... | ;
var listener = function(evt) {
if (!loadStarted) {
loadStarted = true;
_this.onloadstart && this.onloadstart(constructEvent('loadstart', evt));
}
if (evt.type === 'load') {
_this.onloadend && _this.onloadend(constructEvent('loadend', evt));
var e = constructEvent('load', evt);
_this.onl... | {
var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
if (evt.result != null) e.target.result = evt.result;
return e;
} | identifier_body |
angular-file-upload-shim.js | /**!
* AngularJS file upload shim for HTML5 FormData
* @author Danial <danial.farid@gmail.com>
* @version <%= pkg.version %>
*/
(function() {
var hasFlash = function() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch(e) {
if (navigator.mimeTypes["applic... | return function() {
var xhr = new origXHR();
xhr.setRequestHeader = (function(orig) {
return function(header, value) {
if (header === '__setXHR_') {
var val = value(xhr);
// fix for angular < 1.2.0
if (val instanceof Function) {
val(xhr);
}
} else {
... | window.XMLHttpRequest = (function(origXHR) { | random_line_split |
angular-file-upload-shim.js | /**!
* AngularJS file upload shim for HTML5 FormData
* @author Danial <danial.farid@gmail.com>
* @version <%= pkg.version %>
*/
(function() {
var hasFlash = function() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch(e) {
if (navigator.mimeTypes["applic... |
}
}
if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;
script.setAttribute('src', jsUrl || basePath + "FileAPI.min.js");
document.getElementsByTagName('head')[0].appendChild(script);
FileAPI.hasFlash = hasFlash();
}
})();
}
if (!window.FileReader) {
window.FileReader = function() ... | {
basePath = src.substring(0, index);
break;
} | conditional_block |
angular-file-upload-shim.js | /**!
* AngularJS file upload shim for HTML5 FormData
* @author Danial <danial.farid@gmail.com>
* @version <%= pkg.version %>
*/
(function() {
var hasFlash = function() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch(e) {
if (navigator.mimeTypes["applic... | (type, evt) {
var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
if (evt.result != null) e.target.result = evt.result;
return e;
};
var listener = function(evt) {
if (!loadStarted) {
loadStarted = true;
_this.onloadstart && this.onloadstart(constructEven... | constructEvent | identifier_name |
offline.interceptor.js | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, e... | );
| var canDisplayModal = true,
interceptor = {
request: request
};
return interceptor;
/**
* @ngdoc method
* @methodOf openlmis-offline.offlineInterceptor
* @name request
*
* @description
* Cancels request ... | identifier_body |
offline.interceptor.js | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, e... | }
canceler.resolve();
}
return config;
}
}
})();
| canDisplayModal = false;
$injector.get('alertService')
.error('openlmisOffline.actionNotAllowedOffline')
.finally(function() {
canDisplayModal = true;
});
... | conditional_block |
offline.interceptor.js | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, e... | * @description
* Responsible for managing server requests while offline.
*/
angular
.module('openlmis-offline')
.factory('offlineInterceptor', factory)
.config(config);
config.$inject = ['$httpProvider'];
factory.$inject = ['$q', '$injector', 'offlineService'];
... | /**
* @ngdoc service
* @name openlmis-offline.offlineInterceptor
* | random_line_split |
offline.interceptor.js | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, e... | pProvider) {
$httpProvider.interceptors.push('offlineInterceptor');
}
function factory($q, $injector, offlineService) {
var canDisplayModal = true,
interceptor = {
request: request
};
return interceptor;
/**
* @ngdoc method
... | g($htt | identifier_name |
env.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 ... | /// Poison allocations on free
poison_on_free: bool,
/// The argc value passed to main
argc: c_int,
/// The argv value passed to main
argv: **c_char,
/// Print GC debugging info
debug_mem: bool
}
/// Get the global environment settings
/// # Safety Note
/// This will abort the process i... | logspec: *c_char,
/// Record and report detailed information about memory leaks
detailed_leaks: bool,
/// Seed the random number generator
rust_seed: *c_char, | random_line_split |
env.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 ... | {
/// The number of threads to use by default
num_sched_threads: size_t,
/// The minimum size of a stack segment
min_stack_size: size_t,
/// The maximum amount of total stack per task before aborting
max_stack_size: size_t,
/// The default logging configuration
logspec: *c_char,
///... | Environment | identifier_name |
env.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 ... |
extern {
fn rust_get_rt_env() -> &Environment;
}
| {
unsafe { rust_get_rt_env() }
} | identifier_body |
task.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | /// println!("Hello with a native runtime!");
/// }).destroy();
/// # }
/// ```
pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> {
assert!(!self.is_destroyed(), "cannot re-use a destroyed task");
// First, make sure that no one else is in TLS. This does not allow
// r... | /// task.run(|| { | random_line_split |
task.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (mut self: Box<Task>) {
let ops = self.imp.take().unwrap();
ops.yield_now(self);
}
/// Similar to `yield_now`, except that this function may immediately return
/// without yielding (depending on what the runtime decides to do).
pub fn maybe_yield(mut self: Box<Task>) {
let ops =... | yield_now | identifier_name |
task.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
Shared(arc) => {
let blocked_task_ptr: uint = mem::transmute(box arc);
rtassert!(blocked_task_ptr & 0x1 == 0);
blocked_task_ptr | 0x1
}
}
}
/// Convert from an unsafe uint value. Useful for retrieving a pipe's state
/// flag.
... | {
let blocked_task_ptr: uint = mem::transmute(task);
rtassert!(blocked_task_ptr & 0x1 == 0);
blocked_task_ptr
} | conditional_block |
task.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
/// Create a blocked task, unless the task was already killed.
pub fn block(task: Box<Task>) -> BlockedTask {
Owned(task)
}
/// Converts one blocked task handle to a list of many handles to the same.
pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> {
let arc =... | { assert!(self.wake().is_none()); } | identifier_body |
reducer_qos_test.ts | jest.mock("../../redux/store", () => ({
store: {
dispatch: jest.fn(),
getState: jest.fn(() => ({ NO: "NO" })),
}
}));
import { connectivityReducer, DEFAULT_STATE } from "../reducer";
import { Actions } from "../../constants";
import { pingOK, pingNO } from "..";
import { store } from "../../redux/store";
i... | it("marks pings as failed when PING_NO is dispatched", () => {
const action = { type: Actions.PING_NO, payload: { id: "yep", at: 123 } };
const state = connectivityReducer(newState(), action);
const { yep } = state.pings;
expect(yep).toBeTruthy();
if (yep) {
expect(yep.kind).toEqual("timeout... | });
});
| random_line_split |
reducer_qos_test.ts | jest.mock("../../redux/store", () => ({
store: {
dispatch: jest.fn(),
getState: jest.fn(() => ({ NO: "NO" })),
}
}));
import { connectivityReducer, DEFAULT_STATE } from "../reducer";
import { Actions } from "../../constants";
import { pingOK, pingNO } from "..";
import { store } from "../../redux/store";
i... |
});
it("broadcasts PING_OK", () => {
pingOK("yep", 123);
expect(store.dispatch).toHaveBeenCalledWith({
payload: { at: 123, id: "yep" },
type: "PING_OK",
});
});
it("broadcasts PING_NO", () => {
pingNO("yep", 123);
expect(store.dispatch).toHaveBeenCalledWith({
payload: { ... | {
expect(yep.kind).toEqual("complete");
} | conditional_block |
ymovies.py | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 3 of the License, or
(at your option) any l... |
def ymovies_info_season(self, title, season):
try:
q = '%s Season %s' % (cleantitle.query(title), season)
q = '/search/%s.html' % (urllib.quote_plus(q))
q = urlparse.urljoin(self.base_link, q)
for i in range(3):
r = client.request(q)
... | try:
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
t = cleantitle.get(data['tvshowtitle'])
title = data['tvshowtitle']
season = '%01d' % int(season) ; episode = '%01d' % int(episode)
year = re.f... | identifier_body |
ymovies.py | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 3 of the License, or
(at your option) any l... | (self, url):
return directstream.googlepass(url)
def uncensored(a,b):
x = '' ; i = 0
for i, y in enumerate(a):
z = b[i % len(b) - 1]
y = int(ord(str(y)[0])) + int(ord(str(z)[0]))
x += chr(y)
x = base64.b64encode(x)
return x
| resolve | identifier_name |
ymovies.py | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 3 of the License, or
(at your option) any l... |
return urlparse.urlparse(i[0]).path
except:
pass
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}
... | raise Exception() | conditional_block |
ymovies.py | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 3 of the License, or
(at your option) any l... | for i in range(13):
r = client.request(u, referer=ref)
if not r == None: break
r = re.compile('(<li.+?/li>)', re.DOTALL).findall(r)
r = [(client.parseDOM(i, 'li', ret='onclick'), client.parseDOM(i, 'a', ret='title')) for i in r]
if not ep... | u = urlparse.urljoin(self.base_link, r)
| random_line_split |
htmlmodelement.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::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... | use dom::document::Document;
use dom::element::HTMLModElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLModElement {
htmlelement: HTMLElement
}
impl HTMLMod... | use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector}; | random_line_split |
htmlmodelement.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::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... |
}
impl HTMLModElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement {
HTMLModElement {
htmlelement: HTMLElement::new_inherited(HTMLModElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]... | {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLModElementTypeId))
} | identifier_body |
htmlmodelement.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::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> {
let element = HTMLModElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLModElementBinding::Wrap)
}
}
impl Reflectable for HTMLModElement {
... | new | identifier_name |
react-dom-unstable-fizz.node.production.min.js | /** @license React v16.8.2
* react-dom-unstable-fizz.node.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';function | (a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finall... | d | identifier_name |
react-dom-unstable-fizz.node.production.min.js | *
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';function d(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.f... | /** @license React v16.8.2
* react-dom-unstable-fizz.node.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates. | random_line_split | |
react-dom-unstable-fizz.node.production.min.js | /** @license React v16.8.2
* react-dom-unstable-fizz.node.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';function d(a,b){var c="<"+a+">";"string"=... | function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
| {a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e){var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}})} | identifier_body |
react-dom-unstable-fizz.node.production.min.js | /** @license React v16.8.2
* react-dom-unstable-fizz.node.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';function d(a,b){var c="<"+a+">";"string"=... | })}function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
| {var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())} | conditional_block |
ui.rs | // Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | r: u8,
g: u8,
b: u8)
-> UIText {
self.create_text(val, x, y, sx, sy, 0.0, r, g, b)
}
pub fn new_text_rotated(&mut self,
val: &str,
x: f64,
... | identifier_name | |
ui.rs | // Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | g: u8,
b: u8)
-> UIText {
self.create_text(val, x, y, sx, sy, rotation, r, g, b)
}
fn create_text(&mut self,
val: &str,
x: f64,
y: f64,
sx: f64... | random_line_split | |
ui.rs | // Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | sw = (self.page_width / 16.0) as u32;
let sh = (self.page_height / 16.0) as u32;
return p.relative((cx * sw + info.0 as u32) as f32 / (self.page_width as f32),
(cy * sh) as f32 / (self.page_height as f32),
(info.1 - info.0) as f32 / (s... | _character_info[raw as usize];
if page == 0 {
let | conditional_block |
streakgaming.py | # !/usr/bin/python
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of... | "
Constructor...
"""
self.platformName = "Streakgaming"
self.tags = ["social", "news", "gaming"]
########################
# Defining valid modes #
########################
self.isValidMode = {}
self.isValidMode["phonefy"] = False
... | identifier_body | |
streakgaming.py | # !/usr/bin/python
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of... | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################
__author__ = "Yaiza Rubio and Félix ... | #
# 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 | random_line_split |
streakgaming.py | # !/usr/bin/python
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the terms of... | latform):
"""
A <Platform> object for Streakgaming.
"""
def __init__(self):
"""
Constructor...
"""
self.platformName = "Streakgaming"
self.tags = ["social", "news", "gaming"]
########################
# Defining valid modes #
###... | reakgaming(P | identifier_name |
load_test.py | import re
from threading import Thread
import time
from django.core.management.base import BaseCommand
import requests
from mittab.apps.tab.models import Round, TabSettings
from mittab.apps.tab.management.commands import utils
class Command(BaseCommand):
help = "Load test the tournament, connecting via localhos... | def run(self):
self.resp = self.get_resp()
def get_resp(self):
if self.num_errors >= self.MAX_ERRORS:
return None
result = utils.generate_random_results(self.round_obj, self.ballot_code)
result["csrfmiddlewaretoken"] = self.csrf_token
resp = requests.post("... | random_line_split | |
load_test.py | import re
from threading import Thread
import time
from django.core.management.base import BaseCommand
import requests
from mittab.apps.tab.models import Round, TabSettings
from mittab.apps.tab.management.commands import utils
class Command(BaseCommand):
help = "Load test the tournament, connecting via localhos... | (self, host, ballot_code, round_obj):
super(GetCsrfThread, self).__init__()
self.num_errors = 0
self.host = host
self.ballot_code = ballot_code
self.round_obj = round_obj
self.result = (None, None)
def run(self):
resp = self.get_resp()
if resp is None... | __init__ | identifier_name |
load_test.py | import re
from threading import Thread
import time
from django.core.management.base import BaseCommand
import requests
from mittab.apps.tab.models import Round, TabSettings
from mittab.apps.tab.management.commands import utils
class Command(BaseCommand):
help = "Load test the tournament, connecting via localhos... |
class GetCsrfThread(Thread):
REGEX = "name=\"csrfmiddlewaretoken\" value=\"([^\"]+)\""
MAX_ERRORS = 10
def __init__(self, host, ballot_code, round_obj):
super(GetCsrfThread, self).__init__()
self.num_errors = 0
self.host = host
self.ballot_code = ballot_code
self.... | if self.num_errors >= self.MAX_ERRORS:
return None
result = utils.generate_random_results(self.round_obj, self.ballot_code)
result["csrfmiddlewaretoken"] = self.csrf_token
resp = requests.post("http://%s/e_ballots/%s/" % (self.host, self.ballot_code),
r... | identifier_body |
load_test.py | import re
from threading import Thread
import time
from django.core.management.base import BaseCommand
import requests
from mittab.apps.tab.models import Round, TabSettings
from mittab.apps.tab.management.commands import utils
class Command(BaseCommand):
help = "Load test the tournament, connecting via localhos... |
else:
return resp.text
class GetCsrfThread(Thread):
REGEX = "name=\"csrfmiddlewaretoken\" value=\"([^\"]+)\""
MAX_ERRORS = 10
def __init__(self, host, ballot_code, round_obj):
super(GetCsrfThread, self).__init__()
self.num_errors = 0
self.host = host
s... | self.num_errors += 1
return self.get_resp() | conditional_block |
executors.py | # -*- coding:utf-8 -*-
import copy
from zope.interface import implementer
from .interfaces import (
IExecutor,
ISchemaValidation,
IDataValidation,
ICreate,
IDelete,
IEdit
)
from alchemyjsonschema.dictify import (
normalize,
validate_all,
ErrorFound
)
from jsonschema import FormatChec... |
ob = self.context.modelclass(**self.params)
self.context.session.add(ob)
self.context.session.flush()
return ob
class EditExecutor(Executor):
def validation(self, ob=None):
self.params = default_validation(self, IEdit, ob)
def execute(self, ob):
if self.params... | raise RuntimeError("execute after validation") | conditional_block |
executors.py | # -*- coding:utf-8 -*-
import copy
from zope.interface import implementer
from .interfaces import (
IExecutor,
ISchemaValidation,
IDataValidation,
ICreate,
IDelete,
IEdit
)
from alchemyjsonschema.dictify import (
normalize,
validate_all,
ErrorFound
)
from jsonschema import FormatChec... |
def execute(self, ob=None):
if self.params is None:
raise RuntimeError("execute after validation")
ob = self.context.modelclass(**self.params)
self.context.session.add(ob)
self.context.session.flush()
return ob
class EditExecutor(Executor):
def validation(... | self.params = default_validation(self, ICreate, ob) | identifier_body |
executors.py | # -*- coding:utf-8 -*-
import copy
from zope.interface import implementer
from .interfaces import (
IExecutor,
ISchemaValidation,
IDataValidation,
ICreate,
IDelete,
IEdit
)
from alchemyjsonschema.dictify import (
normalize,
validate_all,
ErrorFound
)
from jsonschema import FormatChec... | (self, ob):
self.context.session.delete(ob)
return ob
def create_jsonschema_validation(context, params, ob=None):
def customize_schema(schema):
schema = copy.deepcopy(schema)
# when creating model, id is not needed.
if "id" in schema["required"]:
schema["require... | execute | identifier_name |
executors.py | # -*- coding:utf-8 -*-
import copy
from zope.interface import implementer
from .interfaces import (
IExecutor,
ISchemaValidation,
IDataValidation,
ICreate,
IDelete,
IEdit
)
from alchemyjsonschema.dictify import (
normalize,
validate_all,
ErrorFound
)
from jsonschema import FormatChec... | validate_all(params, schema_validator)
except ErrorFound as err:
raise ValidationError({e.path[0]: e.message for e in err.errors})
return normalize(params, schema)
def delete_jsonschema_validation(context, params):
return params | try: | random_line_split |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... |
FT_Add_Default_Modules(ctx);
FontContextHandle {
ctx: Rc::new(FreeTypeLibraryHandle {
ctx: ctx,
mem: mem,
user: user,
}),
}
}
}
}
| {
panic!("Unable to initialize FreeType library");
} | conditional_block |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... | }
impl FontContextHandle {
pub fn new() -> FontContextHandle {
let user = Box::into_raw(Box::new(User { size: 0 }));
let mem = Box::into_raw(Box::new(FT_MemoryRec_ {
user: user as *mut c_void,
alloc: Some(ft_alloc),
free: Some(ft_free),
realloc: Some(... | } | random_line_split |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... | (&self, ops: &mut MallocSizeOfOps) -> usize {
self.ctx.size_of(ops)
}
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
let user = Box::into_raw(Box::new(User { size: 0 }));
let mem = Box::into_raw(Box::new(FT_MemoryRec_ {
user: user as *mut c_void,
... | size_of | identifier_name |
config.rs | use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;
use error::*;
use serde_json;
lazy_static! {
pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub host: ... | {
let path = config_path();
fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
let mut file = File::open(path)?;
let body = serde_json::to_string(&Config {
host: host.to_string(),
key: key.to_string()
})?;
serde_json::from_str(&body)
.map_err(Comf... | identifier_body | |
config.rs | use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;
use error::*;
use serde_json;
lazy_static! {
pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub host: ... | pub fn write_config(host: &str, key: &str) -> ComfyResult<Config> {
let path = config_path();
fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
let mut file = File::open(path)?;
let body = serde_json::to_string(&Config {
host: host.to_string(),
key: key.to_strin... | .map_err(ComfyError::from)
}
| random_line_split |
config.rs | use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;
use error::*;
use serde_json;
lazy_static! {
pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub host: ... | (host: &str, key: &str) -> ComfyResult<Config> {
let path = config_path();
fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
let mut file = File::open(path)?;
let body = serde_json::to_string(&Config {
host: host.to_string(),
key: key.to_string()
})?;
se... | write_config | identifier_name |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... |
}
}
cursor.next();
}
if found {
cursor.remove();
return buddy_ptr
}
ptr::null_mut()
}
fn get_order_from_size(&self, mut size: usize, _align: usize) -> u32 {
size = Buddy::next_power_of_two(size);
... | {
found = true;
break;
} | conditional_block |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... | }
#[allow(exceeding_bitshifts)]
pub fn next_power_of_two(mut num: usize) -> usize {
if num == 0 {
return 1;
}
num -= 1;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
if mem::size_o... | random_line_split | |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... |
#[allow(exceeding_bitshifts)]
pub fn next_power_of_two(mut num: usize) -> usize {
if num == 0 {
return 1;
}
num -= 1;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
if mem::size_of::<u... | {
assert!(min_block_size >= ::core::mem::size_of::<FreeBlock>());
Buddy {
min_block_size: min_block_size,
min_block_order: Buddy::log2(min_block_size) as u32,
max_order: max_order,
free_lists: free_lists,
}
} | identifier_body |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... | (&mut self, order: u32, start: *mut u8) {
let link = ptr::Unique::new(start as *mut FreeBlock);
self.free_lists[order as usize].push_front(link);
}
unsafe fn split_block(&mut self, block: *mut u8, mut order: u32,
target_order: u32) {
while order > target_order... | add_block_order | identifier_name |
mod.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
pub fn type_inference(cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar> {
let mut grammar = Grammar {
name: agrammar.name,
rules: HashMap::with_capacity(agrammar.rules.len()),
rust_functions: agrammar.rust_functions,
rust_items: agrammar.rust_items,
attributes: agrammar.attributes
};
Infe... | mod bottom_up_unit;
mod top_down_unit;
mod recursive_type;
// mod printer; | random_line_split |
mod.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | {
let mut grammar = Grammar {
name: agrammar.name,
rules: HashMap::with_capacity(agrammar.rules.len()),
rust_functions: agrammar.rust_functions,
rust_items: agrammar.rust_items,
attributes: agrammar.attributes
};
InferenceEngine::infer(&mut grammar, agrammar.rules);
bottom_up_unit_inference(... | identifier_body | |
mod.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | (cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar> {
let mut grammar = Grammar {
name: agrammar.name,
rules: HashMap::with_capacity(agrammar.rules.len()),
rust_functions: agrammar.rust_functions,
rust_items: agrammar.rust_items,
attributes: agrammar.attributes
};
InferenceEngine::infer(&mu... | type_inference | identifier_name |
rapidgator.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rapidgator
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core im... | ( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url)
video_urls = []
return video_urls
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):
encontrados = set()
devuelve = []
#http:... | get_video_url | identifier_name |
rapidgator.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rapidgator
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core im... | return video_urls
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):
encontrados = set()
devuelve = []
#http://rapidgator.net/file/10126555/ElBatallon-byjerobien.avi.html
#http://rapidgator.net/file/15437757
patronvideos = '(rapidgator.net/file/\d+)'
logger.info("[r... | def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url)
video_urls = [] | random_line_split |
rapidgator.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rapidgator
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core im... |
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):
encontrados = set()
devuelve = []
#http://rapidgator.net/file/10126555/ElBatallon-byjerobien.avi.html
#http://rapidgator.net/file/15437757
patronvideos = '(rapidgator.net/file/\d+)'
logger.info("[rapidgator.py] find_vi... | logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url)
video_urls = []
return video_urls | identifier_body |
rapidgator.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rapidgator
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core im... | else:
logger.info(" url duplicada="+url)
return devuelve
| ogger.info(" url="+url)
devuelve.append( [ titulo , url , 'rapidgator' ] )
encontrados.add(url)
| conditional_block |
focusPointsContainer.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import * as _ from 'underscore';
import { EditorState, ContentState } from 'draft-js'
import { TextEditor } from '../../../Shared/index';
import * as questionActions from '../../actions/questions';
import { hashToCollection, SortableList, } from '... | sPointsList() {
const components = this.fPsortedByOrder().map((fp) => {
return (
<div className="card is-fullwidth has-bottom-margin" key={fp.key}>
<header className="card-header">
<input className="regex-name" onChange={(e) => this.handleNameChange(e, fp.key)} placeholder="Name"... | focusPoints } = this.state
if (this.state.fpOrderedIds) {
const focusPoints = focusPoints;
const newFp = {};
this.state.fpOrderedIds.forEach((id, index) => {
const fp = Object.assign({}, focusPoints[id]);
fp.order = index + 1;
newFp[id] = fp;
});
this.props.disp... | identifier_body |
focusPointsContainer.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import * as _ from 'underscore';
import { EditorState, ContentState } from 'draft-js'
import { TextEditor } from '../../../Shared/index';
import * as questionActions from '../../actions/questions';
import { hashToCollection, SortableList, } from '... | deleteConceptResult(conceptResultKey, focusPointKey) {
const { focusPoints } = this.state
if (confirm('⚠️ Are you sure you want to delete this? 😱')) {
const data = focusPoints[focusPointKey];
delete data.conceptResults[conceptResultKey];
this.props.dispatch(questionActions.submitEditedFocusP... | this.props.dispatch(questionActions.deleteFocusPoint(this.props.match.params.questionID, focusPointID));
delete focusPoints[focusPointID]
this.setState({focusPoints: focusPoints})
}
}
| conditional_block |
focusPointsContainer.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import * as _ from 'underscore';
import { EditorState, ContentState } from 'draft-js'
import { TextEditor } from '../../../Shared/index';
import * as questionActions from '../../actions/questions';
import { hashToCollection, SortableList, } from '... | { focusPoints } = this.state
if (this.state.fpOrderedIds) {
const focusPointsCollection = hashToCollection(focusPoints)
return this.state.fpOrderedIds.map(id => focusPointsCollection.find(fp => fp.key === id))
} else {
return hashToCollection(focusPoints).sort((a, b) => a.order - b.order);
... | r() {
const | identifier_name |
focusPointsContainer.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import * as _ from 'underscore';
import { EditorState, ContentState } from 'draft-js'
import { TextEditor } from '../../../Shared/index';
import * as questionActions from '../../actions/questions';
import { hashToCollection, SortableList, } from '... | );
}
}
function select(props) {
return {
questions: props.questions
};
}
export default connect(select)(FocusPointsContainer); | </div>
{this.renderFocusPointsList()}
{this.props.children}
</div> | random_line_split |
estimator.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
# | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ... | # 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 | random_line_split |
estimator.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self, logits, name=None):
"""Retrieves a distribution instance, parameterized by `logits`.
Args:
logits: `float`-like `Tensor` representing the parameters of the
underlying distribution.
name: The Python `str` name to given to this op.
Default value: "distribution".
Returns:
... | distribution | identifier_name |
estimator.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
class _DistributionRegressionHead(_RegressionHead):
"""Creates a _RegressionHead instance from an arbitrary `Distribution`."""
def __init__(self,
make_distribution_fn,
label_dimension,
logits_dimension=None,
label_name=None,
weight_colum... | """Creates a `Head` for regression under a generic distribution.
Args:
make_distribution_fn: Python `callable` which returns a `tf.Distribution`
instance created using only logits.
label_dimension: Number of regression labels per example. This is the size
of the last dimension of the labels `Tens... | identifier_body |
estimator.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
return d
| d = self._make_distribution_fn(logits)
self._distributions[logits] = d | conditional_block |
sso.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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
## Licens... |
return {}
def _fetch_particular_preferences(self, req=None):
"""This hidden method is there to be overwritten in order to get some
particular value from non standard variables.
"""
if req:
ret = {}
req.add_common_vars()
if 'HTTP_SHIB_AUT... | groups = req.subprocess_env[CFG_EXTERNAL_AUTH_SSO_GROUP_VARIABLE].split(CFG_EXTERNAL_AUTH_SSO_GROUPS_SEPARATOR)
# Filtering out uncomfortable groups
groups = [group for group in groups if group not in CFG_EXTERNAL_AUTH_HIDDEN_GROUPS]
for regexp in CFG_EXTERNAL_AUTH_HIDDEN... | conditional_block |
sso.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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
## Licens... |
def in_shibboleth(self, req):
"""
Return True if the current request handler is actually under
Shibboleth control.
"""
return CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env
def auth_user(self, username, password, req=None):
"""
Check USERNAME... | random_line_split | |
sso.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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
## Licens... | (self, username, password, req=None):
"""
Check USERNAME and PASSWORD against the SSO system.
Return (None, None) if authentication failed, or the
(email address, nickname) of the
person if the authentication was successful. In order to do
this you may perhaps have to ke... | auth_user | identifier_name |
sso.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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
## Licens... |
def auth_user(self, username, password, req=None):
"""
Check USERNAME and PASSWORD against the SSO system.
Return (None, None) if authentication failed, or the
(email address, nickname) of the
person if the authentication was successful. In order to do
this you may... | """
Return True if the current request handler is actually under
Shibboleth control.
"""
return CFG_EXTERNAL_AUTH_SSO_EMAIL_VARIABLE in req.subprocess_env | identifier_body |
get-latest-version.js | // Copyright 2019 Google Inc.
//
// 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
// <https://apache.org/licenses/LICENSE-2.0>.
//
// Unless required by applicable law or agreed to in writing... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const get = require('../../shared/get.js');
const predictFileName = require('./predict-file-name.js');
const getLatestVers... | // distributed under the License is distributed on an “AS IS” BASIS, | random_line_split |
buffer.rs | use std::io;
use crossbeam::sync::MsQueue;
// Ensures that we have enough buffers to keep workers busy.
const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2;
const TOTAL_BUFFERS_ADDITIVE: usize = 0;
/// Stores a set number of piece buffers to be used and re-used.
pub struct PieceBuffers {
piece_queue: MsQueue<PieceBuff... | (num_workers: usize) -> usize {
num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE
}
// ----------------------------------------------------------------------------//
/// Piece buffer that can be filled up until it contains a full piece.
#[derive(PartialEq, Eq)]
pub struct PieceBuffer {
buffe... | calculate_total_buffers | identifier_name |
buffer.rs | use std::io;
use crossbeam::sync::MsQueue;
// Ensures that we have enough buffers to keep workers busy.
const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2;
const TOTAL_BUFFERS_ADDITIVE: usize = 0;
/// Stores a set number of piece buffers to be used and re-used.
pub struct PieceBuffers {
piece_queue: MsQueue<PieceBuff... |
}
/// Calculates the optimal number of piece buffers given the number of workers.
fn calculate_total_buffers(num_workers: usize) -> usize {
num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE
}
// ----------------------------------------------------------------------------//
/// Piece buffer tha... | {
self.piece_queue.pop()
} | identifier_body |
buffer.rs | use std::io;
use crossbeam::sync::MsQueue;
// Ensures that we have enough buffers to keep workers busy.
const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2;
const TOTAL_BUFFERS_ADDITIVE: usize = 0;
/// Stores a set number of piece buffers to be used and re-used.
pub struct PieceBuffers {
piece_queue: MsQueue<PieceBuff... | PieceBuffers { piece_queue: piece_queue }
}
/// Checkin the given piece buffer to be re-used.
pub fn checkin(&self, mut buffer: PieceBuffer) {
buffer.bytes_read = 0;
self.piece_queue.push(buffer);
}
/// Checkout a piece buffer (possibly blocking) to be used.
pub fn che... | }
| random_line_split |
make.py | #!/usr/bin/python
import os
import shutil
import zipfile
import zlib
import os.path
def _ignore(src, name ):
if src == './UPLOAD/':
print name
return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py']
else:
return []
def _RecImport(src, dst, zip): | elements.remove(delete)
except ValueError:
pass
for ele in elements:
if os.path.isfile(src + ele):
zip.write(src + ele, dst + ele)
print dst + ele
elif os.path.isdir(src + ele):
_RecImport(src + ele + '/', dst + ele + '/', zip)
tr... | elements = os.listdir(src)
ignored = _ignore('.' + dst, elements)
for delete in ignored:
try: | random_line_split |
make.py | #!/usr/bin/python
import os
import shutil
import zipfile
import zlib
import os.path
def _ignore(src, name ):
if src == './UPLOAD/':
print name
return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py']
else:
return []
def _RecImport(src, dst, zip):
elements = os.listdir... |
try:
shutil.rmtree('tmp')
except OSError:
pass
file = 'Nuked-Klan.zip'
try:
os.remove(file)
except OSError:
pass
zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False)
_RecImport('RESTDIR/', '/', zip)
_RecImport('./', '/UPLOAD/', zip)
| _RecImport(src + ele + '/', dst + ele + '/', zip) | conditional_block |
make.py | #!/usr/bin/python
import os
import shutil
import zipfile
import zlib
import os.path
def _ignore(src, name ):
if src == './UPLOAD/':
print name
return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py']
else:
return []
def _RecImport(src, dst, zip):
|
try:
shutil.rmtree('tmp')
except OSError:
pass
file = 'Nuked-Klan.zip'
try:
os.remove(file)
except OSError:
pass
zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED, False)
_RecImport('RESTDIR/', '/', zip)
_RecImport('./', '/UPLOAD/', zip)
| elements = os.listdir(src)
ignored = _ignore('.' + dst, elements)
for delete in ignored:
try:
elements.remove(delete)
except ValueError:
pass
for ele in elements:
if os.path.isfile(src + ele):
zip.write(src + ele, dst + ele)
print dst ... | identifier_body |
make.py | #!/usr/bin/python
import os
import shutil
import zipfile
import zlib
import os.path
def _ignore(src, name ):
if src == './UPLOAD/':
print name
return ['RESTDIR', 'conf.inc.php', 'Nuked-Klan.zip', '.hg', 'make.py']
else:
return []
def | (src, dst, zip):
elements = os.listdir(src)
ignored = _ignore('.' + dst, elements)
for delete in ignored:
try:
elements.remove(delete)
except ValueError:
pass
for ele in elements:
if os.path.isfile(src + ele):
zip.write(src + ele, dst + ele)
... | _RecImport | identifier_name |
morautils.py | # Utility functions for OpenMORA scripts
#
# Part of OpenMora - https://github.com/OpenMORA
import os, sys, string
import platform
import yaml
def get_mora_paths():
""" Returns a list of paths with MORA modules, from the env var MORA_PATH
"""
if not 'MORA_PATH' in os.environ:
print('**ERROR** Environment variabl... | ():
""" Returns the path of "mora-base" pkg
"""
mora_paths = get_mora_paths() # Get env vars
for p in mora_paths:
tstPath = os.path.normpath(p + "/mora-base")
if os.path.exists(tstPath):
morabase_dir = tstPath
if (len(morabase_dir)==0) or (not os.path.exists(morabase_dir)):
print("Couldn't detect mora... | get_morabase_dir | identifier_name |
morautils.py | # Utility functions for OpenMORA scripts
#
# Part of OpenMora - https://github.com/OpenMORA
import os, sys, string
import platform
import yaml
def get_mora_paths():
""" Returns a list of paths with MORA modules, from the env var MORA_PATH
"""
if not 'MORA_PATH' in os.environ:
print('**ERROR** Environment variabl... | if percent >= 100:
percent = 100
sys.stdout.write("%s %d%%\r" % (loader, percent))
if percent >= 100:
pass
sys.stdout.write("\n")
sys.stdout.flush()
def get_pkgs_root():
'''Returns the path to the parent directory of mora-base'''
morabase_dir = get_morabase_dir()
pkgs_root = os.path.dirname(morabase_dir)... | spaces = math.floor(width - marks)
loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']'
| random_line_split |
morautils.py | # Utility functions for OpenMORA scripts
#
# Part of OpenMora - https://github.com/OpenMORA
import os, sys, string
import platform
import yaml
def get_mora_paths():
""" Returns a list of paths with MORA modules, from the env var MORA_PATH
"""
if not 'MORA_PATH' in os.environ:
print('**ERROR** Environment variabl... |
def read_distro_file():
'''Returns the yaml contents of the distro file'''
morabase_dir = get_morabase_dir()
pkgs_root = os.path.dirname(morabase_dir)
sDistroFile = os.path.normpath( morabase_dir + "/distro/openmora-pkgs.yaml")
assert os.path.exists(sDistroFile)
assert os.path.exists(pkgs_root + "/mora-... | '''Returns the path to the parent directory of mora-base'''
morabase_dir = get_morabase_dir()
pkgs_root = os.path.dirname(morabase_dir)
return pkgs_root | identifier_body |
morautils.py | # Utility functions for OpenMORA scripts
#
# Part of OpenMora - https://github.com/OpenMORA
import os, sys, string
import platform
import yaml
def get_mora_paths():
""" Returns a list of paths with MORA modules, from the env var MORA_PATH
"""
if not 'MORA_PATH' in os.environ:
print('**ERROR** Environment variabl... |
return morabase_dir
import sys, math
def progress(percent):
''' source: http://gunslingerc0de.wordpress.com/2010/08/13/python-command-line-progress-bar/ '''
width = 74
marks = math.floor(width * (percent / 100.0))
spaces = math.floor(width - marks)
loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']... | print("Couldn't detect mora-base in MORA_PATH!!")
sys.exit(1) | conditional_block |
app.module.ts | import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { File } from '@ionic-native/file';
import { AboutPage } from '../pages/about/about... | {}
| AppModule | identifier_name |
app.module.ts | import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { File } from '@ionic-native/file';
import { AboutPage } from '../pages/about/about... | providers: [
StatusBar,
SplashScreen,
File,
NativeAudio,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {} | random_line_split | |
consts.py | #!/usr/bin/python
#
# Copyright (C) 2006-2018 Wyplay, All Rights Reserved.
# This file is part of xbuilder.
#
# xbuilder 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
# (a... | XBUILDER_GPG_LOGFILE = 'gpg.log'
XBUILDER_GPG_LOGLEVEL = 20 # logging.INFO | random_line_split | |
257. Binary Tree Paths.js | /*
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/
/**
* Definition for a binary tree ... |
}
};
//tag: Google Facebook Apple | {
if( node.left !== null ){
traverseTree( node.left, str + node.val + '->' );
}
if( node.right !== null ){
traverseTree( node.right, str + node.val + '->' );
}
} | conditional_block |
257. Binary Tree Paths.js | /*
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/
/**
* Definition for a binary tree ... | (node,str){
if( node.left === null && node.right === null ){
result.push( str+node.val );
}
else{
if( node.left !== null ){
traverseTree( node.left, str + node.val + '->' );
}
if( node.right !== null ){
traverseTree(... | traverseTree | identifier_name |
257. Binary Tree Paths.js | /*
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/
/**
* Definition for a binary tree ... |
};
//tag: Google Facebook Apple | {
if( node.left === null && node.right === null ){
result.push( str+node.val );
}
else{
if( node.left !== null ){
traverseTree( node.left, str + node.val + '->' );
}
if( node.right !== null ){
traverseTree( node.righ... | identifier_body |
257. Binary Tree Paths.js | /*
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 | / \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
... | random_line_split | |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org>
# Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... | sw = Gtk.ScrolledWindow()
sw.set_policy(
Gtk.PolicyType.AUTOMATIC,
Gtk.PolicyType.AUTOMATIC
)
self.textview = Gtk.TextView()
self.textbuffer = self.textview.get_buffer()
self.textview.set_editable(False)
self.textview.set_wrap_mode(Gtk.Wrap... | def __init__(self):
super(Console, self).__init__()
| random_line_split |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org>
# Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... | lf.hide()
return True
| identifier_body | |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org>
# Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... | elf, widget, data=None):
self.hide()
return True
| _click_hide(s | identifier_name |
day_10.rs | pub use tdd_kata::stack_kata::day_10::Stack;
describe! stack_tests {
before_each {
let mut stack: Stack<i32> = Stack::new(20);
}
it "should create a new empty stack" {
assert_eq!(stack.size(), 0);
assert!(stack.is_empty());
}
it "should increase stack size when push into ... |
it "should decrease stack size when pop from it" {
stack.push(20);
let old_size = stack.size();
stack.pop();
assert_eq!(stack.size(), old_size - 1);
}
it "should pop value that was pushed into the stack" {
stack.push(20);
assert_eq!(stack.pop(), Some(20));... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.