file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
preprocessing.py | REDACTED.minigo import sgf_wrapper
from REDACTED.minigo import symmetries
TF_RECORD_CONFIG = tf.python_io.TFRecordOptions(
tf.python_io.TFRecordCompressionType.ZLIB)
def _one_hot(index):
onehot = np.zeros([go.N * go.N + 1], dtype=np.float32)
onehot[index] = 1
return onehot
def make_tf_example(features, ... | pwcs = sgf_wrapper.replay_sgf_file(sgf_filename)
tf_examples = map(_make_tf_example_from_pwc, pwcs)
write_tf_examples(tf_record, tf_examples) | identifier_body | |
preprocessing.py | 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.
# pylint: disable=g-doc-args,missing-docstring,g-doc-return-or-yield,g-space-before-docstring-summary,unused-argument,g-sho... | dataset = dataset.apply(tf.data.experimental.unbatch())
dataset = dataset.apply(
tf.data.experimental.map_and_batch(
functools.partial(_random_rotation, feature_layout), batch_size))
return dataset.make_one_shot_iterator().get_next()
def get_tpu_input_tensors(batch_size,
... | dataset = dataset.map(
functools.partial(batch_parse_tf_example, batch_size, feature_layout))
if random_rotation:
# Unbatch the dataset so we can rotate it | random_line_split |
preprocessing.py | 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.
# pylint: disable=g-doc-args,missing-docstring,g-doc-return-or-yield,g-space-before-docstring-summary,unused-argument,g-sho... | (index):
onehot = np.zeros([go.N * go.N + 1], dtype=np.float32)
onehot[index] = 1
return onehot
def make_tf_example(features, pi, value):
"""
Args:
features: [N, N, FEATURE_DIM] nparray of uint8
pi: [N * N + 1] nparray of float32
value: float
"""
return tf.train.Example(
... | _one_hot | identifier_name |
preprocessing.py | 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.
# pylint: disable=g-doc-args,missing-docstring,g-doc-return-or-yield,g-space-before-docstring-summary,unused-argument,g-sho... |
dataset = dataset.batch(batch_size)
return dataset
def _random_rotation(feature_layout, x_tensor, outcome_tensor):
pi_tensor = outcome_tensor['pi_tensor']
if feature_layout == 'nhwc':
x_rot_tensor, pi_rot_tensor = symmetries.rotate_train_nhwc(
x_tensor, pi_tensor)
else:
x_rot_tensor, pi_ro... | dataset = dataset.shuffle(buffer_size=shuffle_buffer_size) | conditional_block |
webpresence.py | #!/usr/bin/env python
"""
For the moment we're not using this, but it would be nice to do so
at some point. It isn't really relevant to the researcher RDF export, the
idea would be to export details of a web-presence, to compile a complete directory
of websites in the Medical Sciences Division.
"""
... | homepageProp = rdf.createElement('foaf:homepage')
deptElement.appendChild(homepageProp)
wpElem = rdf.createElement('res:WebPresence')
homepageProp.appendChild(wpElem)
title = rdf.createElement('dc:title')
title.appendChild(rdf.createTextNode(deptName + ' Website'))
wpElem.appendChild(t... | #TODO - this will be real data in the future
standardWebmaster = 'webmaster@medsci.ox.ac.uk'
| random_line_split |
webpresence.py | #!/usr/bin/env python
"""
For the moment we're not using this, but it would be nice to do so
at some point. It isn't really relevant to the researcher RDF export, the
idea would be to export details of a web-presence, to compile a complete directory
of websites in the Medical Sciences Division.
"""
... | (rdf, deptElement, deptName):
"""
<foaf:Organization rdf:about="http://www.psy.ox.ac.uk/">
<foaf:homepage>
<res:WebPresence>
<dc:title>Department of Experimental Psychology Website</dc:title>
<dc:creator>
<foaf:Person>
<foaf:mbox>anne.bowt... | addWebPresenceElement | identifier_name |
webpresence.py | #!/usr/bin/env python
"""
For the moment we're not using this, but it would be nice to do so
at some point. It isn't really relevant to the researcher RDF export, the
idea would be to export details of a web-presence, to compile a complete directory
of websites in the Medical Sciences Division.
"""
... | deptElement.appendChild(homepageProp)
wpElem = rdf.createElement('res:WebPresence')
homepageProp.appendChild(wpElem)
title = rdf.createElement('dc:title')
title.appendChild(rdf.createTextNode(deptName + ' Website'))
wpElem.appendChild(title)
creator = rdf.createElement('dc:c... | """
<foaf:Organization rdf:about="http://www.psy.ox.ac.uk/">
<foaf:homepage>
<res:WebPresence>
<dc:title>Department of Experimental Psychology Website</dc:title>
<dc:creator>
<foaf:Person>
<foaf:mbox>anne.bowtell@medsci.ox.ac.uk</foaf:mbox>
</foaf:Perso... | identifier_body |
app_engine_handler.py | # Copyright 2013 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 logging
from appengine_wrappers import webapp2
from handler import Handler
from servlet import Request
class AppEngineHandler(webapp2.RequestHandle... | if profile_mode:
pr.disable()
s = StringIO.StringIO()
pstats.Stats(pr, stream=s).sort_stats(profile_mode).print_stats()
self.response.out.write(s.getvalue())
self.response.headers['Content-Type'] = 'text/plain'
self.response.status = 200
elif response:
... | '''Top-level handler for AppEngine requests. Just converts them into our
internal Servlet architecture.
'''
def get(self):
profile_mode = self.request.get('profile')
if profile_mode:
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
try:
response = None
... | identifier_body |
app_engine_handler.py | # Copyright 2013 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 logging
from appengine_wrappers import webapp2
from handler import Handler
from servlet import Request
class AppEngineHandler(webapp2.RequestHandle... | s = StringIO.StringIO()
pstats.Stats(pr, stream=s).sort_stats(profile_mode).print_stats()
self.response.out.write(s.getvalue())
self.response.headers['Content-Type'] = 'text/plain'
self.response.status = 200
elif response:
self.response.out.write(response.content.To... | logging.exception(e)
finally:
if profile_mode:
pr.disable() | random_line_split |
app_engine_handler.py | # Copyright 2013 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 logging
from appengine_wrappers import webapp2
from handler import Handler
from servlet import Request
class AppEngineHandler(webapp2.RequestHandle... | self.response.out.write('Internal server error')
self.response.status = 500 | conditional_block | |
app_engine_handler.py | # Copyright 2013 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 logging
from appengine_wrappers import webapp2
from handler import Handler
from servlet import Request
class | (webapp2.RequestHandler):
'''Top-level handler for AppEngine requests. Just converts them into our
internal Servlet architecture.
'''
def get(self):
profile_mode = self.request.get('profile')
if profile_mode:
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
t... | AppEngineHandler | identifier_name |
debug.py | #!/usr/bin/env python
## Copyright (C) 2008 Red Hat, Inc.
## Copyright (C) 2008 Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License... |
def get_debugging ():
return _debug
def set_debugging (d):
global _debug
_debug = d
def fatalException (exitcode=1):
nonfatalException (type="fatal", end="Exiting")
sys.exit (exitcode)
def nonfatalException (type="non-fatal", end="Continuing anyway.."):
d = get_debugging ()
set_debuggin... | if _debug:
try:
print x
except:
pass | identifier_body |
debug.py | #!/usr/bin/env python
## Copyright (C) 2008 Red Hat, Inc.
## Copyright (C) 2008 Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License... |
extxt = traceback.format_exception_only (type, value)
for line in traceback.format_tb(tb):
debugprint (line.strip ())
debugprint (extxt[0].strip ())
debugprint (end)
set_debugging (d)
| tblast = tblast[:len (tblast) - 1] | conditional_block |
debug.py | #!/usr/bin/env python
## Copyright (C) 2008 Red Hat, Inc.
## Copyright (C) 2008 Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify | ## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Genera... | ## it under the terms of the GNU General Public License as published by | random_line_split |
debug.py | #!/usr/bin/env python
## Copyright (C) 2008 Red Hat, Inc.
## Copyright (C) 2008 Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License... | (exitcode=1):
nonfatalException (type="fatal", end="Exiting")
sys.exit (exitcode)
def nonfatalException (type="non-fatal", end="Continuing anyway.."):
d = get_debugging ()
set_debugging (True)
debugprint ("Caught %s exception. Traceback:" % type)
(type, value, tb) = sys.exc_info ()
tblast... | fatalException | identifier_name |
__init__.py | import sys
import os
import shutil
from zope.interface.verify import verifyObject
from twisted.trial import unittest
# ugly hack to avoid cyclic imports of scrapy.spider when running this test
# alone
from scrapy.interfaces import ISpiderManager
from scrapy.spidermanager import SpiderManager
from scrapy.http import ... |
def test_load_from_crawler(self):
spider = self.spiderman.create('spider4', a='OK')
self.assertEqual(spider.a, 'OK')
| self.spiderman = SpiderManager(['scrapy.tests.test_spidermanager.test_spiders.spider0'])
assert len(self.spiderman._spiders) == 0 | identifier_body |
__init__.py | import sys
import os
import shutil
from zope.interface.verify import verifyObject
from twisted.trial import unittest
# ugly hack to avoid cyclic imports of scrapy.spider when running this test
# alone
from scrapy.interfaces import ISpiderManager
from scrapy.spidermanager import SpiderManager
from scrapy.http import ... |
def setUp(self):
orig_spiders_dir = os.path.join(module_dir, 'test_spiders')
self.tmpdir = self.mktemp()
os.mkdir(self.tmpdir)
self.spiders_dir = os.path.join(self.tmpdir, 'test_spiders_xxx')
shutil.copytree(orig_spiders_dir, self.spiders_dir)
sys.path.append(self.tm... | class SpiderManagerTest(unittest.TestCase): | random_line_split |
__init__.py | import sys
import os
import shutil
from zope.interface.verify import verifyObject
from twisted.trial import unittest
# ugly hack to avoid cyclic imports of scrapy.spider when running this test
# alone
from scrapy.interfaces import ISpiderManager
from scrapy.spidermanager import SpiderManager
from scrapy.http import ... | (self):
self.assertEqual(self.spiderman.find_by_request(Request('http://scrapy1.org/test')),
['spider1'])
self.assertEqual(self.spiderman.find_by_request(Request('http://scrapy2.org/test')),
['spider2'])
self.assertEqual(set(self.spiderman.find_by_request(Request('http://... | test_find_by_request | identifier_name |
mapstory_tm_world_config.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# do this when > 1.6!!!
# from django.db import migrations, models
from gazetteer.models import GazSource,GazSourceConfig,LocationTypeField,CodeFieldConfig,NameFieldConfig
from skosxl.models import Concept, Scheme, MapRelation
from gazetteer.settings imp... | ():
(sch,created) = Scheme.objects.get_or_create(uri=TARGET_NAMESPACE_FT[:-1], defaults = { 'pref_label' :"Gaz Feature types" })
try:
(ft,created) = Concept.objects.get_or_create(term="ADMIN", defaults = { 'pref_label' :"Populated Place", 'definition':"Populated place"} , scheme = sch)
except:
... | load_base_ft | identifier_name |
mapstory_tm_world_config.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# do this when > 1.6!!!
# from django.db import migrations, models
from gazetteer.models import GazSource,GazSourceConfig,LocationTypeField,CodeFieldConfig,NameFieldConfig
from skosxl.models import Concept, Scheme, MapRelation
from gazetteer.settings imp... | migrations.RunPython(load_config),
]
""" | migrations.RunPython(load_ft_mappings), | random_line_split |
mapstory_tm_world_config.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# do this when > 1.6!!!
# from django.db import migrations, models
from gazetteer.models import GazSource,GazSourceConfig,LocationTypeField,CodeFieldConfig,NameFieldConfig
from skosxl.models import Concept, Scheme, MapRelation
from gazetteer.settings imp... |
"""
class Migration(migrations.Migration):
initial = True
dependencies = [
#('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(load_ft_mappings),
migrations.RunPython(load_config),
]
"""
| try:
GazSourceConfig.objects.filter(name="TM_WorldBoundaries").delete()
except:
pass
config=GazSourceConfig.objects.create(lat_field="lat", name="TM_WorldBoundaries", long_field="lon")
NameFieldConfig.objects.create(config=config,language="en", as_default=True, languageNamespace="", field="n... | identifier_body |
DataSetItem.js | /*!
* ${copyright}
*/
// Provides control sap.ui.ux3.DataSetItem.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Element', './library'],
function(jQuery, Element, library) {
"use strict";
/**
* Constructor for a new DataSetItem.
*
* @param {string} [sId] id for the new control, generated automatically ... | };
DataSetItem.prototype.ondblclick = function(oEvent) {
this.onclick(oEvent);
};
return DataSetItem;
}, /* bExport= */ true); | this.fireSelected({
itemId: this.getId(),
shift: bShift,
ctrl: bCtrl
}); | random_line_split |
styles.ts | /*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modi... |
import { theme } from '@looker/components'
// Diagram styles
export const OVERRIDE_KEY = 'rgb(45, 126, 234)'
export const OVERRIDE_KEY_SUBTLE = '#eaf2fc'
export const DIAGRAM_BACKGROUND_COLOR = theme.colors.ui1
export const TABLE_BACKGROUND_COLOR = theme.colors.ui3
export const DIAGRAM_JOIN_COLOR = theme.colors.ui4... | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/ | random_line_split |
convert_cldr.py | #!/usr/bin/python
from gi.repository import Gdk
from xml.etree.ElementTree import ElementTree, Element
import re
ESCAPE_PATTERN = re.compile(r'\\u\{([0-9A-Fa-f]+?)\}')
ISO_PATTERN = re.compile(r'[A-E]([0-9]+)')
def parse_single_key(value):
key = Element('key')
uc = 0
if hasattr(__builtins__, 'unichr'):
... |
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("supply a CLDR keyboard file")
sys.exit(1)
source = sys.argv[-1]
itree = ElementTree()
itree.parse(source)
root = convert(source, itree)
indent(root)
otree = ElementTree(root)
if hasattr(sys.stdo... | i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
... | identifier_body |
convert_cldr.py | #!/usr/bin/python
from gi.repository import Gdk
from xml.etree.ElementTree import ElementTree, Element
import re
ESCAPE_PATTERN = re.compile(r'\\u\{([0-9A-Fa-f]+?)\}')
ISO_PATTERN = re.compile(r'[A-E]([0-9]+)')
def parse_single_key(value):
key = Element('key')
uc = 0
if hasattr(__builtins__, 'unichr'):
... |
for k, v in sorted(list(rows.items()), key=lambda x: x[0], reverse=True):
row = Element('row')
for key in sorted(v, key=lambda x: x):
row.append(key[1])
level.append(row)
return root
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):... | subkey = parse_single_key(value)
key.append(subkey) | conditional_block |
convert_cldr.py | #!/usr/bin/python
from gi.repository import Gdk
from xml.etree.ElementTree import ElementTree, Element
import re
ESCAPE_PATTERN = re.compile(r'\\u\{([0-9A-Fa-f]+?)\}')
ISO_PATTERN = re.compile(r'[A-E]([0-9]+)')
def parse_single_key(value):
key = Element('key')
uc = 0
if hasattr(__builtins__, 'unichr'):
... | (m):
return chr(int(m.group(1), 16))
else:
def unescape(m):
return chr(int(m.group(1), 16))
value = ESCAPE_PATTERN.sub(unescape, value)
if len(value) > 1:
key.set('text', value)
uc = ord(value[0])
keyval = Gdk.unicode_to_keyval(uc)
name = Gdk.keyval_name(k... | unescape | identifier_name |
convert_cldr.py | #!/usr/bin/python
from gi.repository import Gdk
from xml.etree.ElementTree import ElementTree, Element
import re
ESCAPE_PATTERN = re.compile(r'\\u\{([0-9A-Fa-f]+?)\}')
ISO_PATTERN = re.compile(r'[A-E]([0-9]+)')
def parse_single_key(value):
key = Element('key')
uc = 0
if hasattr(__builtins__, 'unichr'):
... | mode = 'latched'
else:
mode = 'locked'
level.set('mode', mode)
for _map in keymap.iter('map'):
value = _map.get('to')
key = parse_single_key(value)
iso = _map.get('iso')
if not ISO_PATTERN.match(iso):
sys.std... | modifiers = keymap.get('modifiers')
if not modifiers:
mode = 'default'
elif 'shift' in modifiers.split(' ') or 'lock' in modifiers.split(' '): | random_line_split |
doco.rs | use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct Item<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}... |
fn prefix(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
for (i, line) in input.lines().enumerate() {
if i > 0 {
fmt.write_char('\n')?;
}
if line.len() == 0 {
write!(fmt, "{}", pre)?;
} else {
write!(fmt, "{} {}", pre, line.trim())?;... | {
// fix up problems in AWS docs
let escaped_1 = input.replace("<code>\\</code>", "<code>\</code>");
let escaped_2 = escaped_1.replace("\"</p>\"", "</p>");
// parse and render markdown
let markdown = Markdown::new(&escaped_2);
let mut html_renderer = Html::new(Flags::empty(), 0);
let b... | identifier_body |
doco.rs | use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct Item<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}... |
}
Ok(())
}
| {
write!(fmt, "{} {}", pre, line.trim())?;
} | conditional_block |
doco.rs | use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct Item<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}... | if i > 0 {
fmt.write_char('\n')?;
}
if line.len() == 0 {
write!(fmt, "{}", pre)?;
} else {
write!(fmt, "{} {}", pre, line.trim())?;
}
}
Ok(())
} | random_line_split | |
doco.rs | use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct | <T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}
}
pub struct Module<T>(pub T);
impl<T: AsRef<str>> Display for Module<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.... | Item | identifier_name |
call.js | (function (tree) {
//
// A function call node.
//
tree.Call = function (name, args, index) {
this.name = name;
this.args = args;
this.index = index;
};
tree.Call.prototype = {
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we ... | if (this.name in tree.functions) { // 1.
try {
return tree.functions[this.name].apply(tree.functions, args);
} catch (e) {
throw { type: e.type || "Runtime",
message: "error evaluating function `" + this.name + "`" +
... | var args = this.args.map(function (a) { return a.eval(env) });
| random_line_split |
call.js | (function (tree) {
//
// A function call node.
//
tree.Call = function (name, args, index) {
this.name = name;
this.args = args;
this.index = index;
};
tree.Call.prototype = {
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we ... | else { // 2.
return new(tree.Anonymous)(this.name +
"(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")");
}
},
toCSS: function (env) {
return this.eval(env).toCSS();
}
};
})(require('../tree'));
| { // 1.
try {
return tree.functions[this.name].apply(tree.functions, args);
} catch (e) {
throw { type: e.type || "Runtime",
message: "error evaluating function `" + this.name + "`" +
(e.message ? ': ' + e.m... | conditional_block |
model.ts | import Ember from 'ember';
import DS, { ChangedAttributes } from 'ember-data';
import { assertType } from "./lib/assert";
import RSVP from 'rsvp';
const Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
title: DS.attr({ defaultValue: "The default" }),
title2: DS.attr({ defaultValue:... |
})
});
const user = User.create({ username: 'dwickern' });
assertType<string>(user.get('id'));
assertType<string>(user.get('username'));
assertType<boolean>(user.get('verified'));
assertType<Date>(user.get('createdAt'));
assertType<DS.Store>(user.get('store'));
user.serialize();
user.serialize({ includeId: true ... | { return new Date(); } | identifier_body |
model.ts | import Ember from 'ember';
import DS, { ChangedAttributes } from 'ember-data';
import { assertType } from "./lib/assert";
import RSVP from 'rsvp';
const Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
title: DS.attr({ defaultValue: "The default" }),
title2: DS.attr({ defaultValue:... | () { return new Date(); }
})
});
const user = User.create({ username: 'dwickern' });
assertType<string>(user.get('id'));
assertType<string>(user.get('username'));
assertType<boolean>(user.get('verified'));
assertType<Date>(user.get('createdAt'));
assertType<DS.Store>(user.get('store'));
user.serialize();
user.ser... | defaultValue | identifier_name |
model.ts | import Ember from 'ember';
import DS, { ChangedAttributes } from 'ember-data';
import { assertType } from "./lib/assert";
import RSVP from 'rsvp';
const Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
title: DS.attr({ defaultValue: "The default" }),
title2: DS.attr({ defaultValue:... | reloaded = user.reload({});
reloaded = user.reload({ adapterOptions: {} });
reloaded = user.reload({ adapterOptions: { fastAsCanBe: 'yessirree' } }); |
let reloaded: RSVP.Promise<typeof user>;
reloaded = user.reload(); | random_line_split |
main.rs | extern crate rand;
extern crate walkdir;
use walkdir::WalkDir;
use rand::{Rng, thread_rng};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{Error, SeekFrom};
use std::cmp;
use std::path::Path;
fn | () {
let mut recursive: bool = false;
let mut file: String = String::from("");
for argument in env::args().skip(1) {
if argument.to_lowercase() == "--help" || argument.to_lowercase() == "-help" {
help();
return;
} else if argument.to_lowercase() == "--v" || argument.... | main | identifier_name |
main.rs | extern crate rand;
extern crate walkdir;
use walkdir::WalkDir;
use rand::{Rng, thread_rng};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{Error, SeekFrom};
use std::cmp;
use std::path::Path;
fn main() {
let mut recursive: bool = false;
let mut file: String = String::fr... | file = get_path(&file);
if recursive {
for entry in WalkDir::new(file) {
let entry = entry.unwrap();
trumpify_file(entry.path());
}
} else {
trumpify_file(file)
}
}
fn get_path2(file: &str) -> Result<String, Error> {
let path = try!(fs::canonicalize(... | random_line_split | |
main.rs | extern crate rand;
extern crate walkdir;
use walkdir::WalkDir;
use rand::{Rng, thread_rng};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{Error, SeekFrom};
use std::cmp;
use std::path::Path;
fn main() {
let mut recursive: bool = false;
let mut file: String = String::fr... |
fn get_path(file: &str) -> String {
get_path2(file).unwrap_or(file.to_owned())
}
fn version() {
println!("\x1b[32mVersion:");
println!("\x1b[0m trump-0.1.0");
println!("\x1b[32mWebsite:");
println!("\x1b[0m https://github.com/x13machine/trump/");
println!("\x1b[32mCreator:");
printl... | {
let path = try!(fs::canonicalize(file));
Ok(path.display().to_string())
} | identifier_body |
screen_error_message.js | 'frame error:111',
PROXY_CONNECTION_FAILED: 'frame error:130',
PROXY_CONFIG_CHANGED: 'proxy changed',
LOADING_TIMEOUT: 'loading timeout',
PORTAL_DETECTED: 'portal detected'
};
// Frame loading errors.
const NET_ERROR = {
ABORTED_BY_USER: 3
};
// Link which starts guest session for capti... | random_line_split | ||
screen_error_message.js | PROXY_AUTH_CANCELLED: 'frame error:111',
PROXY_CONNECTION_FAILED: 'frame error:130',
PROXY_CONFIG_CHANGED: 'proxy changed',
LOADING_TIMEOUT: 'loading timeout',
PORTAL_DETECTED: 'portal detected'
};
// Frame loading errors.
const NET_ERROR = {
ABORTED_BY_USER: 3
};
// Link which starts g... |
$('gaia | {
// Gaia frame was reloaded. Nothing to do here.
return;
} | conditional_block |
background.ts | module Inknote.Drawing {
export class Background implements IDrawable {
private static _instance: Background;
static get Instance() {
if (!Background._instance) {
Background._instance = new Background();
}
return Background._instance;
... | : number, y: number, canvas: HTMLCanvasElement) {
this.mouse.x = x;
this.mouse.y = y;
return false;
}
order = -10;
mouse = { x: -100, y: -100 };
t = 0;
spinners = [];
constructor() {
}
draw(ctx: CanvasRenderingCon... | Over(x | identifier_name |
background.ts | module Inknote.Drawing {
export class Background implements IDrawable {
private static _instance: Background;
static get Instance() {
if (!Background._instance) {
| return Background._instance;
}
ID = getID();
x: number;
y: number;
hover: boolean;
select: boolean;
isOver(x: number, y: number, canvas: HTMLCanvasElement) {
this.mouse.x = x;
this.mouse.y = y;
return false;
... | Background._instance = new Background();
}
| conditional_block |
background.ts | module Inknote.Drawing {
export class Background implements IDrawable {
private static _instance: Background;
static get Instance() {
if (!Background._instance) {
Background._instance = new Background();
}
return Background._instance;
... | ctx.moveTo(i, 0);
// bulge around mouse?
//var dif = this.chase.x - i;
//if (dif > 0 && dif < 8) dif = 8;
//if (dif <= 0 && dif > -8) dif = -8;
//var blah = 100 / (dif);
//if (Math.abs(dif) < 200) {
... |
// uncomment for striped background.
/*for (var i = 0; i < canvas.width; i += 4){
ctx.beginPath(); | random_line_split |
background.ts | module Inknote.Drawing {
export class Background implements IDrawable {
private static _instance: Background;
static get Instance() {
if (!Background._instance) {
Background._instance = new Background();
}
return Background._instance;
... |
ctx.lineTo(i, canvas.height);
ctx.strokeStyle = Colours.faintBlue;
ctx.stroke();
}*/
this.t++;
// signature
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width / 2, canvas.height / 2);
... |
// uncomment for striped background.
/*for (var i = 0; i < canvas.width; i += 4){
ctx.beginPath();
ctx.moveTo(i, 0);
// bulge around mouse?
//var dif = this.chase.x - i;
//if (dif > 0 && dif < 8) dif = 8;
... | identifier_body |
args.rs | use ::structopt::StructOpt;
///
/// The structure of the commands for the app.
///
/// A large amount of this is generated by StructOpt.
/// See that project for how to write large amounts of this.
///
/// The gist however is that we make a struct that will hold
/// all of our arguments. Commands are then parsed, and ... |
///
/// Builds a new args from the main arguments given.
///
pub fn new_from_args() -> Args {
return Args::from_args();
}
} | pub path: String,
}
impl Args { | random_line_split |
args.rs |
use ::structopt::StructOpt;
///
/// The structure of the commands for the app.
///
/// A large amount of this is generated by StructOpt.
/// See that project for how to write large amounts of this.
///
/// The gist however is that we make a struct that will hold
/// all of our arguments. Commands are then parsed, and... | {
/// Enable logging, use multiple `v`s to increase verbosity.
#[structopt(short = "a", long = "all", help = "Set to show all hidden files and directories.")]
pub all: bool,
/// Set the minimum width of the directory column.
#[structopt(default_value = "0", short = "d", long = "directory-width", ... | Args | identifier_name |
PowerNodePlugin.py | # Copyright 2016, IBM US, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def __init__(self):
self.host = None
self.userid = None
self.password = None
self.version = None
self.machine_type_model = ""
self.serial_number = ""
@staticmethod
def get_type():
return "PowerNode"
@staticmethod
def get_web_url(host):
... |
class PowerNodePlugin(IManagerDevicePlugin.IManagerDevicePlugin):
IPMI_TOOL = "/usr/local/bin/ipmitool" | random_line_split |
PowerNodePlugin.py | # Copyright 2016, IBM US, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
@entry_exit(exclude_index=[0], exclude_name=["self"])
def get_architecture(self):
return None
@entry_exit(exclude_index=[0, 1], exclude_name=["self", "new_password"])
def change_device_password(self, new_password):
"""Update the password of the ipmi default user on the BMC of the open... | _method_ = "PowerNodePlugin.get_version"
cmd_parms = [self.IPMI_TOOL, "-I", "lanplus", "-H", self.host,
"-U", self.userid, "-P", self.password, "mc", "info"]
(rc, stdout, stderr) = execute_command(" ".join(cmd_parms))
if rc != 0:
logging.warning("%s::ipmi query f... | identifier_body |
PowerNodePlugin.py | # Copyright 2016, IBM US, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | (host):
return "https://" + host
@staticmethod
def get_capabilities():
return [constants.MONITORING_CAPABLE]
@entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"])
def connect(self, host, userid, password=None, ssh_key_string=None):
"""connect... | get_web_url | identifier_name |
PowerNodePlugin.py | # Copyright 2016, IBM US, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
for line in stdout:
if "Chassis Part Number" in line:
self.machine_type_model = line.split(":")[1].strip()
elif "Chassis Serial" in line:
self.serial_number = line.split(":")[1].strip()
@entry_exit(exclude_index=[0], exclude_name=["self"])
def di... | raise exceptions.ConnectionException(
"Unable to connect to the device using IPMI") | conditional_block |
theme.ts | export interface ThemeInterface {
pallete: {
black: string;
white: string;
gray: string[];
primary: string[];
secondary: string[];
};
}
export const theme: ThemeInterface = {
pallete: {
black: '#000',
white: '#fff',
gray: [
'#f8f9fa',
'#f1f3f5',
'#e9ecef',
... | ],
},
}; | '#e64980',
'#d6336c',
'#c2255c',
'#a61e4d', | random_line_split |
WorkQueue.js | /*
* Copyright 2016 Google Inc. 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 applicabl... | };
WorkQueue.prototype.resume = function() {
if (this._paused) {
this._paused = false;
this._next();
}
};
WorkQueue.prototype._start = function(task) {
// Consistency check.
if (this._currentTask) {
throw new Error('WorkQueue: called start while running task');
}
// Mark queue as busy, so ... | random_line_split | |
WorkQueue.js | /*
* Copyright 2016 Google Inc. 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 applicabl... | (opts) {
this._queue = [];
this._delay = opts && opts.delay || 0;
this._paused = opts && !!opts.paused || false;
this._currentTask = null;
this._lastFinished = null;
}
WorkQueue.prototype.length = function() {
return this._queue.length;
};
WorkQueue.prototype.push = function(fn, cb) {
var task = new ... | WorkQueue | identifier_name |
WorkQueue.js | /*
* Copyright 2016 Google Inc. 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 applicabl... |
function WorkQueue(opts) {
this._queue = [];
this._delay = opts && opts.delay || 0;
this._paused = opts && !!opts.paused || false;
this._currentTask = null;
this._lastFinished = null;
}
WorkQueue.prototype.length = function() {
return this._queue.length;
};
WorkQueue.prototype.push = function(fn, cb)... | {
this.fn = fn;
this.cb = cb;
this.cfn = null;
} | identifier_body |
WorkQueue.js | /*
* Copyright 2016 Google Inc. 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 applicabl... |
};
WorkQueue.prototype.resume = function() {
if (this._paused) {
this._paused = false;
this._next();
}
};
WorkQueue.prototype._start = function(task) {
// Consistency check.
if (this._currentTask) {
throw new Error('WorkQueue: called start while running task');
}
// Mark queue as busy, so... | {
this._paused = true;
} | conditional_block |
abstractworker.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::script_... |
}
| {
SimpleWorkerErrorHandler { addr: addr }
} | identifier_body |
abstractworker.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::script_... | (addr: Trusted<T>) -> SimpleWorkerErrorHandler<T> {
SimpleWorkerErrorHandler { addr: addr }
}
}
| new | identifier_name |
abstractworker.rs | * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::script_runtime::CommonScriptMsg;
use script_traits::StructuredSerializedData;
use servo_url::ImmutableOrigin;
/// Messages used to control the worke... | /* 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 | random_line_split | |
haxe.py | # -*- coding: utf-8 -*-
"""
wakatime.dependencies.haxe
~~~~~~~~~~~~~~~~~~~~~~~~~~
Parse dependencies from Haxe code.
:copyright: (c) 2018 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
from . import TokenParser
class HaxeParser(TokenParser):
exclude = [
r'^haxe$',
... |
else:
self._process_other(token, content)
def _process_namespace(self, token, content):
if self.state == 'import':
self.append(self._format(content))
self.state = None
else:
self.state = content
def _process_text(self, token, content):
... | self._process_text(token, content) | conditional_block |
haxe.py | # -*- coding: utf-8 -*-
"""
wakatime.dependencies.haxe
~~~~~~~~~~~~~~~~~~~~~~~~~~
Parse dependencies from Haxe code.
:copyright: (c) 2018 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
from . import TokenParser
class HaxeParser(TokenParser):
exclude = [
r'^haxe$',
... | def _process_namespace(self, token, content):
if self.state == 'import':
self.append(self._format(content))
self.state = None
else:
self.state = content
def _process_text(self, token, content):
pass
def _process_other(self, token, content):
... | self._process_text(token, content)
else:
self._process_other(token, content)
| random_line_split |
haxe.py | # -*- coding: utf-8 -*-
"""
wakatime.dependencies.haxe
~~~~~~~~~~~~~~~~~~~~~~~~~~
Parse dependencies from Haxe code.
:copyright: (c) 2018 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
from . import TokenParser
class HaxeParser(TokenParser):
exclude = [
r'^haxe$',
... | return content.strip() | identifier_body | |
haxe.py | # -*- coding: utf-8 -*-
"""
wakatime.dependencies.haxe
~~~~~~~~~~~~~~~~~~~~~~~~~~
Parse dependencies from Haxe code.
:copyright: (c) 2018 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
from . import TokenParser
class | (TokenParser):
exclude = [
r'^haxe$',
]
state = None
def parse(self):
for index, token, content in self.tokens:
self._process_token(token, content)
return self.dependencies
def _process_token(self, token, content):
if self.partial(token) == 'Namespace':
... | HaxeParser | identifier_name |
dice.rs |
use error::DiceParseError;
use generator::Generator;
use regex::Regex;
lazy_static! {
static ref DICE_CMD_PATTERN: Regex = Regex::new(r"^\d+(d\d+)?$").unwrap();
}
/// `Dice` describes a set of dice of the same type that can be "rolled" all at once, i.e. "2d6"
#[derive(Debug, Eq, PartialEq)]
pub struct Dice {
... | use std::str; | random_line_split | |
dice.rs | use std::str;
use error::DiceParseError;
use generator::Generator;
use regex::Regex;
lazy_static! {
static ref DICE_CMD_PATTERN: Regex = Regex::new(r"^\d+(d\d+)?$").unwrap();
}
/// `Dice` describes a set of dice of the same type that can be "rolled" all at once, i.e. "2d6"
#[derive(Debug, Eq, PartialEq)]
pub str... | <T: Generator>(&self, generator: &mut T) -> <T as Generator>::Output {
generator.generate(&self)
}
}
impl str::FromStr for Dice {
type Err = DiceParseError;
fn from_str(s: &str) -> Result<Dice, Self::Err> {
if !DICE_CMD_PATTERN.is_match(s) {
return Err(DiceParseError::InvalidEx... | gen_result | identifier_name |
dice.rs | use std::str;
use error::DiceParseError;
use generator::Generator;
use regex::Regex;
lazy_static! {
static ref DICE_CMD_PATTERN: Regex = Regex::new(r"^\d+(d\d+)?$").unwrap();
}
/// `Dice` describes a set of dice of the same type that can be "rolled" all at once, i.e. "2d6"
#[derive(Debug, Eq, PartialEq)]
pub str... |
/// Generates the result of a dice roll for a given `Dice` value
pub fn gen_result<T: Generator>(&self, generator: &mut T) -> <T as Generator>::Output {
generator.generate(&self)
}
}
impl str::FromStr for Dice {
type Err = DiceParseError;
fn from_str(s: &str) -> Result<Dice, Self::Err> {... | {
Dice {
count: count,
range: range,
}
} | identifier_body |
wordprofile.py | #!/usr/bin/env python3
'''
* Copyright 2015 by Benjamin J. Land (a.k.a. BenLand100)
*
* This file is part of chatlogs.
*
* chatlogs 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 ... |
elif sys.argv[3] == 'regex':
wordtokregex = re.compile('([\w'']+|[\:\=][^ ])')
for i in db.get_iter(query,args):
thin = ' '.join([x.lower() for x in i.msg.split(' ') if len(x) <= maxlen])
words.update([word for word in wordtokregex.findall(thin)])
elif sys.argv[3][0:7] == 'respell':
try:
... | thin = ' '.join([x.lower() for x in i.msg.split(' ') if len(x) <= maxlen])
words.update(nltk.word_tokenize(thin)) | conditional_block |
wordprofile.py | #!/usr/bin/env python3
'''
* Copyright 2015 by Benjamin J. Land (a.k.a. BenLand100)
*
* This file is part of chatlogs.
*
* chatlogs 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 ... | words.update([word for word in parts if word])
print('"---total---"',',',sum(words.values()))
print('"---unique---"',',',len(set(words)))
[print('"'+word[0]+'",',word[1]) for word in words.most_common(int(sys.argv[2]))] | parts = [sgst.suggest(word) for word in parts] | random_line_split |
perf-tool.py | #!/usr/bin/env python
#
# 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
# "... | now = time.time()
self.total_ack_latency += now - self._last_send
self.calls += 1
if self._count:
self._count -= 1
if self._count == 0:
self.stop_time = now
link.close()
return
self._send_message(link)
d... | def __init__(self, count):
self._count = count
self._msg = Message()
self.calls = 0
self.total_ack_latency = 0.0
self.stop_time = None
self.start_time = None
def credit_granted(self, sender_link):
if self.start_time is None:
self.start_time = time... | identifier_body |
perf-tool.py | #!/usr/bin/env python
#
# 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
# "... |
sender.open()
# Run until all messages transfered
while not sender.closed or not receiver.closed:
process_connection(connection, my_socket)
connection.close()
while not connection.closed:
process_connection(connection, my_socket)
duration = s_handler.stop_time - s_handler.sta... | process_connection(connection, my_socket) | conditional_block |
perf-tool.py | #!/usr/bin/env python
#
# 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
# "... | receiver.message_accepted(handle)
self.tx_total_latency += now - message.body['tx-timestamp']
self.receives += 1
if self._count:
self._count -= 1
if self._count == 0:
receiver.close()
return
lc = receiver.capacity
ca... | def message_received(self, receiver, message, handle):
now = time.time() | random_line_split |
perf-tool.py | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... | (self, receiver_link):
receiver_link.add_capacity(self._capacity)
def receiver_remote_closed(self, receiver_link, pn_condition):
"""Peer has closed its end of the link."""
LOG.debug("receiver_remote_closed condition=%s", pn_condition)
receiver_link.close()
def receiver_failed(s... | receiver_active | identifier_name |
AddOrEditTransaction.js | var ctrl = function ($scope, $q, $state, $stateParam, $anchorScroll, categoryService,
eventService, placeService, transactionService) {
$scope.isEditMode = $stateParam.publicId;
$scope.options = {
showWeeks: false
};
const applyToPromise = transactionService.getApplyToList();
$q.when(applyToPromise, ... | $scope.hasSaved = false;
$scope.hasError = true;
console.error(error);
});
};
$scope.cancel = function () {
$state.go('accountTransactions');
};
};
ctrl.$inject = ['$scope', '$q', '$state', '$stateParams', '$anchorScroll', 'categoryService',
'eventService', 'placeService', '... | $scope.submitted = false; | random_line_split |
AddOrEditTransaction.js | var ctrl = function ($scope, $q, $state, $stateParam, $anchorScroll, categoryService,
eventService, placeService, transactionService) {
$scope.isEditMode = $stateParam.publicId;
$scope.options = {
showWeeks: false
};
const applyToPromise = transactionService.getApplyToList();
$q.when(applyToPromise, ... |
}, function (error) {
$scope.submitted = false;
$scope.hasSaved = false;
$scope.hasError = true;
console.error(error);
});
};
$scope.cancel = function () {
$state.go('accountTransactions');
};
};
ctrl.$inject = ['$scope', '$q', '$state', '$stateParams', '$anchor... | {
$scope.submitted = false;
$scope.toExpense = undefined;
$scope.currentTx.amount = null;
$scope.currentTx.category = null;
$scope.currentTx.description = null;
$scope.hasSaved = true;
$scope.hasError = false;
} | conditional_block |
DefinitionService.js | "use strict";
var SourceLine_1 = require("../source/SourceLine");
var Prop_1 = require("../entities/Prop");
var Method_1 = require("../entities/Method");
var MethodKind_1 = require("../kind/MethodKind");
var ProgramError_1 = require("../errors/ProgramError");
var ClassDefn_1 = require("../define/ClassDefn");
var Struct... |
/**
* Collect all definitions from the source code
* */
DefinitionService.prototype.collectDefinitions = function (filename, lines) {
var _this = this;
var defs = [];
var turboLines = [];
var i = 0;
var numLines = lines.length;
var line;
while (... | {
} | identifier_body |
DefinitionService.js | "use strict";
var SourceLine_1 = require("../source/SourceLine");
var Prop_1 = require("../entities/Prop");
var Method_1 = require("../entities/Method");
var MethodKind_1 = require("../kind/MethodKind");
var ProgramError_1 = require("../errors/ProgramError");
var ClassDefn_1 = require("../define/ClassDefn");
var Struct... | }());
exports.DefinitionService = DefinitionService;
//# sourceMappingURL=DefinitionService.js.map | random_line_split | |
DefinitionService.js | "use strict";
var SourceLine_1 = require("../source/SourceLine");
var Prop_1 = require("../entities/Prop");
var Method_1 = require("../entities/Method");
var MethodKind_1 = require("../kind/MethodKind");
var ProgramError_1 = require("../errors/ProgramError");
var ClassDefn_1 = require("../define/ClassDefn");
var Struct... | () {
}
/**
* Collect all definitions from the source code
* */
DefinitionService.prototype.collectDefinitions = function (filename, lines) {
var _this = this;
var defs = [];
var turboLines = [];
var i = 0;
var numLines = lines.length;
var line;
... | DefinitionService | identifier_name |
DefinitionService.js | "use strict";
var SourceLine_1 = require("../source/SourceLine");
var Prop_1 = require("../entities/Prop");
var Method_1 = require("../entities/Method");
var MethodKind_1 = require("../kind/MethodKind");
var ProgramError_1 = require("../errors/ProgramError");
var ClassDefn_1 = require("../define/ClassDefn");
var Struct... |
else if (in_method) {
// TODO: if we're going to be collecting random cruft
// then blank and comment lines at the end of a method
// really should be placed at the beginning of the
// next method. Also see hack in pasteup... | {
if (kind != "struct")
throw new ProgramError_1.ProgramError(filename, i, "@" + m[1] + " is only allowed in structs");
if (in_method)
methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody))... | conditional_block |
DatePicker.js | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in... |
},
hidePickerOnSelect: function() {
Ext.menu.Manager.hideAll();
}
}); | {
me.on('select', me.hidePickerOnSelect, me);
} | conditional_block |
DatePicker.js | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in... | * @private
*/
/**
* @property {Ext.picker.Date} picker
* The {@link Ext.picker.Date} instance for this DateMenu
*/
initComponent : function(){
var me = this,
cfg = Ext.apply({}, me.initialConfig);
// Ensure we clear any listeners so they aren't... | */
pickerId : null,
/**
* @cfg {Number} maxHeight | random_line_split |
Utils.ts | export interface KeyValue {
[key: string]: any
}
export const merge = (...arrays: KeyValue[]): KeyValue => {
const destination = {} as KeyValue
arrays.forEach(function (source) {
var prop
for (prop in source) {
if (prop in destination && destination[prop] === null) {
... |
}
})
return destination
}
export const removeTrailingChar = (dataPath: string, trailing: string): string => {
if (dataPath.length > 1 && dataPath.endsWith(trailing)) {
return dataPath.substring(0, dataPath.length - 1)
}
return dataPath
} | {
// Set new values
destination[prop] = source[prop]
} | conditional_block |
Utils.ts | export interface KeyValue {
[key: string]: any
} | export const merge = (...arrays: KeyValue[]): KeyValue => {
const destination = {} as KeyValue
arrays.forEach(function (source) {
var prop
for (prop in source) {
if (prop in destination && destination[prop] === null) {
destination[prop] = source[prop]
}
... | random_line_split | |
lexer.ts | //import {Rewriter, INVERSES} from './rewriter';
import {count, starts, compact, repeat, invertLiterate,
locationDataToString, debug} from './helpers';
const DEBUG = process.env.NODE_ENV === 'development';
/* Hello token */
const HELLO = /hello/;
/* Comment token */
const COMMENT = /^{-([^#][\s\S]*?)(?:{-[^\n\S]*|-}... | const BOM = 65279;
const MULTI_DENT = /^(?:\n[^\n\S]*)+/
const TRAILING_SPACES = /\s+$/;
const WHITESPACE = /^[^\n\S]+/;
export class Lexer {
literate; // Are we lexing literate CoffeeScript?
indent: number; // The current indentation level.
baseIndent: number; // The overall minimum... | random_line_split | |
lexer.ts | //import {Rewriter, INVERSES} from './rewriter';
import {count, starts, compact, repeat, invertLiterate,
locationDataToString, debug} from './helpers';
const DEBUG = process.env.NODE_ENV === 'development';
/* Hello token */
const HELLO = /hello/;
/* Comment token */
const COMMENT = /^{-([^#][\s\S]*?)(?:{-[^\n\S]*|-}... | (tag, value, offsetInChunk?, length?, origin?) {
let token: any = this.makeToken(tag, value, offsetInChunk, length);
if (origin) token.origin = origin;
this.tokens.push(token);
return token;
}
/* TOKENS */
// 'hello' token
private helloToken() {
let match, input, id, colon;
... | token | identifier_name |
lexer.ts | //import {Rewriter, INVERSES} from './rewriter';
import {count, starts, compact, repeat, invertLiterate,
locationDataToString, debug} from './helpers';
const DEBUG = process.env.NODE_ENV === 'development';
/* Hello token */
const HELLO = /hello/;
/* Comment token */
const COMMENT = /^{-([^#][\s\S]*?)(?:{-[^\n\S]*|-}... |
/* TOKENS */
// 'hello' token
private helloToken() {
let match, input, id, colon;
// if no
if (!(match = HELLO.exec(this.chunk))) return 0;
let token = this.makeToken('HELLO', 'hello');
this.tokens.push(token);
return match[0].length;
}
// comments token
private commentToken... | {
let token: any = this.makeToken(tag, value, offsetInChunk, length);
if (origin) token.origin = origin;
this.tokens.push(token);
return token;
} | identifier_body |
describer.py | from storytext.javaswttoolkit import describer as swtdescriber
from org.eclipse.core.internal.runtime import InternalPlatform
from org.eclipse.ui.forms.widgets import ExpandableComposite
import os
from pprint import pprint
class Describer(swtdescriber.Describer): | self.buildImagesFromBundles()
def buildImagesFromBundles(self):
allImageTypes = [ "gif", "png", "jpg" ]
allImageTypes += [ i.upper() for i in allImageTypes ]
cacheFile = os.path.join(os.getenv("STORYTEXT_HOME"), "osgi_bundle_image_types")
cacheExists = o... | swtdescriber.Describer.stateWidgets = [ ExpandableComposite ] + swtdescriber.Describer.stateWidgets
swtdescriber.Describer.ignoreChildren = (ExpandableComposite,) + swtdescriber.Describer.ignoreChildren
def buildImages(self):
swtdescriber.Describer.buildImages(self) | random_line_split |
describer.py | from storytext.javaswttoolkit import describer as swtdescriber
from org.eclipse.core.internal.runtime import InternalPlatform
from org.eclipse.ui.forms.widgets import ExpandableComposite
import os
from pprint import pprint
class Describer(swtdescriber.Describer):
swtdescriber.Describer.stateWidgets = [ ExpandableC... | (self, entries):
while entries.hasMoreElements():
url = entries.nextElement()
self.storeImageData(url)
def getExpandableCompositeState(self, widget):
return widget.isExpanded()
def getExpandableCompositeDescription(self, widget):
stat... | storeAllImages | identifier_name |
describer.py | from storytext.javaswttoolkit import describer as swtdescriber
from org.eclipse.core.internal.runtime import InternalPlatform
from org.eclipse.ui.forms.widgets import ExpandableComposite
import os
from pprint import pprint
class Describer(swtdescriber.Describer):
swtdescriber.Describer.stateWidgets = [ ExpandableC... |
def getExpandableCompositeState(self, widget):
return widget.isExpanded()
def getExpandableCompositeDescription(self, widget):
state = self.getExpandableCompositeState(widget)
self.widgetsWithState[widget] = state
desc = "Expandable '" + widget.getT... | while entries.hasMoreElements():
url = entries.nextElement()
self.storeImageData(url) | identifier_body |
describer.py | from storytext.javaswttoolkit import describer as swtdescriber
from org.eclipse.core.internal.runtime import InternalPlatform
from org.eclipse.ui.forms.widgets import ExpandableComposite
import os
from pprint import pprint
class Describer(swtdescriber.Describer):
swtdescriber.Describer.stateWidgets = [ ExpandableC... |
def getExpandableCompositeState(self, widget):
return widget.isExpanded()
def getExpandableCompositeDescription(self, widget):
state = self.getExpandableCompositeState(widget)
self.widgetsWithState[widget] = state
desc = "Expandable '" + widget.getT... | url = entries.nextElement()
self.storeImageData(url) | conditional_block |
weird-exprs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | punch_card();
} | union();
special_characters(); | random_line_split |
weird-exprs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
loop { if break { } }
let mut i = 0;
loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
break; }
}
fn evil_lincoln() { let _evil = println!("lincoln"); }
fn dots() {
assert_eq!(String::from(".................................................."),
for... | angrydome | identifier_name |
weird-exprs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
break; }
}
fn evil_lincoln() { let _evil = println!("lincoln"); }
fn dots() {
assert_eq!(String::from(".................................................."),
format!("{:?}", .. .. .. .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. .. .. .. .. ..));
}
fn u8(u... | { match (continue) { 1 => { }, _ => panic!("wat") } } | conditional_block |
weird-exprs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn what() {
fn the(x: &Cell<bool>) {
return while !x.get() { x.set(true); };
}
let i = &Cell::new(false);
let dont = {||the(i)};
dont();
assert!((i.get()));
}
fn zombiejesus() {
loop {
while (return) {
if (return) {
match (return) {
... | {
fn f(_x: ()) { }
f(return);
} | identifier_body |
type-referenced-by-whitelisted-function.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct dl_phdr_info {
pub x: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_dl_phdr_info() | stringify!(x)
)
);
}
extern "C" {
pub fn dl_iterate_phdr(arg1: *mut dl_phdr_info) -> ::std::os::raw::c_int;
}
| {
assert_eq!(
::std::mem::size_of::<dl_phdr_info>(),
4usize,
concat!("Size of: ", stringify!(dl_phdr_info))
);
assert_eq!(
::std::mem::align_of::<dl_phdr_info>(),
4usize,
concat!("Alignment of ", stringify!(dl_phdr_info))
);
assert_eq!(
unsafe ... | identifier_body |
type-referenced-by-whitelisted-function.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct | {
pub x: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_dl_phdr_info() {
assert_eq!(
::std::mem::size_of::<dl_phdr_info>(),
4usize,
concat!("Size of: ", stringify!(dl_phdr_info))
);
assert_eq!(
::std::mem::align_of::<dl_phdr_info>(),
4usize,
conc... | dl_phdr_info | identifier_name |
type-referenced-by-whitelisted-function.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct dl_phdr_info {
pub x: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_dl_phdr_info() {
assert_... | 4usize,
concat!("Alignment of ", stringify!(dl_phdr_info))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<dl_phdr_info>())).x as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(dl_phdr_info),
":... | concat!("Size of: ", stringify!(dl_phdr_info))
);
assert_eq!(
::std::mem::align_of::<dl_phdr_info>(), | random_line_split |
point.rs | //! A 2d point type.
use num::{Num, NumCast};
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A 2d point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T> {
/// x-coordinate.
pub x: T,
/// y-coordinate.
pub y: T,
}
impl<T> Point<T> {
/// Construct a point at (x, y).
pub fn... | #[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Line {
a: f64,
b: f64,
c: f64,
}
impl Line {
/// Returns the `Line` that passes through p and q.
pub fn from_points(p: Point<f64>, q: Point<f64>) -> Line {
let a = p.y - q.y;
let b = q.x - p.x;
let c = p.x * q.y - q.... | random_line_split | |
point.rs | //! A 2d point type.
use num::{Num, NumCast};
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A 2d point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T> {
/// x-coordinate.
pub x: T,
/// y-coordinate.
pub y: T,
}
impl<T> Point<T> {
/// Construct a point at (x, y).
pub fn... | {
sin_theta: f64,
cos_theta: f64,
}
impl Rotation {
/// A rotation of `theta` radians.
pub(crate) fn new(theta: f64) -> Rotation {
let (sin_theta, cos_theta) = theta.sin_cos();
Rotation {
sin_theta,
cos_theta,
}
}
}
impl Point<f64> {
/// Rotates... | Rotation | identifier_name |
point.rs | //! A 2d point type.
use num::{Num, NumCast};
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A 2d point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T> {
/// x-coordinate.
pub x: T,
/// y-coordinate.
pub y: T,
}
impl<T> Point<T> {
/// Construct a point at (x, y).
pub fn... |
/// Returns the square of the Euclidean distance between two points.
pub(crate) fn distance_sq<T: NumCast>(p: Point<T>, q: Point<T>) -> f64 {
let p = p.to_f64();
let q = q.to_f64();
(p.x - q.x).powf(2.0) + (p.y - q.y).powf(2.0)
}
/// A fixed rotation. This struct exists solely to cache the values of `sin... | {
distance_sq(p, q).sqrt()
} | identifier_body |
test_jail_code.py | (self):
res = jailpy(code="""raise Exception('FAIL')""")
self.assertNotEqual(res.status, 0)
self.assertEqual(res.stdout, "")
self.assertEqual(res.stderr, textwrap.dedent("""\
Traceback (most recent call last):
File "jailed_code", line 1, in <module>
... |
class TestMalware(JailCodeHelpers): | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.