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 |
|---|---|---|---|---|
dates.py | import logging
from datetime import datetime
from django import template
from django.utils import timezone
register = template.Library()
logger = logging.getLogger(__name__)
@register.filter(expects_localtime=True)
def fuzzy_time(time):
"""Formats a `datetime.time` object relative to the current time."""
dt... | (time):
"""Returns a `datetime.datetime` object from a `datetime.time` object using the current date."""
return datetime.combine(timezone.localdate(), time)
@register.filter(expects_localtime=True)
def fuzzy_date(date):
"""Formats a `datetime.datetime` object relative to the current time."""
if date.... | time_to_date | identifier_name |
dates.py | import logging
from datetime import datetime
from django import template
from django.utils import timezone
register = template.Library()
logger = logging.getLogger(__name__)
@register.filter(expects_localtime=True)
def fuzzy_time(time):
"""Formats a `datetime.time` object relative to the current time."""
dt... | elif diff.days == 1:
return "yesterday"
elif diff.days < 7:
return "{} days ago".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("last %A")
else:
return date.strftime("%A, %B %d, %Y")
else:
diff ... | elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "{} hour{} ago".format(hrs, "s" if hrs != 1 else "") | random_line_split |
dates.py | import logging
from datetime import datetime
from django import template
from django.utils import timezone
register = template.Library()
logger = logging.getLogger(__name__)
@register.filter(expects_localtime=True)
def fuzzy_time(time):
"""Formats a `datetime.time` object relative to the current time."""
dt... |
now = timezone.localtime()
if date <= now:
diff = now - date
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "{} minutes ago".format(int(second... | date = timezone.make_aware(date) | conditional_block |
get_data.py | import os
import urllib
from glob import glob
import dask.bag as db
import numpy as np
import zarr
from dask.diagnostics import ProgressBar
from netCDF4 import Dataset
def download(url):
opener = urllib.URLopener()
filename = os.path.basename(url)
path = os.path.join('data', filename)
opener.retrieve... | i += m
if __name__ == '__main__':
download_weather()
transform_weather() | i = 0
for d in datasets:
m = d.shape[0]
f[i:i + m] = d[:].filled(np.nan) | random_line_split |
get_data.py | import os
import urllib
from glob import glob
import dask.bag as db
import numpy as np
import zarr
from dask.diagnostics import ProgressBar
from netCDF4 import Dataset
def | (url):
opener = urllib.URLopener()
filename = os.path.basename(url)
path = os.path.join('data', filename)
opener.retrieve(url, path)
def download_weather():
# Create data directory
if not os.path.exists('data'):
os.mkdir('data')
template = ('http://www.esrl.noaa.gov/psd/thredds/fi... | download | identifier_name |
get_data.py | import os
import urllib
from glob import glob
import dask.bag as db
import numpy as np
import zarr
from dask.diagnostics import ProgressBar
from netCDF4 import Dataset
def download(url):
opener = urllib.URLopener()
filename = os.path.basename(url)
path = os.path.join('data', filename)
opener.retrieve... |
if __name__ == '__main__':
download_weather()
transform_weather()
| m = d.shape[0]
f[i:i + m] = d[:].filled(np.nan)
i += m | conditional_block |
get_data.py | import os
import urllib
from glob import glob
import dask.bag as db
import numpy as np
import zarr
from dask.diagnostics import ProgressBar
from netCDF4 import Dataset
def download(url):
opener = urllib.URLopener()
filename = os.path.basename(url)
path = os.path.join('data', filename)
opener.retrieve... |
if __name__ == '__main__':
download_weather()
transform_weather()
| if os.path.exists('sst.day.mean.v2.zarr'):
return
datasets = [Dataset(path)['sst'] for path in sorted(glob('data/*.nc'))]
n = sum(d.shape[0] for d in datasets)
shape = (n, 720, 1440)
chunks = (72, 360, 360)
f = zarr.open_array('sst.day.mean.v2.zarr', shape=shape, chunks=chunks,
... | identifier_body |
shader-gradient.js | var assign = require('object-assign');
var number = require('as-number');
module.exports = function (THREE) {
return function (opt) {
opt = opt || {};
var ret = assign({
transparent: true,
uniforms: {
thickness: { type: 'f', value: number(opt.thickness, 0.1) },
opacity: { type: '... | if (threeVers < 72) {
// Old versions need to specify shader attributes
ret.attributes = {
lineMiter: { type: 'f', value: 0 },
lineDistance: { type: 'f', value: 0 },
lineNormal: { type: 'v2', value: new THREE.Vector2() }
};
}
return ret;
};
}; | var threeVers = (parseInt(THREE.REVISION, 10) || 0) | 0; | random_line_split |
shader-gradient.js | var assign = require('object-assign');
var number = require('as-number');
module.exports = function (THREE) {
return function (opt) {
opt = opt || {};
var ret = assign({
transparent: true,
uniforms: {
thickness: { type: 'f', value: number(opt.thickness, 0.1) },
opacity: { type: '... |
return ret;
};
};
| {
// Old versions need to specify shader attributes
ret.attributes = {
lineMiter: { type: 'f', value: 0 },
lineDistance: { type: 'f', value: 0 },
lineNormal: { type: 'v2', value: new THREE.Vector2() }
};
} | conditional_block |
privacy-ns.rs | // Copyright 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-MIT or ... | (&self) { }
}
pub struct Baz;
pub fn Bar() { }
}
fn test_unused2() {
use foo2::*;
}
fn test_single2() {
use foo2::Bar;
Bar();
}
fn test_list2() {
use foo2::{Bar,Baz};
Bar();
}
fn test_glob2() {
use foo2::*;
Bar();
}
// public type, public value
pub mod foo3 {
pub tra... | dummy | identifier_name |
privacy-ns.rs | // Copyright 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-MIT or ... |
fn test_unused2() {
use foo2::*;
}
fn test_single2() {
use foo2::Bar;
Bar();
}
fn test_list2() {
use foo2::{Bar,Baz};
Bar();
}
fn test_glob2() {
use foo2::*;
Bar();
}
// public type, public value
pub mod foo3 {
pub trait Bar {
fn dummy(&self) { }
}
pub struct Baz;... | } | random_line_split |
privacy-ns.rs | // Copyright 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-MIT or ... |
fn test_single3() {
use foo3::Bar;
Bar();
let _x: Box<Bar>;
}
fn test_list3() {
use foo3::{Bar,Baz};
Bar();
let _x: Box<Bar>;
}
fn test_glob3() {
use foo3::*;
Bar();
let _x: Box<Bar>;
}
fn main() {
}
| {
use foo3::*;
} | identifier_body |
user.service.spec.ts | import { TestBed, async } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { ConnectionBackend, RequestOptions, BaseRequestOptions, Http, Response, ResponseOptions } from '@angular/http';
import { JhiDateUtils } from 'ng-jhipster';
import { UserService, User } from './../../../... | {
provide: ConnectionBackend,
useClass: MockBackend
},
{
provide: RequestOptions,
useClass: BaseRequestOptions
},
Http,
... | beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [ | random_line_split |
tests.py | #!flask/bin/python
import os
import unittest
from coverage import coverage
cov = coverage(branch = True, omit = ['flask/*', 'tests.py'])
cov.start()
from config import basedir
from app import app, db
from app.models import User
from datetime import datetime, timedelta
from app.models import User, Post
class TestCase... | db.session = db.create_scoped_session()
db.session.delete(p)
db.session.commit()
def test_user(self):
# make valid nicknames
n = User.make_valid_nickname('John_123')
assert n == 'John_123'
n = User.make_valid_nickname('John_[123]\n')
assert n == 'John_123'
# create a user
... | # delete the post using a new session | random_line_split |
tests.py | #!flask/bin/python
import os
import unittest
from coverage import coverage
cov = coverage(branch = True, omit = ['flask/*', 'tests.py'])
cov.start()
from config import basedir
from app import app, db
from app.models import User
from datetime import datetime, timedelta
from app.models import User, Post
class TestCase... | (self):
return '<User %r>' % (self.nickname)
if __name__ == '__main__':
try:
unittest.main()
except:
pass
cov.stop()
cov.save()
print "\n\nCoverage Report:\n"
cov.report()
print "HTML version: " + os.path.join(basedir, "tmp/coverage/index.html")
cov.html_report(directory = 'tmp/coverage')
cov.erase()
| __repr__ | identifier_name |
tests.py | #!flask/bin/python
import os
import unittest
from coverage import coverage
cov = coverage(branch = True, omit = ['flask/*', 'tests.py'])
cov.start()
from config import basedir
from app import app, db
from app.models import User
from datetime import datetime, timedelta
from app.models import User, Post
class TestCase... | try:
unittest.main()
except:
pass
cov.stop()
cov.save()
print "\n\nCoverage Report:\n"
cov.report()
print "HTML version: " + os.path.join(basedir, "tmp/coverage/index.html")
cov.html_report(directory = 'tmp/coverage')
cov.erase() | conditional_block | |
tests.py | #!flask/bin/python
import os
import unittest
from coverage import coverage
cov = coverage(branch = True, omit = ['flask/*', 'tests.py'])
cov.start()
from config import basedir
from app import app, db
from app.models import User
from datetime import datetime, timedelta
from app.models import User, Post
class TestCase... |
def test_delete_post(self):
# create a user and a post
u = User(nickname = 'john', email = 'john@example.com')
p = Post(body = 'test post', author = u, timestamp = datetime.utcnow())
db.session.add(u)
db.session.add(p)
db.session.commit()
# query the post and destroy the session
... | u1 = User(nickname = 'john', email = 'john@example.com')
u2 = User(nickname = 'susan', email = 'susan@example.com')
u3 = User(nickname = 'mary', email = 'mary@example.com')
u4 = User(nickname = 'david', email = 'david@example.com')
db.session.add(u1)
db.session.add(u2)
db.session.add(u3)
db.session.add(u4... | identifier_body |
index.js | /**
*
*/
import angularCookie from 'angular-cookies';
import angularTranslate from 'angular-translate';
import dynamicLocale from 'angular-dynamic-locale';
import 'angular-translate/dist/angular-translate-loader-static-files/angular-translate-loader-static-files';
import 'angular-translate/dist/angular-translate-st... | locales: {
ru_RU: {
display: 'Русский',
icon: 'ru',
},
en_US: {
display: 'English',
icon: 'gb',
},
},
preferredLocale: 'en_US',
});
export default MODULE_NAME;
// Services
var services = require.context('./services', true, /... | .config(['tmhDynamicLocaleProvider', tmhDynamicLocaleProvider => {
tmhDynamicLocaleProvider.localeLocationPattern('/node_modules/angular-i18n/angular-locale_{{locale}}.js');
}])
.constant('LOCALES', { | random_line_split |
setup.py | from setuptools import setup, find_packages
with open('README.md') as fp:
long_description = fp.read()
setup(
name='typeform',
version='1.1.0',
description='Python Client wrapper for Typeform API',
long_description=long_description,
long_description_content_type='text/markdown',
keywords=[... | 'Programming Language :: Python :: 3.7',
'Programming Language :: Python',
]
) | 'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6', | random_line_split |
speed_test.py | #!/usr/bin/env python
"""
Benchmark how long it takes to set 10,000 keys in the database.
"""
from __future__ import print_function
import trollius as asyncio
from trollius import From
import logging
import trollius_redis
import time
from six.moves import range
if __name__ == '__main__':
loop = asyncio.get_event_l... | # By using yield from here, we wait for the answer.
yield From(connection.set(u'key', u'value'))
print(u'Done. Duration=', time.time() - start)
print()
# === Benchmark 2 (should be at least 3x as fast) ==
print(u'2. How much time does it... |
# Do 10,000 set requests
for i in range(10 * 1000): | random_line_split |
speed_test.py | #!/usr/bin/env python
"""
Benchmark how long it takes to set 10,000 keys in the database.
"""
from __future__ import print_function
import trollius as asyncio
from trollius import From
import logging
import trollius_redis
import time
from six.moves import range
if __name__ == '__main__':
loop = asyncio.get_event_l... | ():
connection = yield From(trollius_redis.Pool.create(
host=u'localhost', port=6379, poolsize=50))
try:
# === Benchmark 1 ==
print(
u'1. How much time does it take to set 10,000 values '
u'in Redis? (without pipelining)')
... | run | identifier_name |
speed_test.py | #!/usr/bin/env python
"""
Benchmark how long it takes to set 10,000 keys in the database.
"""
from __future__ import print_function
import trollius as asyncio
from trollius import From
import logging
import trollius_redis
import time
from six.moves import range
if __name__ == '__main__':
loop = asyncio.get_event_l... |
print(u'Done. Duration=', time.time() - start)
print()
# === Benchmark 2 (should be at least 3x as fast) ==
print(u'2. How much time does it take if we use asyncio.gather, '
u'and pipeline requests?')
print(u'Starting...')
sta... | yield From(connection.set(u'key', u'value')) | conditional_block |
speed_test.py | #!/usr/bin/env python
"""
Benchmark how long it takes to set 10,000 keys in the database.
"""
from __future__ import print_function
import trollius as asyncio
from trollius import From
import logging
import trollius_redis
import time
from six.moves import range
if __name__ == '__main__':
loop = asyncio.get_event_l... |
loop.run_until_complete(run())
| connection = yield From(trollius_redis.Pool.create(
host=u'localhost', port=6379, poolsize=50))
try:
# === Benchmark 1 ==
print(
u'1. How much time does it take to set 10,000 values '
u'in Redis? (without pipelining)')
print(u'Star... | identifier_body |
render.js | /**
* Created by cthed on 25/02/2016.
* this module will render a chart doughnut for json response fromm web
*/
/**
*
* @type {*[]} data
*/
var data = [
{
value: 61,
color: "#09355C",
label: "Label 1"
}, {
value: 11,
color: "#CBCBCB",
label: "Label 2"
}, {
value: 28,
color: ... | *
* @type {{segmentShowStroke: boolean, animateRotate: boolean, animateScale: boolean, percentageInnerCutout: number, tooltipTemplate: string}} options
*
*/
var options = {
segmentShowStroke: false,
animateRotate: true,
animateScale: false,
percentageInnerCutout: 50,
tooltipTemplate: "<%= value %>%"
}
va... | }];
/** | random_line_split |
v1.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // NB: remove when path reform lands
//#[doc(no_inline)] pub use path::{Path, GenericPath};
// NB: remove when I/O reform lands
//#[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek, BufferPrelude};
// NB: remove when range syntax lands
#[doc(no_inline)] pub use iter::range; | #[stable] #[doc(no_inline)] pub use vec::Vec;
| random_line_split |
bricklet_linear_poti_v2.py | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2022-01-18. #
# #
# Python Bindings Version 2.1.29 #
# ... |
else:
self.registered_callbacks[callback_id] = function
LinearPotiV2 = BrickletLinearPotiV2 # for backward compatibility
| self.registered_callbacks.pop(callback_id, None) | conditional_block |
bricklet_linear_poti_v2.py | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2022-01-18. #
# #
# Python Bindings Version 2.1.29 #
# ... | (Device):
"""
59mm linear potentiometer
"""
DEVICE_IDENTIFIER = 2139
DEVICE_DISPLAY_NAME = 'Linear Poti Bricklet 2.0'
DEVICE_URL_PART = 'linear_poti_v2' # internal
CALLBACK_POSITION = 4
FUNCTION_GET_POSITION = 1
FUNCTION_SET_POSITION_CALLBACK_CONFIGURATION = 2
FUNCTION_GET_PO... | BrickletLinearPotiV2 | identifier_name |
bricklet_linear_poti_v2.py | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2022-01-18. #
# #
# Python Bindings Version 2.1.29 #
# ... |
def set_bootloader_mode(self, mode):
"""
Sets the bootloader mode and returns the status after the requested
mode change was instigated.
You can change from bootloader mode to firmware mode and vice versa. A change
from bootloader mode to firmware mode will only take place... | """
Returns the error count for the communication between Brick and Bricklet.
The errors are divided into
* ACK checksum errors,
* message checksum errors,
* framing errors and
* overflow errors.
The errors counts are for errors that occur on the Bricklet side.... | identifier_body |
bricklet_linear_poti_v2.py | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2022-01-18. #
# #
# Python Bindings Version 2.1.29 #
# ... | """
Registers the given *function* with the given *callback_id*.
"""
if function is None:
self.registered_callbacks.pop(callback_id, None)
else:
self.registered_callbacks[callback_id] = function
LinearPotiV2 = BrickletLinearPotiV2 # for backward compatibi... | return GetIdentity(*self.ipcon.send_request(self, BrickletLinearPotiV2.FUNCTION_GET_IDENTITY, (), '', 33, '8s 8s c 3B 3B H'))
def register_callback(self, callback_id, function): | random_line_split |
dump_results.py | """blah."""
from pyiem.util import get_dbconn
pgconn = get_dbconn("idep")
cursor = pgconn.cursor()
cursor.execute(
"""
SELECT r.hs_id, r.huc_12, p.fpath, extract(year from valid) as yr,
sum(runoff) as sum_runoff,
sum(loss) as sum_loss, sum(delivery) as sum_delivery from
results r JOIN flowpaths p on (r.hs... |
print(str(catchment) + ",%s,%s,%s,%.4f,%.4f,%.4f" % row[1:])
| catchment = int(str(fpath)[:-2]) | conditional_block |
dump_results.py | """blah.""" | from pyiem.util import get_dbconn
pgconn = get_dbconn("idep")
cursor = pgconn.cursor()
cursor.execute(
"""
SELECT r.hs_id, r.huc_12, p.fpath, extract(year from valid) as yr,
sum(runoff) as sum_runoff,
sum(loss) as sum_loss, sum(delivery) as sum_delivery from
results r JOIN flowpaths p on (r.hs_id = p.fid)... | random_line_split | |
Events.js | /*jslint node: true */
var HttpUtils = require('../../utils/HttpUtils');
/**
* Manage Events in Cloud Foundry
* @param {String} endPoint [CC endpoint]
* @constructor
*/
function Events(endPoint) {
"use strict";
this.API_URL = endPoint;
this.REST = new HttpUtils();
}
/**
* Set endpoint
* @param {Str... |
var url = this.API_URL + "/v2/events";
var options = {
method: 'GET',
url: url,
headers: {
Authorization: token_type + ' ' + access_token
},
qs: qs,
useQuerystring: true
};
return this.REST.request(options, "200", true);
};
module.exports = ... | {
qs = filter;
} | conditional_block |
Events.js | /*jslint node: true */
var HttpUtils = require('../../utils/HttpUtils');
/**
* Manage Events in Cloud Foundry
* @param {String} endPoint [CC endpoint]
* @constructor
*/
function | (endPoint) {
"use strict";
this.API_URL = endPoint;
this.REST = new HttpUtils();
}
/**
* Set endpoint
* @param {String} endPoint [CC endpoint]
*/
Events.prototype.setEndPoint = function (endPoint) {
"use strict";
this.API_URL = endPoint;
};
/**
* Get events from CC
* {@link http://apidocs.clo... | Events | identifier_name |
Events.js | /*jslint node: true */
var HttpUtils = require('../../utils/HttpUtils');
/**
* Manage Events in Cloud Foundry
* @param {String} endPoint [CC endpoint]
* @constructor
*/
function Events(endPoint) |
/**
* Set endpoint
* @param {String} endPoint [CC endpoint]
*/
Events.prototype.setEndPoint = function (endPoint) {
"use strict";
this.API_URL = endPoint;
};
/**
* Get events from CC
* {@link http://apidocs.cloudfoundry.org/214/events/list_all_events.html}
* @param {String} token_type [Authenticatio... | {
"use strict";
this.API_URL = endPoint;
this.REST = new HttpUtils();
} | identifier_body |
Events.js | /*jslint node: true */
var HttpUtils = require('../../utils/HttpUtils');
| /**
* Manage Events in Cloud Foundry
* @param {String} endPoint [CC endpoint]
* @constructor
*/
function Events(endPoint) {
"use strict";
this.API_URL = endPoint;
this.REST = new HttpUtils();
}
/**
* Set endpoint
* @param {String} endPoint [CC endpoint]
*/
Events.prototype.setEndPoint = function (en... | random_line_split | |
region.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<ast::NodeId> {
//! Returns the scope when temp created by expr_id will be cleaned up
// check for a designated rvalue scope
let rvalue_scopes = self.rvalue_scopes.borrow();
match rvalue_scopes.get().find(... |
let var_map = self.var_map.borrow();
match var_map.get().find(&var_id) {
Some(&r) => r,
None => { fail!("No enclosing scope for id {}", var_id); } | random_line_split |
region.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 visit_pat(&mut self, p: &Pat, cx: Context) {
resolve_pat(self, p, cx);
}
fn visit_stmt(&mut self, s: &Stmt, cx: Context) {
resolve_stmt(self, s, cx);
}
fn visit_expr(&mut self, ex: &Expr, cx: Context) {
resolve_expr(self, ex, cx);
}
fn visit_local(&mut self, l: &L... | {
resolve_arm(self, a, cx);
} | identifier_body |
region.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 ... | (visitor: &mut RegionResolutionVisitor,
fk: &FnKind,
decl: &ast::FnDecl,
body: &ast::Block,
sp: Span,
id: ast::NodeId,
cx: Context) {
debug!("region::resolve_fn(id={}, \
span={:?}, \
... | resolve_fn | identifier_name |
test_tools.py | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests for the engine module
"""
import numpy as np
import scipy.sparse as ssp
import re
import mock
from nipype.pipeline.plugins.tools import report_crash
def test_report_crash... | name = 'functor')
funkynode.inputs.arg1 = [1,2]
wf.add_nodes([funkynode])
wf.base_dir = '/tmp'
wf.run(plugin='MultiProc')
''' | return arg1
funkynode = pe.MapNode(niu.Function(function=func, input_names=['arg1'], output_names=['out']),
iterfield=['arg1'], | random_line_split |
test_tools.py | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests for the engine module
"""
import numpy as np
import scipy.sparse as ssp
import re
import mock
from nipype.pipeline.plugins.tools import report_crash
def | ():
with mock.patch('pickle.dump', mock.MagicMock()) as mock_pickle_dump:
with mock.patch('nipype.pipeline.plugins.tools.format_exception', mock.MagicMock()): # see iss 1517
mock_pickle_dump.return_value = True
mock_node = mock.MagicMock(name='mock_node')
mock_node._id = ... | test_report_crash | identifier_name |
test_tools.py | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests for the engine module
"""
import numpy as np
import scipy.sparse as ssp
import re
import mock
from nipype.pipeline.plugins.tools import report_crash
def test_report_crash... |
'''
Can use the following code to test that a mapnode crash continues successfully
Need to put this into a nose-test with a timeout
import nipype.interfaces.utility as niu
import nipype.pipeline.engine as pe
wf = pe.Workflow(name='test')
def func(arg1):
if arg1 == 2:
raise Exception('arg cannot be ' + ... | with mock.patch('pickle.dump', mock.MagicMock()) as mock_pickle_dump:
with mock.patch('nipype.pipeline.plugins.tools.format_exception', mock.MagicMock()): # see iss 1517
mock_pickle_dump.return_value = True
mock_node = mock.MagicMock(name='mock_node')
mock_node._id = 'an_id'
... | identifier_body |
__init__.py | # Xlib.ext.__init__ -- X extension modules
#
# Copyright (C) 2000 Peter Liljenberg <petli@ctrl-c.liu.se>
#
# 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 Lic... | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# __extensions__ is a list of tuples: (extname, extmod)
# extname is the name of the extension according to the X
# protocol. extmod is the name of the module in this package.
__extensions__ = [
('XTEST', 'xtest'),
('SHAPE', 'shap... | # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software | random_line_split |
merge.ts | import { isPlainObject } from './is';
/**
* Merge multiple objects into one.
*
* @remarks
*
* Heavily based on https://www.npmjs.com/package/extend.
*
* While extend() fully extends objects, this version only touches own
* properties and not inherited ones. This is intended to extend only option
* objects, no... | {
let target: Record<string, any> = objects.shift();
if (target == null || (!isPlainObject(target) && !Array.isArray(target))) {
target = {};
}
objects
.filter(x => isPlainObject(x) || Array.isArray(x))
.forEach(function(obj: Record<string, any>) {
if (obj == null) return;
for (const ... | identifier_body | |
merge.ts | import { isPlainObject } from './is';
/**
* Merge multiple objects into one.
*
* @remarks
*
* Heavily based on https://www.npmjs.com/package/extend.
*
* While extend() fully extends objects, this version only touches own
* properties and not inherited ones. This is intended to extend only option
* objects, no... | for (const propName in obj) {
if (!obj.hasOwnProperty(propName)) continue;
const propValue: unknown = obj[propName];
const src: unknown = target[propName];
if (target !== propValue) {
if (isPlainObject(propValue)) {
target[propName] = merge(isPlainObject(src... | random_line_split | |
merge.ts | import { isPlainObject } from './is';
/**
* Merge multiple objects into one.
*
* @remarks
*
* Heavily based on https://www.npmjs.com/package/extend.
*
* While extend() fully extends objects, this version only touches own
* properties and not inherited ones. This is intended to extend only option
* objects, no... | (...objects: Record<string, any>[]): Record<string, any> {
let target: Record<string, any> = objects.shift();
if (target == null || (!isPlainObject(target) && !Array.isArray(target))) {
target = {};
}
objects
.filter(x => isPlainObject(x) || Array.isArray(x))
.forEach(function(obj: Record<string, ... | merge | identifier_name |
sync-service.service.ts | import {Router} from '@angular/router';
import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
//Components
import { AssignTaskComponent } from '../../Components/AssignTaskComponent/assign-task.component';
import { LoginComponent } from '... | {
private token:string;
private headers = new Headers(
{'Content-Type': 'application/json'});
constructor(private http:Http,
public router:Router,
public authService:AuthService,
public authGuard:AuthGuard)
{
console.log("Storin... | SyncService | identifier_name |
sync-service.service.ts | import {Router} from '@angular/router';
import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
//Components
import { AssignTaskComponent } from '../../Components/AssignTaskComponent/assign-task.component';
import { LoginComponent } from '... |
else
{
console.log("Please Login (GET Fn - SyncService)");
alert("Please Login");
this.router.navigate['/login'];
}
}
post(endpoint: string, data: any,operation:string)
{
if(this.authGuard.canActivate())
{
console.log("Calling HTTP POST - SyncService");
console.log... | {
console.log("Calling HTTP GET- SyncService");
console.log("Operation = ", operation);
let url=BaseUrl.baseurl+endpoint;
//appending headers
this.headers.append('Authorization',this.token);
return this.http.get(url,this.headers).map(
(response:any) => {
return response.json();
}... | conditional_block |
sync-service.service.ts | import {Router} from '@angular/router';
import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
//Components
import { AssignTaskComponent } from '../../Components/AssignTaskComponent/assign-task.component';
import { LoginComponent } from '... | console.error('An error has occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
get(endpoint: string,operation:string){
if(this.authGuard.canActivate())
{
console.log("Calling HTTP GET- SyncService");
console.log("Operation = ", operation);
let url=B... | public handleError(error: any): Promise<any> { | random_line_split |
sync-service.service.ts | import {Router} from '@angular/router';
import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
//Components
import { AssignTaskComponent } from '../../Components/AssignTaskComponent/assign-task.component';
import { LoginComponent } from '... |
get(endpoint: string,operation:string){
if(this.authGuard.canActivate())
{
console.log("Calling HTTP GET- SyncService");
console.log("Operation = ", operation);
let url=BaseUrl.baseurl+endpoint;
//appending headers
this.headers.append('Authorization',this.token);
return this.http.get(u... | {
console.error('An error has occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
} | identifier_body |
frontPenatausahaan.ts | import { Component, NgZone, Input } from '@angular/core';
import { Subscription } from 'rxjs';
import SiskeudesService from '../stores/siskeudesService';
import SettingsService from '../stores/settingsService';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'front-penatausahaan',... | }
ngOnInit(): void {
this.settings = {};
this.listSiskeudesDb = [];
this.routeSubscription = this.route.queryParams.subscribe(async (params) => {
this.activeUrl = params['url'];
this.settingsSubscription = this.settingsService.getAll().subscribe(settings => {
... | private route: ActivatedRoute,
) { | random_line_split |
frontPenatausahaan.ts | import { Component, NgZone, Input } from '@angular/core';
import { Subscription } from 'rxjs';
import SiskeudesService from '../stores/siskeudesService';
import SettingsService from '../stores/settingsService';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'front-penatausahaan',... |
} | {
this.activeDatabase = db;
this.siskeudesService.setConnection(db.path);
this.router.navigate([`/${this.activeUrl}`], { queryParams: {
path: this.activeDatabase.path
} });
} | identifier_body |
frontPenatausahaan.ts | import { Component, NgZone, Input } from '@angular/core';
import { Subscription } from 'rxjs';
import SiskeudesService from '../stores/siskeudesService';
import SettingsService from '../stores/settingsService';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'front-penatausahaan',... | (value){
this._activeDatabase = value;
}
get activeDatabase(){
return this._activeDatabase;
}
constructor(
private zone: NgZone,
private siskeudesService: SiskeudesService,
private settingsService: SettingsService,
private router: Router,
... | activeDatabase | identifier_name |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
#[macro_use]
extern crate lazy_static;
extern crate uuid;
extern crate rocket;
extern crate rocket_contrib;
use std::collections::HashMap;
use uuid::Uuid;
use rocket_contrib::UUID;
#[cfg(test)]
mod tests;
lazy_static! { | static ref PEOPLE: HashMap<Uuid, &'static str> = {
let mut m = HashMap::new();
let lacy_id = Uuid::parse_str("7f205202-7ba1-4c39-b2fc-3e630722bf9f").unwrap();
let bob_id = Uuid::parse_str("4da34121-bc7d-4fc1-aee6-bf8de0795333").unwrap();
let george_id = Uuid::parse_str("ad962969-4e3d... | // A small people lookup table for the sake of this example. In a real
// application this could be a database lookup. Notice that we use the
// uuid::Uuid type here and not the rocket_contrib::UUID type. | random_line_split |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
#[macro_use]
extern crate lazy_static;
extern crate uuid;
extern crate rocket;
extern crate rocket_contrib;
use std::collections::HashMap;
use uuid::Uuid;
use rocket_contrib::UUID;
#[cfg(test)]
mod tests;
lazy_static! {
// A small people lookup table for the sake o... | () {
rocket::ignite()
.mount("/", routes![people])
.launch();
}
| main | identifier_name |
main.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
#[macro_use]
extern crate lazy_static;
extern crate uuid;
extern crate rocket;
extern crate rocket_contrib;
use std::collections::HashMap;
use uuid::Uuid;
use rocket_contrib::UUID;
#[cfg(test)]
mod tests;
lazy_static! {
// A small people lookup table for the sake o... | {
rocket::ignite()
.mount("/", routes![people])
.launch();
} | identifier_body | |
Measurement.js | Clazz.declarePackage ("JSV.common");
Clazz.load (["JSV.common.Annotation", "$.Coordinate"], "JSV.common.Measurement", null, function () {
c$ = Clazz.decorateAsClass (function () {
this.pt2 = null;
| this.value = 0;
Clazz.instantialize (this, arguments);
}, JSV.common, "Measurement", JSV.common.Annotation);
Clazz.prepareFields (c$, function () {
this.pt2 = new JSV.common.Coordinate ();
});
$_M(c$, "setM1",
function (x, y, spec) {
this.setA (x, y, spec, "", false, false, 0, 6);
this.setPt2 (this.getXVal (... | random_line_split | |
chart.js | //create variables
var barSpacing = 0;
var barWidth = 0;
var chartHeight = 0;
var chartHeightArea = 0;
var chartScale = 0;
var maxValue = 0;
var highestYlable = 0;
var valueMultiplier = 0;
//create a document ready statement
$(document).ready(function(){
//setting the global variables
window.chartHeight = Number($(... | } | random_line_split | |
chart.js | //create variables
var barSpacing = 0;
var barWidth = 0;
var chartHeight = 0;
var chartHeightArea = 0;
var chartScale = 0;
var maxValue = 0;
var highestYlable = 0;
var valueMultiplier = 0;
//create a document ready statement
$(document).ready(function(){
//setting the global variables
window.chartHeight = Number($(... | ){
//get each bar to animate to its proper height
$(".chart-area .chart-bar").each(function(index){
//height relative to chart
var revisedValue = Number($(this).attr("bar-value")) * window.chartScale;
//create a variable for delay
var newDelay = 125*index;
//Animate the bar
$(this).delay(newDelay).anim... | nimateChart( | identifier_name |
chart.js | //create variables
var barSpacing = 0;
var barWidth = 0;
var chartHeight = 0;
var chartHeightArea = 0;
var chartScale = 0;
var maxValue = 0;
var highestYlable = 0;
var valueMultiplier = 0;
//create a document ready statement
$(document).ready(function(){
//setting the global variables
window.chartHeight = Number($(... |
//get each bar to animate to its proper height
$(".chart-area .chart-bar").each(function(index){
//height relative to chart
var revisedValue = Number($(this).attr("bar-value")) * window.chartScale;
//create a variable for delay
var newDelay = 125*index;
//Animate the bar
$(this).delay(newDelay).animat... | identifier_body | |
chart.js | //create variables
var barSpacing = 0;
var barWidth = 0;
var chartHeight = 0;
var chartHeightArea = 0;
var chartScale = 0;
var maxValue = 0;
var highestYlable = 0;
var valueMultiplier = 0;
//create a document ready statement
$(document).ready(function(){
//setting the global variables
window.chartHeight = Number($(... | })
}
//create a new function that will animate our chart
function animateChart(){
//get each bar to animate to its proper height
$(".chart-area .chart-bar").each(function(index){
//height relative to chart
var revisedValue = Number($(this).attr("bar-value")) * window.chartScale;
//create a variable for de... |
window.maxValue = barValue;
window.valueMultiplier = window.maxValue / window.highestYlable;
}
| conditional_block |
account.rs | extern crate meg;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct Options {
pub arg_email: String,
pub flag_show: bool,
}
pub const USAGE: &'static s... | } | random_line_split | |
account.rs | extern crate meg;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct | {
pub arg_email: String,
pub flag_show: bool,
}
pub const USAGE: &'static str = "
Usage:
meg account [options] [<email>]
Options:
-h, --help Print this message
--create Provide an email to create a new account
--show Provide an email to show the accoun... | Options | identifier_name |
account.rs | extern crate meg;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct Options {
pub arg_email: String,
pub flag_show: bool,
}
pub const USAGE: &'static s... |
}
return Ok(None)
}
| {
let mut acct: Show::Showoptions = Show::ShowAcc::new(); //Not reqd - to expand later if
acct.email = options.arg_email.clone(); //multiple accounts needs to be showed
let x = acct.show();
} | conditional_block |
server.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵAnimationEngine} from '@angular/animations/browser';
import {DOCUMENT, PlatformLocation, ViewportScroller, ... | return new ɵAnimationRendererFactory(renderer, engine, zone);
}
export const SERVER_RENDER_PROVIDERS: Provider[] = [
ServerRendererFactory2,
{
provide: RendererFactory2,
useFactory: instantiateServerRendererFactory,
deps: [ServerRendererFactory2, ɵAnimationEngine, NgZone]
},
ServerStylesHost,
{... | renderer: RendererFactory2, engine: ɵAnimationEngine, zone: NgZone) { | random_line_split |
server.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵAnimationEngine} from '@angular/animations/browser';
import {DOCUMENT, PlatformLocation, ViewportScroller, ... | nderer: RendererFactory2, engine: ɵAnimationEngine, zone: NgZone) {
return new ɵAnimationRendererFactory(renderer, engine, zone);
}
export const SERVER_RENDER_PROVIDERS: Provider[] = [
ServerRendererFactory2,
{
provide: RendererFactory2,
useFactory: instantiateServerRendererFactory,
deps: [ServerRend... | ateServerRendererFactory(
re | identifier_name |
server.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵAnimationEngine} from '@angular/animations/browser';
import {DOCUMENT, PlatformLocation, ViewportScroller, ... | return getDOM().createHtmlDocument();
}
}
/**
* @publicApi
*/
export const platformServer =
createPlatformFactory(platformCore, 'server', INTERNAL_SERVER_PLATFORM_PROVIDERS);
/**
* The server platform that supports the runtime compiler.
*
* @publicApi
*/
export const platformDynamicServer =
createPla... | n parseDocument(config.document, config.url);
} else {
| conditional_block |
server.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵAnimationEngine} from '@angular/animations/browser';
import {DOCUMENT, PlatformLocation, ViewportScroller, ... | function instantiateServerRendererFactory(
renderer: RendererFactory2, engine: ɵAnimationEngine, zone: NgZone) {
return new ɵAnimationRendererFactory(renderer, engine, zone);
}
export const SERVER_RENDER_PROVIDERS: Provider[] = [
ServerRendererFactory2,
{
provide: RendererFactory2,
useFactory: insta... | rn () => { DominoAdapter.makeCurrent(); };
}
export | identifier_body |
setup.py | #!/usr/bin/env python
import os.path
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
=======
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
>>>>>>> Update README.md
try:
from set... | (filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
description = 'Google Spreadsheets Python API'
long_description = """
{index}
License
-------
MIT
Download
========
"""
long_description = long_description.lstrip("\n").format(index=read('docs/index.txt'))
version = re.search(r'... | read | identifier_name |
setup.py | #!/usr/bin/env python
import os.path
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
=======
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
>>>>>>> Update README.md
try:
from set... |
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
description = 'Google Spreadsheets Python API'
long_description = """
{index}
License
-------
MIT
Download
========
"""
long_description = long_description.lstrip("\n").format(index=read('docs/index.txt'))
version = re... | os.system('python setup.py sdist upload')
sys.exit() | conditional_block |
setup.py | #!/usr/bin/env python
| import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
=======
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
>>>>>>> Update README.md
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
i... | import os.path
<<<<<<< HEAD
import re
import sys
======= | random_line_split |
setup.py | #!/usr/bin/env python
import os.path
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
=======
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
>>>>>>> Update README.md
try:
from set... |
description = 'Google Spreadsheets Python API'
long_description = """
{index}
License
-------
MIT
Download
========
"""
long_description = long_description.lstrip("\n").format(index=read('docs/index.txt'))
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
read('gspread/__init__.p... | return open(os.path.join(os.path.dirname(__file__), filename)).read() | identifier_body |
index.js | var path = require('path')
module.exports = {
// Webpack aliases
aliases: {
quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'),
src: path.resolve(__dirname, '../src'),
assets: path.resolve(__dirname, '../src/assets'),
components: path.resolve(__dirname, '../src/components')
},
... | // Proxy your API if using any.
// Also see /build/script.dev.js and search for "proxy api requests"
// https://github.com/chimurai/http-proxy-middleware
proxyTable: {}
}
}
/*
* proxyTable example:
*
proxyTable: {
// proxy all requests starting with /api
'/api': {
target: 'ht... | // you need to avoid clearing out the console, so set this
// to "false", otherwise you can set it to "true" to always
// have only the messages regarding your last (re)compilation.
clearConsoleOnRebuild: false,
| random_line_split |
server2_proxy_test.js | var utils = require("../lib/utils.js");
exports.server2_proxy_test = {
setUp: function(done) { | proxy_options_test: function(test) {
test.expect(10);
var proxies = utils.proxies();
test.equal(proxies.length, 6, 'should return six valid proxies');
test.notEqual(proxies[0].server, null, 'server should be configured');
test.equal(proxies[0].config.context, '/defaults', 'should have context set... | // setup here if necessary
done();
}, | random_line_split |
non_terminal.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | #success
}
else {
#failure
}
}
))
.unwrap_success()
}
}
pub struct NonTerminalParserCompiler
{
path: syn::Path,
this_idx: usize
}
impl CompileExpr for NonTerminalParserCompiler
{
fn compile_expr<'a>(&self, context: &mut Context<'a>,
... | state = #recognizer_fn(state);
if state.is_successful() {
state.discard_data(); | random_line_split |
non_terminal.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
}
| {
let parser_fn = parser_name(self.path.clone());
let cardinality = context.expr_cardinality(self.this_idx);
let mut vars_names: Vec<_> = (0..cardinality)
.map(|_| context.next_free_var())
.collect();
// Due to the reverse compilation scheme, variables are given as `a3, a2,...`, however we n... | identifier_body |
non_terminal.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | <'a>(&self, _context: &mut Context<'a>,
continuation: Continuation) -> syn::Expr
{
let recognizer_fn = recognizer_name(self.path.clone());
continuation
.map_success(|success, failure| parse_quote!(
{
state = #recognizer_fn(state);
if state.is_successful() {
st... | compile_expr | identifier_name |
test_domain_priority.py | """This module contains tests that check priority of domains."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.automate.explorer.domain import DomainCollection
from cfme.automate.simulation import simulate
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.u... | (request, domain_collection, original_domain):
# take the Request class and copy it for own purposes.
domain_collection\
.instantiate(name='ManageIQ')\
.namespaces\
.instantiate(name='System')\
.classes\
.instantiate(name='Request')\
.copy_to(original_domain)
... | original_class | identifier_name |
test_domain_priority.py | """This module contains tests that check priority of domains."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.automate.explorer.domain import DomainCollection
from cfme.automate.simulation import simulate
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.u... | Polarion:
assignee: dgaikwad
initialEstimate: 1/12h
caseimportance: low
caseposneg: negative
testtype: functional
startsin: 5.7
casecomponent: Automate
tags: automate
testSteps:
1. create two domains
2. attach the same a... | random_line_split | |
test_domain_priority.py | """This module contains tests that check priority of domains."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.automate.explorer.domain import DomainCollection
from cfme.automate.simulation import simulate
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.u... |
@pytest.fixture(scope="function")
def original_method(request, original_method_write_data, original_class):
method = original_class.methods.create(
name=fauxfactory.gen_alphanumeric(),
location='inline',
script=METHOD_TORSO.format(original_method_write_data))
return method
@pytest.f... | return fauxfactory.gen_alphanumeric(32) | identifier_body |
issue-38147-1.rs | // Copyright 2017 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 ... | struct Foo<'a> {
s: &'a mut String
}
impl<'a> Foo<'a> {
fn f(&self) {
self.s.push('x'); //~ ERROR cannot borrow data mutably
}
}
fn main() {} | random_line_split | |
issue-38147-1.rs | // Copyright 2017 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 main() {}
| {
self.s.push('x'); //~ ERROR cannot borrow data mutably
} | identifier_body |
issue-38147-1.rs | // Copyright 2017 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 ... | <'a> {
s: &'a mut String
}
impl<'a> Foo<'a> {
fn f(&self) {
self.s.push('x'); //~ ERROR cannot borrow data mutably
}
}
fn main() {}
| Foo | identifier_name |
copy from.js | var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var graphics;
var pointerRect;
var rectangles;
function create ()
{
graphics = this.add.graphics({ lineStyle... | rect.height *= 0.95;
}
graphics.strokeRectShape(rect);
}
}
} | rect.width *= 0.95; | random_line_split |
copy from.js | var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var graphics;
var pointerRect;
var rectangles;
function create ()
{
graphics = this.add.graphics({ lineStyle... | {
graphics.clear();
graphics.fillRectShape(pointerRect);
for(var x = 0; x < 10; x++)
{
for(var y = 0; y < 10; y++)
{
var rect = rectangles[x][y];
if(rect.width > 10)
{
rect.width *= 0.95;
rect.height *= 0.95;
... | identifier_body | |
copy from.js | var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var graphics;
var pointerRect;
var rectangles;
function create ()
{
graphics = this.add.graphics({ lineStyle... |
}
this.input.on('pointermove', function (pointer) {
var x = Math.floor(pointer.x / 80);
var y = Math.floor(pointer.y / 60);
pointerRect.setPosition(x * 80, y * 60);
Phaser.Geom.Rectangle.CopyFrom(pointerRect, rectangles[x][y]);
});
}
function update ()
{
graphics.cle... | {
rectangles[x][y] = new Phaser.Geom.Rectangle(x * 80, y * 60, 80, 60);
} | conditional_block |
copy from.js | var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var graphics;
var pointerRect;
var rectangles;
function create ()
{
graphics = this.add.graphics({ lineStyle... | ()
{
graphics.clear();
graphics.fillRectShape(pointerRect);
for(var x = 0; x < 10; x++)
{
for(var y = 0; y < 10; y++)
{
var rect = rectangles[x][y];
if(rect.width > 10)
{
rect.width *= 0.95;
rect.height *= 0.95;
... | update | identifier_name |
__init__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that i... | # This module copyright (C) 2013 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
# | random_line_split |
validation.py | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
def validate_bug_tracker(input_url):
|
def validate_bug_tracker_base_hosting_url(input_url):
"""Check that hosting service bug URLs don't contain %s."""
# Try formatting the URL using an empty tuple to verify that it
# doesn't contain any format characters.
try:
input_url % ()
except TypeError:
raise ValidationError([
... | """
Validates that an issue tracker URI string contains one `%s` Python format
specification type (no other types are supported).
"""
try:
# Ignore escaped `%`'s
test_url = input_url.replace('%%', '')
if test_url.find('%s') == -1:
raise TypeError
# Ensure an... | identifier_body |
validation.py | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
def | (input_url):
"""
Validates that an issue tracker URI string contains one `%s` Python format
specification type (no other types are supported).
"""
try:
# Ignore escaped `%`'s
test_url = input_url.replace('%%', '')
if test_url.find('%s') == -1:
raise TypeError
... | validate_bug_tracker | identifier_name |
validation.py | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
def validate_bug_tracker(input_url):
"""
Validates that an issue tracker URI string contains one `%s` Python format
specification type (no other types are supporte... | def validate_bug_tracker_base_hosting_url(input_url):
"""Check that hosting service bug URLs don't contain %s."""
# Try formatting the URL using an empty tuple to verify that it
# doesn't contain any format characters.
try:
input_url % ()
except TypeError:
raise ValidationError([
... | random_line_split | |
validation.py | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
def validate_bug_tracker(input_url):
"""
Validates that an issue tracker URI string contains one `%s` Python format
specification type (no other types are supporte... |
# Ensure an arbitrary value can be inserted into the URL string
test_url = test_url % 1
except (TypeError, ValueError):
raise ValidationError([
_("%s has invalid format specification type(s). Use only one "
"'%%s' to mark the location of the bug id. If the URI con... | raise TypeError | conditional_block |
submessage.rs | use std::io::{ self, Write };
use byteorder::{ LittleEndian, WriteBytesExt};
pub struct | (pub SubmessageType, pub Vec<u8>);
bitflags! {
flags SubmessageType : u8 {
// const PAD = 0x01, /* Pad */
const LITTLEENDIAN = 0x01, /* Xavier's Endianness hack? */
const ACKNACK = 0x06, /* AckNack */
const HEARTBEAT = 0x07, /* Heartbeat */
const GAP = 0x08, /* Gap */
const INFO_TS = 0x09, /*... | Submessage | identifier_name |
submessage.rs | use std::io::{ self, Write };
use byteorder::{ LittleEndian, WriteBytesExt};
pub struct Submessage(pub SubmessageType, pub Vec<u8>);
bitflags! {
flags SubmessageType : u8 {
// const PAD = 0x01, /* Pad */ | const HEARTBEAT = 0x07, /* Heartbeat */
const GAP = 0x08, /* Gap */
const INFO_TS = 0x09, /* InfoTimestamp */
const INFO_SRC = 0x0c, /* InfoSource */
const INFO_REPLY_IP4 = 0x0d, /* InfoReplyIp4 */
const INFO_DST = 0x0e, /* InfoDestination */
const INFO_REPLY = 0x0f, /* InfoReply */
cons... | const LITTLEENDIAN = 0x01, /* Xavier's Endianness hack? */
const ACKNACK = 0x06, /* AckNack */ | random_line_split |
033.py | #!/usr/bin/env python
#coding:utf-8
"""
Digit canceling fractions
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be... | # run time= 0.0003981590271 | import time
tStart=time.time()
answer()
print 'run time=',time.time()-tStart
# 100 | random_line_split |
033.py | #!/usr/bin/env python
#coding:utf-8
"""
Digit canceling fractions
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be... | ():
denominator=numerator=1
for b in xrange(2,10):
for a in xrange(1,b):
for c in xrange(1,10):
m1=(10*a+b)/float(10*b+c)
m2=a/float(c)
if m1==m2:
numerator*=a
denominator*=c
print denominator/numerator
import time
tStart=time.time()
answer()
print 'run time=',time.time()-tStart
# 100
# r... | answer | identifier_name |
033.py | #!/usr/bin/env python
#coding:utf-8
"""
Digit canceling fractions
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be... |
print denominator/numerator
import time
tStart=time.time()
answer()
print 'run time=',time.time()-tStart
# 100
# run time= 0.0003981590271 | for a in xrange(1,b):
for c in xrange(1,10):
m1=(10*a+b)/float(10*b+c)
m2=a/float(c)
if m1==m2:
numerator*=a
denominator*=c | conditional_block |
033.py | #!/usr/bin/env python
#coding:utf-8
"""
Digit canceling fractions
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be... |
import time
tStart=time.time()
answer()
print 'run time=',time.time()-tStart
# 100
# run time= 0.0003981590271 | denominator=numerator=1
for b in xrange(2,10):
for a in xrange(1,b):
for c in xrange(1,10):
m1=(10*a+b)/float(10*b+c)
m2=a/float(c)
if m1==m2:
numerator*=a
denominator*=c
print denominator/numerator | identifier_body |
testData1.js | define({
input: {
eingabe: {
gegenstandswert: 0
},
gebuehr: 0,
hebesatz: {
mittelwert: "",
nenner: undefined, | zaehler_max: undefined,
zaehler_min: undefined
},
paragraph: "8",
paragraph16: {
checked: false
},
tabelle: "Pauschal",
taetigkeit: "Vorschuss (netto)"
},
expectedOutput: {
eingabe: {
gegenstandswert: 0
},
gebuehr: 0,
hebesatz: {
mittelwert: "",... | zaehler: undefined, | random_line_split |
into_matcher.rs | use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
... | (s: String) -> Matcher {
let with_format = if s.contains(FORMAT_VAR) {
s
} else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol... | from | identifier_name |
into_matcher.rs | use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
... | else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// which would get overwritten with the next replace call
let with_placehold... | {
s
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.