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 |
|---|---|---|---|---|
verify.js | /* 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/. */
var fs = require('fs');
var jsdom = require('jsdom');
function cleanTag (tree) {
cleanAttributes(tree);
}
func... | }
}; | random_line_split | |
verify.js | /* 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/. */
var fs = require('fs');
var jsdom = require('jsdom');
function cleanTag (tree) {
cleanAttributes(tree);
}
func... | (tree) {
checkTag(tree, 'div', { id: 'flathead-app' });
cleanTag(tree);
if (tree._childNodes) {
siftThroughChildren(tree._childNodes, filterCard);
}
else {
throw "No children!";
}
return tree;
}
function filterCard (tree) {
checkTag(tree, 'div', { class: 'ceci-card' });
cleanTag(tree);
... | filterApp | identifier_name |
verify.js | /* 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/. */
var fs = require('fs');
var jsdom = require('jsdom');
function cleanTag (tree) {
cleanAttributes(tree);
}
func... |
}
function filterSection (tree, name) {
checkTag(tree, 'div', { class: name });
cleanTag(tree);
if (tree._childNodes) {
siftThroughChildren(tree._childNodes, filterComponent);
}
return true;
}
function filterSubscription (tree) {
cleanAttributes(tree, ['on', 'for']);
siftThroughChildren(tree._chil... | {
throw "No children!";
} | conditional_block |
rustc.rs | //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
//!
//! This shim will take care of some various tasks that our build process
//! requires that Cargo can't quite do through normal configuration:
//!
//! 1. When compiling build scripts and build dependencies, we need a guaranteed
//! full sta... |
// If we're compiling specifically the `panic_abort` crate then we pass
// the `-C panic=abort` option. Note that we do not do this for any
// other crate intentionally as this is the only crate for now that we
// ship with panic=abort.
//
// This... is a bit of a hack ... | {
cmd.arg("--sysroot").arg(&sysroot);
} | conditional_block |
rustc.rs | //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
//!
//! This shim will take care of some various tasks that our build process
//! requires that Cargo can't quite do through normal configuration:
//!
//! 1. When compiling build scripts and build dependencies, we need a guaranteed
//! full sta... | {
let rusage: libc::rusage = unsafe {
let mut recv = std::mem::zeroed();
// -1 is RUSAGE_CHILDREN, which means to get the rusage for all children
// (and grandchildren, etc) processes that have respectively terminated
// and been waited for.
let retval = libc::getrusage(-1, &... | identifier_body | |
rustc.rs | //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
//!
//! This shim will take care of some various tasks that our build process
//! requires that Cargo can't quite do through normal configuration:
//!
//! 1. When compiling build scripts and build dependencies, we need a guaranteed
//! full sta... | (child: Child) -> Option<String> {
use std::os::windows::io::AsRawHandle;
use winapi::um::{processthreadsapi, psapi, timezoneapi};
let handle = child.as_raw_handle();
macro_rules! try_bool {
($e:expr) => {
if $e != 1 {
return None;
}
};
}
... | format_rusage_data | identifier_name |
rustc.rs | //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
//!
//! This shim will take care of some various tasks that our build process
//! requires that Cargo can't quite do through normal configuration:
//!
//! 1. When compiling build scripts and build dependencies, we need a guaranteed
//! full sta... | let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
let mut dylib_path = bootstrap::util::dylib_path();
dylib_path.insert(0, PathBuf::from(&libdir));
let mut cmd = Command::new(r... | let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new);
| random_line_split |
scroll_viewer_mode.rs | /// The `ScrollMode` defines the mode of a scroll direction.
#[derive(Copy, Debug, Clone, PartialEq)]
pub enum ScrollMode {
/// Scrolling will process by `ScrollViewer` logic
Auto,
/// Scrolling could be handled from outside. It will not be
/// process by `ScrollViewer` logic.
Custom,
/// Scro... | (s: &str) -> ScrollMode {
match s {
"Custom" | "custom" => ScrollMode::Custom,
"Disabled" | "disabled" => ScrollMode::Disabled,
_ => ScrollMode::Auto,
}
}
}
/// `ScrollViewerMode` describes the vertical and horizontal scroll
/// behavior of the `ScrollViewer`.
#[... | from | identifier_name |
scroll_viewer_mode.rs | /// The `ScrollMode` defines the mode of a scroll direction.
#[derive(Copy, Debug, Clone, PartialEq)]
pub enum ScrollMode {
/// Scrolling will process by `ScrollViewer` logic
Auto,
/// Scrolling could be handled from outside. It will not be
/// process by `ScrollViewer` logic.
Custom,
/// Scro... | }
}
}
impl Default for ScrollViewerMode {
fn default() -> ScrollViewerMode {
ScrollViewerMode {
vertical: ScrollMode::Auto,
horizontal: ScrollMode::Auto,
}
}
} | vertical: ScrollMode::from(s.1), | random_line_split |
ember-weakmap-polyfill.js | /* globals Ember, require */
(function() {
var _Ember;
var id = 0;
var dateKey = new Date().getTime();
if (typeof Ember !== 'undefined') {
_Ember = Ember;
} else {
_Ember = require('ember').default;
}
function symbol() {
return '__ember' + dateKey + id++;
}
function UNDEFINED() {}
f... |
if (this.has(obj)) {
delete metaInfo[metaKey][this._id];
return true;
}
return false;
}
if (typeof WeakMap === 'function' && typeof window !== 'undefined' && window.OVERRIDE_WEAKMAP !== true) {
_Ember.WeakMap = WeakMap;
} else {
_Ember.WeakMap = FakeWeakMap;... | */
FakeWeakMap.prototype.delete = function(obj) {
var metaInfo = meta(obj); | random_line_split |
ember-weakmap-polyfill.js | /* globals Ember, require */
(function() {
var _Ember;
var id = 0;
var dateKey = new Date().getTime();
if (typeof Ember !== 'undefined') | else {
_Ember = require('ember').default;
}
function symbol() {
return '__ember' + dateKey + id++;
}
function UNDEFINED() {}
function FakeWeakMap(iterable) {
this._id = symbol();
if (iterable === null || iterable === undefined) {
return;
} else if (Array.isArray(iterable)) {
... | {
_Ember = Ember;
} | conditional_block |
ember-weakmap-polyfill.js | /* globals Ember, require */
(function() {
var _Ember;
var id = 0;
var dateKey = new Date().getTime();
if (typeof Ember !== 'undefined') {
_Ember = Ember;
} else {
_Ember = require('ember').default;
}
function symbol() {
return '__ember' + dateKey + id++;
}
function | () {}
function FakeWeakMap(iterable) {
this._id = symbol();
if (iterable === null || iterable === undefined) {
return;
} else if (Array.isArray(iterable)) {
for (var i = 0; i < iterable.length; i++) {
var key = iterable[i][0];
var value = iterable[i][1];
this.set(key,... | UNDEFINED | identifier_name |
ember-weakmap-polyfill.js | /* globals Ember, require */
(function() {
var _Ember;
var id = 0;
var dateKey = new Date().getTime();
if (typeof Ember !== 'undefined') {
_Ember = Ember;
} else {
_Ember = require('ember').default;
}
function symbol() |
function UNDEFINED() {}
function FakeWeakMap(iterable) {
this._id = symbol();
if (iterable === null || iterable === undefined) {
return;
} else if (Array.isArray(iterable)) {
for (var i = 0; i < iterable.length; i++) {
var key = iterable[i][0];
var value = iterable[i][1];... | {
return '__ember' + dateKey + id++;
} | identifier_body |
index.ts | import styled from 'styled-components' |
import Img from '@/Img'
import { theme } from '@/utils/themes'
import css from '@/utils/css'
export const Wrapper = styled.div<{ center: boolean }>`
${css.flex()};
justify-content: ${({ center }) => (center ? 'center' : 'flex-start')};
flex-wrap: wrap;
color: ${theme('thread.articleDigest')};
width: 100%;
... | random_line_split | |
process_mz_query.py | from __future__ import print_function
import numpy as np
import sys
import bisect
import datetime
import gzip
def | (s):
print("[" + str(datetime.datetime.now()) + "] " + s, file=sys.stderr)
if len(sys.argv) < 3:
print("Usage: process_mz_query.py dump_file[.gz] query_file")
exit(0)
my_print("Reading dump file from %s..." % sys.argv[1])
if sys.argv[1][-2:] == 'gz':
f = gzip.open(sys.argv[1], 'rb')
else:
f = ope... | my_print | identifier_name |
process_mz_query.py | from __future__ import print_function
import numpy as np
import sys
import bisect
import datetime
import gzip
def my_print(s):
print("[" + str(datetime.datetime.now()) + "] " + s, file=sys.stderr)
if len(sys.argv) < 3:
print("Usage: process_mz_query.py dump_file[.gz] query_file")
exit(0)
my_print("Readi... |
my_print("Reading and processing queries from %s..." % sys.argv[2])
def get_one_group_total(mz_lower, mz_upper, mzs, intensities):
return np.sum(intensities[ bisect.bisect_left(mzs, mz_lower) : bisect.bisect_right(mzs, mz_upper) ])
def get_all_totals(mz, tol, spectra):
mz_lower = mz - tol
mz_upper = mz +... | random_line_split | |
process_mz_query.py | from __future__ import print_function
import numpy as np
import sys
import bisect
import datetime
import gzip
def my_print(s):
|
if len(sys.argv) < 3:
print("Usage: process_mz_query.py dump_file[.gz] query_file")
exit(0)
my_print("Reading dump file from %s..." % sys.argv[1])
if sys.argv[1][-2:] == 'gz':
f = gzip.open(sys.argv[1], 'rb')
else:
f = open(sys.argv[1])
spectra = []
arr = []
for line in f:
arr = line.strip().sp... | print("[" + str(datetime.datetime.now()) + "] " + s, file=sys.stderr) | identifier_body |
process_mz_query.py | from __future__ import print_function
import numpy as np
import sys
import bisect
import datetime
import gzip
def my_print(s):
print("[" + str(datetime.datetime.now()) + "] " + s, file=sys.stderr)
if len(sys.argv) < 3:
print("Usage: process_mz_query.py dump_file[.gz] query_file")
exit(0)
my_print("Readi... |
spectra.append( ( arr[0], np.array([ float(x) for x in arr[2].split(" ") ]), np.array([ float(x) for x in arr[1].split(" ") ]) ) )
f.close()
## at this point, spectra array contains triples of the form
## (group_id, list of mzs, list of intensities)
my_print("Reading and processing queries from %s..." % sys.a... | continue | conditional_block |
Draggable.ts | import { Pair } from '@/types'
import { assert, normalize, pair, zip } from '@/utils'
import CanvasZoom from '@/view/CanvasZoom'
import Element from '@/view/Element'
interface Placeable {
position: Pair<number>
}
interface DragOptions {
type: DragType,
position: MousePosition,
element: HTMLElement,
... | [DragType.STICK](position: MousePosition): void {
assert(this.element.parentElement)
const parentProp = this.element.parentElement.getBoundingClientRect() //? use custom Element
this.offset = [ parentProp.x + 50, parentProp.y + 10 ] as Pair<number>
this.dragging(position)
docume... | {
// console.log('Draggable', type, element, object, zoom)
// <? just setter position
// $.Draggable.log(`┌── Starting dragging`, element)
this.element = element
this.object = object
this.callback = callback || (() => void 0)
this.zoom = zoom
this[type]... | identifier_body |
Draggable.ts | import { Pair } from '@/types'
import { assert, normalize, pair, zip } from '@/utils'
import CanvasZoom from '@/view/CanvasZoom'
import Element from '@/view/Element'
interface Placeable {
position: Pair<number> | element: HTMLElement,
object: Placeable,
zoom: CanvasZoom,
callback?: () => void
}
export interface MousePosition {
clientX: number,
clientY: number
}
export enum DragType {
DRAG, STICK
}
export class Draggable {
public element: HTMLElement
public object: Placeable
public zoom... | }
interface DragOptions {
type: DragType,
position: MousePosition, | random_line_split |
Draggable.ts | import { Pair } from '@/types'
import { assert, normalize, pair, zip } from '@/utils'
import CanvasZoom from '@/view/CanvasZoom'
import Element from '@/view/Element'
interface Placeable {
position: Pair<number>
}
interface DragOptions {
type: DragType,
position: MousePosition,
element: HTMLElement,
... | ion: MousePosition): void {
assert(this.element.parentElement)
const parentProp = this.element.parentElement.getBoundingClientRect() //? use custom Element
this.offset = [ parentProp.x + 50, parentProp.y + 10 ] as Pair<number>
this.dragging(position)
document.addEventListener('m... | ype.STICK](posit | identifier_name |
db_test_lib_test.py | #!/usr/bin/env python
from absl.testing import absltest
from typing import Text
from grr_response_core.lib import rdfvalue
from grr_response_server import blob_store
from grr_response_server.databases import db as abstract_db
from grr.test_lib import db_test_lib
class WithDatabaseTest(absltest.TestCase):
def | (self):
@db_test_lib.WithDatabase
def TestMethod(db: abstract_db.Database):
self.assertIsInstance(db, abstract_db.Database)
TestMethod() # pylint: disable=no-value-for-parameter
def testDatabaseWorks(self):
now = rdfvalue.RDFDatetime.Now()
@db_test_lib.WithDatabase
def TestMethod(se... | testDatabaseIsProvided | identifier_name |
db_test_lib_test.py | #!/usr/bin/env python
from absl.testing import absltest
from typing import Text
from grr_response_core.lib import rdfvalue
from grr_response_server import blob_store
from grr_response_server.databases import db as abstract_db
from grr.test_lib import db_test_lib
class WithDatabaseTest(absltest.TestCase):
def tes... |
def testDatabaseIsFresh(self):
@db_test_lib.WithDatabase
def TestMethod(db: abstract_db.Database):
self.assertEqual(db.CountGRRUsers(), 0)
db.WriteGRRUser("foo")
self.assertEqual(db.CountGRRUsers(), 1)
# We execute test method twice to ensure that each time the database is
# rea... | now = rdfvalue.RDFDatetime.Now()
@db_test_lib.WithDatabase
def TestMethod(self, db: abstract_db.Database):
client_id = "C.0123456789abcdef"
db.WriteClientMetadata(client_id, first_seen=now)
client = db.ReadClientFullInfo(client_id)
self.assertEqual(client.metadata.first_seen, now)
... | identifier_body |
db_test_lib_test.py | #!/usr/bin/env python
from absl.testing import absltest
from typing import Text
from grr_response_core.lib import rdfvalue
from grr_response_server import blob_store
from grr_response_server.databases import db as abstract_db
from grr.test_lib import db_test_lib
class WithDatabaseTest(absltest.TestCase):
def tes... | absltest.main() | random_line_split | |
db_test_lib_test.py | #!/usr/bin/env python
from absl.testing import absltest
from typing import Text
from grr_response_core.lib import rdfvalue
from grr_response_server import blob_store
from grr_response_server.databases import db as abstract_db
from grr.test_lib import db_test_lib
class WithDatabaseTest(absltest.TestCase):
def tes... | absltest.main() | conditional_block | |
self_stats.js | $(document).ready(function() {
/* Done setting the chart up? Time to render it!*/
var data = [
{
values: [],
key: 'Event queue length',
color: '#000000'
},
]
/*These lines are all chart setup. Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
... |
}, 'json')
}
});
| {
data[0].values.shift()
} | conditional_block |
self_stats.js | $(document).ready(function() {
/* Done setting the chart up? Time to render it!*/
var data = [
{
values: [],
key: 'Event queue length',
color: '#000000'
},
]
/*These lines are all chart setup. Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
... |
});
| {
var api_url = $('div#data-api-url').data('api-url');
$.get(api_url + 'metrics?fields=event_queue_length', function(json) {
var d = new Date().getTime();
var value = {x: d, y: json.event_queue_length}
data[0].values.push(value);
// Remove old data, to keep the graph performant
if... | identifier_body |
self_stats.js | $(document).ready(function() {
/* Done setting the chart up? Time to render it!*/
var data = [
{
values: [],
key: 'Event queue length',
color: '#000000'
},
]
/*These lines are all chart setup. Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
... | () {
var api_url = $('div#data-api-url').data('api-url');
$.get(api_url + 'metrics?fields=event_queue_length', function(json) {
var d = new Date().getTime();
var value = {x: d, y: json.event_queue_length}
data[0].values.push(value);
// Remove old data, to keep the graph performant
... | updateData | identifier_name |
self_stats.js | $(document).ready(function() {
/* Done setting the chart up? Time to render it!*/
var data = [
{
values: [],
key: 'Event queue length',
color: '#000000'
},
]
/*These lines are all chart setup. Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
... | // Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update() });
return chart;
});
function updateData() {
var api_url = $('div#data-api-url').data('api-url');
$.get(api_url + 'metrics?fields=event_queue_length', function(json) {
var d = new Date().getTime();... | }, 3000);
| random_line_split |
macro_crate_test.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... |
MacExpr::new(quote_expr!(cx, 1i))
}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
-> Gc<Item> {
box(GC) Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
}
}
pub fn foo() {}
| {
cx.span_fatal(sp, "make_a_1 takes no arguments");
} | conditional_block |
macro_crate_test.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... |
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult> {
if !tts.is_empty() {
cx.span_fatal(sp, "make_a_1 takes no arguments");
}
MacExpr::new(quote_expr!(cx, 1i))
}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
... | {
reg.register_macro("make_a_1", expand_make_a_1);
reg.register_syntax_extension(
token::intern("into_foo"),
ItemModifier(expand_into_foo));
} | identifier_body |
macro_crate_test.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... | (cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult> {
if !tts.is_empty() {
cx.span_fatal(sp, "make_a_1 takes no arguments");
}
MacExpr::new(quote_expr!(cx, 1i))
}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
-> ... | expand_make_a_1 | identifier_name |
macro_crate_test.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... | -> Gc<Item> {
box(GC) Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
}
}
pub fn foo() {} |
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>) | random_line_split |
stylesheeteditor.py | #############################################################################
##
## Copyright (C) 2010 Hans-Peter Jansen <hpj@urpla.net>.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may ... | (self, sheetName):
self.loadStyleSheet(sheetName)
def on_styleTextEdit_textChanged(self):
self.ui.applyButton.setEnabled(True)
def on_applyButton_clicked(self):
QApplication.instance().setStyleSheet(
self.ui.styleTextEdit.toPlainText())
self.ui.applyButton.setEn... | on_styleSheetCombo_activated | identifier_name |
stylesheeteditor.py | #############################################################################
##
## Copyright (C) 2010 Hans-Peter Jansen <hpj@urpla.net>.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may ... | self.loadStyleSheet(sheetName)
def on_styleTextEdit_textChanged(self):
self.ui.applyButton.setEnabled(True)
def on_applyButton_clicked(self):
QApplication.instance().setStyleSheet(
self.ui.styleTextEdit.toPlainText())
self.ui.applyButton.setEnabled(False)
d... | self.ui.applyButton.setEnabled(False)
@pyqtSlot(str)
def on_styleSheetCombo_activated(self, sheetName): | random_line_split |
stylesheeteditor.py | #############################################################################
##
## Copyright (C) 2010 Hans-Peter Jansen <hpj@urpla.net>.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may ... |
self.ui.styleCombo.addItems(QStyleFactory.keys())
self.ui.styleCombo.setCurrentIndex(
self.ui.styleCombo.findText(defaultStyle, Qt.MatchContains))
self.ui.styleSheetCombo.setCurrentIndex(
self.ui.styleSheetCombo.findText('Coffee'))
self.loadStyleSheet(... | defaultStyle = regExp.cap(1) | conditional_block |
stylesheeteditor.py | #############################################################################
##
## Copyright (C) 2010 Hans-Peter Jansen <hpj@urpla.net>.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may ... |
def saveStyleSheet(self, fileName):
styleSheet = self.ui.styleTextEdit.toPlainText()
file = QFile(fileName)
if file.open(QFile.WriteOnly):
QTextStream(file) << styleSheet
else:
QMessageBox.information(self, "Unable to open file",
file.err... | file = QFile(':/qss/%s.qss' % sheetName.lower())
file.open(QFile.ReadOnly)
styleSheet = file.readAll()
try:
# Python v2.
styleSheet = unicode(styleSheet, encoding='utf8')
except NameError:
# Python v3.
styleSheet = str(styleSheet, encoding... | identifier_body |
string.rs | use std::fmt;
use std::ops;
#[derive(Clone, Eq)]
pub enum StringOrStatic {
String(String),
Static(&'static str),
}
impl From<&str> for StringOrStatic {
fn from(s: &str) -> Self {
StringOrStatic::String(s.to_owned())
}
}
impl From<String> for StringOrStatic {
fn from(s: String) -> Self {
... | (&self) -> &str {
match self {
StringOrStatic::String(s) => &s,
StringOrStatic::Static(s) => s,
}
}
pub fn to_string(&self) -> String {
format!("{}", self)
}
}
impl ops::Deref for StringOrStatic {
type Target = str;
fn deref(&self) -> &str {
... | as_str | identifier_name |
string.rs | use std::fmt;
use std::ops;
#[derive(Clone, Eq)]
pub enum StringOrStatic {
String(String),
Static(&'static str),
}
impl From<&str> for StringOrStatic {
fn from(s: &str) -> Self {
StringOrStatic::String(s.to_owned())
} | }
impl From<String> for StringOrStatic {
fn from(s: String) -> Self {
StringOrStatic::String(s)
}
}
impl StringOrStatic {
pub fn as_str(&self) -> &str {
match self {
StringOrStatic::String(s) => &s,
StringOrStatic::Static(s) => s,
}
}
pub fn to_stri... | random_line_split | |
Item.js | var virt = require("@nathanfaucett/virt"),
virtDOM = require("@nathanfaucett/virt-dom"),
css = require("@nathanfaucett/css"),
propTypes = require("@nathanfaucett/prop_types"),
domDimensions = require("@nathanfaucett/dom_dimensions"),
getImageDimensions = require("../../utils/getImageDimensions");
... | (props, children, context) {
var _this = this;
virt.Component.call(this, props, children, context);
this.state = {
loaded: false,
ratio: 1,
width: 0,
height: 0,
top: 0,
left: 0
};
this.onMouseOver = function(e) {
return _this.__onMouseOver(e... | Item | identifier_name |
Item.js | var virt = require("@nathanfaucett/virt"),
virtDOM = require("@nathanfaucett/virt-dom"),
css = require("@nathanfaucett/css"),
propTypes = require("@nathanfaucett/prop_types"),
domDimensions = require("@nathanfaucett/dom_dimensions"),
getImageDimensions = require("../../utils/getImageDimensions");
... |
virt.Component.extend(Item, "Item");
ItemPrototype = Item.prototype;
Item.propTypes = {
item: propTypes.object.isRequired,
height: propTypes.number.isRequired
};
Item.contextTypes = {
theme: propTypes.object.isRequired
};
ItemPrototype.__onLoad = function() {
if (!this.state.loaded) {
this.... | {
var _this = this;
virt.Component.call(this, props, children, context);
this.state = {
loaded: false,
ratio: 1,
width: 0,
height: 0,
top: 0,
left: 0
};
this.onMouseOver = function(e) {
return _this.__onMouseOver(e);
};
this.onMouseO... | identifier_body |
Item.js | var virt = require("@nathanfaucett/virt"),
virtDOM = require("@nathanfaucett/virt-dom"),
css = require("@nathanfaucett/css"),
propTypes = require("@nathanfaucett/prop_types"),
domDimensions = require("@nathanfaucett/dom_dimensions"),
getImageDimensions = require("../../utils/getImageDimensions");
... | zIndex: 0,
position: "relative"
},
img: {
position: "absolute",
maxWidth: "inherit",
top: state.top + "px",
left: state.left + "px",
width: state.loaded ? state.width + "px" : "inherit... | width: "100%",
height: props.height + "px",
background: theme.palette.accent2Color // theme.palette.canvasColor
},
imgWrap: { | random_line_split |
Item.js | var virt = require("@nathanfaucett/virt"),
virtDOM = require("@nathanfaucett/virt-dom"),
css = require("@nathanfaucett/css"),
propTypes = require("@nathanfaucett/prop_types"),
domDimensions = require("@nathanfaucett/dom_dimensions"),
getImageDimensions = require("../../utils/getImageDimensions");
... |
return styles;
};
ItemPrototype.render = function() {
var styles = this.getStyles(),
item = this.props.item;
return (
virt.createView("div", {
className: "Item",
style: styles.root
},
virt.createView("a", {
onMouseOv... | {
css.opacity(styles.hover, 0);
} | conditional_block |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | filter_file('mpicc', '$(MPICC)', 'Makefile', string=True)
filter_file('inline void', 'void', 'simul.c', string=True)
make('simul')
mkdirp(prefix.bin)
install('simul', prefix.bin) | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ##############################################################################
from spack import *
class Simul(Package):
"""simul is an MPI coordinated test of parallel
filesystem system calls and library functions. """
homepage = "https://github.com/LLNL/simul"
url = "https://github.com/LLNL/si... | # conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (Package):
"""simul is an MPI coordinated test of parallel
filesystem system calls and library functions. """
homepage = "https://github.com/LLNL/simul"
url = "https://github.com/LLNL/simul/archive/1.16.tar.gz"
version('1.16', 'd616c1046a170c1e1b7956c402d23a95')
version('1.15', 'a5744673c... | Simul | identifier_name |
socket.rs | // 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
// "License"); you may n... |
}
impl TIoChannel for TTcpChannel {
fn split(self) -> ::Result<(ReadHalf<Self>, WriteHalf<Self>)>
where
Self: Sized,
{
let mut s = self;
s.stream
.as_mut()
.and_then(|s| s.try_clone().ok())
.map(
|cloned| {
(R... | {
if let Some(ref mut s) = self.stream {
stream_operation(s)
} else {
Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),)
}
} | identifier_body |
socket.rs | // 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
// "License"); you may n... | else {
Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),)
}
}
}
impl TIoChannel for TTcpChannel {
fn split(self) -> ::Result<(ReadHalf<Self>, WriteHalf<Self>)>
where
Self: Sized,
{
let mut s = self;
s.stream
.as_mut()
... | {
stream_operation(s)
} | conditional_block |
socket.rs | // 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
// "License"); you may n... | )
} else {
match TcpStream::connect(&remote_address) {
Ok(s) => {
self.stream = Some(s);
Ok(())
}
Err(e) => Err(From::from(e)),
}
}
}
/// Shut down this channel.
///
... | TransportErrorKind::AlreadyOpen,
"tcp connection previously opened",
), | random_line_split |
socket.rs | // 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
// "License"); you may n... | <F, T>(&mut self, mut stream_operation: F) -> io::Result<T>
where
F: FnMut(&mut TcpStream) -> io::Result<T>,
{
if let Some(ref mut s) = self.stream {
stream_operation(s)
} else {
Err(io::Error::new(ErrorKind::NotConnected, "tcp endpoint not connected"),)
... | if_set | identifier_name |
thread_local.rs | use std::cell::RefCell;
use std::mem;
use thread::Thread;
pub struct Data {
pub current_thread: Thread,
pub parkable: bool, // i.e. for frame stack lock
}
pub unsafe fn init(data: Data) {
set_data_ptr(Box::new(RefCell::new(data)));
}
pub fn data() -> &'static RefCell<Data> {
unsafe{&*get_data_ptr(... | let mut data: *const RefCell<Data>;
asm!("movq %fs:0, $0" : "=r"(data) ::: "volatile");
data
}
#[cfg(target_arch = "x86_64")]
unsafe fn set_data_ptr(data: Box<RefCell<Data>>) {
let data_ptr: *const RefCell<Data> = mem::transmute(data);
asm!("movq $0, %fs:0" :: "r"(data_ptr) :: "volatile");
} |
#[cfg(target_arch = "x86_64")]
unsafe fn get_data_ptr() -> *const RefCell<Data> { | random_line_split |
thread_local.rs | use std::cell::RefCell;
use std::mem;
use thread::Thread;
pub struct Data {
pub current_thread: Thread,
pub parkable: bool, // i.e. for frame stack lock
}
pub unsafe fn init(data: Data) {
set_data_ptr(Box::new(RefCell::new(data)));
}
pub fn data() -> &'static RefCell<Data> {
unsafe{&*get_data_ptr(... | {
let data_ptr: *const RefCell<Data> = mem::transmute(data);
asm!("movq $0, %fs:0" :: "r"(data_ptr) :: "volatile");
} | identifier_body | |
thread_local.rs | use std::cell::RefCell;
use std::mem;
use thread::Thread;
pub struct Data {
pub current_thread: Thread,
pub parkable: bool, // i.e. for frame stack lock
}
pub unsafe fn init(data: Data) {
set_data_ptr(Box::new(RefCell::new(data)));
}
pub fn data() -> &'static RefCell<Data> {
unsafe{&*get_data_ptr(... | () -> *const RefCell<Data> {
let mut data: *const RefCell<Data>;
asm!("movq %fs:0, $0" : "=r"(data) ::: "volatile");
data
}
#[cfg(target_arch = "x86_64")]
unsafe fn set_data_ptr(data: Box<RefCell<Data>>) {
let data_ptr: *const RefCell<Data> = mem::transmute(data);
asm!("movq $0, %fs:0" :: "r"(data_p... | get_data_ptr | identifier_name |
hyperparams_builder.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... | (regularizer):
"""Builds a tf-slim regularizer from config.
Args:
regularizer: hyperparams_pb2.Hyperparams.regularizer proto.
Returns:
tf-slim regularizer.
Raises:
ValueError: On unknown regularizer.
"""
regularizer_oneof = regularizer.WhichOneof('regularizer_oneof')
if regularizer_oneof =... | _build_regularizer | identifier_name |
hyperparams_builder.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... |
raise ValueError('Unknown regularizer function: {}'.format(regularizer_oneof))
def _build_initializer(initializer):
"""Build a tf initializer from config.
Args:
initializer: hyperparams_pb2.Hyperparams.regularizer proto.
Returns:
tf initializer.
Raises:
ValueError: On unknown initializer.
... | return slim.l2_regularizer(scale=float(regularizer.l2_regularizer.weight)) | conditional_block |
hyperparams_builder.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... | batch_norm_params = None
if hyperparams_config.HasField('batch_norm'):
batch_norm = slim.batch_norm
batch_norm_params = _build_batch_norm_params(
hyperparams_config.batch_norm, is_training)
affected_ops = [slim.conv2d, slim.separable_conv2d, slim.conv2d_transpose]
if hyperparams_config.HasField... | hyperparams_pb2.Hyperparams):
raise ValueError('hyperparams_config not of type '
'hyperparams_pb.Hyperparams.')
batch_norm = None | random_line_split |
hyperparams_builder.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... |
def _build_activation_fn(activation_fn):
"""Builds a callable activation from config.
Args:
activation_fn: hyperparams_pb2.Hyperparams.activation
Returns:
Callable activation function.
Raises:
ValueError: On unknown activation function.
"""
if activation_fn == hyperparams_pb2.Hyperparams.N... | """Builds tf-slim arg_scope for convolution ops based on the config.
Returns an arg_scope to use for convolution ops containing weights
initializer, weights regularizer, activation function, batch norm function
and batch norm parameters based on the configuration.
Note that if the batch_norm parameteres are n... | identifier_body |
test_main.py | import sys
import pytest
from flask import current_app
from flask_wtf import Form
from wtforms import TextField
from faker import Faker
import arrow
import uuid
from unifispot.core.models import Wifisite,Device,Guesttrack
from tests.helpers import get_guestentry_url,randomMAC,loggin_as_admin
def test_guest_portal(se... |
#with invalid MAC/APMAC
res = client.get(get_guestentry_url(site1,mac='11:22:33:44',apmac='22:44:55')).status
assert '404 NOT FOUND' == res , 'Getting :%s instead 404 for\
with empty MAC/APMAC' %res
#with invalid sitekey
site2 = Wifisite(sitekey = 'test',backend_type='unifi')
... | random_line_split | |
test_main.py | import sys
import pytest
from flask import current_app
from flask_wtf import Form
from wtforms import TextField
from faker import Faker
import arrow
import uuid
from unifispot.core.models import Wifisite,Device,Guesttrack
from tests.helpers import get_guestentry_url,randomMAC,loggin_as_admin
def | (session,client):
#test unifi entry point
site1 = Wifisite.query.get(1)
#with emptry MAC/APMAC
res = client.get(get_guestentry_url(site1)).status
assert '404 NOT FOUND' == res , 'Getting :%s instead 404 for\
with empty MAC/APMAC' %res
#with invalid MAC/APMAC
res = client.get(ge... | test_guest_portal | identifier_name |
test_main.py | import sys
import pytest
from flask import current_app
from flask_wtf import Form
from wtforms import TextField
from faker import Faker
import arrow
import uuid
from unifispot.core.models import Wifisite,Device,Guesttrack
from tests.helpers import get_guestentry_url,randomMAC,loggin_as_admin
def test_guest_portal(se... | site1 = Wifisite.query.get(1)
#with emptry MAC/APMAC
res = client.get(get_guestentry_url(site1)).status
assert '404 NOT FOUND' == res , 'Getting :%s instead 404 for\
with empty MAC/APMAC' %res
#with invalid MAC/APMAC
res = client.get(get_guestentry_url(site1,mac='11:22:33:44',apmac='22... | identifier_body | |
glob.js | // Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, ... | () {
if (--n === 0)
self._finish()
}
}
Glob.prototype._realpathSet = function (index, cb) {
var matchset = this.matches[index]
if (!matchset)
return cb()
var found = Object.keys(matchset)
var self = this
var n = found.length
if (n === 0)
return cb()
var set = this.matches[index] =... | next | identifier_name |
glob.js | // Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, ... |
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
// old api surface
glob.glob = glob
function extend (origin, add) {
if (add === null || typeof add !== 'object') {
return origin
}
var keys = Object.keys(add)
var i = keys.length
while (i--) {
origin[keys[i]] = add[keys[i]]
}... | {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}
if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}
return new Glob(pattern, options, cb)
} | identifier_body |
glob.js | // Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, ... | var e = eq[i]
this._emitMatch(e[0], e[1])
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0)
this._processQueue.length = 0
for (var i = 0; i < pq.length; i ++) {
var p = pq[i]
this._processing--
this._process(p[0], p[1], p[2]... | random_line_split | |
storage.ts | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... |
};
}
/**
* Delete a key from the URI.
*/
function _unset(key) {
let items = _componentToDict(_readComponent());
delete items[key];
_writeComponent(_dictToComponent(items));
}
}
| {
if (_.isEqual(newVal, defaultVal)) {
_unset(URIStorageName);
} else {
set(URIStorageName, newVal);
}
} | conditional_block |
storage.ts | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... |
/**
* Store a string in the URI, with a corresponding key.
*/
export function setString(key: string, value: string) {
let items = _componentToDict(_readComponent());
items[key] = value;
_writeComponent(_dictToComponent(items));
}
/**
* Return a number stored in the URI, given a correspon... | {
let items = _componentToDict(_readComponent());
return items[key];
} | identifier_body |
storage.ts | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... | (
propertyName: string, defaultVal: boolean): Function {
return _getObserver(getBoolean, setBoolean, propertyName, defaultVal);
}
/**
* Return a function that updates URIStorage when a string property changes.
*/
export function getStringObserver(
propertyName: string, defaultVal: string): ... | getBooleanObserver | identifier_name |
storage.ts | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... | export function getObject(key: string): Object {
let items = _componentToDict(_readComponent());
return items[key] === undefined ? undefined : JSON.parse(atob(items[key]));
}
/**
* Store an object in the URI, with a corresponding key.
*/
export function setObject(key: string, value: Object) {
... | /**
* Return an object stored in the URI, given a corresponding key.
* Undefined if not found.
*/ | random_line_split |
runUnitTests.py | #!/usr/bin/env python
#
# =========================================================================
# This file is part of six.sicd-python
# =========================================================================
#
# (C) Copyright 2004 - 2016, MDA Information Systems LLC
#
# six.sicd-python is free software; you can... |
if __name__ == '__main__':
utils.setPaths()
run()
| install = utils.installPath()
unitTestDir = os.path.join(install, 'unittests')
childDirs = os.listdir(unitTestDir)
for childDir in childDirs:
for test in os.listdir(os.path.join(unitTestDir, childDir)):
print(os.path.join(unitTestDir, childDir, test))
testPathname = os.path.j... | identifier_body |
runUnitTests.py | #!/usr/bin/env python
#
# =========================================================================
# This file is part of six.sicd-python
# =========================================================================
#
# (C) Copyright 2004 - 2016, MDA Information Systems LLC
#
# six.sicd-python is free software; you can... | # You should have received a copy of the GNU Lesser General Public
# License along with this program; If not,
# see <http://www.gnu.org/licenses/>.
#
import os
from subprocess import call
import sys
import utils
def run():
install = utils.installPath()
unitTestDir = os.path.join(install, 'unittests')
chi... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# | random_line_split |
runUnitTests.py | #!/usr/bin/env python
#
# =========================================================================
# This file is part of six.sicd-python
# =========================================================================
#
# (C) Copyright 2004 - 2016, MDA Information Systems LLC
#
# six.sicd-python is free software; you can... | ():
install = utils.installPath()
unitTestDir = os.path.join(install, 'unittests')
childDirs = os.listdir(unitTestDir)
for childDir in childDirs:
for test in os.listdir(os.path.join(unitTestDir, childDir)):
print(os.path.join(unitTestDir, childDir, test))
testPathname = o... | run | identifier_name |
runUnitTests.py | #!/usr/bin/env python
#
# =========================================================================
# This file is part of six.sicd-python
# =========================================================================
#
# (C) Copyright 2004 - 2016, MDA Information Systems LLC
#
# six.sicd-python is free software; you can... | utils.setPaths()
run() | conditional_block | |
label.rs | use Scalar;
use color::{Color, Colorable};
use elmesque::Element;
use graphics::character::CharacterCache;
use label::FontSize;
use theme::Theme;
use ui::GlyphCache;
use widget::{self, Widget, WidgetId};
/// Displays some given text centred within a rectangle.
#[derive(Clone, Debug)]
pub struct Label<'a> {
common... | let widget::UpdateArgs { prev_state, .. } = args;
let widget::State { state: State(ref string), .. } = *prev_state;
if &string[..] != self.text { Some(State(self.text.to_string())) } else { None }
}
/// Construct an Element for the Label.
fn draw<'b, C>(args: widget::DrawArgs<'b, Se... | where C: CharacterCache,
{ | random_line_split |
label.rs |
use Scalar;
use color::{Color, Colorable};
use elmesque::Element;
use graphics::character::CharacterCache;
use label::FontSize;
use theme::Theme;
use ui::GlyphCache;
use widget::{self, Widget, WidgetId};
/// Displays some given text centred within a rectangle.
#[derive(Clone, Debug)]
pub struct Label<'a> {
commo... | (&mut self) -> &mut widget::CommonBuilder { &mut self.common }
fn unique_kind(&self) -> &'static str { "Label" }
fn init_state(&self) -> State { State(String::new()) }
fn style(&self) -> Style { self.style.clone() }
fn default_width<C: CharacterCache>(&self, theme: &Theme, glyph_cache: &GlyphCache<C>) ... | common_mut | identifier_name |
label.rs |
use Scalar;
use color::{Color, Colorable};
use elmesque::Element;
use graphics::character::CharacterCache;
use label::FontSize;
use theme::Theme;
use ui::GlyphCache;
use widget::{self, Widget, WidgetId};
/// Displays some given text centred within a rectangle.
#[derive(Clone, Debug)]
pub struct Label<'a> {
commo... | else { None }
}
/// Construct an Element for the Label.
fn draw<'b, C>(args: widget::DrawArgs<'b, Self, C>) -> Element
where C: CharacterCache,
{
use elmesque::form::{text, collage};
use elmesque::text::Text;
let widget::DrawArgs { state, style, theme, .. } = args;
... | { Some(State(self.text.to_string())) } | conditional_block |
io.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | blic toString () {
return `Io<${this.options.token}>`
}
private connected () {
return this.ws && this.ws.readyState === WebSocket.OPEN
}
public async start (): Promise<void> {
log.verbose('Io', 'start()')
if (this.lifeTimer) {
throw new Error('lifeTimer exist')
}
this.state.on(... | options.apihost = options.apihost || config.apihost
options.protocol = options.protocol || config.default.DEFAULT_PROTOCOL
this.id = options.wechaty.id
this.protocol = options.protocol + '|' + options.wechaty.id + '|' + config.serviceIp + '|' + options.servicePort
log.verbose('Io', 'instantiated... | identifier_body |
io.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | : WebSocket.Data) {
log.silly('Io', 'initWebSocket() ws.on(message): %s', data)
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
if (typeof data !== 'string') {
throw new Error('data should be string...')
}
const ioEvent: IoEve... | ssage (data | identifier_name |
io.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | protocol? : string,
servicePort? : number,
}
export const IO_EVENT_DICT = {
botie : 'tbw',
error : 'tbw',
heartbeat : 'tbw',
jsonrpc : 'JSON RPC',
login : 'tbw',
logout : 'tbw',
message : 'tbw',
raw : 'tbw',
reset : 'tbw',
scan : 'tbw',
shutdown : 'tbw',
... | random_line_split | |
formant.py | ###################################
## SPADE formant analysis script ##
###################################
## Processes and extracts 'static' (single point) formant values, along with linguistic
## and acoustic information from corpora collected as part of the SPeech Across Dialects
## of English (SPADE) project.
##... | 'The corpus {0} does not have a directory (available: {1}). Please make it with a {0}.yaml file inside.'.format(
args.corpus_name, ', '.join(directories)))
sys.exit(1)
corpus_conf = common.load_config(corpus_name)
print('Processing...')
## apply corpus reset or docker a... |
## sanity-check the corpus name (i.e., that it directs to a YAML file)
if args.corpus_name not in directories:
print( | random_line_split |
formant.py | ###################################
## SPADE formant analysis script ##
###################################
## Processes and extracts 'static' (single point) formant values, along with linguistic
## and acoustic information from corpora collected as part of the SPeech Across Dialects
## of English (SPADE) project.
##... |
## Determine the class of phone labels to be used for formant analysis
## based on lists provided in the YAML file.
if corpus_conf['stressed_vowels']:
vowels_to_analyze = corpus_conf['stressed_vowels']
else:
vowels_to_analyze = corpus_conf['vowel_inventory']
... | vowel_prototypes_path = os.path.join(base_dir, corpus_name, '{}_prototypes.csv'.format(corpus_name)) | conditional_block |
config_validation.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
# Note: this module is tested by a unit test config_validation_test.py,
# rather than recipe simulation tests.
_BISECT_CONFIG_SCHEMA = {
'com... | (config, schema, key): # pragma: no cover
"""Checks the correctness of the given field in a config."""
if schema[key].get('required') and config.get(key) is None:
raise ValidationFail('Required key "%s" missing.' % key)
if config.get(key) is None:
return # Optional field.
value = config[key]
field_t... | validate_key | identifier_name |
config_validation.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
# Note: this module is tested by a unit test config_validation_test.py,
# rather than recipe simulation tests.
_BISECT_CONFIG_SCHEMA = {
'com... |
def _validate_metric(bisect_mode, metric): # pragma: no cover
if bisect_mode not in ('mean', 'std_dev'):
return
if not (isinstance(metric, basestring) and metric.count('/') == 1):
raise ValidationFail('Invalid value for "metric": %s' % metric)
| try:
earlier = int(good_revision)
later = int(bad_revision)
except ValueError:
return # The revisions could be sha1 hashes.
if earlier >= later:
raise ValidationFail('Order of good_revision (%d) and bad_revision(%d) '
'is reversed.' % (earlier, later)) | identifier_body |
config_validation.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
# Note: this module is tested by a unit test config_validation_test.py,
# rather than recipe simulation tests.
_BISECT_CONFIG_SCHEMA = {
'com... |
if 'good_revision' in schema and 'bad_revision' in schema:
_validate_revisions(config.get('good_revision'), config.get('bad_revision'))
if 'bisect_mode' in schema and 'metric' in schema:
_validate_metric(config.get('bisect_mode'), config.get('metric'))
def validate_key(config, schema, key): # pragma: n... | schema = _BISECT_CONFIG_SCHEMA if schema is None else schema
for key in set(schema):
validate_key(config, schema, key) | random_line_split |
config_validation.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
# Note: this module is tested by a unit test config_validation_test.py,
# rather than recipe simulation tests.
_BISECT_CONFIG_SCHEMA = {
'com... |
def _validate_integer(value, key): # pragma: no cover
try:
int(value)
except ValueError:
_fail(value, key)
def _validate_boolean(value, key): # pragma: no cover
if value not in (True, False):
_fail(value, key)
def _validate_revisions(good_revision, bad_revision): # pragma: no cover
try:
... | _fail(value, key) | conditional_block |
validator.schema.test.ts | import * as fs from 'fs';
import * as mocha from 'mocha'
import {expect} from 'chai'
import {Validator} from '../src/validator/validator'
describe('Validate Schemas', () => {
var validator: Validator; | .then(() => done())
.catch((err: any) => done(err));
})
it('BasicValidation', (done) => {
var fileContent = fs.readFileSync('./test/baseFiles/validParam.json', 'utf8').toString();
let paramSchema: any = JSON.parse(fileContent);
_self.validator.validateSchema('./test/baseF... | var _self = this;
before((done) => {
_self.validator = new Validator();
_self.validator.Initialize() | random_line_split |
shift.ts | import { Data } from '../models';
export function shift(data: Data): Data | {
const placement = data.placement;
const basePlacement = placement.split(' ')[0];
const shiftVariation = placement.split(' ')[1];
if (shiftVariation) {
const { host, target } = data.offsets;
const isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
const side = isVertical ? 'left' : 'top... | identifier_body | |
shift.ts | import { Data } from '../models';
export function | (data: Data): Data {
const placement = data.placement;
const basePlacement = placement.split(' ')[0];
const shiftVariation = placement.split(' ')[1];
if (shiftVariation) {
const { host, target } = data.offsets;
const isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
const side = isVerti... | shift | identifier_name |
shift.ts | import { Data } from '../models';
export function shift(data: Data): Data {
const placement = data.placement;
const basePlacement = placement.split(' ')[0];
const shiftVariation = placement.split(' ')[1];
if (shiftVariation) {
const { host, target } = data.offsets; | const shiftOffsets = {
start: { [side]: host[side] },
end: {
[side]: (host[side] ?? 0) + host[measurement] - target[measurement]
}
};
data.offsets.target = {
...target, ...{
[side]: (side === shiftVariation ? shiftOffsets.start[side] : shiftOffsets.end[side])
}... | const isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
const side = isVertical ? 'left' : 'top';
const measurement = isVertical ? 'width' : 'height';
| random_line_split |
shift.ts | import { Data } from '../models';
export function shift(data: Data): Data {
const placement = data.placement;
const basePlacement = placement.split(' ')[0];
const shiftVariation = placement.split(' ')[1];
if (shiftVariation) |
return data;
}
| {
const { host, target } = data.offsets;
const isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
const side = isVertical ? 'left' : 'top';
const measurement = isVertical ? 'width' : 'height';
const shiftOffsets = {
start: { [side]: host[side] },
end: {
[side]: (host[... | conditional_block |
bootstrap-table-en-US.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jQuery));
}(this, (function ($... | if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
var SPECIES = wellKnownSymbol('species');
var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and se... | C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES$1]; | random_line_split |
bootstrap-table-en-US.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jQuery));
}(this, (function ($... | (fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
/* global globalThis -- safe */
check(typeof globalThi... | createCommonjsModule | identifier_name |
bootstrap-table-en-US.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jQuery));
}(this, (function ($... |
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
/* global globalThis -- safe */
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
check(typeof... | {
return module = { exports: {} }, fn(module, module.exports), module.exports;
} | identifier_body |
cell-static.ts | import { Gutters } from './gutters';
import { Gutters as DefaultGutters, GuttersProps } from '../components/gutters';
import { CellProperties } from './cell-properties';
/**
* Creates a single breakpoint sized grid.
*
* @param {string | number} size The size of your cell. Can be `full` (default) for ... |
return css;
};
| {
css = css.concat(Gutters(gutter, gutterType, gutterPosition));
} | conditional_block |
cell-static.ts | import { Gutters } from './gutters';
import { Gutters as DefaultGutters, GuttersProps } from '../components/gutters';
import { CellProperties } from './cell-properties';
/**
* Creates a single breakpoint sized grid.
*
* @param {string | number} size The size of your cell. Can be `full` (default) for ... |
return css;
}; | random_line_split | |
index.tsx | import React, { FC, ReactElement } from 'react';
import styled from 'styled-components';
import theme from '../../theme';
import { isMac } from '../../utils';
type P = {
title?: string;
children?: ReactElement | ReactElement[] | string;
};
const Layout: FC<P> = ({ title = '', children }) => {
return (
<Win>... | text-align: center;
-webkit-app-region: drag;
-webkit-user-select: none;
`; | random_line_split | |
licenseck.py | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
#... | ] | random_line_split | |
fitadd.run.js | var options;
chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
options = response;
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
WireUp();
clearInterval(readyStateCheckInterval);
}
}, 10);
});
function WireUp(){... | else{
if (options.editShortcut){
fitadd.fitnesseui.RegisterEditShortcut();
if (options.cloneShortcut){
fitadd.fitnesseui.RegisterCloneLink();
}
}
}
}
}
| {
if (options.saveShortcut){
fitadd.fitnesseui.RegisterSaveShortcut();
}
if (options.autoFormat){
fitadd.fitnesseui.RegisterAutoFormatOnSave();
}
} | conditional_block |
fitadd.run.js | var options;
chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
options = response;
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
WireUp();
clearInterval(readyStateCheckInterval);
}
}, 10);
});
function WireUp(){... | fitadd.fitnesseui.RegisterEditShortcut();
if (options.cloneShortcut){
fitadd.fitnesseui.RegisterCloneLink();
}
}
}
}
} | random_line_split | |
fitadd.run.js | var options;
chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
options = response;
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
WireUp();
clearInterval(readyStateCheckInterval);
}
}, 10);
});
function | (){
if (fitadd.fitnessepage.IsFitnesse()){
if (fitadd.fitnessepage.AreAdding()){
if (options.cloneShortcut){
fitadd.fitnesseui.LoadClonedContentIfNeeded();
}
}
if (options.spEnabled){
fitadd.fixtures.search.RegisterHandlers(options);
}
if (fitadd.fitnessepage.AreEditing()){
... | WireUp | identifier_name |
fitadd.run.js | var options;
chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
options = response;
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
WireUp();
clearInterval(readyStateCheckInterval);
}
}, 10);
});
function WireUp() | {
if (fitadd.fitnessepage.IsFitnesse()){
if (fitadd.fitnessepage.AreAdding()){
if (options.cloneShortcut){
fitadd.fitnesseui.LoadClonedContentIfNeeded();
}
}
if (options.spEnabled){
fitadd.fixtures.search.RegisterHandlers(options);
}
if (fitadd.fitnessepage.AreEditing()){
... | identifier_body | |
Gruntfile.js | 'use strict';
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required grunt tasks
require('jit-grunt')(grunt, {
lockfile: 'grunt-lock'
});
// Configurable paths
var config = ... | files: [{
expand: true,
cwd: '.tmp/css/',
src: '{,*/}*.css',
dest: '<%= config.public_dir %>/css'
}]
}
}
});
grunt.registerTask('serve', 'Start the server and preview your app', f... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.