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 |
|---|---|---|---|---|
product.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved
# $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
# This program is free software: you can redistribute it and/or modify
# it under the ... | tlet_categ_ids = []
outlet_categ_ids.append(self.env.ref('product_outlet.product_category_o1').id)
outlet_categ_ids.append(self.env.ref('product_outlet.product_category_o2').id)
outlet_products = self.env['product.product'].search([('categ_id', 'in', outlet_categ_ids),
... | identifier_body | |
darknet53_test.py | import pytoolkit as tk
module = tk.applications.darknet53
def | ():
model = module.create(input_shape=(256, 256, 3), weights=None)
assert tuple(module.get_1_over_1(model).shape[1:3]) == (256, 256)
assert tuple(module.get_1_over_2(model).shape[1:3]) == (128, 128)
assert tuple(module.get_1_over_4(model).shape[1:3]) == (64, 64)
assert tuple(module.get_1_over_8(mode... | test_model | identifier_name |
darknet53_test.py | import pytoolkit as tk
module = tk.applications.darknet53
def test_model():
model = module.create(input_shape=(256, 256, 3), weights=None)
assert tuple(module.get_1_over_1(model).shape[1:3]) == (256, 256)
assert tuple(module.get_1_over_2(model).shape[1:3]) == (128, 128)
assert tuple(module.get_1_over... | def test_save_load(tmpdir):
model = module.create(input_shape=(256, 256, 3), weights=None)
tk.models.save(model, str(tmpdir / "model.h5"))
tk.models.load(str(tmpdir / "model.h5")) | random_line_split | |
darknet53_test.py | import pytoolkit as tk
module = tk.applications.darknet53
def test_model():
|
def test_save_load(tmpdir):
model = module.create(input_shape=(256, 256, 3), weights=None)
tk.models.save(model, str(tmpdir / "model.h5"))
tk.models.load(str(tmpdir / "model.h5"))
| model = module.create(input_shape=(256, 256, 3), weights=None)
assert tuple(module.get_1_over_1(model).shape[1:3]) == (256, 256)
assert tuple(module.get_1_over_2(model).shape[1:3]) == (128, 128)
assert tuple(module.get_1_over_4(model).shape[1:3]) == (64, 64)
assert tuple(module.get_1_over_8(model).shape... | identifier_body |
1624396968492-InitMigration.ts | import {MigrationInterface, QueryRunner} from 'typeorm'
export class InitMigration1624396968492 implements MigrationInterface {
name = 'InitMigration1624396968492'
public async up(queryRunner: QueryRunner): Promise<void> |
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "workout_set"`)
await queryRunner.query(`DROP TABLE "exercise"`)
await queryRunner.query(`DROP TABLE "user"`)
}
}
| {
await queryRunner.query(
`CREATE TABLE "user" ("uuid" varchar PRIMARY KEY NOT NULL, "email" varchar NOT NULL, "password" varchar NOT NULL, "firstName" varchar NOT NULL, "lastName" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now'... | identifier_body |
1624396968492-InitMigration.ts | import {MigrationInterface, QueryRunner} from 'typeorm'
export class | implements MigrationInterface {
name = 'InitMigration1624396968492'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "user" ("uuid" varchar PRIMARY KEY NOT NULL, "email" varchar NOT NULL, "password" varchar NOT NULL, "firstName" varchar NOT NULL, "lastNam... | InitMigration1624396968492 | identifier_name |
1624396968492-InitMigration.ts | import {MigrationInterface, QueryRunner} from 'typeorm'
export class InitMigration1624396968492 implements MigrationInterface {
name = 'InitMigration1624396968492' | )
await queryRunner.query(
`CREATE TABLE "exercise" ("uuid" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "hasRepetitions" boolean NOT NULL DEFAULT (0), "hasWeight" boolean NOT NULL DEFAULT (0), "hasTime" boolean NOT NULL DEFAULT (0), "hasDistance" boolean NOT NULL DEFAULT (0)... |
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "user" ("uuid" varchar PRIMARY KEY NOT NULL, "email" varchar NOT NULL, "password" varchar NOT NULL, "firstName" varchar NOT NULL, "lastName" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('n... | random_line_split |
curve.rs | /// (c) David Alan Gilbert <dave@treblig.org> 2016
/// Licensed under GPLv3, see the LICENSE file for a full copy
// A curve to interpolate between points
// This is currently a Quadratic Bezier; pretty simple.
use point_line::Pointf;
pub struct | {
pub start : Pointf,
pub control : Pointf,
pub end : Pointf,
}
// From https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B.C3.A9zier_curves
fn quad_interp(t: f64, s: f64, c: f64, e: f64) -> f64 {
(1.0-t)*(1.0-t)*s + 2.0*(1.0-t)*t*c + t*t*e
}
// Reworking the above to give c as the answer and specify... | Bezierq | identifier_name |
curve.rs | /// (c) David Alan Gilbert <dave@treblig.org> 2016
/// Licensed under GPLv3, see the LICENSE file for a full copy
// A curve to interpolate between points
// This is currently a Quadratic Bezier; pretty simple.
use point_line::Pointf;
pub struct Bezierq {
pub start : Pointf,
pub control : Pointf,
pub end : Poi... | } | x: find_control(s.x, m.x, e.x, mid_t),
y: find_control(s.y, m.y, e.y, mid_t) } }
} | random_line_split |
test_versions.py | import json
import pathlib
import re
import pytest
import snafu.versions
version_paths = list(snafu.versions.VERSIONS_DIR_PATH.iterdir())
version_names = [p.stem for p in version_paths]
@pytest.mark.parametrize('path', version_paths, ids=version_names)
def test_version_definitions(path):
assert path.suffix ==... | (name, force_32, result):
version = snafu.versions.get_version(name, force_32=force_32)
assert str(version) == result
@pytest.mark.parametrize('name, force_32, cmd', [
('3.6', False, 'python3.exe'),
('3.6', True, 'python3.exe'),
('2.7', False, 'python2.exe'),
('2.7', True, 'python2.exe'),
])
d... | test_str | identifier_name |
test_versions.py | import json
import pathlib
import re
import pytest
import snafu.versions
version_paths = list(snafu.versions.VERSIONS_DIR_PATH.iterdir())
version_names = [p.stem for p in version_paths]
@pytest.mark.parametrize('path', version_paths, ids=version_names)
def test_version_definitions(path):
assert path.suffix ==... |
assert not data, 'superfulous keys: {}'.format(', '.join(data.keys()))
def test_get_version_cpython_msi():
version = snafu.versions.get_version('3.4', force_32=False)
assert version == snafu.versions.CPythonMSIVersion(
name='3.4',
url='https://www.python.org/ftp/python/3.4.4/python-3.4.4... | assert data.pop('url')
assert re.match(r'^[a-f\d]{32}$', data.pop('md5_sum')) | conditional_block |
test_versions.py | import json
import pathlib
import re
import pytest
import snafu.versions
version_paths = list(snafu.versions.VERSIONS_DIR_PATH.iterdir())
version_names = [p.stem for p in version_paths]
@pytest.mark.parametrize('path', version_paths, ids=version_names)
def test_version_definitions(path):
assert path.suffix ==... |
def test_get_version_cpython():
version = snafu.versions.get_version('3.5', force_32=False)
assert version == snafu.versions.CPythonVersion(
name='3.5',
url='https://www.python.org/ftp/python/3.5.4/python-3.5.4-amd64.exe',
md5_sum='4276742a4a75a8d07260f13fe956eec4',
version_in... | version = snafu.versions.get_version('3.4', force_32=True)
assert version == snafu.versions.CPythonMSIVersion(
name='3.4',
url='https://www.python.org/ftp/python/3.4.4/python-3.4.4.msi',
md5_sum='e96268f7042d2a3d14f7e23b2535738b',
version_info=(3, 4, 4),
) | identifier_body |
test_versions.py | import json
import pathlib
import re
import pytest
import snafu.versions
version_paths = list(snafu.versions.VERSIONS_DIR_PATH.iterdir())
version_names = [p.stem for p in version_paths]
@pytest.mark.parametrize('path', version_paths, ids=version_names)
def test_version_definitions(path):
assert path.suffix ==... | ('3.6', True, 'Python 3.6-32'),
('3.4', False, 'Python 3.4'),
('3.4', True, 'Python 3.4'),
])
def test_str(name, force_32, result):
version = snafu.versions.get_version(name, force_32=force_32)
assert str(version) == result
@pytest.mark.parametrize('name, force_32, cmd', [
('3.6', False, 'pyth... | ('3.6', False, 'Python 3.6'), | random_line_split |
gpu.rs | use maplit::hashmap;
use crate::GpuState;
use std::{collections::HashMap, mem};
#[repr(C)]
#[derive(Copy, Clone)]
pub(crate) struct GenHeightmapsUniforms {
pub position: [i32; 2],
pub origin: [i32; 2],
pub spacing: f32,
pub in_slot: i32,
pub out_slot: i32,
pub level_resolution: i32,
pub fa... | dimensions: (u32, u32, u32),
uniforms: &U,
) {
if self.uniforms.is_none() {
self.uniforms = Some(device.create_buffer(&wgpu::BufferDescriptor {
size: mem::size_of::<U>() as u64,
usage: wgpu::BufferUsage::COPY_DST | wgpu::BufferUsage::UNIFORM,
... | state: &GpuState, | random_line_split |
gpu.rs | use maplit::hashmap;
use crate::GpuState;
use std::{collections::HashMap, mem};
#[repr(C)]
#[derive(Copy, Clone)]
pub(crate) struct GenHeightmapsUniforms {
pub position: [i32; 2],
pub origin: [i32; 2],
pub spacing: f32,
pub in_slot: i32,
pub out_slot: i32,
pub level_resolution: i32,
pub fa... | (&mut self) -> bool {
if self.shader.refresh() {
self.bindgroup_pipeline = None;
true
} else {
false
}
}
pub fn run(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
state: &GpuState,
dimens... | refresh | identifier_name |
gpu.rs | use maplit::hashmap;
use crate::GpuState;
use std::{collections::HashMap, mem};
#[repr(C)]
#[derive(Copy, Clone)]
pub(crate) struct GenHeightmapsUniforms {
pub position: [i32; 2],
pub origin: [i32; 2],
pub spacing: f32,
pub in_slot: i32,
pub out_slot: i32,
pub level_resolution: i32,
pub fa... |
}
pub fn run(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
state: &GpuState,
dimensions: (u32, u32, u32),
uniforms: &U,
) {
if self.uniforms.is_none() {
self.uniforms = Some(device.create_buffer(&wgpu::BufferDescr... | {
false
} | conditional_block |
mod.rs | //! Data structures related to the `/proc/<pid>/*` files
//!
//! The `Process` struct can load everything about a running process, and
//! provides some aggregate data about them.
mod cmd_line;
mod stat;
use std::fmt;
use crate::linux::{Jiffies, Ratio, PAGESIZE};
use crate::procfs::Result;
pub use self::cmd_line::C... | else {
cmd
}
}
/// What percent this process is using
///
/// First argument should be in bytes.
pub fn percent_ram(&self, of_bytes: usize) -> f64 {
pages_to_bytes(self.stat.rss) as f64 / of_bytes as f64 * 100.0
}
/// Compare this processes cpu utilization sinc... | {
self.stat.comm.clone()
} | conditional_block |
mod.rs | //! Data structures related to the `/proc/<pid>/*` files
//!
//! The `Process` struct can load everything about a running process, and
//! provides some aggregate data about them.
mod cmd_line;
mod stat;
| use crate::procfs::Result;
pub use self::cmd_line::CmdLine;
pub use self::stat::{Stat, State};
/// Information about a running process
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct Process {
/// The stat info for a process
pub stat: Stat,
/// The command line, as revealed by the /proc fs
... | use std::fmt;
use crate::linux::{Jiffies, Ratio, PAGESIZE}; | random_line_split |
mod.rs | //! Data structures related to the `/proc/<pid>/*` files
//!
//! The `Process` struct can load everything about a running process, and
//! provides some aggregate data about them.
mod cmd_line;
mod stat;
use std::fmt;
use crate::linux::{Jiffies, Ratio, PAGESIZE};
use crate::procfs::Result;
pub use self::cmd_line::C... | <'a>(
&'a self,
start_process: &'a Process,
total_cpu: Jiffies,
) -> ProcessCpuUsage<'a> {
let (start_ps, end_ps) = (&start_process.stat, &self.stat);
if end_ps.utime < start_ps.utime || end_ps.stime < start_ps.stime {
panic!("End process is before start process (... | cpu_utilization_since | identifier_name |
convert.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Eduard Broecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
# Redistributions of source code must retain the above co... |
if __name__ == '__main__':
sys.exit(cli_convert())
| """
canmatrix.cli.convert [options] import-file export-file
import-file: *.dbc|*.dbf|*.kcd|*.arxml|*.json|*.xls(x)|*.sym
export-file: *.dbc|*.dbf|*.kcd|*.arxml|*.json|*.xls(x)|*.sym|*.py
\n"""
root_logger = canmatrix.log.setup_logger()
if silent is True:
# only print error messages, ... | identifier_body |
convert.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Eduard Broecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
# Redistributions of source code must retain the above co... | ():
input = ""
output = ""
for suppFormat, features in canmatrix.formats.supportedFormats.items():
if 'load' in features:
input += suppFormat + "\n"
if 'dump' in features:
output += suppFormat + "\n"
return (input, output)
@click.command()
# global switches
@cli... | get_formats | identifier_name |
convert.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Eduard Broecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
# Redistributions of source code must retain the above co... | @click.option('--dbcExportEncoding', 'dbcExportEncoding', default="iso-8859-1", help="Export charset of dbc (relevant for units), maybe utf-8\ndefault iso-8859-1")
@click.option('--dbcExportCommentEncoding', 'dbcExportCommentEncoding', default="iso-8859-1", help="Export charset of comments in dbc\ndefault iso-8859-1")
... | @click.option('--arxmlExportVersion', 'arVersion', default="3.2.3", help="Set output AUTOSAR version\ncurrently only 3.2.3 and 4.1.0 are supported\ndefault 3.2.3")
# dbc switches
@click.option('--dbcImportEncoding', 'dbcImportEncoding', default="iso-8859-1", help="Import charset of dbc (relevant for units), maybe utf-... | random_line_split |
convert.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Eduard Broecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
# Redistributions of source code must retain the above co... |
if 'dump' in features:
output += suppFormat + "\n"
return (input, output)
@click.command()
# global switches
@click.option('-v', '--verbose', 'verbosity', count=True, default=1)
@click.option('-s', '--silent/--no-silent', is_flag=True, default=False, help="don't print status messages to stdou... | input += suppFormat + "\n" | conditional_block |
struct-partial-move-1.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 ... | // `..p` moves all fields *except* `p.y` in this context.
Partial { y: f(p.y), ..p }
}
pub fn main() {
let p = f((S::new(3), S::new(4)), |S { val: z }| S::new(z+1));
assert_eq!(p, Partial { x: S::new(3), y: S::new(5) });
} |
pub fn f<T, F>((b1, b2): (T, T), mut f: F) -> Partial<T> where F: FnMut(T) -> T {
let p = Partial { x: b1, y: b2 };
// Move of `p` is legal even though we are also moving `p.y`; the | random_line_split |
struct-partial-move-1.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 ... | (v: int) -> S { S { val: v } } }
impl Drop for S { fn drop(&mut self) { } }
pub fn f<T, F>((b1, b2): (T, T), mut f: F) -> Partial<T> where F: FnMut(T) -> T {
let p = Partial { x: b1, y: b2 };
// Move of `p` is legal even though we are also moving `p.y`; the
// `..p` moves all fields *except* `p.y` in this... | new | identifier_name |
struct-partial-move-1.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 main() {
let p = f((S::new(3), S::new(4)), |S { val: z }| S::new(z+1));
assert_eq!(p, Partial { x: S::new(3), y: S::new(5) });
}
| {
let p = Partial { x: b1, y: b2 };
// Move of `p` is legal even though we are also moving `p.y`; the
// `..p` moves all fields *except* `p.y` in this context.
Partial { y: f(p.y), ..p }
} | identifier_body |
package.js | /* global Package, Npm */
Package.describe({
name: 'procempa:keycloak-auth',
version: '1.0.0',
summary: 'Meteor Keycloak Handshake flow',
git: 'https://github.com/Procempa/meteor-keycloak-auth.git',
documentation: 'README.md' |
Package.onUse(function(api) {
api.use('ecmascript@0.1.4');
api.use('service-configuration@1.0.1');
api.export('KeycloakServer', 'server');
api.export('KeycloakClient', 'client');
api.mainModule('client-main.js', 'client');
api.mainModule('server-main.js', 'server');
});
Npm.depends({
'lodash': '4.16.1',
'fal... | }); | random_line_split |
index_controller.js | /**
* Controller for single index detail
*/
import _ from 'lodash';
import uiRoutes from 'ui/routes';
import uiModules from 'ui/modules';
import routeInitProvider from 'plugins/monitoring/lib/route_init';
import ajaxErrorHandlersProvider from 'plugins/monitoring/lib/ajax_error_handler';
import template from 'plugins/... | (clusters) {
$scope.clusters = clusters;
$scope.cluster = _.find($scope.clusters, { cluster_uuid: globalState.cluster_uuid });
}
setClusters($route.current.locals.clusters);
$scope.pageData = $route.current.locals.pageData;
$scope.indexName = $route.current.params.index;
title($scope.cluster, `Elasti... | setClusters | identifier_name |
index_controller.js | /**
* Controller for single index detail
*/
import _ from 'lodash';
import uiRoutes from 'ui/routes';
import uiModules from 'ui/modules';
import routeInitProvider from 'plugins/monitoring/lib/route_init';
import ajaxErrorHandlersProvider from 'plugins/monitoring/lib/ajax_error_handler';
import template from 'plugins/... | 'index_size',
{
name: 'index_mem',
keys: [ 'index_mem_overall' ],
config: 'xpack.monitoring.chart.elasticsearch.index.index_memory'
},
'index_document_count',
'index_segment_count'
]
})
.then(response => response.data)
.catch((err) => {
const ajaxError... | 'index_request_rate_primary'
]
}, | random_line_split |
index_controller.js | /**
* Controller for single index detail
*/
import _ from 'lodash';
import uiRoutes from 'ui/routes';
import uiModules from 'ui/modules';
import routeInitProvider from 'plugins/monitoring/lib/route_init';
import ajaxErrorHandlersProvider from 'plugins/monitoring/lib/ajax_error_handler';
import template from 'plugins/... |
const uiModule = uiModules.get('monitoring', []);
uiModule.controller('indexView', (timefilter, $route, title, Private, globalState, $executor, $http, monitoringClusters, $scope) => {
timefilter.enabled = true;
function setClusters(clusters) {
$scope.clusters = clusters;
$scope.cluster = _.find($scope.cl... | {
const timeBounds = timefilter.getBounds();
const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/indices/${$route.current.params.index}`;
return $http.post(url, {
timeRange: {
min: timeBounds.min.toISOString(),
max: timeBounds.max.toISOString()
},
metrics: ... | identifier_body |
adb_install_apk.py | #!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import multiprocessing
import optparse
import os
import sys
from pylib import android_commands
from pylib import test_options_pa... |
def main(argv):
parser = optparse.OptionParser()
test_options_parser.AddBuildTypeOption(parser)
test_options_parser.AddInstallAPKOption(parser)
options, args = parser.parse_args(argv)
if len(args) > 1:
raise Exception('Error: Unknown argument:', args[1:])
devices = android_commands.GetAttachedDevic... | options, device = args
apk_path = os.path.join(os.environ['CHROME_SRC'],
'out', options.build_type,
'apks', options.apk)
result = android_commands.AndroidCommands(device=device).ManagedInstall(
apk_path, False, options.apk_package)
print '----- Installed ... | identifier_body |
adb_install_apk.py | #!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import multiprocessing
import optparse
import os
import sys
from pylib import android_commands
from pylib import test_options_pa... |
devices = android_commands.GetAttachedDevices()
if not devices:
raise Exception('Error: no connected devices')
pool = multiprocessing.Pool(len(devices))
# Send a tuple (options, device) per instance of DeploySingleDevice.
pool.map(InstallApk, zip([options] * len(devices), devices))
if __name__ == '__... | raise Exception('Error: Unknown argument:', args[1:]) | conditional_block |
adb_install_apk.py | #!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import multiprocessing
import optparse
import os
import sys
from pylib import android_commands
from pylib import test_options_pa... |
if __name__ == '__main__':
sys.exit(main(sys.argv)) | pool.map(InstallApk, zip([options] * len(devices), devices)) | random_line_split |
adb_install_apk.py | #!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import multiprocessing
import optparse
import os
import sys
from pylib import android_commands
from pylib import test_options_pa... | (args):
options, device = args
apk_path = os.path.join(os.environ['CHROME_SRC'],
'out', options.build_type,
'apks', options.apk)
result = android_commands.AndroidCommands(device=device).ManagedInstall(
apk_path, False, options.apk_package)
print '----- ... | InstallApk | identifier_name |
sdb_dump_patch.py | import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.b... | (sdb_path, patch_name):
from sdb import SDB
with open(sdb_path, "rb") as f:
buf = f.read()
g_logger.debug("loading database")
s = SDB()
s.vsParse(bytearray(buf))
g_logger.debug("done loading database")
index = SdbIndex()
g_logger.debug("indexing strings")
index.index_sdb(s)... | _main | identifier_name |
sdb_dump_patch.py | import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.b... |
def vsParseFd(self, fd):
raise NotImplementedError()
def dump_patch(bits, arch=ARCH_32):
ps = GreedyVArray(sdb.PATCHBITS)
ps.vsParse(bits.value.value)
for i, _ in ps:
p = ps[int(i)]
print(" opcode: %s" % str(p["opcode"]))
print(" module name: %s" % p.module_name)
... | soffset = offset
while offset < len(bytez):
c = self._C()
try:
offset = c.vsParse(bytez, offset=offset, fast=False)
except:
break
self.vsAddElement(c)
return offset | identifier_body |
sdb_dump_patch.py | import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.b... | d = x86.i386Disasm()
elif arch == ARCH_64:
d = x64.Amd64Disasm()
else:
raise RuntimeError('unknown arch: ' + str(arch))
offset = 0
while True:
if offset >= len(buf):
break
o = d.disasm(buf, offset, base)
yield "0x%x: %s" % (base + offset, str(... |
def disassemble(buf, base=0, arch=ARCH_32):
if arch == ARCH_32: | random_line_split |
sdb_dump_patch.py | import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.b... |
print("")
def _main(sdb_path, patch_name):
from sdb import SDB
with open(sdb_path, "rb") as f:
buf = f.read()
g_logger.debug("loading database")
s = SDB()
s.vsParse(bytearray(buf))
g_logger.debug("done loading database")
index = SdbIndex()
g_logger.debug("indexing st... | print(" " + l) | conditional_block |
chokidarWatcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
/**
* Normalizes a set of root paths by grouping by the most parent root path.
* equests with Sub paths are skipped if they have the same ignored set as the parent.
*/
export function normalizeRoots(requests: IWatcherRequest[]): { [basePath: string]: IWatcherRequest[] } {
requests = requests.sort((r1, r2) => r1.b... | {
for (let request of requests) {
if (request.basePath === path) {
return false;
}
if (paths.isEqualOrParent(path, request.basePath)) {
if (!request.parsedPattern) {
if (request.ignored && request.ignored.length > 0) {
let pattern = `{${request.ignored.map(i => i + '/**').join(',')}}`;
reques... | identifier_body |
chokidarWatcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
return this._watcherCount;
}
private _watch(basePath: string, requests: IWatcherRequest[]): IWatcher {
if (this._options.verboseLogging) {
console.log(`Start watching: ${basePath}]`);
}
const pollingInterval = this._options.pollingInterval || 1000;
const watcherOpts: chokidar.IOptions = {
igno... | wacherCount | identifier_name |
chokidarWatcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | let ignored = (request.ignored || []).sort();
if (prevRequest && (paths.isEqualOrParent(basePath, prevRequest.basePath))) {
if (!isEqualIgnore(ignored, prevRequest.ignored)) {
result[prevRequest.basePath].push({ basePath, ignored });
}
} else {
prevRequest = { basePath, ignored };
result[basePath]... | let prevRequest: IWatcherRequest = null;
let result: { [basePath: string]: IWatcherRequest[] } = Object.create(null);
for (let request of requests) {
let basePath = request.basePath; | random_line_split |
chokidarWatcherService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
let chokidarWatcher = chokidar.watch(realBasePath, watcherOpts);
this._watcherCount++;
// Detect if for some reason the native watcher library fails to load
if (isMacintosh && !chokidarWatcher.options.useFsEvents) {
console.error('Watcher is not using native fsevents library and is falling back to uneffic... | {
console.warn(`Watcher basePath does not match version on disk and was corrected (original: ${basePath}, real: ${realBasePath})`);
} | conditional_block |
fm_demod.py | #
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later versi... | fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain | @param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim): | random_line_split |
fm_demod.py | #
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later versi... | (fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate:... | demod_200kf3e_cf | identifier_name |
fm_demod.py | #
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later versi... |
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseban... | """
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: intege... | identifier_body |
fm_demod.py | #
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later versi... |
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +... | DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self) | conditional_block |
statuses.ts | export const BattleStatuses: {[k: string]: ModdedPureEffectData} = {
brn: {
inherit: true,
onResidual(pokemon) {
this.damage(pokemon.baseMaxhp / 8);
},
},
par: {
inherit: true,
onModifySpe(spe, pokemon) {
if (!pokemon.hasAbility('quickfeet')) {
return this.chainModify(0.25);
}
},
},
confus... | }
const damage = this.getDamage(pokemon, pokemon, 40);
if (typeof damage !== 'number') throw new Error("Confusion damage not dealt");
this.damage(damage, pokemon, pokemon, {
id: 'confused',
effectType: 'Move',
type: '???',
} as ActiveMove);
return false;
},
},
choicelock: {
inherit: ... | return; | random_line_split |
statuses.ts | export const BattleStatuses: {[k: string]: ModdedPureEffectData} = {
brn: {
inherit: true,
| (pokemon) {
this.damage(pokemon.baseMaxhp / 8);
},
},
par: {
inherit: true,
onModifySpe(spe, pokemon) {
if (!pokemon.hasAbility('quickfeet')) {
return this.chainModify(0.25);
}
},
},
confusion: {
inherit: true,
onBeforeMove(pokemon) {
pokemon.volatiles.confusion.time--;
if (!pokemon.v... | onResidual | identifier_name |
statuses.ts | export const BattleStatuses: {[k: string]: ModdedPureEffectData} = {
brn: {
inherit: true,
onResidual(pokemon) {
this.damage(pokemon.baseMaxhp / 8);
},
},
par: {
inherit: true,
onModifySpe(spe, pokemon) {
if (!pokemon.hasAbility('quickfeet')) {
return this.chainModify(0.25);
}
},
},
confus... | ,
},
};
| {} | identifier_body |
main.rs | extern crate feroxide;
use feroxide::data_atoms::*;
use feroxide::data_molecules::*;
use feroxide::data_sef::*;
use feroxide::data_sep::*;
use feroxide::*;
fn main() | {
// You can create digital molecules with ease on two ways:
// ... the easy way
let carbondioxide = Molecule::from_string("CO2").unwrap();
// ... and the fast way
let carbonmonoxide = Molecule {
compounds: vec![
MoleculeCompound {
atom: CARBON,
a... | identifier_body | |
main.rs | extern crate feroxide;
use feroxide::data_atoms::*;
use feroxide::data_molecules::*;
use feroxide::data_sef::*;
use feroxide::data_sep::*;
use feroxide::*;
fn | () {
// You can create digital molecules with ease on two ways:
// ... the easy way
let carbondioxide = Molecule::from_string("CO2").unwrap();
// ... and the fast way
let carbonmonoxide = Molecule {
compounds: vec![
MoleculeCompound {
atom: CARBON,
... | main | identifier_name |
main.rs | extern crate feroxide;
use feroxide::data_atoms::*;
use feroxide::data_molecules::*;
use feroxide::data_sef::*;
use feroxide::data_sep::*;
use feroxide::*;
fn main() {
// You can create digital molecules with ease on two ways:
// ... the easy way
let carbondioxide = Molecule::from_string("CO2").unwrap();
... | println!("\n\n");
println!("Container: {}", redox_container);
println!("\tcan have the following reaction:");
println!("Redox reaction: \n{}", redox.symbol());
println!("Total reaction: {}", redox.elem_reaction().symbol());
for _ in 0..100 {
redox_container.react(&re... | conditional_block | |
main.rs | extern crate feroxide;
use feroxide::data_atoms::*;
use feroxide::data_molecules::*;
use feroxide::data_sef::*;
use feroxide::data_sep::*;
use feroxide::*;
fn main() {
// You can create digital molecules with ease on two ways:
// ... the easy way
let carbondioxide = Molecule::from_string("CO2").unwrap();
... | element: ion_from_atom!(OXYGEN.clone()),
moles: Moles::from(10000000000.0),
},
],
available_energy: Energy::from(100_000f64), // in Joules
};
// Specify the reaction that will occur
// H₂O + CO₂ ⇌ H₂CO₃
let reaction = ElemReaction {
l... | ContainerCompound { | random_line_split |
entry.js | /*
Copyright 2016 Paul Bevis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
}
return undefined;
};
}
| {
return value;
} | conditional_block |
entry.js | /*
Copyright 2016 Paul Bevis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software | */
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import Spelling from './js/containers/spelling';
import {createStore} from 'redux';
import spellingAppReducers from './js/reducers/spelling';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEven... | 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 |
11-tensormrtrix.py | # -*- coding: utf-8 -*-
from core.toad.generictask import GenericTask
from lib.images import Images
__author__ = "Mathieu Desrosiers, Arnaud Bore"
__copyright__ = "Copyright (C) 2016, TOAD"
__credits__ = ["Mathieu Desrosiers", "Arnaud Bore"]
class TensorMrtrix(GenericTask):
def __init__(self, subject):
... |
self.launchCommand(cmd)
cmd = "mrmath {} {} mean {} -nthreads {} -quiet ".format(value2, value3, rdImage, self.getNTreadsMrtrix())
self.launchCommand(cmd)
cmd = "mrmath {} {} {} mean {} -nthreads {} -quiet ".format(adImage, value2, value3, mdImage, self.getNTreadsMrtrix())
... | cmd += "-mask {} ".format(mask) | conditional_block |
11-tensormrtrix.py | # -*- coding: utf-8 -*-
from core.toad.generictask import GenericTask
from lib.images import Images
__author__ = "Mathieu Desrosiers, Arnaud Bore"
__copyright__ = "Copyright (C) 2016, TOAD"
__credits__ = ["Mathieu Desrosiers", "Arnaud Bore"]
class TensorMrtrix(GenericTask):
def __init__(self, subject):
... |
def meetRequirement(self):
return Images((self.getUpsamplingImage('dwi', 'upsample'), "upsampled diffusion"),
(self.getUpsamplingImage('grad', None, 'b'), "gradient encoding b file"),
(self.getRegistrationImage('mask', 'resample'), 'brain mask'))
def isDirty(se... | return self.get("ignore") | identifier_body |
11-tensormrtrix.py | # -*- coding: utf-8 -*-
from core.toad.generictask import GenericTask
from lib.images import Images
__author__ = "Mathieu Desrosiers, Arnaud Bore"
__copyright__ = "Copyright (C) 2016, TOAD"
__credits__ = ["Mathieu Desrosiers", "Arnaud Bore"]
class TensorMrtrix(GenericTask): |
def implement(self):
dwi = self.getUpsamplingImage('dwi', 'upsample')
bFile = self.getUpsamplingImage('grad', None, 'b')
mask = self.getRegistrationImage('mask', 'resample')
iterWLS = self.get('iter') # Number of iteration for tensor estimations
tensorsMrtrix = self.__... |
def __init__(self, subject):
GenericTask.__init__(self, subject, 'upsampling', 'registration', 'masking', 'qa') | random_line_split |
11-tensormrtrix.py | # -*- coding: utf-8 -*-
from core.toad.generictask import GenericTask
from lib.images import Images
__author__ = "Mathieu Desrosiers, Arnaud Bore"
__copyright__ = "Copyright (C) 2016, TOAD"
__credits__ = ["Mathieu Desrosiers", "Arnaud Bore"]
class TensorMrtrix(GenericTask):
def __init__(self, subject):
... | (self):
return self.get("ignore")
def meetRequirement(self):
return Images((self.getUpsamplingImage('dwi', 'upsample'), "upsampled diffusion"),
(self.getUpsamplingImage('grad', None, 'b'), "gradient encoding b file"),
(self.getRegistrationImage('mask', 'resample... | isIgnore | identifier_name |
series_test.py | import unittest
from series import slices
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0
class SeriesTest(unittest.TestCase):
def test_slices_of_one_from_one(self):
self.assertEqual(slices("1", 1), ["1"])
def test_slices_of_one_from_two(self):
self.assertEqual(s... | unittest.main() | conditional_block | |
series_test.py | import unittest
from series import slices
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0
class SeriesTest(unittest.TestCase):
def test_slices_of_one_from_one(self):
self.assertEqual(slices("1", 1), ["1"])
def test_slices_of_one_from_two(self):
self.assertEqual(s... | slices("12345", 0)
def test_slice_length_cannot_be_negative(self):
with self.assertRaisesWithMessage(ValueError):
slices("123", -1)
def test_empty_series_is_invalid(self):
with self.assertRaisesWithMessage(ValueError):
slices("", 1)
# Utility functions
... |
def test_slice_length_cannot_be_zero(self):
with self.assertRaisesWithMessage(ValueError): | random_line_split |
series_test.py | import unittest
from series import slices
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0
class SeriesTest(unittest.TestCase):
def test_slices_of_one_from_one(self):
self.assertEqual(slices("1", 1), ["1"])
def test_slices_of_one_from_two(self):
self.assertEqual(s... |
def test_slice_length_cannot_be_negative(self):
with self.assertRaisesWithMessage(ValueError):
slices("123", -1)
def test_empty_series_is_invalid(self):
with self.assertRaisesWithMessage(ValueError):
slices("", 1)
# Utility functions
def setUp(self):
t... | with self.assertRaisesWithMessage(ValueError):
slices("12345", 0) | identifier_body |
series_test.py | import unittest
from series import slices
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0
class SeriesTest(unittest.TestCase):
def test_slices_of_one_from_one(self):
self.assertEqual(slices("1", 1), ["1"])
def test_slices_of_one_from_two(self):
self.assertEqual(s... | (self, exception):
return self.assertRaisesRegex(exception, r".+")
if __name__ == "__main__":
unittest.main()
| assertRaisesWithMessage | identifier_name |
read_file.rs | /*
* How to read a file.
* Future work: as a variant, we may use the C bindings to call mmap/munmap
*/
use std::io;
use std::result;
/* read the file path by calling the read_whole_file_str function */
fn | (path: ~str) -> ~str {
let res = io::read_whole_file_str(&Path(path));
if result::is_err(&res) {
fail!(~"file_reader error: " + result::get_err(&res));
}
res.get()
}
/* read the file path line by line */
fn read_file_lines(path: ~str) -> ~str {
let res = io::file_reader(&Path(path));
if result:... | read_file_whole | identifier_name |
read_file.rs | /*
* How to read a file.
* Future work: as a variant, we may use the C bindings to call mmap/munmap
*/
use std::io;
use std::result;
/* read the file path by calling the read_whole_file_str function */
fn read_file_whole(path: ~str) -> ~str {
let res = io::read_whole_file_str(&Path(path));
if result::is_err(... |
fn main() {
let filename = ~"read_file.rs";
//let content = read_file_whole(copy filename);
let content = read_file_lines(copy filename);
io::println("the content of " + filename + " is [\n" + content + "]");
}
| {
let res = io::file_reader(&Path(path));
if result::is_err(&res) {
fail!(~"file_reader error: " + result::get_err(&res));
}
let mut content = ~"";
let reader = res.get();
loop {
let line = reader.read_line();
if reader.eof() {
break;
}
// read_line does not ret... | identifier_body |
read_file.rs | /*
* How to read a file. |
use std::io;
use std::result;
/* read the file path by calling the read_whole_file_str function */
fn read_file_whole(path: ~str) -> ~str {
let res = io::read_whole_file_str(&Path(path));
if result::is_err(&res) {
fail!(~"file_reader error: " + result::get_err(&res));
}
res.get()
}
/* read the file... | * Future work: as a variant, we may use the C bindings to call mmap/munmap
*/ | random_line_split |
read_file.rs | /*
* How to read a file.
* Future work: as a variant, we may use the C bindings to call mmap/munmap
*/
use std::io;
use std::result;
/* read the file path by calling the read_whole_file_str function */
fn read_file_whole(path: ~str) -> ~str {
let res = io::read_whole_file_str(&Path(path));
if result::is_err(... |
let mut content = ~"";
let reader = res.get();
loop {
let line = reader.read_line();
if reader.eof() {
break;
}
// read_line does not return the '\n', so we add it
content = content + line + "\n";
}
content
}
fn main() {
let filename = ~"read_file.rs";
//l... | {
fail!(~"file_reader error: " + result::get_err(&res));
} | conditional_block |
TrayHandler.test.main.ts | /*
* Wire
* Copyright (C) 2019 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This progr... | flashFrameSpy.restore();
});
});
describe('with tray icon initialization', () => {
it('updates the badge counter and stops flashing the app frame when app is in focus while receiving new messages', async () => {
const tray = new TrayHandler();
tray.initTray(TrayMock);
... | assert.ok(flashFrameSpy.firstCall.calledWith(false));
assert.strictEqual(tray['lastUnreadCount'], 1);
| random_line_split |
lev_distance.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | else {
dcol[j + 1] = cmp::min(current, next);
dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
}
current = next;
t_last = j;
}
}
dcol[t_last + 1]
}
#[test]
fn test_lev_distance() {
use std::char::{ from_u32, MAX };
// Test ... | {
dcol[j + 1] = current;
} | conditional_block |
lev_distance.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
let mut dcol: Vec<_> = (0..t.len() + 1).collect();
let mut t_last = 0;
for (i, sc) in me.chars().enumerate() {
let mut current = i;
dcol[0] = current + 1;
for (j, tc) in t.chars().enumerate() {
let next = dcol[j + 1];
if sc == tc {
dcol[j... | if me.is_empty() { return t.chars().count(); }
if t.is_empty() { return me.chars().count(); } | random_line_split |
lev_distance.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
use std::char::{ from_u32, MAX };
// Test bytelength agnosticity
for c in (0..MAX as u32)
.filter_map(|i| from_u32(i))
.map(|i| i.to_string()) {
assert_eq!(lev_distance(&c[..], &c[..]), 0);
}
let a = "\nMäry häd ä little lämb\n\nLittle lämb\n";
let b = "\nMar... | identifier_body | |
lev_distance.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
use std::char::{ from_u32, MAX };
// Test bytelength agnosticity
for c in (0..MAX as u32)
.filter_map(|i| from_u32(i))
.map(|i| i.to_string()) {
assert_eq!(lev_distance(&c[..], &c[..]), 0);
}
let a = "\nMäry häd ä little lämb\n\nLittle lämb\n";
let b = "\n... | test_lev_distance | identifier_name |
newjobpost.js | (function(){
'use strict';
/**
* @ngdoc function
* @name 343LandingPageApp.controller:NewjobpostCtrl
* @description
* # NewjobpostCtrl
* Controller of the 343LandingPageApp
*/
angular.module('343LandingPageApp')
.controller('NewjobpostCtrl', ['$scope', '$http', 'authFact', function ($scope, $http, a... | var req = {
method: 'POST',
url: 'http://neadcom.wwwss24.a2hosted.com/343TruckingAPI/api/v1/trucking/job',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $scope.job
};
$scope.save = function(){
$http(req)
.then(function(response){
// su... | random_line_split | |
landing-util.js | (function($) {
/**
* Moves elements to/from the first positions of their respective parents.
* @param {jQuery} $elements Elements (or selector) to move.
* @param {bool} condition If true, moves elements to the top. Otherwise, moves elements back to their original locations.
*/
$.prioritize = function... | // Not moved? Move it.
if (!$e.data(key)) {
// Condition is false? Bail.
if (!condition)
return;
// Get placeholder (which will serve as our point of reference for when this element needs to move back).
$p = $e.prev();
// Couldn't find anything? Means this ... | // No parent? Bail.
if ($parent.length == 0)
return;
| random_line_split |
averesultgraph-consumer-bread.py | # Draw graph x-axios is the number of nodes in the network.
import re
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter # useful for `logit` scale
from mininet.log import setLogLevel, output, info
# Read the experimental result data file in a specfied ... |
# randomly generate color
def get_cmap(n, name='hsv'):
'''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
RGB color; the keyword argument name must be a standard mpl colormap name.'''
return plt.cm.get_cmap(name, n)
# Draw statistical graph
def drawStatGraph(dataFilePath, dataFile... | "aveCol: the specified colume used for calculating a average value"
# Caculate average value according to a specified column
# Read data file and generate a list
dataList = readFileData(dataFilePath, dataFileDir, dataFileName)
sortDataList = listSort(dataList, aveCol)
conNodes = []
aveConNumOutI... | identifier_body |
averesultgraph-consumer-bread.py | # Draw graph x-axios is the number of nodes in the network.
import re
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter # useful for `logit` scale
from mininet.log import setLogLevel, output, info
# Read the experimental result data file in a specfied ... | (dataFilePath, dataFileDir):
dataFileList = os.listdir("%s/data/%s" % (dataFilePath, dataFileDir))
# delete file names that are not statistic result.
i = 0
for dataFileName in dataFileList:
if not ("statResult" in dataFileName):
dataFileList.pop(i)
i = i+1
# Sort data fil... | sortDataFile | identifier_name |
averesultgraph-consumer-bread.py | # Draw graph x-axios is the number of nodes in the network.
import re
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter # useful for `logit` scale
from mininet.log import setLogLevel, output, info
# Read the experimental result data file in a specfied ... | j = j+1
else:
flag = False
i = j
conNodes.append(int(tmp))
aveConNumOutInt.append(conNumOutInt/n)
aveDelay.append(Delay/n)
aveNumOutInt.append(numOutInt/n)
aveIntPLR.append(IntPLR/n)
aveDataPLR.append(DataPLR/n)
... | numOutInt = numOutInt + float(sortDataList[j][4].strip())
IntPLR = IntPLR + float(sortDataList[j][8].strip())
DataPLR = DataPLR + float(sortDataList[j][9].strip())
PLR = PLR + float(sortDataList[j][10].strip()) | random_line_split |
averesultgraph-consumer-bread.py | # Draw graph x-axios is the number of nodes in the network.
import re
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter # useful for `logit` scale
from mininet.log import setLogLevel, output, info
# Read the experimental result data file in a specfied ... |
i = j
conNodes.append(int(tmp))
aveConNumOutInt.append(conNumOutInt/n)
aveDelay.append(Delay/n)
aveNumOutInt.append(numOutInt/n)
aveIntPLR.append(IntPLR/n)
aveDataPLR.append(DataPLR/n)
avePLR.append(PLR/n)
return conNodes, aveConNumOutInt, aveDelay, ... | if sortDataList[j][aveCol] == tmp:
n = n + 1
conNumOutInt = conNumOutInt + float(sortDataList[j][2].strip())
Delay = Delay + float(sortDataList[j][3].strip())
numOutInt = numOutInt + float(sortDataList[j][4].strip())
IntPLR = IntPLR + float... | conditional_block |
socket.service.ts | ///<reference path="../../../node_modules/@angular/core/src/facade/async.d.ts"/>
import {EventEmitter, Inject, Injectable, Output} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { APP_CONFIG, AppConfig } from '../app.config';
import { AppService } from './app.service';
import * as io from 'socket.io... | console.log(`Disconnected from https://yalabenanotlob.herokuapp.com`);
this.socket.emit('logout', this.appService.user);
}
} | private disconnect() { | random_line_split |
socket.service.ts | ///<reference path="../../../node_modules/@angular/core/src/facade/async.d.ts"/>
import {EventEmitter, Inject, Injectable, Output} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { APP_CONFIG, AppConfig } from '../app.config';
import { AppService } from './app.service';
import * as io from 'socket.io... |
see(id: any) {
console.log(id);
this.socket.emit('see notification', id);
}
checkout(order: any) {
this.socket.emit('checkout', order);
}
notify(notification: string) {
this.socket.emit('new notification', notification);
}
// Handle connection opening
private connect() {
console.l... | {
this.socket.on('connect', () => this.connect());
this.socket.on('disconnect', () => this.disconnect());
this.socket.on('error', (error: string) => {
console.log(`ERROR: "${error}"`);
});
// Return observable which follows "notification" and "order checkout" signals from socket stream
re... | identifier_body |
socket.service.ts | ///<reference path="../../../node_modules/@angular/core/src/facade/async.d.ts"/>
import {EventEmitter, Inject, Injectable, Output} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { APP_CONFIG, AppConfig } from '../app.config';
import { AppService } from './app.service';
import * as io from 'socket.io... | () {
console.log(`Disconnected from https://yalabenanotlob.herokuapp.com`);
this.socket.emit('logout', this.appService.user);
}
}
| disconnect | identifier_name |
materialise.py | from __future__ import absolute_import, print_function, division
import operator
from collections import OrderedDict
from itertools import islice
from petl.compat import izip_longest, text_type, next
from petl.util.base import asindices, Table
def listoflists(tbl):
return [list(row) for row in tbl]
Table.li... |
Table.listoftuples = listoftuples
Table.lot = listoftuples
def tupleoflists(tbl):
return tuple(list(row) for row in tbl)
Table.tupleoflists = tupleoflists
Table.tol = tupleoflists
def columns(table, missing=None):
"""
Construct a :class:`dict` mapping field names to lists of values. E.g.::
>... |
def listoftuples(tbl):
return [tuple(row) for row in tbl]
| random_line_split |
materialise.py | from __future__ import absolute_import, print_function, division
import operator
from collections import OrderedDict
from itertools import islice
from petl.compat import izip_longest, text_type, next
from petl.util.base import asindices, Table
def | (tbl):
return [list(row) for row in tbl]
Table.listoflists = listoflists
Table.lol = listoflists
def tupleoftuples(tbl):
return tuple(tuple(row) for row in tbl)
Table.tupleoftuples = tupleoftuples
Table.tot = tupleoftuples
def listoftuples(tbl):
return [tuple(row) for row in tbl]
Table.listoftuple... | listoflists | identifier_name |
materialise.py | from __future__ import absolute_import, print_function, division
import operator
from collections import OrderedDict
from itertools import islice
from petl.compat import izip_longest, text_type, next
from petl.util.base import asindices, Table
def listoflists(tbl):
return [list(row) for row in tbl]
Table.li... | self.cachecomplete = True | conditional_block | |
materialise.py | from __future__ import absolute_import, print_function, division
import operator
from collections import OrderedDict
from itertools import islice
from petl.compat import izip_longest, text_type, next
from petl.util.base import asindices, Table
def listoflists(tbl):
return [list(row) for row in tbl]
Table.li... | for row in self.cache:
yield row
if not self.cachecomplete:
# serve the remainder from the inner iterator
it = iter(self.inner)
for row in islice(it, len(self.cache), None):
# maybe there's more room in the cache?
if not self.n or... | identifier_body | |
weaktuple.py | """tuple sub-class which holds weak references to objects"""
import weakref
class WeakTuple( tuple ):
"""tuple sub-class holding weakrefs to items
The weak reference tuple is intended to allow you
to store references to a list of objects without
needing to manage weak references directly.
For th... |
count += 1
return -1
def __add__(self, other):
"""Return a new path with other as tail"""
return tuple(self) + other
def __eq__( self, sequence ):
"""Compare the tuple to another (==)"""
return list(self) == sequence
def __ge__( self, sequence ):
... | return count | conditional_block |
weaktuple.py | """tuple sub-class which holds weak references to objects"""
import weakref
class WeakTuple( tuple ):
"""tuple sub-class holding weakrefs to items
The weak reference tuple is intended to allow you
to store references to a list of objects without
needing to manage weak references directly.
For th... | ( self, item ):
"""Unwrap an individual item
This is a fairly trivial operation at the moment,
it merely calls the item with no arguments and
returns the result.
"""
ref = item()
if ref is None:
raise weakref.ReferenceError( """%s instance no longer v... | unwrap | identifier_name |
weaktuple.py | """tuple sub-class which holds weak references to objects"""
import weakref
class WeakTuple( tuple ):
"""tuple sub-class holding weakrefs to items
The weak reference tuple is intended to allow you
to store references to a list of objects without
needing to manage weak references directly.
For th... | return """%s( %s )"""%( self.__class__.__name__, super(WeakTuple,self).__repr__()) | random_line_split | |
weaktuple.py | """tuple sub-class which holds weak references to objects"""
import weakref
class WeakTuple( tuple ):
"""tuple sub-class holding weakrefs to items
The weak reference tuple is intended to allow you
to store references to a list of objects without
needing to manage weak references directly.
For th... |
def __ge__( self, sequence ):
"""Compare the tuple to another (>=)"""
return list(self) >= sequence
def __gt__( self, sequence ):
"""Compare the tuple to another (>)"""
return list(self) > sequence
def __le__( self, sequence ):
"""Compare the tuple to anothe... | """Compare the tuple to another (==)"""
return list(self) == sequence | identifier_body |
Accra.py | '''tzinfo timezone information for Africa/Accra.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Accra(DstTzInfo):
'''Africa/Accra timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Accra'
_utc_tr... | i(1200,1200,'GHST'),
i(0,0,'GMT'),
i(1200,1200,'GHST'),
i(0,0,'GMT'),
i(1200,1200,'GHST'),
i(0,0,'GMT'),
i(1200,1200,'GHST'),
i(0,0,'GMT'),
i(1200,1200,'GHST'),
i(0,0,'GMT'),
i(1200,1200,'GHST'),
i(0,0,'GMT'),
i(1200,1200,'GHST'),
i(0,0,'GMT'),
]
Accra = Accra() | i(0,0,'GMT'), | random_line_split |
Accra.py | '''tzinfo timezone information for Africa/Accra.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class | (DstTzInfo):
'''Africa/Accra timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Accra'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1918,1,1,0,0,52),
d(1936,9,1,0,0,0),
d(1936,12,30,23,40,0),
d(1937,9,1,0,0,0),
d(1937,12,30,23,40,0),
d(1938,9,1,0,0,0),
d(1938,12,30,23,40,0),
d(1939,9,1,... | Accra | identifier_name |
Accra.py | '''tzinfo timezone information for Africa/Accra.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Accra(DstTzInfo):
|
Accra = Accra()
| '''Africa/Accra timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Accra'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1918,1,1,0,0,52),
d(1936,9,1,0,0,0),
d(1936,12,30,23,40,0),
d(1937,9,1,0,0,0),
d(1937,12,30,23,40,0),
d(1938,9,1,0,0,0),
d(1938,12,30,23,40,0),
d(1939,9,1,0,0,0),
d(1939,12... | identifier_body |
models.py | import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import Context
from django.template.loader import render_t... | to be sent when a signal is emited.
"""
content_type = ContentType.objects.get_for_model(observed)
observed_items = self.filter(content_type=content_type, object_id=observed.id, signal=signal)
return observed_items
def get_for(self, observed, observer, signal):
conte... | """
Returns all ObservedItems for an observed object, | random_line_split |
models.py | import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import Context
from django.template.loader import render_t... |
notice_type = NoticeType.objects.get(label=label)
current_site = Site.objects.get_current()
notices_url = u"http://%s%s" % (
unicode(current_site),
reverse("notification_notices"),
)
current_language = get_language()
formats = (
'short.txt',
'full.txt',
... | extra_context = {} | conditional_block |
models.py | import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import Context
from django.template.loader import render_t... | (self):
"""
returns value of self.unseen but also changes it to false.
Use this in a template to mark an unseen notice differently the first
time it is shown.
"""
unseen = self.unseen
if unseen:
self.unseen = False
self.save()
retu... | is_unseen | identifier_name |
models.py | import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import Context
from django.template.loader import render_t... |
class Meta:
verbose_name = _("notice type")
verbose_name_plural = _("notice types")
# if this gets updated, the create() method below needs to be as well...
NOTICE_MEDIA = (
("1", _("Email")),
)
# how spam-sensitive is the medium
NOTICE_MEDIA_DEFAULTS = {
"1": 2 # email
}
class NoticeS... | return self.label | identifier_body |
modules.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config)... | sync_arguments | identifier_name |
modules.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
#[cfg(feature="ipc")]
fn sync_arguments(io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let ser... | {
None
} | identifier_body |
modules.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | pub use ipc::IpcSocket;
pub use ipc::binary::serialize;
}
#[cfg(feature="ipc")]
pub fn hypervisor(base_path: &Path) -> Option<Hypervisor> {
Some(Hypervisor
::with_url(&service_urls::with_base(base_path.to_str().unwrap(), HYPERVISOR_IPC_URL))
.io_path(base_path.to_str().unwrap()))
}
#[cfg(not(feature="ipc"))]
p... | random_line_split | |
modules.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
log_settings: &LogConfig,
)
-> Result<SyncM... | {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.