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 |
|---|---|---|---|---|
setup.py | #!/usr/bin/python
import os
import sys
extra_opts = {'test_suite': 'tests'}
extra_deps = []
extra_test_deps = []
if sys.version_info[:2] == (2, 6):
extra_deps.append('argparse')
extra_deps.append('simplejson')
extra_test_deps.append('unittest2')
extra_opts['test_suite'] = 'unittest2.collector'
try:
... | },
**extra_opts
) | random_line_split | |
1139f0b4c9e3_order_name_not_unique.py | """order name not unique
Revision ID: 1139f0b4c9e3
Revises: 220436d6dcdc
Create Date: 2016-05-31 08:59:21.225314
"""
# revision identifiers, used by Alembic.
revision = '1139f0b4c9e3'
down_revision = '220436d6dcdc'
from alembic import op
import sqlalchemy as sa
def | ():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('orders_name_key', 'orders', type_='unique')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint('orders_name_key', 'orders', ['name'... | upgrade | identifier_name |
1139f0b4c9e3_order_name_not_unique.py | """order name not unique
Revision ID: 1139f0b4c9e3
Revises: 220436d6dcdc
Create Date: 2016-05-31 08:59:21.225314
"""
# revision identifiers, used by Alembic.
revision = '1139f0b4c9e3'
down_revision = '220436d6dcdc'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Al... |
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint('orders_name_key', 'orders', ['name'])
### end Alembic commands ###
| op.drop_constraint('orders_name_key', 'orders', type_='unique')
### end Alembic commands ### | identifier_body |
1139f0b4c9e3_order_name_not_unique.py | """order name not unique
Revision ID: 1139f0b4c9e3 | # revision identifiers, used by Alembic.
revision = '1139f0b4c9e3'
down_revision = '220436d6dcdc'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('orders_name_key', 'orders', type_='unique')
### end Alembic comma... | Revises: 220436d6dcdc
Create Date: 2016-05-31 08:59:21.225314
"""
| random_line_split |
App.js | Kanboard.App = function() {
this.controllers = {};
};
Kanboard.App.prototype.get = function(controller) {
return this.controllers[controller];
};
Kanboard.App.prototype.execute = function() {
for (var className in Kanboard) {
if (className !== "App") {
var controller = new Kanboard[cla... |
input.autocomplete({
source: input.data("search-url"),
minLength: 1,
select: function(event, ui) {
$("input[name=" + field + "]").val(ui.item.id);
if (extraFields) {
var fields = extraFields.split(',');
... | {
input.parent().find("button[type=submit]").attr('disabled','disabled');
} | conditional_block |
App.js | Kanboard.App = function() {
this.controllers = {};
};
Kanboard.App.prototype.get = function(controller) {
return this.controllers[controller];
};
Kanboard.App.prototype.execute = function() {
for (var className in Kanboard) {
if (className !== "App") {
var controller = new Kanboard[cla... | $("#app-loading-icon").remove();
}; | Kanboard.App.prototype.showLoadingIcon = function() {
$("body").append('<span id="app-loading-icon"> <i class="fa fa-spinner fa-spin"></i></span>');
};
Kanboard.App.prototype.hideLoadingIcon = function() { | random_line_split |
moon.py | from i3pystatus import IntervalModule, formatp
import datetime
import math
import decimal
import os
from i3pystatus.core.util import TimeWrapper
dec = decimal.Decimal
class MoonPhase(IntervalModule):
"""
Available Formatters
status: Allows for mapping of current moon phase
- New Moon:
- Waxin... |
return phase
def run(self):
fdict = {
"status": self.status[self.current_phase()],
"illum": self.illum(),
}
self.output = {
"full_text": formatp(self.format, **fdict),
"color": self.color[self.current_phase()],
}
| phase = lunarCycle * 2 | conditional_block |
moon.py | from i3pystatus import IntervalModule, formatp
import datetime
import math
import decimal
import os
from i3pystatus.core.util import TimeWrapper
dec = decimal.Decimal
class MoonPhase(IntervalModule):
"""
Available Formatters
status: Allows for mapping of current moon phase
- New Moon:
- Waxin... | def current_phase(self):
lunarCycle = self.pos()
index = (lunarCycle * dec(8)) + dec("0.5")
index = math.floor(index)
return {
0: "New Moon",
1: "Waxing Crescent",
2: "First Quarter",
3: "Waxing Gibbous",
4: "Full Moon",
... | random_line_split | |
moon.py | from i3pystatus import IntervalModule, formatp
import datetime
import math
import decimal
import os
from i3pystatus.core.util import TimeWrapper
dec = decimal.Decimal
class | (IntervalModule):
"""
Available Formatters
status: Allows for mapping of current moon phase
- New Moon:
- Waxing Crescent:
- First Quarter:
- Waxing Gibbous:
- Full Moon:
- Waning Gibbous:
- Last Quarter:
- Waning Crescent:
"""
settings = (
"format",
... | MoonPhase | identifier_name |
moon.py | from i3pystatus import IntervalModule, formatp
import datetime
import math
import decimal
import os
from i3pystatus.core.util import TimeWrapper
dec = decimal.Decimal
class MoonPhase(IntervalModule):
"""
Available Formatters
status: Allows for mapping of current moon phase
- New Moon:
- Waxin... |
def current_phase(self):
lunarCycle = self.pos()
index = (lunarCycle * dec(8)) + dec("0.5")
index = math.floor(index)
return {
0: "New Moon",
1: "Waxing Crescent",
2: "First Quarter",
3: "Waxing Gibbous",
4: "Full Moon"... | days_in_second = 86400
now = datetime.datetime.now()
difference = now - datetime.datetime(2001, 1, 1)
days = dec(difference.days) + (dec(difference.seconds) / dec(days_in_second))
lunarCycle = dec("0.20439731") + (days * dec("0.03386319269"))
return lunarCycle % dec(1) | identifier_body |
test_directoryscanner.py | import unittest
from os import path
from API.directoryscanner import find_runs_in_directory
path_to_module = path.abspath(path.dirname(__file__))
class TestDirectoryScanner(unittest.TestCase):
def test_sample_names_spaces(self):
runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-s... |
def test_find_sample_sheet_name_variations(self):
runs = find_runs_in_directory(path.join(path_to_module, "sample-sheet-name-variations"))
self.assertEqual(1, len(runs))
| runs = find_runs_in_directory(path.join(path_to_module, "completed"))
self.assertEqual(0, len(runs)) | identifier_body |
test_directoryscanner.py | import unittest
from os import path
from API.directoryscanner import find_runs_in_directory
path_to_module = path.abspath(path.dirname(__file__))
class TestDirectoryScanner(unittest.TestCase):
def test_sample_names_spaces(self):
runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-s... | (self):
runs = find_runs_in_directory(path.join(path_to_module, "sample-sheet-name-variations"))
self.assertEqual(1, len(runs))
| test_find_sample_sheet_name_variations | identifier_name |
test_directoryscanner.py | import unittest
from os import path
from API.directoryscanner import find_runs_in_directory
path_to_module = path.abspath(path.dirname(__file__))
class TestDirectoryScanner(unittest.TestCase):
def test_sample_names_spaces(self):
runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-s... |
def test_single_end(self):
runs = find_runs_in_directory(path.join(path_to_module, "single_end"))
self.assertEqual(1, len(runs))
self.assertEqual("SINGLE_END", runs[0].metadata["layoutType"])
samples = runs[0].sample_list
self.assertEqual(3, len(samples))
for sampl... | self.assertEqual(sample.get_id(), sample.get_id().strip()) | conditional_block |
test_directoryscanner.py | import unittest
from os import path
from API.directoryscanner import find_runs_in_directory
path_to_module = path.abspath(path.dirname(__file__))
class TestDirectoryScanner(unittest.TestCase):
def test_sample_names_spaces(self):
runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-s... | self.assertEqual(3, len(samples))
for sample in samples:
self.assertEqual(sample.get_id(), sample.get_id().strip())
def test_single_end(self):
runs = find_runs_in_directory(path.join(path_to_module, "single_end"))
self.assertEqual(1, len(runs))
self.assertEqual("... | self.assertEqual(1, len(runs))
samples = runs[0].sample_list | random_line_split |
sync.py | import fnmatch
import os
import re
import shutil
import sys
import uuid
from base import Step, StepRunner
from tree import Commit
here = os.path.abspath(os.path.split(__file__)[0])
bsd_license = """W3C 3-clause BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitte... |
includes = [re.compile(fnmatch.translate(item)) for item in includes]
for tree_path in tree.paths():
if (any(item.match(tree_path) for item in excludes) and
not any(item.match(tree_path) for item in includes)):
continue
source_path = os.path.join(tree.root, tree_path)... | includes = [] | conditional_block |
sync.py | import fnmatch
import os
import re
import shutil
import sys
import uuid
from base import Step, StepRunner
from tree import Commit
here = os.path.abspath(os.path.split(__file__)[0])
bsd_license = """W3C 3-clause BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitte... | (self, state):
from manifest import manifest
state.manifest_path = os.path.join(state.metadata_path, "MANIFEST.json")
state.test_manifest = manifest.Manifest("/")
class UpdateManifest(Step):
"""Update the manifest to match the tests in the sync tree checkout"""
def create(self, state)... | create | identifier_name |
sync.py | import fnmatch
import os
import re
import shutil
import sys
import uuid
from base import Step, StepRunner
from tree import Commit
here = os.path.abspath(os.path.split(__file__)[0])
bsd_license = """W3C 3-clause BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitte... | def add_license(dest):
"""Write the bsd license string to a LICENSE file.
:param dest: Directory in which to place the LICENSE file."""
with open(os.path.join(dest, "LICENSE"), "w") as f:
f.write(bsd_license)
class UpdateCheckout(Step):
"""Pull changes from upstream into the local sync tree."... |
add_license(dest)
| random_line_split |
sync.py | import fnmatch
import os
import re
import shutil
import sys
import uuid
from base import Step, StepRunner
from tree import Commit
here = os.path.abspath(os.path.split(__file__)[0])
bsd_license = """W3C 3-clause BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitte... |
class LoadManifest(Step):
"""Load the test manifest"""
provides = ["manifest_path", "test_manifest"]
def create(self, state):
from manifest import manifest
state.manifest_path = os.path.join(state.metadata_path, "MANIFEST.json")
state.test_manifest = manifest.Manifest("/")
cla... | if state.target_rev is None:
#Use upstream branch HEAD as the base commit
state.sync_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"],
state.sync["branch"])
else:
state.sync_commit = Commit(state... | identifier_body |
test_generated_python.py | import numpy as np
import scipy
import scipy.linalg
import time
import os
import sys
def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1):
env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg}
exec(symbolcode, env)
targets = env['targets']
env1 = env.copy()
env2 = env.copy()
... |
if __name__ == "__main__":
default_test_dir = "tests/gen_python/"
run_tests(default_test_dir)
| run_test(os.path.join(dirname, testdir)) | conditional_block |
test_generated_python.py | import numpy as np
import scipy
import scipy.linalg
import time
import os
import sys
def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1):
|
def run_test(dirname):
with open(os.path.join(dirname, "table.py")) as f:
symbolcode = f.read()
with open(os.path.join(dirname, "naive.py")) as f:
naive_code = f.read()
with open(os.path.join(dirname, "optimized.py")) as f:
optimized_code = f.read()
targets, errs, relerrs, n... | env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg}
exec(symbolcode, env)
targets = env['targets']
env1 = env.copy()
env2 = env.copy()
totaltime = 0.0
time1 = 0.0
time2 = 0.0
n = 0
while totaltime < max_seconds:
t1 = time.time()
exec(code1, env1)
... | identifier_body |
test_generated_python.py | import numpy as np
import scipy
import scipy.linalg
import time
import os
import sys
def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1):
env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg}
exec(symbolcode, env)
targets = env['targets']
env1 = env.copy()
env2 = env.copy()
... | (dirname):
with open(os.path.join(dirname, "table.py")) as f:
symbolcode = f.read()
with open(os.path.join(dirname, "naive.py")) as f:
naive_code = f.read()
with open(os.path.join(dirname, "optimized.py")) as f:
optimized_code = f.read()
targets, errs, relerrs, naive_time, opt... | run_test | identifier_name |
test_generated_python.py | import numpy as np
import scipy
import scipy.linalg
import time
import os
import sys
def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1):
env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg}
exec(symbolcode, env)
targets = env['targets']
env1 = env.copy()
env2 = env.copy()
... | t2 = time.time()
exec(code2, env2)
t3 = time.time()
time1 += t2-t1
time2 += t3-t2
totaltime += t3-t1
n += 1
errs = [np.max(np.abs(np.asarray(env1[target]).flatten()-np.asarray(env2[target]).flatten())) for target in targets]
relerrs = [np.max(np... | n = 0
while totaltime < max_seconds:
t1 = time.time()
exec(code1, env1) | random_line_split |
migrate.py | from optparse import OptionParser
import simplejson as json
import spotify_client
import datatype
import datetime
import time
import calendar
import wiki
import omni_redis
def migrate_v1(path_in, path_out):
client = spotify_client.Client()
uris = []
with open(path_in, 'rb') as f:
for line in f:
... |
def main():
parser = OptionParser()
parser.add_option('-i', dest='input')
parser.add_option('-o', dest='output')
parser.add_option('-w', dest='wiki', action="store_true")
options, args = parser.parse_args()
if options.wiki:
add_countries(options.input, options.output)
els... | tracks = []
artist_countries = {}
with open(path_in, 'rb') as f:
for line in f:
doc = json.loads(line)
tracks.append(doc)
artist_countries[doc['a']['n']] = None
for i,artist in enumerate(artist_countries.iterkeys()):
artist_countries[artist]=wiki.country_f... | identifier_body |
migrate.py | from optparse import OptionParser
import simplejson as json
import spotify_client
import datatype
import datetime
import time
import calendar
import wiki
import omni_redis
def migrate_v1(path_in, path_out):
client = spotify_client.Client()
uris = []
with open(path_in, 'rb') as f:
for line in f:
... | ():
parser = OptionParser()
parser.add_option('-i', dest='input')
parser.add_option('-o', dest='output')
parser.add_option('-w', dest='wiki', action="store_true")
options, args = parser.parse_args()
if options.wiki:
add_countries(options.input, options.output)
else:
... | main | identifier_name |
migrate.py | from optparse import OptionParser
import simplejson as json
import spotify_client
import datatype
import datetime
import time
import calendar
import wiki
import omni_redis
def migrate_v1(path_in, path_out):
client = spotify_client.Client()
uris = []
with open(path_in, 'rb') as f:
for line in f:
... |
print 'putting %d tracks' % len(tracks)
omni_redis.put_view('default', view, tracks)
migrate = migrate_v2
def add_countries(path_in, path_out):
tracks = []
artist_countries = {}
with open(path_in, 'rb') as f:
for line in f:
doc = json.loads(line)
tracks.append(... | t.meta.date_added = t.meta.date_added or int(round(time.time()))
t.meta.last_modified = t.meta.last_modified or int(round(time.time())) | conditional_block |
migrate.py | from optparse import OptionParser
import simplejson as json
import spotify_client
import datatype
import datetime
import time
import calendar
import wiki
import omni_redis
def migrate_v1(path_in, path_out):
client = spotify_client.Client()
uris = []
with open(path_in, 'rb') as f:
for line in f:
... | f.write('%s\n' % json.dumps(t))
def main():
parser = OptionParser()
parser.add_option('-i', dest='input')
parser.add_option('-o', dest='output')
parser.add_option('-w', dest='wiki', action="store_true")
options, args = parser.parse_args()
if options.wiki:
add_count... | random_line_split | |
training_utils_test.ts | /**
* @license
* Copyright 2019 Google LLC. 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 a... | * See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import '@tensorflow/tfjs-node';
import * as tf from '@tensorflow/tfjs-core';
// tslint:disable-next-line: no-imports-from-dist
i... | random_line_split | |
expr.rs | #![allow(dead_code)]
use super::*;
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Expr {
Nil,
Bool(bool),
Int(i64),
Flt(f64),
Str(String),
Sym(Symbol),
Func(Arc<Function>),
Macro(Arc<Macro>),
List(List),
Vector(Vector),
Map(Map),
}
impl Expr { | } else {
None
}
}
pub fn int(&self) -> Option<i64> {
if let Expr::Int(x) = *self {
Some(x)
} else {
None
}
}
pub fn flt(&self) -> Option<f64> {
if let Expr::Flt(x) = *self {
Some(x)
} else {
... | pub fn boolean(&self) -> Option<bool> {
if let Expr::Bool(x) = *self {
Some(x) | random_line_split |
expr.rs | #![allow(dead_code)]
use super::*;
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Expr {
Nil,
Bool(bool),
Int(i64),
Flt(f64),
Str(String),
Sym(Symbol),
Func(Arc<Function>),
Macro(Arc<Macro>),
List(List),
Vector(Vector),
Map(Map),
}
impl Expr {
pub f... |
pub fn is_flt(&self) -> bool {
self.flt().is_some()
}
pub fn is_num(&self) -> bool {
match *self {
Expr::Flt(_) | Expr::Int(_) => true,
_ => false,
}
}
pub fn map_int<E, F>(self, f: F) -> Expr
where
F: FnOnce(i64) -> E,
E: Into<... | {
self.int().is_some()
} | identifier_body |
expr.rs | #![allow(dead_code)]
use super::*;
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Expr {
Nil,
Bool(bool),
Int(i64),
Flt(f64),
Str(String),
Sym(Symbol),
Func(Arc<Function>),
Macro(Arc<Macro>),
List(List),
Vector(Vector),
Map(Map),
}
impl Expr {
pub f... | (&self) -> Option<&Vector> {
if let Expr::Vector(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn func(&self) -> Option<Arc<Function>> {
if let Expr::Func(ref x) = *self {
Some(x.clone())
} else {
None
}
}
... | vector | identifier_name |
astconv.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 static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type. `getter` is a function that returns the type
// corresponding to a definition ID:
pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>(
sel... | {
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(self, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
} | identifier_body |
astconv.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 ... | (
tcx: ty::ctxt,
span: span,
a_r: Option<@ast::Lifetime>,
res: Result<ty::Region, RegionError>) -> ty::Region
{
match res {
result::Ok(r) => r,
result::Err(ref e) => {
let descr = match a_r {
None => ~"anonymous lifetime",
Some(a) => fmt!("... | get_region_reporting_err | identifier_name |
astconv.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 ... |
};
get_region_reporting_err(self.tcx(), span, opt_lifetime, res)
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty {
let tcx = self.tcx();
let ty::... | {
(lifetime.span, rscope.named_region(lifetime.span,
lifetime.ident))
} | conditional_block |
astconv.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 ... | * Note that the self region for the `foo` defaulted to `&` in the first
* case but `&a` in the second. Basically, defaults that appear inside
* an rptr (`&r.T`) use the region `r` that appears in the rptr.
*/
use core::prelude::*;
use middle::const_eval;
use middle::ty::{arg, substs};
use middle::ty::{ty_param_s... | * Case (b) says that if you have a type:
* type foo<'self> = ...;
* type bar = fn(&foo, &a.foo)
* The fully expanded version of type bar is:
* type bar = fn(&'foo &, &a.foo<'a>) | random_line_split |
static-assets-loader.ts | /*
* Copyright 2021 ThoughtWorks, 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 agr... | {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
outputPath: configOptions.production ? "media/" : "fonts/",
... | identifier_body | |
static-assets-loader.ts | /*
* Copyright 2021 ThoughtWorks, 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 agr... | */
import {ConfigOptions} from "config/variables";
import webpack from "webpack";
export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
... | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. | random_line_split |
static-assets-loader.ts | /*
* Copyright 2021 ThoughtWorks, 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 agr... | (configOptions: ConfigOptions): webpack.RuleSetRule {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
outputPath: con... | getStaticAssetsLoader | identifier_name |
reporter.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::cpu::collector::{register_collector, Collector, CollectorHandle};
use crate::cpu::recorder::CpuRecords;
use crate::Config;
use std::fmt::{self, Display, Formatter};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;... | (scheduler: Scheduler<Task>) -> Self {
Self { scheduler }
}
}
impl Collector for CpuRecordsCollector {
fn collect(&self, records: Arc<CpuRecords>) {
self.scheduler.schedule(Task::CpuRecords(records)).ok();
}
}
pub enum Task {
ConfigChange(Config),
CpuRecords(Arc<CpuRecords>),
}
im... | new | identifier_name |
reporter.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::cpu::collector::{register_collector, Collector, CollectorHandle};
use crate::cpu::recorder::CpuRecords;
use crate::Config;
use std::fmt::{self, Display, Formatter};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;... |
}
impl Runnable for ResourceMeteringReporter {
type Task = Task;
fn run(&mut self, task: Self::Task) {
match task {
Task::ConfigChange(new_config) => {
let old_config_enabled = self.config.enabled;
let old_config_agent_address = self.config.agent_address.cl... | {
let channel = {
let cb = ChannelBuilder::new(self.env.clone())
.keepalive_time(Duration::from_secs(10))
.keepalive_timeout(Duration::from_secs(3));
cb.connect(&self.config.agent_address)
};
self.client = Some(ResourceUsageAgentClient::new... | identifier_body |
reporter.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::cpu::collector::{register_collector, Collector, CollectorHandle};
use crate::cpu::recorder::CpuRecords;
use crate::Config;
use std::fmt::{self, Display, Formatter};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;... | req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
... |
for (tag, (timestamp_list, cpu_time_ms_list, _)) in records {
let mut req = CpuTimeRecord::default();
req.set_resource_group_tag(tag); | random_line_split |
mod.rs | // This file is released under the same terms as Rust itself.
pub mod github_status;
pub mod jenkins;
use config::PipelinesConfig;
use hyper::Url;
use pipeline::{GetPipelineId, PipelineId};
use vcs::Commit;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CiId(pub i32);
#[derive(Clone, Debug)]
pub enum... | {
BuildStarted(CiId, Commit, Option<Url>),
BuildSucceeded(CiId, Commit, Option<Url>),
BuildFailed(CiId, Commit, Option<Url>),
}
impl GetPipelineId for Event {
fn pipeline_id<C: PipelinesConfig + ?Sized>(&self, config: &C) -> PipelineId {
let ci_id = match *self {
Event::BuildStarte... | Event | identifier_name |
mod.rs | // This file is released under the same terms as Rust itself.
pub mod github_status;
pub mod jenkins;
use config::PipelinesConfig;
use hyper::Url;
use pipeline::{GetPipelineId, PipelineId};
use vcs::Commit;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CiId(pub i32);
#[derive(Clone, Debug)]
pub enum... |
impl GetPipelineId for Event {
fn pipeline_id<C: PipelinesConfig + ?Sized>(&self, config: &C) -> PipelineId {
let ci_id = match *self {
Event::BuildStarted(i, _, _) => i,
Event::BuildSucceeded(i, _, _) => i,
Event::BuildFailed(i, _, _) => i,
};
config.by_... | BuildSucceeded(CiId, Commit, Option<Url>),
BuildFailed(CiId, Commit, Option<Url>),
} | random_line_split |
arm.rs | //! Contains arm-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
use capstone_sys::{
arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter,
cs_arm_op__bindgen_ty_2};
use libc::c_uint;
pub use crate::arch::arch_builder::arm::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{... |
/// Vector size
pub fn vector_size(&self) -> i32 {
self.0.vector_size as i32
}
/// Type of vector data
pub fn vector_data(&self) -> ArmVectorData {
self.0.vector_data
}
/// CPS mode for CPS instruction
pub fn cps_mode(&self) -> ArmCPSMode {
self.0.cps_mode
... | {
self.0.usermode
} | identifier_body |
arm.rs | //! Contains arm-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
use capstone_sys::{
arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter,
cs_arm_op__bindgen_ty_2}; | use libc::c_uint;
pub use crate::arch::arch_builder::arm::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{RegId, RegIdInt};
pub use capstone_sys::arm_insn_group as ArmInsnGroup;
pub use capstone_sys::arm_insn as ArmInsn;
pub use capstone_sys::arm_reg as ArmReg;
pub use capstone_sys::arm_vectordata_type ... | random_line_split | |
arm.rs | //! Contains arm-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
use capstone_sys::{
arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter,
cs_arm_op__bindgen_ty_2};
use libc::c_uint;
pub use crate::arch::arch_builder::arm::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{... | (&self) -> RegId {
RegId(self.0.index as RegIdInt)
}
/// Scale for index register (can be 1, or -1)
pub fn scale(&self) -> i32 {
self.0.scale as i32
}
/// Disp value
pub fn disp(&self) -> i32 {
self.0.disp as i32
}
}
impl_PartialEq_repr_fields!(ArmOpMem;
base, ... | index | identifier_name |
utils.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... |
result = arg.find(c)
if not result == -1:
if result == 0 or not arg[result - 1] == '\\':
raise exception.SSHInjectionThreat(command=cmd_list)
def create_channel(client, width, height):
"""Invoke an interactive shell session on server."""
channel = ... | continue | conditional_block |
utils.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | >>> make_dev_path('xvdc')
/dev/xvdc
>>> make_dev_path('xvdc', 1)
/dev/xvdc1
"""
path = os.path.join(base, dev)
if partition:
path += str(partition)
return path
def sanitize_hostname(hostname):
"""Return a hostname which conforms to RFC-952 and RFC-1123 specs."""
if six... | """Return a path to a particular device.
| random_line_split |
utils.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... |
def is_int_like(val):
"""Check if a value looks like an int."""
try:
return str(int(val)) == str(val)
except Exception:
return False
def check_exclusive_options(**kwargs):
"""Checks that only one of the provided options is actually not-none.
Iterates over all the kwargs passed ... | try:
return int(obj)
except (ValueError, TypeError):
pass
# Try "2.5" -> 2
try:
return int(float(obj))
except (ValueError, TypeError):
pass
# Eck, not sure what this is then.
if not quiet:
raise TypeError(_("Can not translate %s to integer.") % (obj))
... | identifier_body |
utils.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | (*cmd, **kwargs):
"""Convenience wrapper around oslo's execute() method."""
if 'run_as_root' in kwargs and 'root_helper' not in kwargs:
kwargs['root_helper'] = get_root_helper()
return processutils.execute(*cmd, **kwargs)
def check_ssh_injection(cmd_list):
ssh_injection_pattern = ['`', '$', '|... | execute | identifier_name |
test_path_utilities.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from nose.tools import ok_
import os
from py_utilities.fs.path_utilities import expanded_abspath
from py_utilities.fs.path_utilities import filename
from py_utilities.fs.path_utilities import get_first_dir_path
from py_utilities.fs.path_utilities import get_first_file_path... | (unittest.TestCase):
def test_expanded_abspath(self):
home = os.environ["HOME"]
ok_(expanded_abspath("~") == home)
ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo'))
ok_(expanded_abspath("/foo") == "/foo")
ok_(expanded_abspath("/foo/bar") == "/foo/bar")
def tes... | TestPath | identifier_name |
test_path_utilities.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from nose.tools import ok_
import os
from py_utilities.fs.path_utilities import expanded_abspath
from py_utilities.fs.path_utilities import filename
from py_utilities.fs.path_utilities import get_first_dir_path
from py_utilities.fs.path_utilities import get_first_file_path... |
def test_expanded_abspath(self):
home = os.environ["HOME"]
ok_(expanded_abspath("~") == home)
ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo'))
ok_(expanded_abspath("/foo") == "/foo")
ok_(expanded_abspath("/foo/bar") == "/foo/bar")
def test_filename(self):
... | class TestPath(unittest.TestCase): | random_line_split |
test_path_utilities.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from nose.tools import ok_
import os
from py_utilities.fs.path_utilities import expanded_abspath
from py_utilities.fs.path_utilities import filename
from py_utilities.fs.path_utilities import get_first_dir_path
from py_utilities.fs.path_utilities import get_first_file_path... |
def test_get_first_dir_path(self):
dir = tempfile.mkdtemp()
home = os.environ["HOME"]
fake = '/foo/bar/x/y/z/a'
ok_(dir == get_first_dir_path([dir]))
ok_(dir == get_first_dir_path([dir, home]))
ok_(home == get_first_dir_path([home, dir]))
ok_(home == get_fir... | ok_(filename(path) == 'bar') | conditional_block |
test_path_utilities.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from nose.tools import ok_
import os
from py_utilities.fs.path_utilities import expanded_abspath
from py_utilities.fs.path_utilities import filename
from py_utilities.fs.path_utilities import get_first_dir_path
from py_utilities.fs.path_utilities import get_first_file_path... |
# vim: filetype=python
| f = tempfile.mkstemp()[1]
fake = '/foo/bar/x/y/z/a'
ok_(f == get_first_file_path([f]))
ok_(f == get_first_file_path([f, fake]))
ok_(f == get_first_file_path([fake, f])) | identifier_body |
base.ts | import { assert, unreachable } from '../../../common/util/util.js';
import { kTextureFormatInfo } from '../../capability_info.js';
import { align } from '../../util/math.js';
import { reifyExtent3D } from '../../util/unions.js';
/**
* Compute the maximum mip level count allowed for a given texture size and texture di... | else if (dimension === 'cube') {
arrayLayerCount = 6;
} else {
arrayLayerCount = 1;
}
}
return {
format,
dimension,
aspect,
baseMipLevel,
mipLevelCount,
baseArrayLayer,
arrayLayerCount,
};
}
| {
arrayLayerCount = reifyExtent3D(texture.size).depthOrArrayLayers - baseArrayLayer;
} | conditional_block |
base.ts | import { assert, unreachable } from '../../../common/util/util.js';
import { kTextureFormatInfo } from '../../capability_info.js';
import { align } from '../../util/math.js';
import { reifyExtent3D } from '../../util/unions.js';
/**
* Compute the maximum mip level count allowed for a given texture size and texture di... |
/** Reifies the optional fields of `GPUTextureDescriptor`.
* MAINTENANCE_TODO: viewFormats should not be omitted here, but it seems likely that the
* @webgpu/types definition will have to change before we can include it again.
*/
export function reifyTextureDescriptor(
desc: Readonly<GPUTextureDescriptor>
): Requ... | case '3d':
return ['3d'] as const;
}
} | random_line_split |
base.ts | import { assert, unreachable } from '../../../common/util/util.js';
import { kTextureFormatInfo } from '../../capability_info.js';
import { align } from '../../util/math.js';
import { reifyExtent3D } from '../../util/unions.js';
/**
* Compute the maximum mip level count allowed for a given texture size and texture di... | ({
size,
dimension = '2d',
}: {
readonly size: Readonly<GPUExtent3DDict> | readonly number[];
readonly dimension?: GPUTextureDimension;
}): number {
const sizeDict = reifyExtent3D(size);
let maxMippedDimension = 0;
switch (dimension) {
case '1d':
maxMippedDimension = 1; // No mipmaps allowed.
... | maxMipLevelCount | identifier_name |
base.ts | import { assert, unreachable } from '../../../common/util/util.js';
import { kTextureFormatInfo } from '../../capability_info.js';
import { align } from '../../util/math.js';
import { reifyExtent3D } from '../../util/unions.js';
/**
* Compute the maximum mip level count allowed for a given texture size and texture di... |
/**
* Compute the "virtual size" of a mip level of a texture (not accounting for texel block rounding).
*/
export function virtualMipSize(
dimension: GPUTextureDimension,
size: readonly [number, number, number],
mipLevel: number
): [number, number, number] {
const shiftMinOne = (n: number) => Math.max(1, n ... | {
switch (dimension) {
case '1d':
assert(level === 0 && baseSize.height === 1 && baseSize.depthOrArrayLayers === 1);
return { width: baseSize.width, height: 1, depthOrArrayLayers: 1 };
case '2d': {
assert(Math.max(baseSize.width, baseSize.height) >> level > 0);
const virtualWidthAtLe... | identifier_body |
0012_auto_20160411_1630.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-11 14:30
from __future__ import unicode_literals
from django.db import migrations
import isi_mip.choiceorotherfield.models
class Migration(migrations.Migration):
| dependencies = [
('climatemodels', '0011_auto_20160407_1050'),
]
operations = [
migrations.AlterField(
model_name='impactmodel',
name='resolution',
field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('0.5°x0.5°', '0.5°x0.5°')], he... | identifier_body | |
0012_auto_20160411_1630.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-11 14:30
from __future__ import unicode_literals
from django.db import migrations
import isi_mip.choiceorotherfield.models
class | (migrations.Migration):
dependencies = [
('climatemodels', '0011_auto_20160407_1050'),
]
operations = [
migrations.AlterField(
model_name='impactmodel',
name='resolution',
field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('... | Migration | identifier_name |
0012_auto_20160411_1630.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-11 14:30
from __future__ import unicode_literals
from django.db import migrations
import isi_mip.choiceorotherfield.models |
dependencies = [
('climatemodels', '0011_auto_20160407_1050'),
]
operations = [
migrations.AlterField(
model_name='impactmodel',
name='resolution',
field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('0.5°x0.5°', '0.5°x0.5°')... |
class Migration(migrations.Migration): | random_line_split |
SSR.test.tsx | /**
* @jest-environment node
*/
import { renderToString } from 'react-dom/server'
import { IS_BROWSER } from '../src/utils/isBrowser'
import { now } from '../src/utils/now'
import { DEFAULT_ELEMENT } from '../src/utils/defaults'
import { useIdleTimer } from '../src/useIdleTimer'
describe('Server Side Rendering', ()... | it('Should not bind events', () => {
const App = () => {
const idleTimer = useIdleTimer()
idleTimer.start()
idleTimer.pause()
return (
<div>{idleTimer.isIdle()}</div>
)
}
expect(() => renderToString(<App />)).not.toThrow()
})
}) |
it('Should return now', () => {
expect(now()).toBeDefined()
})
| random_line_split |
absurd_extreme_comparisons.rs | use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use clippy_utils::comparisons::{normalize_comparison, Rel};
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_... | } | random_line_split | |
absurd_extreme_comparisons.rs | use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use clippy_utils::comparisons::{normalize_comparison, Rel};
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_... | {
Minimum,
Maximum,
}
struct ExtremeExpr<'a> {
which: ExtremeType,
expr: &'a Expr<'a>,
}
enum AbsurdComparisonResult {
AlwaysFalse,
AlwaysTrue,
InequalityImpossible,
}
fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
if let ExprKind:... | ExtremeType | identifier_name |
absurd_extreme_comparisons.rs | use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use clippy_utils::comparisons::{normalize_comparison, Rel};
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_... |
fn detect_absurd_comparison<'tcx>(
cx: &LateContext<'tcx>,
op: BinOpKind,
lhs: &'tcx Expr<'_>,
rhs: &'tcx Expr<'_>,
) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
use ExtremeType::{Maximum, Minimum};
/... | {
if let ExprKind::Cast(cast_exp, _) = expr.kind {
let precast_ty = cx.typeck_results().expr_ty(cast_exp);
let cast_ty = cx.typeck_results().expr_ty(expr);
return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
}
false
} | identifier_body |
BufferedTokenStream.py | #
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... |
else:
# no EOF token in tokens. skip check if p indexes a fetched token.
skipEofCheck = self.index < len(self.tokens)
else:
# not yet initialized
skipEofCheck = False
if not skipEofCheck and self.LA(1) == Token.EOF:
raise ... | skipEofCheck = self.index < len(self.tokens) - 1 | conditional_block |
BufferedTokenStream.py | #
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... | (self, tokenIndex, channel=-1):
self.lazyInit()
if tokenIndex<0 or tokenIndex>=len(self.tokens):
raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1))
from antlr4.Lexer import Lexer
prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT... | getHiddenTokensToLeft | identifier_name |
BufferedTokenStream.py | #
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... | self.index = -1
# Given a starting index, return the index of the next token on channel.
# Return i if tokens[i] is on channel. Return -1 if there are no tokens
# on channel between i and EOF.
#/
def nextTokenOnChannel(self, i, channel):
self.sync(i)
if i>=len(self.toke... | self.tokens = [] | random_line_split |
BufferedTokenStream.py | #
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... |
class BufferedTokenStream(TokenStream):
def __init__(self, tokenSource):
# The {@link TokenSource} from which tokens for this stream are fetched.
self.tokenSource = tokenSource
# A collection of all tokens fetched from the token source. The list is
# considered a complete view o... | pass | identifier_body |
myApp.js | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this sof... | });
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new Helloworld();
layer.init();
this.addChild(layer);
}
}); | random_line_split | |
myApp.js | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this sof... |
}
},
onTouchesEnded:function (touches, event) {
this.isMouseDown = false;
},
onTouchesCancelled:function (touches, event) {
console.log("onTouchesCancelled");
}
});
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
... | {
//this.circle.setPosition(cc.p(touches[0].getLocation().x, touches[0].getLocation().y));
} | conditional_block |
api.ts | import * as firebase from "firebase";
import fetch from "isomorphic-fetch";
import * as jwt from "jsonwebtoken";
import ClientOAuth2 from "client-oauth2";
import fakeOfferingData from "./data/offering-data.json";
import fakeClassData from "./data/small-class-data.json";
import { parseUrl, validFsId, urlParam, urlHash... |
const resourceLinkParam = resourceLinkId ? `&resource_link_id=${resourceLinkId}` : "";
const targetUserParam = targetUserId ? `&target_user_id=${targetUserId}` : "";
return `${baseUrl}/api/v1/jwt/firebase?firebase_app=${firebaseApp}&class_hash=${classHash}${resourceLinkParam}${targetUserParam}`;
};
export funct... | {
return null;
} | conditional_block |
api.ts | import * as firebase from "firebase";
import fetch from "isomorphic-fetch";
import * as jwt from "jsonwebtoken";
import ClientOAuth2 from "client-oauth2";
import fakeOfferingData from "./data/offering-data.json";
import fakeClassData from "./data/small-class-data.json";
import { parseUrl, validFsId, urlParam, urlHash... | });
});
}
export function reportSettingsFireStorePath(LTIData: ILTIPartial) {
const {platformId, platformUserId, resourceLinkId} = LTIData;
// Note this is similiar to the makeSourceKey function however in this case it is just
// stripping off the protocol if there is one. It will also leave any trailing s... | } | random_line_split |
api.ts | import * as firebase from "firebase";
import fetch from "isomorphic-fetch";
import * as jwt from "jsonwebtoken";
import ClientOAuth2 from "client-oauth2";
import fakeOfferingData from "./data/offering-data.json";
import fakeClassData from "./data/small-class-data.json";
import { parseUrl, validFsId, urlParam, urlHash... |
export function fetchOfferingData() {
const offeringUrl = urlParam("offering");
if (offeringUrl) {
return fetch(offeringUrl, {headers: {Authorization: getAuthHeader()}})
.then(checkStatus)
.then((response: Body) => response.json());
} else {
return new Promise(resolve => setTimeout(() => res... | {
if (urlParam("token")) {
return `Bearer ${urlParam("token")}`;
}
if (accessToken) {
return `Bearer ${accessToken}`;
}
throw new APIError("No token available to set auth header", { status: 0, statusText: "No token available to set auth header" });
} | identifier_body |
api.ts | import * as firebase from "firebase";
import fetch from "isomorphic-fetch";
import * as jwt from "jsonwebtoken";
import ClientOAuth2 from "client-oauth2";
import fakeOfferingData from "./data/offering-data.json";
import fakeClassData from "./data/small-class-data.json";
import { parseUrl, validFsId, urlParam, urlHash... | (sourceKey: string, instanceParams?: { platformId?: string; resourceLinkId?: string }) {
const path = `/sources/${sourceKey}/feedback_settings`;
if (instanceParams) {
return path + `/${validFsId(instanceParams.platformId + "-" + instanceParams.resourceLinkId)}`;
}
return path;
}
// The updateFeedbackSettin... | feedbackSettingsFirestorePath | identifier_name |
codegen_common.py | #!/usr/bin/python
##########################################################################
#
# MTraceCheck
# Copyright 2017 The Regents of the University of Michigan
# Doowon Lee and Valeria Bertacco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance ... | (intermediate, regBitWidth):
maxSignatureFlushCount = 0
perthreadSignatureSizes = dict()
for thread in intermediate:
pathCount = 0
signatureFlushCount = 0
for intermediateCode in intermediate[thread]:
if (intermediateCode["type"] == "profile"):
# reg, targ... | compute_max_signature_size | identifier_name |
codegen_common.py | #!/usr/bin/python
##########################################################################
#
# MTraceCheck
# Copyright 2017 The Regents of the University of Michigan
# Doowon Lee and Valeria Bertacco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance ... | #cppString += " printf(\" 0x%%lx 0x%%0%dlx\", address, result);\n" % signatureSize
cppString += "#endif\n"
cppString += " }\n"
cppString += " }\n"
cppString += " if (signatureMap.find(resultVector) == signatureMap.end())\n"
cppString += " signat... | cppString += " %s result = (%s)*(%s*)address;\n" % (wordTypeString, wordTypeString, wordTypeString)
cppString += " resultVector.push_back(result);\n"
#cppString += "#ifndef NO_PRINT\n"
cppString += "#if 0\n"
cppString += " printf(\" 0x%%0%dlx\", result);\... | random_line_split |
codegen_common.py | #!/usr/bin/python
##########################################################################
#
# MTraceCheck
# Copyright 2017 The Regents of the University of Michigan
# Doowon Lee and Valeria Bertacco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance ... |
####################################################################
# BSS section (section to be written by test threads)
####################################################################
def generate_bss_section(bssName, bssSize):
#bssArray = []
#for i in range(bssSize):
# bssArray += [0x00]
... | assert(memLocs <= 0x10000)
#dataArray = []
#for i in range(memLocs):
# data = [i & 0xFF, (i >> 8) & 0xFF, 0xFF, 0xFF]
# dataArray += data
## Data contents will be initialized in test manager, so just create a placeholder
if (strideType == 0):
dataArray = [0xFF for i in range(memLoc... | identifier_body |
codegen_common.py | #!/usr/bin/python
##########################################################################
#
# MTraceCheck
# Copyright 2017 The Regents of the University of Michigan
# Doowon Lee and Valeria Bertacco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance ... |
perthreadSignatureSizes[thread] = (signatureFlushCount + 1) * regBitWidth / 8
if (signatureFlushCount > maxSignatureFlushCount):
maxSignatureFlushCount = signatureFlushCount
# Number of bytes for each signature
temp = (maxSignatureFlushCount + 1) * regBitWidth / 8
# Log2 ceiling... | if (intermediateCode["type"] == "profile"):
# reg, targets
if ((pathCount * len(intermediateCode["targets"])) > ((1 << regBitWidth) - 1)):
pathCount = 0
signatureFlushCount += 1
if (pathCount == 0):
pathCount = l... | conditional_block |
queue.py | """Queue implementation using Linked list."""
from __future__ import print_function
from linked_list import Linked_List, Node
class | (Linked_List):
def __init__(self):
Linked_List.__init__(self)
def enqueue(self, item):
node = Node(item)
self.insert_front(node)
def dequeue(self):
return self.remove_end()
def is_empty(self):
return self.count == 0
def size(self):
return self.cou... | Queue | identifier_name |
queue.py | """Queue implementation using Linked list."""
|
def __init__(self):
Linked_List.__init__(self)
def enqueue(self, item):
node = Node(item)
self.insert_front(node)
def dequeue(self):
return self.remove_end()
def is_empty(self):
return self.count == 0
def size(self):
return self.count
def test_q... | from __future__ import print_function
from linked_list import Linked_List, Node
class Queue(Linked_List): | random_line_split |
queue.py | """Queue implementation using Linked list."""
from __future__ import print_function
from linked_list import Linked_List, Node
class Queue(Linked_List):
def __init__(self):
Linked_List.__init__(self)
def enqueue(self, item):
node = Node(item)
self.insert_front(node)
def dequeue(... | test_queue() | conditional_block | |
queue.py | """Queue implementation using Linked list."""
from __future__ import print_function
from linked_list import Linked_List, Node
class Queue(Linked_List):
def __init__(self):
Linked_List.__init__(self)
def enqueue(self, item):
node = Node(item)
self.insert_front(node)
def dequeue(... |
def size(self):
return self.count
def test_queue():
print("\n\n QUEUE TESTING")
queue = Queue()
print("Queue Empty?", queue.is_empty())
queue.enqueue("A")
queue.enqueue("B")
queue.enqueue("C")
print("Queue Size:", queue.size())
print(queue)
print("DEQUEUEING 1")
p... | return self.count == 0 | identifier_body |
setup.py | from setuptools import setup#, find_packages, Extension
import distutils.command.build as _build
import setuptools.command.install as _install
import sys
import os
import os.path as op
import distutils.spawn as ds
import distutils.dir_util as dd
import posixpath
def run_cmake(arg=""):
"""
Forcing to run cmak... | (self):
run_cmake()
# Now populate the extension module attribute.
#self.distribution.ext_modules = get_ext_modules()
_build.build.run(self)
class install(_install.install):
def run(self):
if not posixpath.exists("src/zq.so"):
run_cmake()
ds.spawn(['make... | run | identifier_name |
setup.py | from setuptools import setup#, find_packages, Extension
import distutils.command.build as _build
import setuptools.command.install as _install
import sys
import os
import os.path as op
import distutils.spawn as ds
import distutils.dir_util as dd
import posixpath
def run_cmake(arg=""):
"""
Forcing to run cmak... |
ds.spawn(['make', 'install'])
#self.distribution.ext_modules = get_ext_modules()
self.do_egg_install()
with open('README.txt') as file:
clips6_long_desc = file.read()
setup(
name = "zq",
version = '0.6',
description = 'ZQL - Zabbix Query Language',
install_requires = ["cyt... | run_cmake() | conditional_block |
setup.py | from setuptools import setup#, find_packages, Extension
import distutils.command.build as _build
import setuptools.command.install as _install
import sys
import os
import os.path as op
import distutils.spawn as ds
import distutils.dir_util as dd
import posixpath
def run_cmake(arg=""):
"""
Forcing to run cmak... |
class install(_install.install):
def run(self):
if not posixpath.exists("src/zq.so"):
run_cmake()
ds.spawn(['make', 'install'])
#self.distribution.ext_modules = get_ext_modules()
self.do_egg_install()
with open('README.txt') as file:
clips6_long_desc = file.read()
... | def run(self):
run_cmake()
# Now populate the extension module attribute.
#self.distribution.ext_modules = get_ext_modules()
_build.build.run(self) | identifier_body |
setup.py | from setuptools import setup#, find_packages, Extension
import distutils.command.build as _build
import setuptools.command.install as _install
import sys
import os
import os.path as op
import distutils.spawn as ds
import distutils.dir_util as dd
import posixpath
def run_cmake(arg=""):
"""
Forcing to run cmak... | ],
# ext_modules is not present here. This will be generated through CMake via the
# build or install commands
cmdclass={'install':install,'build': build},
zip_safe=False,
packages = ['zq'],
package_data = {
'zq': ['zq.so', '*.pyx', '*.pyi']
}
) | 'Environment :: Console :: Curses' | random_line_split |
compress.rs | use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use ::image;
use ::image::GenericImage;
use dct;
use quantize;
use color_space;
use compressed_image;
use protobuf::Message; |
use flate2::Compression;
use flate2::write::ZlibEncoder;
pub fn compress_file(input_filename: &Path) {
let file_stem = match input_filename.file_stem() {
Some(stem) => stem,
None => panic!("Invalid input filename: Could not automatically determine output file"),
};
let file_container ... | random_line_split | |
compress.rs | use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use ::image;
use ::image::GenericImage;
use dct;
use quantize;
use color_space;
use compressed_image;
use protobuf::Message;
use flate2::Compression;
use flate2::write::ZlibEncoder;
pub fn compress_file(input_filename: &Path) {
let file... | {
dct::dct2_2d(width, height, &mut uncompressed_channel_data);
quantize::encode(width, height, &uncompressed_channel_data)
} | identifier_body | |
compress.rs | use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use ::image;
use ::image::GenericImage;
use dct;
use quantize;
use color_space;
use compressed_image;
use protobuf::Message;
use flate2::Compression;
use flate2::write::ZlibEncoder;
pub fn compress_file(input_filename: &Path) {
let file... | (input_filename: &Path, output_filename: &Path) {
if let Some(extension) = output_filename.extension() {
assert!(extension == "msca",
"Output file for compression must be 'msca'")
} else {
panic!("Output file for compression must be msca")
}
let input_image = image... | compress_file_to_output | identifier_name |
chal-new.js | function load_chal_template(chal_type_name) |
nonce = "{{ nonce }}";
$.get(script_root + '/admin/chal_types', function(data){
console.log(data);
$("#create-chals-select").empty();
var chal_type_amt = Object.keys(data).length;
if (chal_type_amt > 1){
var option = "<option> -- </option>";
$("#create-chals-select").append(option);
... | {
$.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){
var template = Handlebars.compile(template_data);
$("#create-chal-entry-div").html(template({'nonce':nonce, 'script_root':script_root}));
$... | identifier_body |
chal-new.js | function | (chal_type_name){
$.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){
var template = Handlebars.compile(template_data);
$("#create-chal-entry-div").html(template({'nonce':nonce, 'script_root':script_ro... | load_chal_template | identifier_name |
chal-new.js | function load_chal_template(chal_type_name){
$.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){
var template = Handlebars.compile(template_data);
$("#create-chal-entry-div").html(template({'nonce':non... |
});
$('#create-chals-select').change(function(){
var chal_type_name = $(this).find("option:selected").text();
load_chal_template(chal_type_name);
});
| {
var key = Object.keys(data)[0];
$("#create-chals-select").parent().parent().parent().empty();
load_chal_template(data[key]);
} | conditional_block |
chal-new.js | function load_chal_template(chal_type_name){
$.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){
var template = Handlebars.compile(template_data);
$("#create-chal-entry-div").html(template({'nonce':non... | $("#create-chals-select").parent().parent().parent().empty();
load_chal_template(data[key]);
}
});
$('#create-chals-select').change(function(){
var chal_type_name = $(this).find("option:selected").text();
load_chal_template(chal_type_name);
}); | var option = "<option value='{0}'>{1}</option>".format(key, data[key]);
$("#create-chals-select").append(option);
}
} else if (chal_type_amt == 1) {
var key = Object.keys(data)[0]; | random_line_split |
config.rs | use crate::files;
use crate::package;
use std::path::PathBuf;
use serde_json;
use treeflection::{Node, NodeRunner, NodeToken};
#[derive(Clone, Serialize, Deserialize, Node)]
pub struct Config {
pub current_package: Option<String>,
pub netplay_region: Option<String>,
pub auto_save_replay: ... | }
impl Config {
fn get_path() -> PathBuf {
let mut path = files::get_path();
path.push("config.json");
path
}
pub fn load() -> Config {
if let Ok (json) = files::load_json(Config::get_path()) {
if let Ok (mut config) = serde_json::from_value::<Config>(json) {
... | pub physical_device_name: Option<String>, | random_line_split |
config.rs | use crate::files;
use crate::package;
use std::path::PathBuf;
use serde_json;
use treeflection::{Node, NodeRunner, NodeToken};
#[derive(Clone, Serialize, Deserialize, Node)]
pub struct Config {
pub current_package: Option<String>,
pub netplay_region: Option<String>,
pub auto_save_replay: ... | () -> Config {
if let Ok (json) = files::load_json(Config::get_path()) {
if let Ok (mut config) = serde_json::from_value::<Config>(json) {
// current_package may have been deleted since config was last saved
if let Some (ref current_package) = config.current_package.c... | load | identifier_name |
config.rs | use crate::files;
use crate::package;
use std::path::PathBuf;
use serde_json;
use treeflection::{Node, NodeRunner, NodeToken};
#[derive(Clone, Serialize, Deserialize, Node)]
pub struct Config {
pub current_package: Option<String>,
pub netplay_region: Option<String>,
pub auto_save_replay: ... |
warn!("{:?} is invalid or does not exist, loading default values", Config::get_path());
Config::default()
}
pub fn save(&self) {
files::save_struct(Config::get_path(), self);
}
}
impl Default for Config {
fn default() -> Config {
Config {
current_package: ... | {
if let Ok (mut config) = serde_json::from_value::<Config>(json) {
// current_package may have been deleted since config was last saved
if let Some (ref current_package) = config.current_package.clone() {
if !package::exists(current_package.as_str()) {
... | conditional_block |
core.js | var fs = require('fs');
// Core functions for loading and reloading modules
module.exports = (function()
{
var core =
{
// Define core variables
client: false,
secrets: false,
loaded: {},
modules: [],
init: function(client, modules, secrets)
{
... |
return {
init: core.init,
load: core.load,
unload: core.unload,
reload: core.reload
};
})(); | }
}; | random_line_split |
core.js | var fs = require('fs');
// Core functions for loading and reloading modules
module.exports = (function()
{
var core =
{
// Define core variables
client: false,
secrets: false,
loaded: {},
modules: [],
init: function(client, modules, secrets)
{
... |
},
load: function(module)
{
var path = "./"+module.type+"/"+module.name+".js";
// Make sure the module exists!
if(fs.existsSync(path))
{
// Create a unique ID for the module based on it's type and name
... | {
core.load(core.modules[i]);
} | conditional_block |
index.js | const symbols = require('../symbols');
const createToken = require('../create-token');
const cleanToken = require('./clean');
let depthPointer = 0;
const addTokenToExprTree = (ast, token) => {
let level = ast;
for (let i = 0; i < depthPointer; i++) {
//set the level to the rightmost deepest branch
level = ... | addTokenToExprTree(ast, token);
}
return ast;
}; | } else if (token.type === symbols.RPAREN) {
popExpr();
continue;
}
| random_line_split |
index.js | const symbols = require('../symbols');
const createToken = require('../create-token');
const cleanToken = require('./clean');
let depthPointer = 0;
const addTokenToExprTree = (ast, token) => {
let level = ast;
for (let i = 0; i < depthPointer; i++) {
//set the level to the rightmost deepest branch
level = ... |
return ast;
};
| {
const token = tokens[i];
if (token.type === symbols.LPAREN) {
pushExpr(ast);
continue;
} else if (token.type === symbols.RPAREN) {
popExpr();
continue;
}
addTokenToExprTree(ast, token);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.