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 |
|---|---|---|---|---|
main.rs | #![feature(async_await)]
use futures_util::stream::StreamExt;
use std::env;
use std::io::*;
use std::process::Stdio;
use tokio::codec::{FramedRead, LinesCodec};
use tokio::prelude::*;
use tokio::process::{Child, Command};
const USAGE: &str = "args: config_file";
struct Qemu {
pub process: Child,
}
impl Qemu {
fn new(disk_file: &str) -> Self {
let cmd: &str = &vec![
"qemu-system-x86_64.exe",
"-m",
"4G",
"-no-reboot",
"-no-shutdown",
"-drive",
&format!("file={},format=raw,if=ide", disk_file),
"-monitor",
"stdio",
"-s",
"-S",
]
.join(" ");
let process = Command::new("sh")
.args(&["-c", cmd])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("Unable to start qemu");
Self { process }
}
fn terminate(mut self) {
{
self.process
.stdin()
.as_mut()
.unwrap()
.write_all(b"q\n")
.unwrap();
}
let ecode = self.process.wait().expect("failed to wait on child");
assert!(ecode.success());
}
}
struct Gdb {
pub process: Child,
stdout: FramedRead<Vec<u8>, LinesCodec>,
}
impl Gdb {
fn new() -> Self {
let process = Command::new("gdb")
.stdin(Stdio::piped())
.stdout(Stdio::null())
// .stderr(Stdio::null())
.spawn()
.expect("Unable to start gdb");
let stdout = process.stdout().take().unwrap();
Self {
process,
stdout: FramedRead::new(stdout, LinesCodec::new()),
}
}
fn read(&mut self) -> Vec<u8> {
let mut result = Vec::new();
self.process
.stdout
.as_mut()
.unwrap()
.read_to_end(&mut result)
.unwrap();
result
}
fn write(&mut self, bytes: &[u8]) {
self.process
.stdin
.as_mut()
.unwrap()
.write_all(bytes)
.unwrap();
}
fn start(&mut self) {}
fn terminate(mut self) { | let ecode = self.process.wait().expect("failed to wait on child");
assert!(ecode.success());
}
}
#[tokio::main]
async fn main() {
let _args: Vec<_> = env::args().skip(1).collect();
let mut qemu = Qemu::new("build/test_disk.img");
let mut gdb = Gdb::new();
gdb.start();
std::thread::sleep_ms(1000);
gdb.terminate();
qemu.terminate();
println!("DONE")
} | self.write(b"q\n"); | random_line_split |
output7off.py | # THIS IS THE PYTHON CODE FOR PiFACE OUTPUT OFF
#
# Copyright (C) 2014 Tim Massey
#
# 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 program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Also add information on how to contact you by electronic and paper mail.
#!/usr/bin/python
import pifacedigitalio
pifacedigital = pifacedigitalio.PiFaceDigital()
pifacedigital.output_pins[7].turn_off() | random_line_split | |
stokes.py | # 24.05.2007, c
# last revision: 25.02.2008
from sfepy import data_dir
from sfepy.fem.periodic import *
filename_mesh = data_dir + '/meshes/2d/special/channels_symm944t.mesh'
if filename_mesh.find( 'symm' ):
region_1 = {
'name' : 'Y1',
'select' : """elements of group 3""",
}
region_2 = {
'name' : 'Y2',
'select' : """elements of group 4 +e elements of group 6
+e elements of group 8""",
}
region_4 = {
'name' : 'Y1Y2',
'select' : """r.Y1 +e r.Y2""",
}
region_5 = {
'name' : 'Walls',
'select' : """r.EBCGamma1 +n r.EBCGamma2""",
}
region_310 = {
'name' : 'EBCGamma1',
'select' : """(elements of group 1 *n elements of group 3)
+n
(elements of group 2 *n elements of group 3)
""",
}
region_320 = {
'name' : 'EBCGamma2',
'select' : """(elements of group 5 *n elements of group 4)
+n
(elements of group 1 *n elements of group 4)
+n
(elements of group 7 *n elements of group 6)
+n
(elements of group 2 *n elements of group 6)
+n
(elements of group 9 *n elements of group 8)
+n
(elements of group 2 *n elements of group 8)
""",
}
w2 = 0.499
# Sides.
region_20 = {
'name' : 'Left',
'select' : 'nodes in (x < %.3f)' % -w2,
}
region_21 = {
'name' : 'Right',
'select' : 'nodes in (x > %.3f)' % w2,
}
region_22 = {
'name' : 'Bottom',
'select' : 'nodes in (y < %.3f)' % -w2,
}
region_23 = {
'name' : 'Top',
'select' : 'nodes in (y > %.3f)' % w2,
}
field_1 = {
'name' : '2_velocity',
'dtype' : 'real',
'shape' : (2,),
'region' : 'Y1Y2',
'approx_order' : 2,
}
field_2 = {
'name' : 'pressure',
'dtype' : 'real',
'shape' : (1,),
'region' : 'Y1Y2',
'approx_order' : 1,
}
variable_1 = {
'name' : 'u',
'kind' : 'unknown field',
'field' : '2_velocity',
'order' : 0,
}
variable_2 = {
'name' : 'v',
'kind' : 'test field',
'field' : '2_velocity',
'dual' : 'u',
}
variable_3 = {
'name' : 'p',
'kind' : 'unknown field',
'field' : 'pressure',
'order' : 1,
}
variable_4 = {
'name' : 'q',
'kind' : 'test field',
'field' : 'pressure',
'dual' : 'p',
}
integral_1 = {
'name' : 'i1',
'kind' : 'v',
'quadrature' : 'gauss_o2_d2',
}
equations = {
'balance' :
"""dw_div_grad.i1.Y1Y2( fluid.viscosity, v, u )
- dw_stokes.i1.Y1Y2( v, p ) = 0""",
'incompressibility' :
"""dw_stokes.i1.Y1Y2( u, q ) = 0""",
}
material_1 = {
'name' : 'fluid',
'values' : {
'viscosity' : 1.0,
'density' : 1e0,
},
}
ebc_1 = {
'name' : 'walls',
'region' : 'Walls',
'dofs' : {'u.all' : 0.0},
}
ebc_2 = {
'name' : 'top_velocity',
'region' : 'Top',
'dofs' : {'u.1' : -1.0, 'u.0' : 0.0},
}
ebc_10 = {
'name' : 'bottom_pressure',
'region' : 'Bottom',
'dofs' : {'p.0' : 0.0},
}
| 'region' : ['Left', 'Right'],
'dofs' : {'u.all' : 'u.all', 'p.0' : 'p.0'},
'match' : 'match_y_line',
}
functions = {
'match_y_line' : (match_y_line,),
}
##
# FE assembling parameters.
fe = {
'chunk_size' : 100,
'cache_override' : True,
}
solver_0 = {
'name' : 'ls',
'kind' : 'ls.scipy_direct',
}
solver_1 = {
'name' : 'newton',
'kind' : 'nls.newton',
'i_max' : 2,
'eps_a' : 1e-8,
'eps_r' : 1e-2,
'macheps' : 1e-16,
'lin_red' : 1e-2, # Linear system error < (eps_a * lin_red).
'ls_red' : 0.1,
'ls_red_warp' : 0.001,
'ls_on' : 1.1,
'ls_min' : 1e-5,
'check' : 0,
'delta' : 1e-6,
'is_plot' : False,
'problem' : 'nonlinear', # 'nonlinear' or 'linear' (ignore i_max)
}
save_format = 'hdf5' # 'hdf5' or 'vtk' | epbc_1 = {
'name' : 'u_rl', | random_line_split |
stokes.py | # 24.05.2007, c
# last revision: 25.02.2008
from sfepy import data_dir
from sfepy.fem.periodic import *
filename_mesh = data_dir + '/meshes/2d/special/channels_symm944t.mesh'
if filename_mesh.find( 'symm' ):
|
w2 = 0.499
# Sides.
region_20 = {
'name' : 'Left',
'select' : 'nodes in (x < %.3f)' % -w2,
}
region_21 = {
'name' : 'Right',
'select' : 'nodes in (x > %.3f)' % w2,
}
region_22 = {
'name' : 'Bottom',
'select' : 'nodes in (y < %.3f)' % -w2,
}
region_23 = {
'name' : 'Top',
'select' : 'nodes in (y > %.3f)' % w2,
}
field_1 = {
'name' : '2_velocity',
'dtype' : 'real',
'shape' : (2,),
'region' : 'Y1Y2',
'approx_order' : 2,
}
field_2 = {
'name' : 'pressure',
'dtype' : 'real',
'shape' : (1,),
'region' : 'Y1Y2',
'approx_order' : 1,
}
variable_1 = {
'name' : 'u',
'kind' : 'unknown field',
'field' : '2_velocity',
'order' : 0,
}
variable_2 = {
'name' : 'v',
'kind' : 'test field',
'field' : '2_velocity',
'dual' : 'u',
}
variable_3 = {
'name' : 'p',
'kind' : 'unknown field',
'field' : 'pressure',
'order' : 1,
}
variable_4 = {
'name' : 'q',
'kind' : 'test field',
'field' : 'pressure',
'dual' : 'p',
}
integral_1 = {
'name' : 'i1',
'kind' : 'v',
'quadrature' : 'gauss_o2_d2',
}
equations = {
'balance' :
"""dw_div_grad.i1.Y1Y2( fluid.viscosity, v, u )
- dw_stokes.i1.Y1Y2( v, p ) = 0""",
'incompressibility' :
"""dw_stokes.i1.Y1Y2( u, q ) = 0""",
}
material_1 = {
'name' : 'fluid',
'values' : {
'viscosity' : 1.0,
'density' : 1e0,
},
}
ebc_1 = {
'name' : 'walls',
'region' : 'Walls',
'dofs' : {'u.all' : 0.0},
}
ebc_2 = {
'name' : 'top_velocity',
'region' : 'Top',
'dofs' : {'u.1' : -1.0, 'u.0' : 0.0},
}
ebc_10 = {
'name' : 'bottom_pressure',
'region' : 'Bottom',
'dofs' : {'p.0' : 0.0},
}
epbc_1 = {
'name' : 'u_rl',
'region' : ['Left', 'Right'],
'dofs' : {'u.all' : 'u.all', 'p.0' : 'p.0'},
'match' : 'match_y_line',
}
functions = {
'match_y_line' : (match_y_line,),
}
##
# FE assembling parameters.
fe = {
'chunk_size' : 100,
'cache_override' : True,
}
solver_0 = {
'name' : 'ls',
'kind' : 'ls.scipy_direct',
}
solver_1 = {
'name' : 'newton',
'kind' : 'nls.newton',
'i_max' : 2,
'eps_a' : 1e-8,
'eps_r' : 1e-2,
'macheps' : 1e-16,
'lin_red' : 1e-2, # Linear system error < (eps_a * lin_red).
'ls_red' : 0.1,
'ls_red_warp' : 0.001,
'ls_on' : 1.1,
'ls_min' : 1e-5,
'check' : 0,
'delta' : 1e-6,
'is_plot' : False,
'problem' : 'nonlinear', # 'nonlinear' or 'linear' (ignore i_max)
}
save_format = 'hdf5' # 'hdf5' or 'vtk'
| region_1 = {
'name' : 'Y1',
'select' : """elements of group 3""",
}
region_2 = {
'name' : 'Y2',
'select' : """elements of group 4 +e elements of group 6
+e elements of group 8""",
}
region_4 = {
'name' : 'Y1Y2',
'select' : """r.Y1 +e r.Y2""",
}
region_5 = {
'name' : 'Walls',
'select' : """r.EBCGamma1 +n r.EBCGamma2""",
}
region_310 = {
'name' : 'EBCGamma1',
'select' : """(elements of group 1 *n elements of group 3)
+n
(elements of group 2 *n elements of group 3)
""",
}
region_320 = {
'name' : 'EBCGamma2',
'select' : """(elements of group 5 *n elements of group 4)
+n
(elements of group 1 *n elements of group 4)
+n
(elements of group 7 *n elements of group 6)
+n
(elements of group 2 *n elements of group 6)
+n
(elements of group 9 *n elements of group 8)
+n
(elements of group 2 *n elements of group 8)
""",
} | conditional_block |
Rangoon.py | '''tzinfo timezone information for Asia/Rangoon.'''
from pytz.tzinfo import DstTzInfo |
class Rangoon(DstTzInfo):
'''Asia/Rangoon timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Rangoon'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1919,12,31,17,35,24),
d(1942,4,30,17,30,0),
d(1945,5,2,15,0,0),
]
_transition_info = [
i(23100,0,'RMT'),
i(23400,0,'BURT'),
i(32400,0,'JST'),
i(23400,0,'MMT'),
]
Rangoon = Rangoon() | from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i | random_line_split |
Rangoon.py | '''tzinfo timezone information for Asia/Rangoon.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class | (DstTzInfo):
'''Asia/Rangoon timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Rangoon'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1919,12,31,17,35,24),
d(1942,4,30,17,30,0),
d(1945,5,2,15,0,0),
]
_transition_info = [
i(23100,0,'RMT'),
i(23400,0,'BURT'),
i(32400,0,'JST'),
i(23400,0,'MMT'),
]
Rangoon = Rangoon()
| Rangoon | identifier_name |
Rangoon.py | '''tzinfo timezone information for Asia/Rangoon.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Rangoon(DstTzInfo):
|
Rangoon = Rangoon()
| '''Asia/Rangoon timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Rangoon'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1919,12,31,17,35,24),
d(1942,4,30,17,30,0),
d(1945,5,2,15,0,0),
]
_transition_info = [
i(23100,0,'RMT'),
i(23400,0,'BURT'),
i(32400,0,'JST'),
i(23400,0,'MMT'),
] | identifier_body |
test_compare_components.py | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals
import os
import json
from flexmock import flexmock
from atomic_reactor.constants import (PLUGIN_FETCH_WORKER_METADATA_KEY,
PLUGIN_COMPARE_COMPONENTS_KEY)
from atomic_reactor.core import DockerTasker
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import PostBuildPluginsRunner, PluginFailedException
from atomic_reactor.util import ImageName
from tests.constants import MOCK_SOURCE, TEST_IMAGE, INPUT_IMAGE, FILES
from tests.docker_mock import mock_docker
import pytest
class MockSource(object):
def __init__(self, tmpdir):
tmpdir = str(tmpdir)
self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')
self.path = tmpdir
def get_dockerfile_path(self):
return self.dockerfile_path, self.path
class MockInsideBuilder(object):
def __init__(self):
mock_docker()
self.tasker = DockerTasker()
self.base_image = ImageName(repo='fedora', tag='25')
self.image_id = 'image_id'
self.image = INPUT_IMAGE
self.df_path = 'df_path'
self.df_dir = 'df_dir'
def | (x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return None
def ensure_not_built(self):
pass
def mock_workflow(tmpdir):
workflow = DockerBuildWorkflow(MOCK_SOURCE, TEST_IMAGE)
setattr(workflow, 'builder', MockInsideBuilder())
setattr(workflow, 'source', MockSource(tmpdir))
setattr(workflow.builder, 'source', MockSource(tmpdir))
setattr(workflow, 'postbuild_result', {})
return workflow
def mock_metadatas():
json_x_path = os.path.join(FILES, "example-koji-metadata-x86_64.json")
json_p_path = os.path.join(FILES, "example-koji-metadata-ppc64le.json")
with open(json_x_path) as json_data:
metadatas_x = json.load(json_data)
with open(json_p_path) as json_data:
metadatas_p = json.load(json_data)
# need to keep data separate otherwise deepcopy and edit 'arch'
worker_metadatas = {
'x86_64': metadatas_x,
'ppc64le': metadatas_p,
}
return worker_metadatas
@pytest.mark.parametrize('fail', [True, False])
def test_compare_components_plugin(tmpdir, fail):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
if fail:
# example data has 2 log items before component item hence output[2]
worker_metadatas['ppc64le']['output'][2]['components'][0]['version'] = "bacon"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
if fail:
with pytest.raises(PluginFailedException):
runner.run()
else:
runner.run()
def test_no_components(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
del worker_metadatas['x86_64']['output'][2]['components']
del worker_metadatas['ppc64le']['output'][2]['components']
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
def test_bad_component_type(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
worker_metadatas['x86_64']['output'][2]['components'][0]['type'] = "foo"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
| simplegen | identifier_name |
test_compare_components.py | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals |
from flexmock import flexmock
from atomic_reactor.constants import (PLUGIN_FETCH_WORKER_METADATA_KEY,
PLUGIN_COMPARE_COMPONENTS_KEY)
from atomic_reactor.core import DockerTasker
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import PostBuildPluginsRunner, PluginFailedException
from atomic_reactor.util import ImageName
from tests.constants import MOCK_SOURCE, TEST_IMAGE, INPUT_IMAGE, FILES
from tests.docker_mock import mock_docker
import pytest
class MockSource(object):
def __init__(self, tmpdir):
tmpdir = str(tmpdir)
self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')
self.path = tmpdir
def get_dockerfile_path(self):
return self.dockerfile_path, self.path
class MockInsideBuilder(object):
def __init__(self):
mock_docker()
self.tasker = DockerTasker()
self.base_image = ImageName(repo='fedora', tag='25')
self.image_id = 'image_id'
self.image = INPUT_IMAGE
self.df_path = 'df_path'
self.df_dir = 'df_dir'
def simplegen(x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return None
def ensure_not_built(self):
pass
def mock_workflow(tmpdir):
workflow = DockerBuildWorkflow(MOCK_SOURCE, TEST_IMAGE)
setattr(workflow, 'builder', MockInsideBuilder())
setattr(workflow, 'source', MockSource(tmpdir))
setattr(workflow.builder, 'source', MockSource(tmpdir))
setattr(workflow, 'postbuild_result', {})
return workflow
def mock_metadatas():
json_x_path = os.path.join(FILES, "example-koji-metadata-x86_64.json")
json_p_path = os.path.join(FILES, "example-koji-metadata-ppc64le.json")
with open(json_x_path) as json_data:
metadatas_x = json.load(json_data)
with open(json_p_path) as json_data:
metadatas_p = json.load(json_data)
# need to keep data separate otherwise deepcopy and edit 'arch'
worker_metadatas = {
'x86_64': metadatas_x,
'ppc64le': metadatas_p,
}
return worker_metadatas
@pytest.mark.parametrize('fail', [True, False])
def test_compare_components_plugin(tmpdir, fail):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
if fail:
# example data has 2 log items before component item hence output[2]
worker_metadatas['ppc64le']['output'][2]['components'][0]['version'] = "bacon"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
if fail:
with pytest.raises(PluginFailedException):
runner.run()
else:
runner.run()
def test_no_components(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
del worker_metadatas['x86_64']['output'][2]['components']
del worker_metadatas['ppc64le']['output'][2]['components']
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
def test_bad_component_type(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
worker_metadatas['x86_64']['output'][2]['components'][0]['type'] = "foo"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run() |
import os
import json | random_line_split |
test_compare_components.py | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals
import os
import json
from flexmock import flexmock
from atomic_reactor.constants import (PLUGIN_FETCH_WORKER_METADATA_KEY,
PLUGIN_COMPARE_COMPONENTS_KEY)
from atomic_reactor.core import DockerTasker
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import PostBuildPluginsRunner, PluginFailedException
from atomic_reactor.util import ImageName
from tests.constants import MOCK_SOURCE, TEST_IMAGE, INPUT_IMAGE, FILES
from tests.docker_mock import mock_docker
import pytest
class MockSource(object):
def __init__(self, tmpdir):
tmpdir = str(tmpdir)
self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')
self.path = tmpdir
def get_dockerfile_path(self):
return self.dockerfile_path, self.path
class MockInsideBuilder(object):
def __init__(self):
mock_docker()
self.tasker = DockerTasker()
self.base_image = ImageName(repo='fedora', tag='25')
self.image_id = 'image_id'
self.image = INPUT_IMAGE
self.df_path = 'df_path'
self.df_dir = 'df_dir'
def simplegen(x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return None
def ensure_not_built(self):
pass
def mock_workflow(tmpdir):
workflow = DockerBuildWorkflow(MOCK_SOURCE, TEST_IMAGE)
setattr(workflow, 'builder', MockInsideBuilder())
setattr(workflow, 'source', MockSource(tmpdir))
setattr(workflow.builder, 'source', MockSource(tmpdir))
setattr(workflow, 'postbuild_result', {})
return workflow
def mock_metadatas():
json_x_path = os.path.join(FILES, "example-koji-metadata-x86_64.json")
json_p_path = os.path.join(FILES, "example-koji-metadata-ppc64le.json")
with open(json_x_path) as json_data:
metadatas_x = json.load(json_data)
with open(json_p_path) as json_data:
metadatas_p = json.load(json_data)
# need to keep data separate otherwise deepcopy and edit 'arch'
worker_metadatas = {
'x86_64': metadatas_x,
'ppc64le': metadatas_p,
}
return worker_metadatas
@pytest.mark.parametrize('fail', [True, False])
def test_compare_components_plugin(tmpdir, fail):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
if fail:
# example data has 2 log items before component item hence output[2]
worker_metadatas['ppc64le']['output'][2]['components'][0]['version'] = "bacon"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
if fail:
with pytest.raises(PluginFailedException):
runner.run()
else:
|
def test_no_components(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
del worker_metadatas['x86_64']['output'][2]['components']
del worker_metadatas['ppc64le']['output'][2]['components']
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
def test_bad_component_type(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
worker_metadatas['x86_64']['output'][2]['components'][0]['type'] = "foo"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
| runner.run() | conditional_block |
test_compare_components.py | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals
import os
import json
from flexmock import flexmock
from atomic_reactor.constants import (PLUGIN_FETCH_WORKER_METADATA_KEY,
PLUGIN_COMPARE_COMPONENTS_KEY)
from atomic_reactor.core import DockerTasker
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import PostBuildPluginsRunner, PluginFailedException
from atomic_reactor.util import ImageName
from tests.constants import MOCK_SOURCE, TEST_IMAGE, INPUT_IMAGE, FILES
from tests.docker_mock import mock_docker
import pytest
class MockSource(object):
def __init__(self, tmpdir):
|
def get_dockerfile_path(self):
return self.dockerfile_path, self.path
class MockInsideBuilder(object):
def __init__(self):
mock_docker()
self.tasker = DockerTasker()
self.base_image = ImageName(repo='fedora', tag='25')
self.image_id = 'image_id'
self.image = INPUT_IMAGE
self.df_path = 'df_path'
self.df_dir = 'df_dir'
def simplegen(x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return None
def ensure_not_built(self):
pass
def mock_workflow(tmpdir):
workflow = DockerBuildWorkflow(MOCK_SOURCE, TEST_IMAGE)
setattr(workflow, 'builder', MockInsideBuilder())
setattr(workflow, 'source', MockSource(tmpdir))
setattr(workflow.builder, 'source', MockSource(tmpdir))
setattr(workflow, 'postbuild_result', {})
return workflow
def mock_metadatas():
json_x_path = os.path.join(FILES, "example-koji-metadata-x86_64.json")
json_p_path = os.path.join(FILES, "example-koji-metadata-ppc64le.json")
with open(json_x_path) as json_data:
metadatas_x = json.load(json_data)
with open(json_p_path) as json_data:
metadatas_p = json.load(json_data)
# need to keep data separate otherwise deepcopy and edit 'arch'
worker_metadatas = {
'x86_64': metadatas_x,
'ppc64le': metadatas_p,
}
return worker_metadatas
@pytest.mark.parametrize('fail', [True, False])
def test_compare_components_plugin(tmpdir, fail):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
if fail:
# example data has 2 log items before component item hence output[2]
worker_metadatas['ppc64le']['output'][2]['components'][0]['version'] = "bacon"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
if fail:
with pytest.raises(PluginFailedException):
runner.run()
else:
runner.run()
def test_no_components(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
del worker_metadatas['x86_64']['output'][2]['components']
del worker_metadatas['ppc64le']['output'][2]['components']
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
def test_bad_component_type(tmpdir):
workflow = mock_workflow(tmpdir)
worker_metadatas = mock_metadatas()
# example data has 2 log items before component item hence output[2]
worker_metadatas['x86_64']['output'][2]['components'][0]['type'] = "foo"
workflow.postbuild_results[PLUGIN_FETCH_WORKER_METADATA_KEY] = worker_metadatas
runner = PostBuildPluginsRunner(
None,
workflow,
[{
'name': PLUGIN_COMPARE_COMPONENTS_KEY,
"args": {}
}]
)
with pytest.raises(PluginFailedException):
runner.run()
| tmpdir = str(tmpdir)
self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')
self.path = tmpdir | identifier_body |
color.ts | import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color'
import { FlowerSlot, Flower } from '../types/flower'
export const percentageIndex = [
0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32,
35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67,
70, 74, 77, 80, 83, 87, 90, 93, 96, 100
]
export const rgbIndex = [
0, 8, 16, 24, 32, 41,
49, 57, 65, 74, 82, 90,
98, 106, 115, 123, 131, 139,
148, 156, 164, 172, 180, 189,
197, 205, 213, 222, 230, 238,
246, 255
]
export function formatRgb(rgb: Rgb): string {
return rgb.join(',')
}
function getIndex(percentage: number): number {
const index = percentageIndex.indexOf(percentage)
if (index < 0){
throw new Error('Invalid color index ! Something went wrong, please contact to admin.')
}
return index
}
export function pergentageToIndex(color: ColorPercentage): ColorIndex {
return [getIndex(color[Red]), getIndex(color[Green]), getIndex(color[Blue])]
}
export function indexToPercentage(index: ColorIndex): ColorPercentage {
return [percentageIndex[index[Red]], percentageIndex[index[Green]], percentageIndex[index[Blue]]]
}
export function indexToRgb(index: ColorIndex): Rgb {
return [rgbIndex[index[Red]], rgbIndex[index[Green]], rgbIndex[index[Blue]]]
}
/**
* Blend flower color values (percentage -> index)
*/
function blendValues(values: number[]): number {
function foldSum(arr: number[]): number {
return arr.reduce((a, b) => a + b)
}
switch (values.length){
case 0:
return 0
case 1:
return getIndex(values[0])
case 2:
return (foldSum(values.map(getIndex)) * 33 / 64) | 0
case 3:
return (foldSum(values.map(getIndex)) * 34 / 99) | 0
case 4:
return (foldSum(values.map(getIndex)) * 33 / 128) | 0
default:
throw new Error('Invalid flowers count ! Some logic went wrong...')
}
}
function blendFlowers(slots: FlowerSlot[]): ColorPercentage {
const filledSlot = <Flower[]>slots.filter(slot => slot != null)
const reds = filledSlot.map(s => s.color[Red])
const greens = filledSlot.map(s => s.color[Green])
const blues = filledSlot.map(s => s.color[Blue])
return indexToPercentage([
blendValues(reds),
blendValues(greens),
blendValues(blues)
])
}
function | (value: number, bleach: number): number {
if (bleach == 0){
return value
}
const bleached = value + (bleach * 16)
return bleached > 87 ? 87 : bleached
}
function bleachStain(color: ColorPercentage, bleach: number): ColorPercentage {
return [
bleachValue(color[Red], bleach),
bleachValue(color[Green], bleach),
bleachValue(color[Blue], bleach)
]
}
export function combineStain(flowerSlot: FlowerSlot[], bleach: number): Rgb {
return percentageToRgb(bleachStain(blendFlowers(flowerSlot), bleach))
}
export function rgbToPercentage(rgb: Rgb): ColorPercentage {
return [
((rgb[Red] / 2.55) | 0),
((rgb[Green] / 2.55) | 0),
((rgb[Blue] / 2.55) | 0)
]
}
export function percentageToRgb(percentage: ColorPercentage): Rgb {
return [
(percentage[Red] * 2.55) | 0,
(percentage[Green] * 2.55) | 0,
(percentage[Blue] * 2.55) | 0
]
}
export function rgbToHsv(rgb: Rgb): Hsv {
const [red, green, blue] = rgb
const max = Math.max(red, green, blue)
const min = Math.min(red, green, blue)
const hue = (min == max)
? 0
: (min == blue)
? (60 * ((green - red) / (max - min)) + 60)
: (min == red)
? (60 * ((blue - green) / (max - min)) + 180)
: (60 * ((red - blue) / (max - min)) + 300)
const saturation = ((max - min) / max) * 100
const value = (max / 2.55)
return [hue | 0, saturation | 0, value | 0]
}
export function hsvToRgb(hsv: Hsv): Rgb {
const [hue, saturation, value] = hsv
const max = (value * 2.55) | 0
const min = (max - ((saturation / 100) * max)) | 0
if (hue < 60){
return [max, ((hue / 60) * (max - min) + min) | 0, min]
} else if (hue < 120){
return [(((120 - hue) / 60) * (max - min) + min) | 0, max, min]
} else if (hue < 180){
return [min, max, (((hue - 120) / 60) * (max - min) + min) | 0]
} else if (hue < 240){
return [min, (((240 - hue) / 60) * (max - min) + min) | 0, max]
} else if (hue < 300){
return [(((hue - 240) / 60) * (max - min) + min) | 0, min, max]
} else {
return [max, min, (((360 - hue) / 60) * (max - min) + min) | 0]
}
}
| bleachValue | identifier_name |
color.ts | import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color'
import { FlowerSlot, Flower } from '../types/flower'
export const percentageIndex = [
0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32,
35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67,
70, 74, 77, 80, 83, 87, 90, 93, 96, 100
]
export const rgbIndex = [
0, 8, 16, 24, 32, 41,
49, 57, 65, 74, 82, 90,
98, 106, 115, 123, 131, 139,
148, 156, 164, 172, 180, 189,
197, 205, 213, 222, 230, 238,
246, 255
]
export function formatRgb(rgb: Rgb): string {
return rgb.join(',')
}
function getIndex(percentage: number): number {
const index = percentageIndex.indexOf(percentage)
if (index < 0){
throw new Error('Invalid color index ! Something went wrong, please contact to admin.')
}
return index
}
export function pergentageToIndex(color: ColorPercentage): ColorIndex {
return [getIndex(color[Red]), getIndex(color[Green]), getIndex(color[Blue])]
}
export function indexToPercentage(index: ColorIndex): ColorPercentage {
return [percentageIndex[index[Red]], percentageIndex[index[Green]], percentageIndex[index[Blue]]]
}
export function indexToRgb(index: ColorIndex): Rgb {
return [rgbIndex[index[Red]], rgbIndex[index[Green]], rgbIndex[index[Blue]]]
}
/**
* Blend flower color values (percentage -> index)
*/
function blendValues(values: number[]): number {
function foldSum(arr: number[]): number {
return arr.reduce((a, b) => a + b)
}
switch (values.length){
case 0:
return 0
case 1:
return getIndex(values[0])
case 2:
return (foldSum(values.map(getIndex)) * 33 / 64) | 0
case 3:
return (foldSum(values.map(getIndex)) * 34 / 99) | 0
case 4:
return (foldSum(values.map(getIndex)) * 33 / 128) | 0
default:
throw new Error('Invalid flowers count ! Some logic went wrong...')
}
}
function blendFlowers(slots: FlowerSlot[]): ColorPercentage {
const filledSlot = <Flower[]>slots.filter(slot => slot != null)
const reds = filledSlot.map(s => s.color[Red])
const greens = filledSlot.map(s => s.color[Green])
const blues = filledSlot.map(s => s.color[Blue])
return indexToPercentage([
blendValues(reds),
blendValues(greens),
blendValues(blues)
])
}
function bleachValue(value: number, bleach: number): number {
if (bleach == 0){
return value
}
const bleached = value + (bleach * 16)
return bleached > 87 ? 87 : bleached
}
function bleachStain(color: ColorPercentage, bleach: number): ColorPercentage {
return [
bleachValue(color[Red], bleach),
bleachValue(color[Green], bleach),
bleachValue(color[Blue], bleach)
]
}
export function combineStain(flowerSlot: FlowerSlot[], bleach: number): Rgb {
return percentageToRgb(bleachStain(blendFlowers(flowerSlot), bleach))
}
export function rgbToPercentage(rgb: Rgb): ColorPercentage {
return [
((rgb[Red] / 2.55) | 0),
((rgb[Green] / 2.55) | 0),
((rgb[Blue] / 2.55) | 0)
]
}
export function percentageToRgb(percentage: ColorPercentage): Rgb {
return [
(percentage[Red] * 2.55) | 0,
(percentage[Green] * 2.55) | 0,
(percentage[Blue] * 2.55) | 0
]
}
export function rgbToHsv(rgb: Rgb): Hsv |
export function hsvToRgb(hsv: Hsv): Rgb {
const [hue, saturation, value] = hsv
const max = (value * 2.55) | 0
const min = (max - ((saturation / 100) * max)) | 0
if (hue < 60){
return [max, ((hue / 60) * (max - min) + min) | 0, min]
} else if (hue < 120){
return [(((120 - hue) / 60) * (max - min) + min) | 0, max, min]
} else if (hue < 180){
return [min, max, (((hue - 120) / 60) * (max - min) + min) | 0]
} else if (hue < 240){
return [min, (((240 - hue) / 60) * (max - min) + min) | 0, max]
} else if (hue < 300){
return [(((hue - 240) / 60) * (max - min) + min) | 0, min, max]
} else {
return [max, min, (((360 - hue) / 60) * (max - min) + min) | 0]
}
}
| {
const [red, green, blue] = rgb
const max = Math.max(red, green, blue)
const min = Math.min(red, green, blue)
const hue = (min == max)
? 0
: (min == blue)
? (60 * ((green - red) / (max - min)) + 60)
: (min == red)
? (60 * ((blue - green) / (max - min)) + 180)
: (60 * ((red - blue) / (max - min)) + 300)
const saturation = ((max - min) / max) * 100
const value = (max / 2.55)
return [hue | 0, saturation | 0, value | 0]
} | identifier_body |
color.ts | import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color'
import { FlowerSlot, Flower } from '../types/flower'
export const percentageIndex = [
0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32,
35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67,
70, 74, 77, 80, 83, 87, 90, 93, 96, 100
]
export const rgbIndex = [
0, 8, 16, 24, 32, 41,
49, 57, 65, 74, 82, 90,
98, 106, 115, 123, 131, 139,
148, 156, 164, 172, 180, 189,
197, 205, 213, 222, 230, 238,
246, 255
]
export function formatRgb(rgb: Rgb): string {
return rgb.join(',')
}
function getIndex(percentage: number): number {
const index = percentageIndex.indexOf(percentage)
if (index < 0){
throw new Error('Invalid color index ! Something went wrong, please contact to admin.')
}
return index
}
export function pergentageToIndex(color: ColorPercentage): ColorIndex {
return [getIndex(color[Red]), getIndex(color[Green]), getIndex(color[Blue])]
}
export function indexToPercentage(index: ColorIndex): ColorPercentage {
return [percentageIndex[index[Red]], percentageIndex[index[Green]], percentageIndex[index[Blue]]]
}
export function indexToRgb(index: ColorIndex): Rgb {
return [rgbIndex[index[Red]], rgbIndex[index[Green]], rgbIndex[index[Blue]]]
}
/**
* Blend flower color values (percentage -> index)
*/
function blendValues(values: number[]): number {
function foldSum(arr: number[]): number {
return arr.reduce((a, b) => a + b)
}
switch (values.length){
case 0:
return 0
case 1:
return getIndex(values[0])
case 2:
return (foldSum(values.map(getIndex)) * 33 / 64) | 0
case 3:
return (foldSum(values.map(getIndex)) * 34 / 99) | 0
case 4:
return (foldSum(values.map(getIndex)) * 33 / 128) | 0
default:
throw new Error('Invalid flowers count ! Some logic went wrong...')
}
}
function blendFlowers(slots: FlowerSlot[]): ColorPercentage {
const filledSlot = <Flower[]>slots.filter(slot => slot != null)
const reds = filledSlot.map(s => s.color[Red])
const greens = filledSlot.map(s => s.color[Green])
const blues = filledSlot.map(s => s.color[Blue])
return indexToPercentage([
blendValues(reds),
blendValues(greens),
blendValues(blues)
])
}
function bleachValue(value: number, bleach: number): number {
if (bleach == 0){
return value
}
const bleached = value + (bleach * 16)
return bleached > 87 ? 87 : bleached
}
function bleachStain(color: ColorPercentage, bleach: number): ColorPercentage {
return [
bleachValue(color[Red], bleach),
bleachValue(color[Green], bleach),
bleachValue(color[Blue], bleach)
]
}
export function combineStain(flowerSlot: FlowerSlot[], bleach: number): Rgb {
return percentageToRgb(bleachStain(blendFlowers(flowerSlot), bleach))
}
export function rgbToPercentage(rgb: Rgb): ColorPercentage {
return [
((rgb[Red] / 2.55) | 0),
((rgb[Green] / 2.55) | 0),
((rgb[Blue] / 2.55) | 0)
]
}
export function percentageToRgb(percentage: ColorPercentage): Rgb {
return [
(percentage[Red] * 2.55) | 0,
(percentage[Green] * 2.55) | 0,
(percentage[Blue] * 2.55) | 0
]
}
export function rgbToHsv(rgb: Rgb): Hsv {
const [red, green, blue] = rgb
const max = Math.max(red, green, blue)
const min = Math.min(red, green, blue)
const hue = (min == max)
? 0
: (min == blue)
? (60 * ((green - red) / (max - min)) + 60)
: (min == red)
? (60 * ((blue - green) / (max - min)) + 180)
: (60 * ((red - blue) / (max - min)) + 300)
const saturation = ((max - min) / max) * 100
const value = (max / 2.55)
return [hue | 0, saturation | 0, value | 0]
}
export function hsvToRgb(hsv: Hsv): Rgb {
const [hue, saturation, value] = hsv
const max = (value * 2.55) | 0
const min = (max - ((saturation / 100) * max)) | 0
if (hue < 60){
return [max, ((hue / 60) * (max - min) + min) | 0, min]
} else if (hue < 120){
return [(((120 - hue) / 60) * (max - min) + min) | 0, max, min]
} else if (hue < 180){
return [min, max, (((hue - 120) / 60) * (max - min) + min) | 0]
} else if (hue < 240){
return [min, (((240 - hue) / 60) * (max - min) + min) | 0, max]
} else if (hue < 300){
return [(((hue - 240) / 60) * (max - min) + min) | 0, min, max]
} else |
}
| {
return [max, min, (((360 - hue) / 60) * (max - min) + min) | 0]
} | conditional_block |
color.ts | import { Rgb, Red, Green, Blue, Hsv, ColorIndex, ColorPercentage } from '../types/color'
import { FlowerSlot, Flower } from '../types/flower'
export const percentageIndex = [
0, 3, 6, 9, 12, 16, 19, 22, 25, 29, 32,
35, 38, 41, 45, 48, 51, 54, 58, 61, 64, 67,
70, 74, 77, 80, 83, 87, 90, 93, 96, 100
]
export const rgbIndex = [
0, 8, 16, 24, 32, 41,
49, 57, 65, 74, 82, 90,
98, 106, 115, 123, 131, 139,
148, 156, 164, 172, 180, 189,
197, 205, 213, 222, 230, 238,
246, 255
]
export function formatRgb(rgb: Rgb): string {
return rgb.join(',')
}
function getIndex(percentage: number): number {
const index = percentageIndex.indexOf(percentage)
if (index < 0){
throw new Error('Invalid color index ! Something went wrong, please contact to admin.')
}
return index
}
export function pergentageToIndex(color: ColorPercentage): ColorIndex {
return [getIndex(color[Red]), getIndex(color[Green]), getIndex(color[Blue])]
}
export function indexToPercentage(index: ColorIndex): ColorPercentage {
return [percentageIndex[index[Red]], percentageIndex[index[Green]], percentageIndex[index[Blue]]]
}
export function indexToRgb(index: ColorIndex): Rgb {
return [rgbIndex[index[Red]], rgbIndex[index[Green]], rgbIndex[index[Blue]]]
}
/**
* Blend flower color values (percentage -> index)
*/
function blendValues(values: number[]): number {
function foldSum(arr: number[]): number {
return arr.reduce((a, b) => a + b)
}
switch (values.length){
case 0:
return 0
case 1:
return getIndex(values[0])
case 2:
return (foldSum(values.map(getIndex)) * 33 / 64) | 0
case 3:
return (foldSum(values.map(getIndex)) * 34 / 99) | 0
case 4:
return (foldSum(values.map(getIndex)) * 33 / 128) | 0
default:
throw new Error('Invalid flowers count ! Some logic went wrong...')
}
}
function blendFlowers(slots: FlowerSlot[]): ColorPercentage {
const filledSlot = <Flower[]>slots.filter(slot => slot != null)
const reds = filledSlot.map(s => s.color[Red])
const greens = filledSlot.map(s => s.color[Green])
const blues = filledSlot.map(s => s.color[Blue])
return indexToPercentage([
blendValues(reds),
blendValues(greens),
blendValues(blues)
])
}
function bleachValue(value: number, bleach: number): number {
if (bleach == 0){
return value
}
const bleached = value + (bleach * 16)
return bleached > 87 ? 87 : bleached
}
function bleachStain(color: ColorPercentage, bleach: number): ColorPercentage {
return [
bleachValue(color[Red], bleach),
bleachValue(color[Green], bleach),
bleachValue(color[Blue], bleach)
]
}
export function combineStain(flowerSlot: FlowerSlot[], bleach: number): Rgb {
return percentageToRgb(bleachStain(blendFlowers(flowerSlot), bleach))
}
export function rgbToPercentage(rgb: Rgb): ColorPercentage {
return [
((rgb[Red] / 2.55) | 0),
((rgb[Green] / 2.55) | 0),
((rgb[Blue] / 2.55) | 0)
]
}
export function percentageToRgb(percentage: ColorPercentage): Rgb {
return [
(percentage[Red] * 2.55) | 0,
(percentage[Green] * 2.55) | 0,
(percentage[Blue] * 2.55) | 0
]
}
export function rgbToHsv(rgb: Rgb): Hsv {
const [red, green, blue] = rgb
const max = Math.max(red, green, blue)
const min = Math.min(red, green, blue)
const hue = (min == max)
? 0
: (min == blue)
? (60 * ((green - red) / (max - min)) + 60)
: (min == red)
? (60 * ((blue - green) / (max - min)) + 180)
: (60 * ((red - blue) / (max - min)) + 300)
const saturation = ((max - min) / max) * 100
const value = (max / 2.55)
return [hue | 0, saturation | 0, value | 0]
}
export function hsvToRgb(hsv: Hsv): Rgb {
const [hue, saturation, value] = hsv
| if (hue < 60){
return [max, ((hue / 60) * (max - min) + min) | 0, min]
} else if (hue < 120){
return [(((120 - hue) / 60) * (max - min) + min) | 0, max, min]
} else if (hue < 180){
return [min, max, (((hue - 120) / 60) * (max - min) + min) | 0]
} else if (hue < 240){
return [min, (((240 - hue) / 60) * (max - min) + min) | 0, max]
} else if (hue < 300){
return [(((hue - 240) / 60) * (max - min) + min) | 0, min, max]
} else {
return [max, min, (((360 - hue) / 60) * (max - min) + min) | 0]
}
} | const max = (value * 2.55) | 0
const min = (max - ((saturation / 100) * max)) | 0
| random_line_split |
test_dms.py | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
import MDAnalysis as mda
import numpy as np
import pytest
from numpy.testing import assert_equal
from MDAnalysis.lib.mdamath import triclinic_vectors
from MDAnalysisTests.datafiles import (DMS)
class TestDMSReader(object):
@pytest.fixture()
def | (self):
return mda.Universe(DMS)
@pytest.fixture()
def ts(self, universe):
return universe.trajectory.ts
def test_global_cell(self, ts):
assert ts.dimensions is None
def test_velocities(self, ts):
assert_equal(hasattr(ts, "_velocities"), False)
def test_number_of_coords(self, universe):
# Desired value taken from VMD
# Info) Atoms: 3341
assert_equal(len(universe.atoms), 3341)
def test_coords_atom_0(self, universe):
# Desired coordinates taken directly from the SQLite file. Check unit
# conversion
coords_0 = np.array([-11.0530004501343,
26.6800003051758,
12.7419996261597, ],
dtype=np.float32)
assert_equal(universe.atoms[0].position, coords_0)
def test_n_frames(self, universe):
assert_equal(universe.trajectory.n_frames, 1,
"wrong number of frames in pdb")
def test_time(self, universe):
assert_equal(universe.trajectory.time, 0.0,
"wrong time of the frame")
def test_frame(self, universe):
assert_equal(universe.trajectory.frame, 0, "wrong frame number "
"(0-based, should be 0 for single frame readers)")
def test_frame_index_0(self, universe):
universe.trajectory[0]
assert_equal(universe.trajectory.ts.frame, 0,
"frame number for frame index 0 should be 0")
def test_frame_index_1_raises_IndexError(self, universe):
with pytest.raises(IndexError):
universe.trajectory[1]
| universe | identifier_name |
test_dms.py | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
import MDAnalysis as mda
import numpy as np
import pytest
from numpy.testing import assert_equal
from MDAnalysis.lib.mdamath import triclinic_vectors
from MDAnalysisTests.datafiles import (DMS)
class TestDMSReader(object):
@pytest.fixture()
def universe(self):
return mda.Universe(DMS)
@pytest.fixture()
def ts(self, universe):
return universe.trajectory.ts
def test_global_cell(self, ts):
assert ts.dimensions is None
def test_velocities(self, ts):
assert_equal(hasattr(ts, "_velocities"), False)
def test_number_of_coords(self, universe):
# Desired value taken from VMD
# Info) Atoms: 3341
assert_equal(len(universe.atoms), 3341)
def test_coords_atom_0(self, universe):
# Desired coordinates taken directly from the SQLite file. Check unit
# conversion
coords_0 = np.array([-11.0530004501343,
26.6800003051758,
12.7419996261597, ],
dtype=np.float32)
assert_equal(universe.atoms[0].position, coords_0)
def test_n_frames(self, universe):
assert_equal(universe.trajectory.n_frames, 1,
"wrong number of frames in pdb")
def test_time(self, universe):
assert_equal(universe.trajectory.time, 0.0,
"wrong time of the frame") | "(0-based, should be 0 for single frame readers)")
def test_frame_index_0(self, universe):
universe.trajectory[0]
assert_equal(universe.trajectory.ts.frame, 0,
"frame number for frame index 0 should be 0")
def test_frame_index_1_raises_IndexError(self, universe):
with pytest.raises(IndexError):
universe.trajectory[1] |
def test_frame(self, universe):
assert_equal(universe.trajectory.frame, 0, "wrong frame number " | random_line_split |
test_dms.py | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
import MDAnalysis as mda
import numpy as np
import pytest
from numpy.testing import assert_equal
from MDAnalysis.lib.mdamath import triclinic_vectors
from MDAnalysisTests.datafiles import (DMS)
class TestDMSReader(object):
@pytest.fixture()
def universe(self):
return mda.Universe(DMS)
@pytest.fixture()
def ts(self, universe):
return universe.trajectory.ts
def test_global_cell(self, ts):
assert ts.dimensions is None
def test_velocities(self, ts):
assert_equal(hasattr(ts, "_velocities"), False)
def test_number_of_coords(self, universe):
# Desired value taken from VMD
# Info) Atoms: 3341
|
def test_coords_atom_0(self, universe):
# Desired coordinates taken directly from the SQLite file. Check unit
# conversion
coords_0 = np.array([-11.0530004501343,
26.6800003051758,
12.7419996261597, ],
dtype=np.float32)
assert_equal(universe.atoms[0].position, coords_0)
def test_n_frames(self, universe):
assert_equal(universe.trajectory.n_frames, 1,
"wrong number of frames in pdb")
def test_time(self, universe):
assert_equal(universe.trajectory.time, 0.0,
"wrong time of the frame")
def test_frame(self, universe):
assert_equal(universe.trajectory.frame, 0, "wrong frame number "
"(0-based, should be 0 for single frame readers)")
def test_frame_index_0(self, universe):
universe.trajectory[0]
assert_equal(universe.trajectory.ts.frame, 0,
"frame number for frame index 0 should be 0")
def test_frame_index_1_raises_IndexError(self, universe):
with pytest.raises(IndexError):
universe.trajectory[1]
| assert_equal(len(universe.atoms), 3341) | identifier_body |
fixedaspectsvgwidget.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
fixedaspectsvgwidget.py
---------------------
Date : August 2016
Copyright : (C) 2016 Boundless, http://boundlessgeo.com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'August 2016'
__copyright__ = '(C) 2016 Boundless, http://boundlessgeo.com'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QRect
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtSvg import QSvgWidget
class FixedAspectSvgWidget(QSvgWidget):
def | (self, event):
painter = QPainter(self)
painter.setViewport(self.centeredViewport(self.size()))
self.renderer().render(painter)
def centeredViewport(self, size):
width = size.width()
height = size.height()
aspectRatio = float(self.renderer().defaultSize().width()) / float(self.renderer().defaultSize().height())
heightFromWidth = int(width / aspectRatio)
widthFromHeight = int(height * aspectRatio)
if heightFromWidth <= height:
return QRect(0, (height - heightFromWidth) / 2, width, heightFromWidth)
else:
return QRect((width - widthFromHeight) / 2, 0, widthFromHeight, height)
| paintEvent | identifier_name |
fixedaspectsvgwidget.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
fixedaspectsvgwidget.py
---------------------
Date : August 2016
Copyright : (C) 2016 Boundless, http://boundlessgeo.com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'August 2016'
__copyright__ = '(C) 2016 Boundless, http://boundlessgeo.com'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QRect
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtSvg import QSvgWidget
class FixedAspectSvgWidget(QSvgWidget):
def paintEvent(self, event):
|
def centeredViewport(self, size):
width = size.width()
height = size.height()
aspectRatio = float(self.renderer().defaultSize().width()) / float(self.renderer().defaultSize().height())
heightFromWidth = int(width / aspectRatio)
widthFromHeight = int(height * aspectRatio)
if heightFromWidth <= height:
return QRect(0, (height - heightFromWidth) / 2, width, heightFromWidth)
else:
return QRect((width - widthFromHeight) / 2, 0, widthFromHeight, height)
| painter = QPainter(self)
painter.setViewport(self.centeredViewport(self.size()))
self.renderer().render(painter) | identifier_body |
fixedaspectsvgwidget.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
fixedaspectsvgwidget.py
---------------------
Date : August 2016
Copyright : (C) 2016 Boundless, http://boundlessgeo.com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or * | __author__ = 'Alexander Bruy'
__date__ = 'August 2016'
__copyright__ = '(C) 2016 Boundless, http://boundlessgeo.com'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QRect
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtSvg import QSvgWidget
class FixedAspectSvgWidget(QSvgWidget):
def paintEvent(self, event):
painter = QPainter(self)
painter.setViewport(self.centeredViewport(self.size()))
self.renderer().render(painter)
def centeredViewport(self, size):
width = size.width()
height = size.height()
aspectRatio = float(self.renderer().defaultSize().width()) / float(self.renderer().defaultSize().height())
heightFromWidth = int(width / aspectRatio)
widthFromHeight = int(height * aspectRatio)
if heightFromWidth <= height:
return QRect(0, (height - heightFromWidth) / 2, width, heightFromWidth)
else:
return QRect((width - widthFromHeight) / 2, 0, widthFromHeight, height) | * (at your option) any later version. *
* *
***************************************************************************
"""
| random_line_split |
fixedaspectsvgwidget.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
fixedaspectsvgwidget.py
---------------------
Date : August 2016
Copyright : (C) 2016 Boundless, http://boundlessgeo.com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'August 2016'
__copyright__ = '(C) 2016 Boundless, http://boundlessgeo.com'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QRect
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtSvg import QSvgWidget
class FixedAspectSvgWidget(QSvgWidget):
def paintEvent(self, event):
painter = QPainter(self)
painter.setViewport(self.centeredViewport(self.size()))
self.renderer().render(painter)
def centeredViewport(self, size):
width = size.width()
height = size.height()
aspectRatio = float(self.renderer().defaultSize().width()) / float(self.renderer().defaultSize().height())
heightFromWidth = int(width / aspectRatio)
widthFromHeight = int(height * aspectRatio)
if heightFromWidth <= height:
|
else:
return QRect((width - widthFromHeight) / 2, 0, widthFromHeight, height)
| return QRect(0, (height - heightFromWidth) / 2, width, heightFromWidth) | conditional_block |
downloadAsImage.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may 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 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.
*/
import { SyntheticEvent } from 'react';
import domToImage, { Options } from 'dom-to-image';
import kebabCase from 'lodash/kebabCase';
import { t } from '@superset-ui/core';
import { addWarningToast } from 'src/messageToasts/actions';
/**
* @remark
* same as https://github.com/apache/incubator-superset/blob/c53bc4ddf9808a8bb6916bbe3cb31935d33a2420/superset-frontend/stylesheets/less/variables.less#L34
*/
const GRAY_BACKGROUND_COLOR = '#F5F5F5';
/**
* generate a consistent file stem from a description and date
*
* @param description title or description of content of file
* @param date date when file was generated
*/
const generateFileStem = (description: string, date = new Date()) => {
return `${kebabCase(description)}-${date
.toISOString()
.replace(/[: ]/g, '-')}`;
};
/**
* Create an event handler for turning an element into an image
*
* @param selector css selector of the parent element which should be turned into image
* @param description name or a short description of what is being printed.
* Value will be normalized, and a date as well as a file extension will be added.
* @param backgroundColor background color to apply to screenshot document
* @returns event handler
*/
export default function downloadAsImage(
selector: string,
description: string,
domToImageOptions: Options = {},
) | {
return (event: SyntheticEvent) => {
const elementToPrint = event.currentTarget.closest(selector);
if (!elementToPrint)
return addWarningToast(
t('Image download failed, please refresh and try again.'),
);
return domToImage
.toJpeg(elementToPrint, {
quality: 0.95,
bgcolor: GRAY_BACKGROUND_COLOR,
...domToImageOptions,
})
.then(dataUrl => {
const link = document.createElement('a');
link.download = `${generateFileStem(description)}.jpg`;
link.href = dataUrl;
link.click();
});
};
} | identifier_body | |
downloadAsImage.ts | * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may 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 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.
*/
import { SyntheticEvent } from 'react';
import domToImage, { Options } from 'dom-to-image';
import kebabCase from 'lodash/kebabCase';
import { t } from '@superset-ui/core';
import { addWarningToast } from 'src/messageToasts/actions';
/**
* @remark
* same as https://github.com/apache/incubator-superset/blob/c53bc4ddf9808a8bb6916bbe3cb31935d33a2420/superset-frontend/stylesheets/less/variables.less#L34
*/
const GRAY_BACKGROUND_COLOR = '#F5F5F5';
/**
* generate a consistent file stem from a description and date
*
* @param description title or description of content of file
* @param date date when file was generated
*/
const generateFileStem = (description: string, date = new Date()) => {
return `${kebabCase(description)}-${date
.toISOString()
.replace(/[: ]/g, '-')}`;
};
/**
* Create an event handler for turning an element into an image
*
* @param selector css selector of the parent element which should be turned into image
* @param description name or a short description of what is being printed.
* Value will be normalized, and a date as well as a file extension will be added.
* @param backgroundColor background color to apply to screenshot document
* @returns event handler
*/
export default function downloadAsImage(
selector: string,
description: string,
domToImageOptions: Options = {},
) {
return (event: SyntheticEvent) => {
const elementToPrint = event.currentTarget.closest(selector);
if (!elementToPrint)
return addWarningToast(
t('Image download failed, please refresh and try again.'),
);
return domToImage
.toJpeg(elementToPrint, {
quality: 0.95,
bgcolor: GRAY_BACKGROUND_COLOR,
...domToImageOptions,
})
.then(dataUrl => {
const link = document.createElement('a');
link.download = `${generateFileStem(description)}.jpg`;
link.href = dataUrl;
link.click();
});
};
} | /**
* Licensed to the Apache Software Foundation (ASF) under one | random_line_split | |
downloadAsImage.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may 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 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.
*/
import { SyntheticEvent } from 'react';
import domToImage, { Options } from 'dom-to-image';
import kebabCase from 'lodash/kebabCase';
import { t } from '@superset-ui/core';
import { addWarningToast } from 'src/messageToasts/actions';
/**
* @remark
* same as https://github.com/apache/incubator-superset/blob/c53bc4ddf9808a8bb6916bbe3cb31935d33a2420/superset-frontend/stylesheets/less/variables.less#L34
*/
const GRAY_BACKGROUND_COLOR = '#F5F5F5';
/**
* generate a consistent file stem from a description and date
*
* @param description title or description of content of file
* @param date date when file was generated
*/
const generateFileStem = (description: string, date = new Date()) => {
return `${kebabCase(description)}-${date
.toISOString()
.replace(/[: ]/g, '-')}`;
};
/**
* Create an event handler for turning an element into an image
*
* @param selector css selector of the parent element which should be turned into image
* @param description name or a short description of what is being printed.
* Value will be normalized, and a date as well as a file extension will be added.
* @param backgroundColor background color to apply to screenshot document
* @returns event handler
*/
export default function | (
selector: string,
description: string,
domToImageOptions: Options = {},
) {
return (event: SyntheticEvent) => {
const elementToPrint = event.currentTarget.closest(selector);
if (!elementToPrint)
return addWarningToast(
t('Image download failed, please refresh and try again.'),
);
return domToImage
.toJpeg(elementToPrint, {
quality: 0.95,
bgcolor: GRAY_BACKGROUND_COLOR,
...domToImageOptions,
})
.then(dataUrl => {
const link = document.createElement('a');
link.download = `${generateFileStem(description)}.jpg`;
link.href = dataUrl;
link.click();
});
};
}
| downloadAsImage | identifier_name |
scroll-tofixed-view.js | var $ = require('jquery');
var CoreView = require('backbone/core-view');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var REQUIRED_OPTS = [
'el'
];
module.exports = CoreView.extend({
events: {
'click .js-foo': '_fooHandler'
},
initialize: function (opts) {
checkAndBuildOpts(opts, REQUIRED_OPTS, this); | this._onWindowScroll = this._onWindowScroll.bind(this);
this._topBoundary = this.$el.offset().top;
this._initBinds();
},
_initBinds: function () {
this._bindScroll();
},
_onWindowScroll: function () {
this.$el.toggleClass('is-fixed', $(window).scrollTop() > this._topBoundary);
},
_unbindScroll: function () {
$(window).unbind('scroll', this._onWindowScroll);
},
_bindScroll: function () {
this._unbindScroll();
$(window).bind('scroll', this._onWindowScroll);
},
clean: function () {
this._unbindScroll();
}
}); | random_line_split | |
jquery.loadHtml.js | /*!
* ------------------------------
* jQuery.loadHtmlComponents.js v0.1.0
* http://anasnakawa.github.com/jquery.loadHtmlComponents
* license: MIT license (http://opensource.org/licenses/MIT)
* ------------------------------
*/
// ------------------------------
// table of content
// ------------------------------
// a header title
// - sub title
// a method
// ------------------------------
// a header title
// --------------
// sub title
// a method
// describe your method
//
// * **param:** {type} paramName what to do with this parameter
//
// e.g: if you want to provide an example, that would be nice
// ------------------------------
(function ($) {
'use strict';
var defaults = {
attr: 'data-component-url'
, extension: 'html'
, componentsFolder: ''
}
, loadHtml = function(options) {
options = $.extend(defaults, options);
// component url attribute
var attr = options.attr
// load status attribute
, state = attr + '-state'
// load done value for status attribute
, done = 'ready'
// load pending value for status attribute
, pending = 'pending'
// cache all components
, selector = '[' + attr + ']:not([' + state + '])';
// for all elements with component url not in ready state
return this.find( selector ).each(function () {
// debugger;
var $self = $(this)
// fetch url
, componentUrl = $self.attr(attr)
// ability to add component name without extension (.html)
, url = ( options.componentsFolder + '/' ) + ( componentUrl.match('.' + options.extension + '$') ? componentUrl : componentUrl + '.' + options.extension );
$self.attr(state, pending);
// load content and append
$self.load(url, function () {
| return $self.loadHtml(options);
}
});
});
};
$.fn.loadHtml = loadHtml;
$.fn.loadHtml.defaults = defaults;
})(jQuery); | // set state to ready
$self.attr(state, done)
if( $self.attr(options.attr + '-skip') !== 'true' ) { | random_line_split |
jquery.loadHtml.js | /*!
* ------------------------------
* jQuery.loadHtmlComponents.js v0.1.0
* http://anasnakawa.github.com/jquery.loadHtmlComponents
* license: MIT license (http://opensource.org/licenses/MIT)
* ------------------------------
*/
// ------------------------------
// table of content
// ------------------------------
// a header title
// - sub title
// a method
// ------------------------------
// a header title
// --------------
// sub title
// a method
// describe your method
//
// * **param:** {type} paramName what to do with this parameter
//
// e.g: if you want to provide an example, that would be nice
// ------------------------------
(function ($) {
'use strict';
var defaults = {
attr: 'data-component-url'
, extension: 'html'
, componentsFolder: ''
}
, loadHtml = function(options) {
options = $.extend(defaults, options);
// component url attribute
var attr = options.attr
// load status attribute
, state = attr + '-state'
// load done value for status attribute
, done = 'ready'
// load pending value for status attribute
, pending = 'pending'
// cache all components
, selector = '[' + attr + ']:not([' + state + '])';
// for all elements with component url not in ready state
return this.find( selector ).each(function () {
// debugger;
var $self = $(this)
// fetch url
, componentUrl = $self.attr(attr)
// ability to add component name without extension (.html)
, url = ( options.componentsFolder + '/' ) + ( componentUrl.match('.' + options.extension + '$') ? componentUrl : componentUrl + '.' + options.extension );
$self.attr(state, pending);
// load content and append
$self.load(url, function () {
// set state to ready
$self.attr(state, done)
if( $self.attr(options.attr + '-skip') !== 'true' ) |
});
});
};
$.fn.loadHtml = loadHtml;
$.fn.loadHtml.defaults = defaults;
})(jQuery); | {
return $self.loadHtml(options);
} | conditional_block |
operation_display.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class OperationDisplay(Model):
| """Display metadata associated with the operation.
:param provider: Service provider: Microsoft Network.
:type provider: str
:param resource: Resource on which the operation is performed.
:type resource: str
:param operation: Type of the operation: get, read, delete, etc.
:type operation: str
:param description: Description of the operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(self, provider=None, resource=None, operation=None, description=None):
super(OperationDisplay, self).__init__()
self.provider = provider
self.resource = resource
self.operation = operation
self.description = description | identifier_body | |
operation_display.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class OperationDisplay(Model):
"""Display metadata associated with the operation.
:param provider: Service provider: Microsoft Network.
:type provider: str
:param resource: Resource on which the operation is performed.
:type resource: str
:param operation: Type of the operation: get, read, delete, etc.
:type operation: str
:param description: Description of the operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(self, provider=None, resource=None, operation=None, description=None):
super(OperationDisplay, self).__init__() | self.provider = provider
self.resource = resource
self.operation = operation
self.description = description | random_line_split | |
operation_display.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class OperationDisplay(Model):
"""Display metadata associated with the operation.
:param provider: Service provider: Microsoft Network.
:type provider: str
:param resource: Resource on which the operation is performed.
:type resource: str
:param operation: Type of the operation: get, read, delete, etc.
:type operation: str
:param description: Description of the operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def | (self, provider=None, resource=None, operation=None, description=None):
super(OperationDisplay, self).__init__()
self.provider = provider
self.resource = resource
self.operation = operation
self.description = description
| __init__ | identifier_name |
devlinks.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::collections::HashSet;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::{fs, str};
use crate::engine::Pool;
use crate::stratis::StratisResult;
use crate::engine::engine::DEV_PATH;
use crate::engine::types::{Name, PoolUuid};
/// Set up the root Stratis directory, where dev links as well as temporary
/// MDV mounts will be created. This must occur before any pools are setup.
pub fn setup_dev_path() -> StratisResult<()> {
if let Err(err) = fs::create_dir(DEV_PATH) {
if err.kind() != ErrorKind::AlreadyExists {
return Err(From::from(err));
}
}
Ok(())
}
/// Setup the pool directory and the symlinks in /stratis for the specified pool and filesystems
/// it contains.
// Don't just remove and recreate everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn setup_pool_devlinks(pool_name: &str, pool: &Pool) {
if let Err(err) = || -> StratisResult<()> {
let pool_path = pool_directory(pool_name);
if !pool_path.exists() {
pool_added(pool_name);
}
let mut existing_files = fs::read_dir(pool_path)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for (fs_name, _, fs) in pool.filesystems() {
filesystem_added(pool_name, &fs_name, &fs.devnode());
existing_files.remove(&fs_name.to_owned());
}
for leftover in existing_files {
filesystem_removed(pool_name, &leftover);
}
Ok(())
}() {
warn!(
"setup_pool_devlinks failed for /stratis/{}, reason {:?}",
pool_name, err
);
};
}
/// Clean up directories and symlinks under /stratis based on current
/// config. Clear out any directory or file that doesn't correspond to a pool.
// Don't just remove everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn cleanup_devlinks<'a, I: Iterator<Item = &'a (Name, PoolUuid, &'a Pool)>>(pools: I) {
if let Err(err) = || -> StratisResult<()> {
let mut existing_dirs = fs::read_dir(DEV_PATH)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for &(ref pool_name, _, _) in pools {
existing_dirs.remove(&pool_name.to_owned());
}
for leftover in existing_dirs {
pool_removed(&Name::new(leftover));
}
Ok(())
}() {
warn!("cleanup_devlinks failed, reason {:?}", err);
}
}
/// Create a directory when a pool is added.
pub fn pool_added(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::create_dir(&p) {
warn!("unable to create pool directory {:?}, reason {:?}", p, e);
}
}
/// Remove the directory and its contents when the pool is removed.
pub fn pool_removed(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::remove_dir_all(&p) {
warn!("unable to remove pool directory {:?}, reason {:?}", p, e);
}
}
/// Rename the directory to match the pool's new name.
pub fn pool_renamed(old_name: &str, new_name: &str) {
let old = pool_directory(old_name);
let new = pool_directory(new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename pool directory old {:?}, new {:?}, reason {:?}",
old, new, e
);
}
}
/// Create a symlink to the new filesystem's block device within its pool's
/// directory.
pub fn | (pool_name: &str, fs_name: &str, devnode: &Path) {
let p = filesystem_mount_path(pool_name, fs_name);
// Remove existing and recreate to ensure it points to the correct devnode
let _ = fs::remove_file(&p);
if let Err(e) = symlink(devnode, &p) {
warn!(
"unable to create symlink for {:?} -> {:?}, reason {:?}",
devnode, p, e
);
}
}
/// Remove the symlink when the filesystem is destroyed.
pub fn filesystem_removed(pool_name: &str, fs_name: &str) {
let p = filesystem_mount_path(pool_name, fs_name);
if let Err(e) = fs::remove_file(&p) {
warn!(
"unable to remove symlink for filesystem {:?}, reason {:?}",
p, e
);
}
}
/// Rename the symlink to track the filesystem's new name.
pub fn filesystem_renamed(pool_name: &str, old_name: &str, new_name: &str) {
let old = filesystem_mount_path(pool_name, old_name);
let new = filesystem_mount_path(pool_name, new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename filesystem symlink for {:?} -> {:?}, reason {:?}",
old, new, e
);
}
}
/// Given a pool name, synthesize a pool directory name for storing filesystem
/// mount paths.
fn pool_directory<T: AsRef<str>>(pool_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref()].iter().collect()
}
/// Given a pool name and a filesystem name, return the path it should be
/// available as a device for mounting.
pub fn filesystem_mount_path<T: AsRef<str>>(pool_name: T, fs_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref(), fs_name.as_ref()]
.iter()
.collect()
}
| filesystem_added | identifier_name |
devlinks.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::collections::HashSet;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::{fs, str};
use crate::engine::Pool;
use crate::stratis::StratisResult;
use crate::engine::engine::DEV_PATH;
use crate::engine::types::{Name, PoolUuid};
/// Set up the root Stratis directory, where dev links as well as temporary
/// MDV mounts will be created. This must occur before any pools are setup. | if err.kind() != ErrorKind::AlreadyExists {
return Err(From::from(err));
}
}
Ok(())
}
/// Setup the pool directory and the symlinks in /stratis for the specified pool and filesystems
/// it contains.
// Don't just remove and recreate everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn setup_pool_devlinks(pool_name: &str, pool: &Pool) {
if let Err(err) = || -> StratisResult<()> {
let pool_path = pool_directory(pool_name);
if !pool_path.exists() {
pool_added(pool_name);
}
let mut existing_files = fs::read_dir(pool_path)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for (fs_name, _, fs) in pool.filesystems() {
filesystem_added(pool_name, &fs_name, &fs.devnode());
existing_files.remove(&fs_name.to_owned());
}
for leftover in existing_files {
filesystem_removed(pool_name, &leftover);
}
Ok(())
}() {
warn!(
"setup_pool_devlinks failed for /stratis/{}, reason {:?}",
pool_name, err
);
};
}
/// Clean up directories and symlinks under /stratis based on current
/// config. Clear out any directory or file that doesn't correspond to a pool.
// Don't just remove everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn cleanup_devlinks<'a, I: Iterator<Item = &'a (Name, PoolUuid, &'a Pool)>>(pools: I) {
if let Err(err) = || -> StratisResult<()> {
let mut existing_dirs = fs::read_dir(DEV_PATH)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for &(ref pool_name, _, _) in pools {
existing_dirs.remove(&pool_name.to_owned());
}
for leftover in existing_dirs {
pool_removed(&Name::new(leftover));
}
Ok(())
}() {
warn!("cleanup_devlinks failed, reason {:?}", err);
}
}
/// Create a directory when a pool is added.
pub fn pool_added(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::create_dir(&p) {
warn!("unable to create pool directory {:?}, reason {:?}", p, e);
}
}
/// Remove the directory and its contents when the pool is removed.
pub fn pool_removed(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::remove_dir_all(&p) {
warn!("unable to remove pool directory {:?}, reason {:?}", p, e);
}
}
/// Rename the directory to match the pool's new name.
pub fn pool_renamed(old_name: &str, new_name: &str) {
let old = pool_directory(old_name);
let new = pool_directory(new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename pool directory old {:?}, new {:?}, reason {:?}",
old, new, e
);
}
}
/// Create a symlink to the new filesystem's block device within its pool's
/// directory.
pub fn filesystem_added(pool_name: &str, fs_name: &str, devnode: &Path) {
let p = filesystem_mount_path(pool_name, fs_name);
// Remove existing and recreate to ensure it points to the correct devnode
let _ = fs::remove_file(&p);
if let Err(e) = symlink(devnode, &p) {
warn!(
"unable to create symlink for {:?} -> {:?}, reason {:?}",
devnode, p, e
);
}
}
/// Remove the symlink when the filesystem is destroyed.
pub fn filesystem_removed(pool_name: &str, fs_name: &str) {
let p = filesystem_mount_path(pool_name, fs_name);
if let Err(e) = fs::remove_file(&p) {
warn!(
"unable to remove symlink for filesystem {:?}, reason {:?}",
p, e
);
}
}
/// Rename the symlink to track the filesystem's new name.
pub fn filesystem_renamed(pool_name: &str, old_name: &str, new_name: &str) {
let old = filesystem_mount_path(pool_name, old_name);
let new = filesystem_mount_path(pool_name, new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename filesystem symlink for {:?} -> {:?}, reason {:?}",
old, new, e
);
}
}
/// Given a pool name, synthesize a pool directory name for storing filesystem
/// mount paths.
fn pool_directory<T: AsRef<str>>(pool_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref()].iter().collect()
}
/// Given a pool name and a filesystem name, return the path it should be
/// available as a device for mounting.
pub fn filesystem_mount_path<T: AsRef<str>>(pool_name: T, fs_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref(), fs_name.as_ref()]
.iter()
.collect()
} | pub fn setup_dev_path() -> StratisResult<()> {
if let Err(err) = fs::create_dir(DEV_PATH) { | random_line_split |
devlinks.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::collections::HashSet;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::{fs, str};
use crate::engine::Pool;
use crate::stratis::StratisResult;
use crate::engine::engine::DEV_PATH;
use crate::engine::types::{Name, PoolUuid};
/// Set up the root Stratis directory, where dev links as well as temporary
/// MDV mounts will be created. This must occur before any pools are setup.
pub fn setup_dev_path() -> StratisResult<()> {
if let Err(err) = fs::create_dir(DEV_PATH) {
if err.kind() != ErrorKind::AlreadyExists {
return Err(From::from(err));
}
}
Ok(())
}
/// Setup the pool directory and the symlinks in /stratis for the specified pool and filesystems
/// it contains.
// Don't just remove and recreate everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn setup_pool_devlinks(pool_name: &str, pool: &Pool) {
if let Err(err) = || -> StratisResult<()> {
let pool_path = pool_directory(pool_name);
if !pool_path.exists() {
pool_added(pool_name);
}
let mut existing_files = fs::read_dir(pool_path)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for (fs_name, _, fs) in pool.filesystems() {
filesystem_added(pool_name, &fs_name, &fs.devnode());
existing_files.remove(&fs_name.to_owned());
}
for leftover in existing_files {
filesystem_removed(pool_name, &leftover);
}
Ok(())
}() {
warn!(
"setup_pool_devlinks failed for /stratis/{}, reason {:?}",
pool_name, err
);
};
}
/// Clean up directories and symlinks under /stratis based on current
/// config. Clear out any directory or file that doesn't correspond to a pool.
// Don't just remove everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn cleanup_devlinks<'a, I: Iterator<Item = &'a (Name, PoolUuid, &'a Pool)>>(pools: I) {
if let Err(err) = || -> StratisResult<()> {
let mut existing_dirs = fs::read_dir(DEV_PATH)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for &(ref pool_name, _, _) in pools {
existing_dirs.remove(&pool_name.to_owned());
}
for leftover in existing_dirs {
pool_removed(&Name::new(leftover));
}
Ok(())
}() |
}
/// Create a directory when a pool is added.
pub fn pool_added(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::create_dir(&p) {
warn!("unable to create pool directory {:?}, reason {:?}", p, e);
}
}
/// Remove the directory and its contents when the pool is removed.
pub fn pool_removed(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::remove_dir_all(&p) {
warn!("unable to remove pool directory {:?}, reason {:?}", p, e);
}
}
/// Rename the directory to match the pool's new name.
pub fn pool_renamed(old_name: &str, new_name: &str) {
let old = pool_directory(old_name);
let new = pool_directory(new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename pool directory old {:?}, new {:?}, reason {:?}",
old, new, e
);
}
}
/// Create a symlink to the new filesystem's block device within its pool's
/// directory.
pub fn filesystem_added(pool_name: &str, fs_name: &str, devnode: &Path) {
let p = filesystem_mount_path(pool_name, fs_name);
// Remove existing and recreate to ensure it points to the correct devnode
let _ = fs::remove_file(&p);
if let Err(e) = symlink(devnode, &p) {
warn!(
"unable to create symlink for {:?} -> {:?}, reason {:?}",
devnode, p, e
);
}
}
/// Remove the symlink when the filesystem is destroyed.
pub fn filesystem_removed(pool_name: &str, fs_name: &str) {
let p = filesystem_mount_path(pool_name, fs_name);
if let Err(e) = fs::remove_file(&p) {
warn!(
"unable to remove symlink for filesystem {:?}, reason {:?}",
p, e
);
}
}
/// Rename the symlink to track the filesystem's new name.
pub fn filesystem_renamed(pool_name: &str, old_name: &str, new_name: &str) {
let old = filesystem_mount_path(pool_name, old_name);
let new = filesystem_mount_path(pool_name, new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename filesystem symlink for {:?} -> {:?}, reason {:?}",
old, new, e
);
}
}
/// Given a pool name, synthesize a pool directory name for storing filesystem
/// mount paths.
fn pool_directory<T: AsRef<str>>(pool_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref()].iter().collect()
}
/// Given a pool name and a filesystem name, return the path it should be
/// available as a device for mounting.
pub fn filesystem_mount_path<T: AsRef<str>>(pool_name: T, fs_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref(), fs_name.as_ref()]
.iter()
.collect()
}
| {
warn!("cleanup_devlinks failed, reason {:?}", err);
} | conditional_block |
devlinks.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::collections::HashSet;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::{fs, str};
use crate::engine::Pool;
use crate::stratis::StratisResult;
use crate::engine::engine::DEV_PATH;
use crate::engine::types::{Name, PoolUuid};
/// Set up the root Stratis directory, where dev links as well as temporary
/// MDV mounts will be created. This must occur before any pools are setup.
pub fn setup_dev_path() -> StratisResult<()> {
if let Err(err) = fs::create_dir(DEV_PATH) {
if err.kind() != ErrorKind::AlreadyExists {
return Err(From::from(err));
}
}
Ok(())
}
/// Setup the pool directory and the symlinks in /stratis for the specified pool and filesystems
/// it contains.
// Don't just remove and recreate everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn setup_pool_devlinks(pool_name: &str, pool: &Pool) {
if let Err(err) = || -> StratisResult<()> {
let pool_path = pool_directory(pool_name);
if !pool_path.exists() {
pool_added(pool_name);
}
let mut existing_files = fs::read_dir(pool_path)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for (fs_name, _, fs) in pool.filesystems() {
filesystem_added(pool_name, &fs_name, &fs.devnode());
existing_files.remove(&fs_name.to_owned());
}
for leftover in existing_files {
filesystem_removed(pool_name, &leftover);
}
Ok(())
}() {
warn!(
"setup_pool_devlinks failed for /stratis/{}, reason {:?}",
pool_name, err
);
};
}
/// Clean up directories and symlinks under /stratis based on current
/// config. Clear out any directory or file that doesn't correspond to a pool.
// Don't just remove everything in case there are processes
// (e.g. user shells) with the current working directory within the tree.
pub fn cleanup_devlinks<'a, I: Iterator<Item = &'a (Name, PoolUuid, &'a Pool)>>(pools: I) {
if let Err(err) = || -> StratisResult<()> {
let mut existing_dirs = fs::read_dir(DEV_PATH)?
.map(|dir_e| {
dir_e.and_then(|d| Ok(d.file_name().into_string().expect("Unix is utf-8")))
})
.collect::<Result<HashSet<_>, _>>()?;
for &(ref pool_name, _, _) in pools {
existing_dirs.remove(&pool_name.to_owned());
}
for leftover in existing_dirs {
pool_removed(&Name::new(leftover));
}
Ok(())
}() {
warn!("cleanup_devlinks failed, reason {:?}", err);
}
}
/// Create a directory when a pool is added.
pub fn pool_added(pool: &str) |
/// Remove the directory and its contents when the pool is removed.
pub fn pool_removed(pool: &str) {
let p = pool_directory(pool);
if let Err(e) = fs::remove_dir_all(&p) {
warn!("unable to remove pool directory {:?}, reason {:?}", p, e);
}
}
/// Rename the directory to match the pool's new name.
pub fn pool_renamed(old_name: &str, new_name: &str) {
let old = pool_directory(old_name);
let new = pool_directory(new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename pool directory old {:?}, new {:?}, reason {:?}",
old, new, e
);
}
}
/// Create a symlink to the new filesystem's block device within its pool's
/// directory.
pub fn filesystem_added(pool_name: &str, fs_name: &str, devnode: &Path) {
let p = filesystem_mount_path(pool_name, fs_name);
// Remove existing and recreate to ensure it points to the correct devnode
let _ = fs::remove_file(&p);
if let Err(e) = symlink(devnode, &p) {
warn!(
"unable to create symlink for {:?} -> {:?}, reason {:?}",
devnode, p, e
);
}
}
/// Remove the symlink when the filesystem is destroyed.
pub fn filesystem_removed(pool_name: &str, fs_name: &str) {
let p = filesystem_mount_path(pool_name, fs_name);
if let Err(e) = fs::remove_file(&p) {
warn!(
"unable to remove symlink for filesystem {:?}, reason {:?}",
p, e
);
}
}
/// Rename the symlink to track the filesystem's new name.
pub fn filesystem_renamed(pool_name: &str, old_name: &str, new_name: &str) {
let old = filesystem_mount_path(pool_name, old_name);
let new = filesystem_mount_path(pool_name, new_name);
if let Err(e) = fs::rename(&old, &new) {
warn!(
"unable to rename filesystem symlink for {:?} -> {:?}, reason {:?}",
old, new, e
);
}
}
/// Given a pool name, synthesize a pool directory name for storing filesystem
/// mount paths.
fn pool_directory<T: AsRef<str>>(pool_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref()].iter().collect()
}
/// Given a pool name and a filesystem name, return the path it should be
/// available as a device for mounting.
pub fn filesystem_mount_path<T: AsRef<str>>(pool_name: T, fs_name: T) -> PathBuf {
vec![DEV_PATH, pool_name.as_ref(), fs_name.as_ref()]
.iter()
.collect()
}
| {
let p = pool_directory(pool);
if let Err(e) = fs::create_dir(&p) {
warn!("unable to create pool directory {:?}, reason {:?}", p, e);
}
} | identifier_body |
engageya.js | /**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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.
*/
// src/polyfills.js must be the first import.
import '../polyfills';
import {draw3p, init} from '../integration-lib';
import {register} from '../3p';
import {engageya} from '../../ads/vendors/engageya';
init(window); | register('engageya', engageya);
window.draw3p = draw3p; | random_line_split | |
fence_rmw.rs | //! This mod provides orderings to use with RMW operations
//! that optimally handle the case when all loads and stores
//! after an RMW operation must be ordered after the operation.
//! # Example:
//! ```
//! use std::sync::atomic::{AtomicUsize, fence, Ordering};
//! use atomic_utilities::fence_rmw::{RMWOrder, fence_rmw};
//!
//! let atomic_refcnt = AtomicUsize::new(0);
//! atomic_refcnt.fetch_add(1, RMWOrder);
//!
//! // ... do work here
//! // This will be ordered after the store of the fetch_add
//! // and will use minimal fences for various hardware platforms
//! atomic_refcnt.fetch_sub(1, Ordering::Release);
//! ```
use std::sync::atomic::Ordering;
#[cfg(any(target_platform = "x86", target_platform = "x86_64"))]
mod internal_ordering {
use std::sync::atomic::Ordering;
pub const RMW_O: Ordering = Ordering::Acquire;
#[inline(always)]
pub fn the_fence() {}
}
#[cfg(not(any(target_platform = "x86", target_platform = "x86_64")))]
mod internal_ordering {
use std::sync::atomic::{Ordering, fence};
pub const RMW_O: Ordering = Ordering::Relaxed;
pub fn the_fence() |
}
/// The ordering to be used for RMW operations in this fencing scheme
#[allow(non_upper_case_globals)]
pub const RMWOrder: Ordering = internal_ordering::RMW_O;
/// The fence to be used after the RMW
#[inline(always)]
pub fn fence_rmw() {
internal_ordering::the_fence()
}
| {
fence(Ordering::SeqCst)
} | identifier_body |
fence_rmw.rs | //! This mod provides orderings to use with RMW operations
//! that optimally handle the case when all loads and stores
//! after an RMW operation must be ordered after the operation.
//! # Example:
//! ```
//! use std::sync::atomic::{AtomicUsize, fence, Ordering};
//! use atomic_utilities::fence_rmw::{RMWOrder, fence_rmw};
//!
//! let atomic_refcnt = AtomicUsize::new(0);
//! atomic_refcnt.fetch_add(1, RMWOrder);
//!
//! // ... do work here
//! // This will be ordered after the store of the fetch_add
//! // and will use minimal fences for various hardware platforms
//! atomic_refcnt.fetch_sub(1, Ordering::Release);
//! ```
use std::sync::atomic::Ordering;
#[cfg(any(target_platform = "x86", target_platform = "x86_64"))]
mod internal_ordering {
use std::sync::atomic::Ordering;
pub const RMW_O: Ordering = Ordering::Acquire;
#[inline(always)]
pub fn the_fence() {}
}
#[cfg(not(any(target_platform = "x86", target_platform = "x86_64")))] | mod internal_ordering {
use std::sync::atomic::{Ordering, fence};
pub const RMW_O: Ordering = Ordering::Relaxed;
pub fn the_fence() {
fence(Ordering::SeqCst)
}
}
/// The ordering to be used for RMW operations in this fencing scheme
#[allow(non_upper_case_globals)]
pub const RMWOrder: Ordering = internal_ordering::RMW_O;
/// The fence to be used after the RMW
#[inline(always)]
pub fn fence_rmw() {
internal_ordering::the_fence()
} | random_line_split | |
fence_rmw.rs | //! This mod provides orderings to use with RMW operations
//! that optimally handle the case when all loads and stores
//! after an RMW operation must be ordered after the operation.
//! # Example:
//! ```
//! use std::sync::atomic::{AtomicUsize, fence, Ordering};
//! use atomic_utilities::fence_rmw::{RMWOrder, fence_rmw};
//!
//! let atomic_refcnt = AtomicUsize::new(0);
//! atomic_refcnt.fetch_add(1, RMWOrder);
//!
//! // ... do work here
//! // This will be ordered after the store of the fetch_add
//! // and will use minimal fences for various hardware platforms
//! atomic_refcnt.fetch_sub(1, Ordering::Release);
//! ```
use std::sync::atomic::Ordering;
#[cfg(any(target_platform = "x86", target_platform = "x86_64"))]
mod internal_ordering {
use std::sync::atomic::Ordering;
pub const RMW_O: Ordering = Ordering::Acquire;
#[inline(always)]
pub fn the_fence() {}
}
#[cfg(not(any(target_platform = "x86", target_platform = "x86_64")))]
mod internal_ordering {
use std::sync::atomic::{Ordering, fence};
pub const RMW_O: Ordering = Ordering::Relaxed;
pub fn the_fence() {
fence(Ordering::SeqCst)
}
}
/// The ordering to be used for RMW operations in this fencing scheme
#[allow(non_upper_case_globals)]
pub const RMWOrder: Ordering = internal_ordering::RMW_O;
/// The fence to be used after the RMW
#[inline(always)]
pub fn | () {
internal_ordering::the_fence()
}
| fence_rmw | identifier_name |
admin-projects.js | 'use strict';
angular.module('projects', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('projects', {
url: '/projects',
controller: 'ProjectsCtrl'
})
.state('projects.project', {
url: '/:project',
controller: 'ProjectsCtrl'
});
}])
.controller('ProjectsCtrl', ['$scope', function($scope) {
var self = this;
var project1 = {
name: 'The Insomniac',
placecard: 'cube-18.jpg',
date: (new Date(2015, 5)).getTime(),
sref: 'The-Insomniac',
content: ''
};
var project4 = {
name: 'TileTraveler',
placecard: 'composition-01.jpg',
date: (new Date(2013, 11)).getTime();
sref: 'TileTraveler',
content: ''
};
var project2 = {
name: 'GIS Lookup System',
placecard: 'photoshoot-09.jpg',
date: (new Date(2015, 5)).getTime(),
sref: 'GIS',
content: ''
};
var project3 = {
name: 'Protein Cavity Finder',
placecard: 'cube-13.jpg',
date: (new Date(2015, 4)).getTime(),
sref: 'Protein-Cavity-Finder',
content: ''
};
self.activeProject = '';
self.projectItems = [project1, project2, project3, project4];
self.projectFormData = [];
self.newProject = {name: '', placecard: '', month: 1 + (new Date()).getMonth(), year: 1970 + (new Date()).getYear(), sref: '', content: ''};
for (var i = 0; i < self.projectItems.length; i++)
{
var projectItem = projectItems[i];
self.projectFormData["_"+projectItem.sref] = {};
self.projectFormData["_"+projectItem.sref].name = projectItem.name;
self.projectFormData["_"+projectItem.sref].placecard = projectItem.placecard;
self.projectFormData["_"+projectItem.sref].date = projectItem.date;
self.projectFormData["_"+projectItem.sref].sref = projectItem.sref;
self.projectFormData["_"+projectItem.sref].content = projectItem.content;
}
$scope.$watch('$stateParams.project', function(val) {
if (val != null)
{
var newProject = self.getFromSref(val);
self.activeProject = newProject;
}
});
self.getFromSref = function (sref) {
var theProject self.projectItems.filter(function(obj)
{
return obj.sref === sref;
})
return ((theProject[0] === null || theProject[0] === undefined) ? null : theProject[0]);
};
self.resetProjectForm = function(sref) {
var modelProject = self.getFromSref(name);
self.projectFormData["_" + sref].name = modelProject.name;
self.projectFormData["_" + sref].placecard = modelProject.placecard;
self.projectFormData["_" + sref].date = modelProject.date;
self.projectFormData["_" + sref].sref = modelProject.sref;
self.projectFormData["_" + sref].content = modelProject.content;
}
self.updateProject = function(sref)
{
var projectFields = self.projectFormData["_"+sref];
var updatedProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content};
console.log("Updated: \n", updatedProject);
}
self.deleteProject = function(date)
{
var delProject = self.getFromSref(name);
if($window.confirm("Delete project '" + delProject.title + "'?"))
|
}
self.submitProject = function() {
var projectFields = self.projectFormData["_"+sref];
var newProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content};
console.log("Submitting: ", newProject);
}
}]) | {
console.log("Deleted: \n", delProject);
} | conditional_block |
admin-projects.js | 'use strict';
angular.module('projects', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('projects', {
url: '/projects',
controller: 'ProjectsCtrl'
})
.state('projects.project', {
url: '/:project',
controller: 'ProjectsCtrl'
});
}])
.controller('ProjectsCtrl', ['$scope', function($scope) {
var self = this;
var project1 = {
name: 'The Insomniac',
placecard: 'cube-18.jpg',
date: (new Date(2015, 5)).getTime(),
sref: 'The-Insomniac',
content: ''
}; | name: 'TileTraveler',
placecard: 'composition-01.jpg',
date: (new Date(2013, 11)).getTime();
sref: 'TileTraveler',
content: ''
};
var project2 = {
name: 'GIS Lookup System',
placecard: 'photoshoot-09.jpg',
date: (new Date(2015, 5)).getTime(),
sref: 'GIS',
content: ''
};
var project3 = {
name: 'Protein Cavity Finder',
placecard: 'cube-13.jpg',
date: (new Date(2015, 4)).getTime(),
sref: 'Protein-Cavity-Finder',
content: ''
};
self.activeProject = '';
self.projectItems = [project1, project2, project3, project4];
self.projectFormData = [];
self.newProject = {name: '', placecard: '', month: 1 + (new Date()).getMonth(), year: 1970 + (new Date()).getYear(), sref: '', content: ''};
for (var i = 0; i < self.projectItems.length; i++)
{
var projectItem = projectItems[i];
self.projectFormData["_"+projectItem.sref] = {};
self.projectFormData["_"+projectItem.sref].name = projectItem.name;
self.projectFormData["_"+projectItem.sref].placecard = projectItem.placecard;
self.projectFormData["_"+projectItem.sref].date = projectItem.date;
self.projectFormData["_"+projectItem.sref].sref = projectItem.sref;
self.projectFormData["_"+projectItem.sref].content = projectItem.content;
}
$scope.$watch('$stateParams.project', function(val) {
if (val != null)
{
var newProject = self.getFromSref(val);
self.activeProject = newProject;
}
});
self.getFromSref = function (sref) {
var theProject self.projectItems.filter(function(obj)
{
return obj.sref === sref;
})
return ((theProject[0] === null || theProject[0] === undefined) ? null : theProject[0]);
};
self.resetProjectForm = function(sref) {
var modelProject = self.getFromSref(name);
self.projectFormData["_" + sref].name = modelProject.name;
self.projectFormData["_" + sref].placecard = modelProject.placecard;
self.projectFormData["_" + sref].date = modelProject.date;
self.projectFormData["_" + sref].sref = modelProject.sref;
self.projectFormData["_" + sref].content = modelProject.content;
}
self.updateProject = function(sref)
{
var projectFields = self.projectFormData["_"+sref];
var updatedProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content};
console.log("Updated: \n", updatedProject);
}
self.deleteProject = function(date)
{
var delProject = self.getFromSref(name);
if($window.confirm("Delete project '" + delProject.title + "'?"))
{
console.log("Deleted: \n", delProject);
}
}
self.submitProject = function() {
var projectFields = self.projectFormData["_"+sref];
var newProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content};
console.log("Submitting: ", newProject);
}
}]) | var project4 = { | random_line_split |
poland.ts | import { Country } from '../jsvat';
export const poland: Country = {
name: 'Poland',
codes: ['PL', 'POL', '616'],
calcFn: (vat: string): boolean => {
let total = 0;
// Extract the next digit and multiply by the counter.
for (let i = 0; i < 9; i++) {
total += Number(vat.charAt(i)) * poland.rules.multipliers.common[i];
}
// Establish check digits subtracting modulus 11 from 11.
total = total % 11;
if (total > 9) {
total = 0;
}
// Compare it with the last character of the VAT number. If it's the same, then it's valid.
const expect = Number(vat.slice(9, 10));
return total === expect;
},
rules: {
multipliers: { | common: [6, 5, 7, 2, 3, 4, 5, 6, 7]
},
regex: [/^(PL)(\d{10})$/]
}
}; | random_line_split | |
poland.ts | import { Country } from '../jsvat';
export const poland: Country = {
name: 'Poland',
codes: ['PL', 'POL', '616'],
calcFn: (vat: string): boolean => {
let total = 0;
// Extract the next digit and multiply by the counter.
for (let i = 0; i < 9; i++) {
total += Number(vat.charAt(i)) * poland.rules.multipliers.common[i];
}
// Establish check digits subtracting modulus 11 from 11.
total = total % 11;
if (total > 9) |
// Compare it with the last character of the VAT number. If it's the same, then it's valid.
const expect = Number(vat.slice(9, 10));
return total === expect;
},
rules: {
multipliers: {
common: [6, 5, 7, 2, 3, 4, 5, 6, 7]
},
regex: [/^(PL)(\d{10})$/]
}
};
| {
total = 0;
} | conditional_block |
lock.py | """Locks on Zigbee Home Automation networks."""
import functools
import voluptuous as vol
from zigpy.zcl.foundation import Status
from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .core import discovery
from .core.const import (
CHANNEL_DOORLOCK,
DATA_ZHA,
SIGNAL_ADD_ENTITIES,
SIGNAL_ATTR_UPDATED,
)
from .core.registries import ZHA_ENTITIES
from .entity import ZhaEntity
# The first state is Zigbee 'Not fully locked'
STATE_LIST = [STATE_UNLOCKED, STATE_LOCKED, STATE_UNLOCKED]
MULTI_MATCH = functools.partial(ZHA_ENTITIES.multipass_match, Platform.LOCK)
VALUE_TO_STATE = dict(enumerate(STATE_LIST))
SERVICE_SET_LOCK_USER_CODE = "set_lock_user_code"
SERVICE_ENABLE_LOCK_USER_CODE = "enable_lock_user_code"
SERVICE_DISABLE_LOCK_USER_CODE = "disable_lock_user_code"
SERVICE_CLEAR_LOCK_USER_CODE = "clear_lock_user_code"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: entity_platform.AddEntitiesCallback,
) -> None:
"""Set up the Zigbee Home Automation Door Lock from config entry."""
entities_to_create = hass.data[DATA_ZHA][Platform.LOCK]
unsub = async_dispatcher_connect(
hass,
SIGNAL_ADD_ENTITIES,
functools.partial(
discovery.async_add_entities, async_add_entities, entities_to_create
),
)
config_entry.async_on_unload(unsub)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service( # type: ignore
SERVICE_SET_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
vol.Required("user_code"): cv.string,
},
"async_set_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_ENABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_enable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_DISABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_disable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_CLEAR_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_clear_lock_user_code",
)
@MULTI_MATCH(channel_names=CHANNEL_DOORLOCK)
class ZhaDoorLock(ZhaEntity, LockEntity):
"""Representation of a ZHA lock."""
def __init__(self, unique_id, zha_device, channels, **kwargs):
"""Init this sensor."""
super().__init__(unique_id, zha_device, channels, **kwargs)
self._doorlock_channel = self.cluster_channels.get(CHANNEL_DOORLOCK)
async def async_added_to_hass(self):
"""Run when about to be added to hass."""
await super().async_added_to_hass()
self.async_accept_signal(
self._doorlock_channel, SIGNAL_ATTR_UPDATED, self.async_set_state
)
@callback
def async_restore_last_state(self, last_state):
"""Restore previous state."""
self._state = VALUE_TO_STATE.get(last_state.state, last_state.state)
@property
def is_locked(self) -> bool:
"""Return true if entity is locked."""
if self._state is None:
return False
return self._state == STATE_LOCKED
@property
def extra_state_attributes(self):
"""Return state attributes."""
return self.state_attributes
async def async_lock(self, **kwargs):
"""Lock the lock."""
result = await self._doorlock_channel.lock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with lock_door: %s", result)
return
self.async_write_ha_state()
async def async_unlock(self, **kwargs):
"""Unlock the lock."""
result = await self._doorlock_channel.unlock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with unlock_door: %s", result)
return
self.async_write_ha_state()
async def async_update(self):
"""Attempt to retrieve state from the lock."""
await super().async_update()
await self.async_get_state()
@callback
def async_set_state(self, attr_id, attr_name, value):
"""Handle state update from channel."""
self._state = VALUE_TO_STATE.get(value, self._state)
self.async_write_ha_state()
async def async_get_state(self, from_cache=True):
"""Attempt to retrieve state from the lock."""
if self._doorlock_channel:
state = await self._doorlock_channel.get_attribute_value(
"lock_state", from_cache=from_cache
)
if state is not None:
self._state = VALUE_TO_STATE.get(state, self._state)
async def refresh(self, time):
"""Call async_get_state at an interval."""
await self.async_get_state(from_cache=False)
async def async_set_lock_user_code(self, code_slot: int, user_code: str) -> None:
"""Set the user_code to index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_set_user_code(code_slot, user_code)
self.debug("User code at slot %s set", code_slot)
async def async_enable_lock_user_code(self, code_slot: int) -> None:
"""Enable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_enable_user_code(code_slot)
self.debug("User code at slot %s enabled", code_slot)
async def async_disable_lock_user_code(self, code_slot: int) -> None:
"""Disable user_code at index X on the lock."""
if self._doorlock_channel:
|
async def async_clear_lock_user_code(self, code_slot: int) -> None:
"""Clear the user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_clear_user_code(code_slot)
self.debug("User code at slot %s cleared", code_slot)
| await self._doorlock_channel.async_disable_user_code(code_slot)
self.debug("User code at slot %s disabled", code_slot) | conditional_block |
lock.py | """Locks on Zigbee Home Automation networks."""
import functools
import voluptuous as vol
from zigpy.zcl.foundation import Status
from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .core import discovery
from .core.const import (
CHANNEL_DOORLOCK,
DATA_ZHA,
SIGNAL_ADD_ENTITIES,
SIGNAL_ATTR_UPDATED,
)
from .core.registries import ZHA_ENTITIES
from .entity import ZhaEntity
# The first state is Zigbee 'Not fully locked'
STATE_LIST = [STATE_UNLOCKED, STATE_LOCKED, STATE_UNLOCKED]
MULTI_MATCH = functools.partial(ZHA_ENTITIES.multipass_match, Platform.LOCK)
VALUE_TO_STATE = dict(enumerate(STATE_LIST))
SERVICE_SET_LOCK_USER_CODE = "set_lock_user_code"
SERVICE_ENABLE_LOCK_USER_CODE = "enable_lock_user_code"
SERVICE_DISABLE_LOCK_USER_CODE = "disable_lock_user_code"
SERVICE_CLEAR_LOCK_USER_CODE = "clear_lock_user_code"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: entity_platform.AddEntitiesCallback,
) -> None:
"""Set up the Zigbee Home Automation Door Lock from config entry."""
entities_to_create = hass.data[DATA_ZHA][Platform.LOCK]
unsub = async_dispatcher_connect(
hass,
SIGNAL_ADD_ENTITIES,
functools.partial(
discovery.async_add_entities, async_add_entities, entities_to_create
),
)
config_entry.async_on_unload(unsub)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service( # type: ignore
SERVICE_SET_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
vol.Required("user_code"): cv.string,
},
"async_set_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_ENABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_enable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_DISABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_disable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_CLEAR_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_clear_lock_user_code",
)
@MULTI_MATCH(channel_names=CHANNEL_DOORLOCK)
class ZhaDoorLock(ZhaEntity, LockEntity):
"""Representation of a ZHA lock."""
def __init__(self, unique_id, zha_device, channels, **kwargs):
"""Init this sensor."""
super().__init__(unique_id, zha_device, channels, **kwargs)
self._doorlock_channel = self.cluster_channels.get(CHANNEL_DOORLOCK)
async def async_added_to_hass(self):
"""Run when about to be added to hass."""
await super().async_added_to_hass()
self.async_accept_signal(
self._doorlock_channel, SIGNAL_ATTR_UPDATED, self.async_set_state
)
@callback
def async_restore_last_state(self, last_state):
"""Restore previous state."""
self._state = VALUE_TO_STATE.get(last_state.state, last_state.state)
@property
def is_locked(self) -> bool:
"""Return true if entity is locked."""
if self._state is None:
return False
return self._state == STATE_LOCKED
@property
def extra_state_attributes(self):
"""Return state attributes."""
return self.state_attributes
async def async_lock(self, **kwargs):
"""Lock the lock."""
result = await self._doorlock_channel.lock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with lock_door: %s", result)
return
self.async_write_ha_state()
async def async_unlock(self, **kwargs):
"""Unlock the lock."""
result = await self._doorlock_channel.unlock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with unlock_door: %s", result)
return
self.async_write_ha_state()
async def async_update(self):
"""Attempt to retrieve state from the lock."""
await super().async_update()
await self.async_get_state()
@callback
def async_set_state(self, attr_id, attr_name, value):
"""Handle state update from channel."""
self._state = VALUE_TO_STATE.get(value, self._state)
self.async_write_ha_state()
async def async_get_state(self, from_cache=True):
"""Attempt to retrieve state from the lock."""
if self._doorlock_channel:
state = await self._doorlock_channel.get_attribute_value(
"lock_state", from_cache=from_cache
)
if state is not None:
self._state = VALUE_TO_STATE.get(state, self._state)
async def refresh(self, time):
"""Call async_get_state at an interval."""
await self.async_get_state(from_cache=False)
async def async_set_lock_user_code(self, code_slot: int, user_code: str) -> None:
"""Set the user_code to index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_set_user_code(code_slot, user_code)
self.debug("User code at slot %s set", code_slot)
async def async_enable_lock_user_code(self, code_slot: int) -> None:
"""Enable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_enable_user_code(code_slot)
self.debug("User code at slot %s enabled", code_slot)
async def | (self, code_slot: int) -> None:
"""Disable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_disable_user_code(code_slot)
self.debug("User code at slot %s disabled", code_slot)
async def async_clear_lock_user_code(self, code_slot: int) -> None:
"""Clear the user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_clear_user_code(code_slot)
self.debug("User code at slot %s cleared", code_slot)
| async_disable_lock_user_code | identifier_name |
lock.py | """Locks on Zigbee Home Automation networks."""
import functools
import voluptuous as vol
from zigpy.zcl.foundation import Status
from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .core import discovery
from .core.const import (
CHANNEL_DOORLOCK,
DATA_ZHA,
SIGNAL_ADD_ENTITIES,
SIGNAL_ATTR_UPDATED,
)
from .core.registries import ZHA_ENTITIES
from .entity import ZhaEntity
# The first state is Zigbee 'Not fully locked'
STATE_LIST = [STATE_UNLOCKED, STATE_LOCKED, STATE_UNLOCKED]
MULTI_MATCH = functools.partial(ZHA_ENTITIES.multipass_match, Platform.LOCK)
VALUE_TO_STATE = dict(enumerate(STATE_LIST))
SERVICE_SET_LOCK_USER_CODE = "set_lock_user_code"
SERVICE_ENABLE_LOCK_USER_CODE = "enable_lock_user_code"
SERVICE_DISABLE_LOCK_USER_CODE = "disable_lock_user_code"
SERVICE_CLEAR_LOCK_USER_CODE = "clear_lock_user_code"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: entity_platform.AddEntitiesCallback,
) -> None:
"""Set up the Zigbee Home Automation Door Lock from config entry."""
entities_to_create = hass.data[DATA_ZHA][Platform.LOCK]
unsub = async_dispatcher_connect(
hass,
SIGNAL_ADD_ENTITIES,
functools.partial(
discovery.async_add_entities, async_add_entities, entities_to_create
),
)
config_entry.async_on_unload(unsub)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service( # type: ignore
SERVICE_SET_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
vol.Required("user_code"): cv.string,
},
"async_set_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_ENABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_enable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_DISABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_disable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_CLEAR_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_clear_lock_user_code",
)
@MULTI_MATCH(channel_names=CHANNEL_DOORLOCK)
class ZhaDoorLock(ZhaEntity, LockEntity):
"""Representation of a ZHA lock."""
def __init__(self, unique_id, zha_device, channels, **kwargs):
"""Init this sensor."""
super().__init__(unique_id, zha_device, channels, **kwargs)
self._doorlock_channel = self.cluster_channels.get(CHANNEL_DOORLOCK)
async def async_added_to_hass(self):
"""Run when about to be added to hass."""
await super().async_added_to_hass()
self.async_accept_signal(
self._doorlock_channel, SIGNAL_ATTR_UPDATED, self.async_set_state
)
@callback
def async_restore_last_state(self, last_state):
"""Restore previous state."""
self._state = VALUE_TO_STATE.get(last_state.state, last_state.state)
@property
def is_locked(self) -> bool:
"""Return true if entity is locked."""
if self._state is None:
return False
return self._state == STATE_LOCKED
@property
def extra_state_attributes(self):
"""Return state attributes."""
return self.state_attributes
async def async_lock(self, **kwargs):
"""Lock the lock."""
result = await self._doorlock_channel.lock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with lock_door: %s", result)
return
self.async_write_ha_state()
async def async_unlock(self, **kwargs):
"""Unlock the lock."""
result = await self._doorlock_channel.unlock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with unlock_door: %s", result)
return
self.async_write_ha_state()
async def async_update(self):
"""Attempt to retrieve state from the lock."""
await super().async_update()
await self.async_get_state()
@callback
def async_set_state(self, attr_id, attr_name, value):
"""Handle state update from channel."""
self._state = VALUE_TO_STATE.get(value, self._state)
self.async_write_ha_state()
async def async_get_state(self, from_cache=True):
"""Attempt to retrieve state from the lock."""
if self._doorlock_channel:
state = await self._doorlock_channel.get_attribute_value(
"lock_state", from_cache=from_cache
)
if state is not None:
self._state = VALUE_TO_STATE.get(state, self._state)
async def refresh(self, time):
"""Call async_get_state at an interval."""
await self.async_get_state(from_cache=False)
async def async_set_lock_user_code(self, code_slot: int, user_code: str) -> None:
"""Set the user_code to index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_set_user_code(code_slot, user_code)
self.debug("User code at slot %s set", code_slot)
async def async_enable_lock_user_code(self, code_slot: int) -> None:
|
async def async_disable_lock_user_code(self, code_slot: int) -> None:
"""Disable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_disable_user_code(code_slot)
self.debug("User code at slot %s disabled", code_slot)
async def async_clear_lock_user_code(self, code_slot: int) -> None:
"""Clear the user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_clear_user_code(code_slot)
self.debug("User code at slot %s cleared", code_slot)
| """Enable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_enable_user_code(code_slot)
self.debug("User code at slot %s enabled", code_slot) | identifier_body |
lock.py | """Locks on Zigbee Home Automation networks."""
import functools
import voluptuous as vol
from zigpy.zcl.foundation import Status
from homeassistant.components.lock import STATE_LOCKED, STATE_UNLOCKED, LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .core import discovery
from .core.const import (
CHANNEL_DOORLOCK,
DATA_ZHA,
SIGNAL_ADD_ENTITIES,
SIGNAL_ATTR_UPDATED,
)
from .core.registries import ZHA_ENTITIES
from .entity import ZhaEntity
# The first state is Zigbee 'Not fully locked'
STATE_LIST = [STATE_UNLOCKED, STATE_LOCKED, STATE_UNLOCKED]
MULTI_MATCH = functools.partial(ZHA_ENTITIES.multipass_match, Platform.LOCK)
VALUE_TO_STATE = dict(enumerate(STATE_LIST))
SERVICE_SET_LOCK_USER_CODE = "set_lock_user_code"
SERVICE_ENABLE_LOCK_USER_CODE = "enable_lock_user_code"
SERVICE_DISABLE_LOCK_USER_CODE = "disable_lock_user_code"
SERVICE_CLEAR_LOCK_USER_CODE = "clear_lock_user_code"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: entity_platform.AddEntitiesCallback,
) -> None:
"""Set up the Zigbee Home Automation Door Lock from config entry."""
entities_to_create = hass.data[DATA_ZHA][Platform.LOCK]
unsub = async_dispatcher_connect(
hass,
SIGNAL_ADD_ENTITIES,
functools.partial(
discovery.async_add_entities, async_add_entities, entities_to_create
),
)
config_entry.async_on_unload(unsub)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service( # type: ignore
SERVICE_SET_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
vol.Required("user_code"): cv.string,
},
"async_set_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_ENABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_enable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_DISABLE_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_disable_lock_user_code",
)
platform.async_register_entity_service( # type: ignore
SERVICE_CLEAR_LOCK_USER_CODE,
{
vol.Required("code_slot"): vol.Coerce(int),
},
"async_clear_lock_user_code",
)
@MULTI_MATCH(channel_names=CHANNEL_DOORLOCK) | def __init__(self, unique_id, zha_device, channels, **kwargs):
"""Init this sensor."""
super().__init__(unique_id, zha_device, channels, **kwargs)
self._doorlock_channel = self.cluster_channels.get(CHANNEL_DOORLOCK)
async def async_added_to_hass(self):
"""Run when about to be added to hass."""
await super().async_added_to_hass()
self.async_accept_signal(
self._doorlock_channel, SIGNAL_ATTR_UPDATED, self.async_set_state
)
@callback
def async_restore_last_state(self, last_state):
"""Restore previous state."""
self._state = VALUE_TO_STATE.get(last_state.state, last_state.state)
@property
def is_locked(self) -> bool:
"""Return true if entity is locked."""
if self._state is None:
return False
return self._state == STATE_LOCKED
@property
def extra_state_attributes(self):
"""Return state attributes."""
return self.state_attributes
async def async_lock(self, **kwargs):
"""Lock the lock."""
result = await self._doorlock_channel.lock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with lock_door: %s", result)
return
self.async_write_ha_state()
async def async_unlock(self, **kwargs):
"""Unlock the lock."""
result = await self._doorlock_channel.unlock_door()
if not isinstance(result, list) or result[0] is not Status.SUCCESS:
self.error("Error with unlock_door: %s", result)
return
self.async_write_ha_state()
async def async_update(self):
"""Attempt to retrieve state from the lock."""
await super().async_update()
await self.async_get_state()
@callback
def async_set_state(self, attr_id, attr_name, value):
"""Handle state update from channel."""
self._state = VALUE_TO_STATE.get(value, self._state)
self.async_write_ha_state()
async def async_get_state(self, from_cache=True):
"""Attempt to retrieve state from the lock."""
if self._doorlock_channel:
state = await self._doorlock_channel.get_attribute_value(
"lock_state", from_cache=from_cache
)
if state is not None:
self._state = VALUE_TO_STATE.get(state, self._state)
async def refresh(self, time):
"""Call async_get_state at an interval."""
await self.async_get_state(from_cache=False)
async def async_set_lock_user_code(self, code_slot: int, user_code: str) -> None:
"""Set the user_code to index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_set_user_code(code_slot, user_code)
self.debug("User code at slot %s set", code_slot)
async def async_enable_lock_user_code(self, code_slot: int) -> None:
"""Enable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_enable_user_code(code_slot)
self.debug("User code at slot %s enabled", code_slot)
async def async_disable_lock_user_code(self, code_slot: int) -> None:
"""Disable user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_disable_user_code(code_slot)
self.debug("User code at slot %s disabled", code_slot)
async def async_clear_lock_user_code(self, code_slot: int) -> None:
"""Clear the user_code at index X on the lock."""
if self._doorlock_channel:
await self._doorlock_channel.async_clear_user_code(code_slot)
self.debug("User code at slot %s cleared", code_slot) | class ZhaDoorLock(ZhaEntity, LockEntity):
"""Representation of a ZHA lock."""
| random_line_split |
mock_executor.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use tipb::FieldType;
use crate::interface::*;
use tidb_query_common::storage::IntervalRange;
use tidb_query_datatype::codec::batch::LazyBatchColumnVec;
use tidb_query_datatype::codec::data_type::VectorValue;
use tidb_query_datatype::expr::EvalWarnings;
/// A simple mock executor that will return batch data according to a fixture without any
/// modification.
///
/// Normally this should be only used in tests.
pub struct MockExecutor {
schema: Vec<FieldType>,
results: std::vec::IntoIter<BatchExecuteResult>,
}
impl MockExecutor {
pub fn new(schema: Vec<FieldType>, results: Vec<BatchExecuteResult>) -> Self {
assert!(!results.is_empty());
Self {
schema,
results: results.into_iter(),
}
}
}
impl BatchExecutor for MockExecutor {
type StorageStats = ();
fn schema(&self) -> &[FieldType] {
&self.schema
}
fn next_batch(&mut self, _scan_rows: usize) -> BatchExecuteResult {
self.results.next().unwrap()
}
fn collect_exec_stats(&mut self, _dest: &mut ExecuteStats) {
// Do nothing
}
fn collect_storage_stats(&mut self, _dest: &mut Self::StorageStats) {
// Do nothing
}
fn take_scanned_range(&mut self) -> IntervalRange {
// Do nothing
unreachable!()
}
fn can_be_cached(&self) -> bool {
false
}
}
pub struct MockScanExecutor {
pub rows: Vec<i64>,
pub pos: usize,
schema: Vec<FieldType>,
}
impl MockScanExecutor {
pub fn new(rows: Vec<i64>, schema: Vec<FieldType>) -> Self {
MockScanExecutor {
rows,
pos: 0,
schema,
}
}
}
impl BatchExecutor for MockScanExecutor {
type StorageStats = ();
fn schema(&self) -> &[FieldType] {
&self.schema
}
fn next_batch(&mut self, scan_rows: usize) -> BatchExecuteResult {
let real_scan_rows = std::cmp::min(scan_rows, self.rows.len());
// just one column
let mut res_col = Vec::new();
let mut res_logical_rows = Vec::new();
let mut cur_row_idx = 0;
while self.pos < self.rows.len() && cur_row_idx < real_scan_rows {
res_col.push(Some(self.rows[self.pos]));
res_logical_rows.push(cur_row_idx);
self.pos += 1;
cur_row_idx += 1;
}
let is_drained = self.pos >= self.rows.len();
BatchExecuteResult {
physical_columns: LazyBatchColumnVec::from(vec![VectorValue::Int(res_col.into())]),
logical_rows: res_logical_rows,
warnings: EvalWarnings::default(),
is_drained: Ok(is_drained),
}
}
fn collect_exec_stats(&mut self, _dest: &mut ExecuteStats) {
// Do nothing
}
fn | (&mut self, _dest: &mut Self::StorageStats) {
// Do nothing
}
fn take_scanned_range(&mut self) -> IntervalRange {
// Do nothing
unreachable!()
}
fn can_be_cached(&self) -> bool {
false
}
}
| collect_storage_stats | identifier_name |
mock_executor.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use tipb::FieldType;
use crate::interface::*;
use tidb_query_common::storage::IntervalRange;
use tidb_query_datatype::codec::batch::LazyBatchColumnVec;
use tidb_query_datatype::codec::data_type::VectorValue;
use tidb_query_datatype::expr::EvalWarnings;
/// A simple mock executor that will return batch data according to a fixture without any
/// modification.
///
/// Normally this should be only used in tests.
pub struct MockExecutor {
schema: Vec<FieldType>,
results: std::vec::IntoIter<BatchExecuteResult>,
}
impl MockExecutor {
pub fn new(schema: Vec<FieldType>, results: Vec<BatchExecuteResult>) -> Self {
assert!(!results.is_empty());
Self {
schema,
results: results.into_iter(),
}
}
}
impl BatchExecutor for MockExecutor {
type StorageStats = ();
fn schema(&self) -> &[FieldType] {
&self.schema
}
fn next_batch(&mut self, _scan_rows: usize) -> BatchExecuteResult {
self.results.next().unwrap()
}
fn collect_exec_stats(&mut self, _dest: &mut ExecuteStats) {
// Do nothing
}
fn collect_storage_stats(&mut self, _dest: &mut Self::StorageStats) {
// Do nothing
}
fn take_scanned_range(&mut self) -> IntervalRange {
// Do nothing |
fn can_be_cached(&self) -> bool {
false
}
}
pub struct MockScanExecutor {
pub rows: Vec<i64>,
pub pos: usize,
schema: Vec<FieldType>,
}
impl MockScanExecutor {
pub fn new(rows: Vec<i64>, schema: Vec<FieldType>) -> Self {
MockScanExecutor {
rows,
pos: 0,
schema,
}
}
}
impl BatchExecutor for MockScanExecutor {
type StorageStats = ();
fn schema(&self) -> &[FieldType] {
&self.schema
}
fn next_batch(&mut self, scan_rows: usize) -> BatchExecuteResult {
let real_scan_rows = std::cmp::min(scan_rows, self.rows.len());
// just one column
let mut res_col = Vec::new();
let mut res_logical_rows = Vec::new();
let mut cur_row_idx = 0;
while self.pos < self.rows.len() && cur_row_idx < real_scan_rows {
res_col.push(Some(self.rows[self.pos]));
res_logical_rows.push(cur_row_idx);
self.pos += 1;
cur_row_idx += 1;
}
let is_drained = self.pos >= self.rows.len();
BatchExecuteResult {
physical_columns: LazyBatchColumnVec::from(vec![VectorValue::Int(res_col.into())]),
logical_rows: res_logical_rows,
warnings: EvalWarnings::default(),
is_drained: Ok(is_drained),
}
}
fn collect_exec_stats(&mut self, _dest: &mut ExecuteStats) {
// Do nothing
}
fn collect_storage_stats(&mut self, _dest: &mut Self::StorageStats) {
// Do nothing
}
fn take_scanned_range(&mut self) -> IntervalRange {
// Do nothing
unreachable!()
}
fn can_be_cached(&self) -> bool {
false
}
} | unreachable!()
} | random_line_split |
win32.py | """SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Platform/win32.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import os
import os.path
import string
import sys
import tempfile
from SCons.Platform.posix import exitvalmap
# XXX See note below about why importing SCons.Action should be
# eventually refactored.
import SCons.Action
import SCons.Util
class TempFileMunge:
"""A callable class. You can set an Environment variable to this,
then call it with a string argument, then it will perform temporary
file substitution on it. This is used to circumvent the win32 long command
line limitation.
Example usage:
env["TEMPFILE"] = TempFileMunge
env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}"
"""
def __init__(self, cmd):
self.cmd = cmd
def __call__(self, target, source, env, for_signature):
if for_signature:
return self.cmd
cmd = env.subst_list(self.cmd, 0, target, source)[0]
try:
maxline = int(env.subst('$MAXLINELENGTH'))
except ValueError:
maxline = 2048
if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline:
return self.cmd
else:
# We do a normpath because mktemp() has what appears to be
# a bug in Win32 that will use a forward slash as a path
# delimiter. Win32's link mistakes that for a command line
# switch and barfs.
#
# We use the .lnk suffix for the benefit of the Phar Lap
# linkloc linker, which likes to append an .lnk suffix if
# none is given.
tmp = os.path.normpath(tempfile.mktemp('.lnk'))
native_tmp = SCons.Util.get_native_path(tmp)
if env['SHELL'] and env['SHELL'] == 'sh':
# The sh shell will try to escape the backslashes in the
# path, so unescape them.
native_tmp = string.replace(native_tmp, '\\', r'\\\\')
# In Cygwin, we want to use rm to delete the temporary
# file, because del does not exist in the sh shell.
rm = env.Detect('rm') or 'del'
else:
# Don't use 'rm' if the shell is not sh, because rm won't
# work with the win32 shells (cmd.exe or command.com) or
# win32 path names.
rm = 'del'
args = map(SCons.Util.quote_spaces, cmd[1:])
open(tmp, 'w').write(string.join(args, " ") + "\n")
# XXX Using the SCons.Action.print_actions value directly
# like this is bogus, but expedient. This class should
# really be rewritten as an Action that defines the
# __call__() and strfunction() methods and lets the
# normal action-execution logic handle whether or not to
# print/execute the action. The problem, though, is all
# of that is decided before we execute this method as
# part of expanding the $TEMPFILE construction variable.
# Consequently, refactoring this will have to wait until
# we get more flexible with allowing Actions to exist
# independently and get strung together arbitrarily like
# Ant tasks. In the meantime, it's going to be more
# user-friendly to not let obsession with architectural
# purity get in the way of just being helpful, so we'll
# reach into SCons.Action directly.
if SCons.Action.print_actions:
print("Using tempfile "+native_tmp+" for command line:\n"+
str(cmd[0]) + " " + string.join(args," "))
return [ cmd[0], '@' + native_tmp + '\n' + rm, native_tmp ]
# The upshot of all this is that, if you are using Python 1.5.2,
# you had better have cmd or command.com in your PATH when you run
# scons.
def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
# There is no direct way to do that in python. What we do
# here should work for most cases:
# In case stdout (stderr) is not redirected to a file,
# we redirect it into a temporary file tmpFileStdout
# (tmpFileStderr) and copy the contents of this file
# to stdout (stderr) given in the argument
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
# one temporary file for stdout and stderr
tmpFileStdout = os.path.normpath(tempfile.mktemp())
tmpFileStderr = os.path.normpath(tempfile.mktemp())
# check if output is redirected
stdoutRedirected = 0
stderrRedirected = 0
for arg in args:
# are there more possibilities to redirect stdout ?
if (string.find( arg, ">", 0, 1 ) != -1 or
string.find( arg, "1>", 0, 2 ) != -1):
stdoutRedirected = 1
# are there more possibilities to redirect stderr ?
if string.find( arg, "2>", 0, 2 ) != -1:
stderrRedirected = 1
# redirect output of non-redirected streams to our tempfiles
if stdoutRedirected == 0:
args.append(">" + str(tmpFileStdout))
if stderrRedirected == 0:
args.append("2>" + str(tmpFileStderr))
# actually do the spawn
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
# catch any error
ret = exitvalmap[e[0]]
if stderr != None:
stderr.write("scons: %s: %s\n" % (cmd, e[1]))
# copy child output from tempfiles to our streams
# and do clean up stuff
if stdout != None and stdoutRedirected == 0:
try:
stdout.write(open( tmpFileStdout, "r" ).read())
os.remove( tmpFileStdout )
except (IOError, OSError):
pass
if stderr != None and stderrRedirected == 0:
try:
stderr.write(open( tmpFileStderr, "r" ).read())
os.remove( tmpFileStderr )
except (IOError, OSError):
pass
return ret
def spawn(sh, escape, cmd, args, env):
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
ret = exitvalmap[e[0]]
sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
return ret
# Windows does not allow special characters in file names anyway, so
# no need for a complex escape function, we will just quote the arg.
escape = lambda x: '"' + x + '"'
# Get the windows system directory name
def get_system_root():
# A resonable default if we can't read the registry
try:
val = os.environ['SYSTEMROOT']
except KeyError:
val = "C:/WINDOWS"
pass
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except KeyboardInterrupt:
raise
except:
pass
return val
# Get the location of the program files directory
def get_program_files_dir():
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
except SCons.Util.RegError:
val = ''
pass
if val == '':
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
return val
def generate(env):
# Attempt to find cmd.exe (for WinNT/2k/XP) or
# command.com for Win9x
cmd_interp = ''
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'System32\\cmd.exe')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'command.com')
except KeyboardInterrupt:
raise
except:
pass
# For the special case of not having access to the registry, we
# use a temporary path and pathext to attempt to find the command
# interpreter. If we fail, we try to find the interpreter through
# the env's PATH. The problem with that is that it might not
# contain an ENV and a PATH.
if not cmd_interp:
systemroot = r'C:\Windows'
if os.environ.has_key('SYSTEMROOT'):
systemroot = os.environ['SYSTEMROOT']
tmp_path = systemroot + os.pathsep + \
os.path.join(systemroot,'System32')
tmp_pathext = '.com;.exe;.bat;.cmd'
if os.environ.has_key('PATHEXT'):
tmp_pathext = os.environ['PATHEXT']
cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = env.Detect('cmd')
if not cmd_interp:
cmd_interp = env.Detect('command')
if not env.has_key('ENV'):
env['ENV'] = {}
# Import things from the external environment to the construction
# environment's ENV. This is a potential slippery slope, because we
# *don't* want to make builds dependent on the user's environment by
# default. We're doing this for SYSTEMROOT, though, because it's
# needed for anything that uses sockets, and seldom changes. Weigh
# the impact carefully before adding other variables to this list.
import_env = [ 'SYSTEMROOT' ]
for var in import_env:
v = os.environ.get(var)
if v:
env['ENV'][var] = v
env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ]
env['PSPAWN'] = piped_spawn
env['SPAWN'] = spawn
env['SHELL'] = cmd_interp | env['TEMPFILE'] = TempFileMunge
env['MAXLINELENGTH'] = 2048
env['ESCAPE'] = escape | random_line_split | |
win32.py | """SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Platform/win32.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import os
import os.path
import string
import sys
import tempfile
from SCons.Platform.posix import exitvalmap
# XXX See note below about why importing SCons.Action should be
# eventually refactored.
import SCons.Action
import SCons.Util
class TempFileMunge:
"""A callable class. You can set an Environment variable to this,
then call it with a string argument, then it will perform temporary
file substitution on it. This is used to circumvent the win32 long command
line limitation.
Example usage:
env["TEMPFILE"] = TempFileMunge
env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}"
"""
def __init__(self, cmd):
self.cmd = cmd
def __call__(self, target, source, env, for_signature):
if for_signature:
return self.cmd
cmd = env.subst_list(self.cmd, 0, target, source)[0]
try:
maxline = int(env.subst('$MAXLINELENGTH'))
except ValueError:
maxline = 2048
if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline:
return self.cmd
else:
# We do a normpath because mktemp() has what appears to be
# a bug in Win32 that will use a forward slash as a path
# delimiter. Win32's link mistakes that for a command line
# switch and barfs.
#
# We use the .lnk suffix for the benefit of the Phar Lap
# linkloc linker, which likes to append an .lnk suffix if
# none is given.
tmp = os.path.normpath(tempfile.mktemp('.lnk'))
native_tmp = SCons.Util.get_native_path(tmp)
if env['SHELL'] and env['SHELL'] == 'sh':
# The sh shell will try to escape the backslashes in the
# path, so unescape them.
native_tmp = string.replace(native_tmp, '\\', r'\\\\')
# In Cygwin, we want to use rm to delete the temporary
# file, because del does not exist in the sh shell.
rm = env.Detect('rm') or 'del'
else:
# Don't use 'rm' if the shell is not sh, because rm won't
# work with the win32 shells (cmd.exe or command.com) or
# win32 path names.
rm = 'del'
args = map(SCons.Util.quote_spaces, cmd[1:])
open(tmp, 'w').write(string.join(args, " ") + "\n")
# XXX Using the SCons.Action.print_actions value directly
# like this is bogus, but expedient. This class should
# really be rewritten as an Action that defines the
# __call__() and strfunction() methods and lets the
# normal action-execution logic handle whether or not to
# print/execute the action. The problem, though, is all
# of that is decided before we execute this method as
# part of expanding the $TEMPFILE construction variable.
# Consequently, refactoring this will have to wait until
# we get more flexible with allowing Actions to exist
# independently and get strung together arbitrarily like
# Ant tasks. In the meantime, it's going to be more
# user-friendly to not let obsession with architectural
# purity get in the way of just being helpful, so we'll
# reach into SCons.Action directly.
if SCons.Action.print_actions:
print("Using tempfile "+native_tmp+" for command line:\n"+
str(cmd[0]) + " " + string.join(args," "))
return [ cmd[0], '@' + native_tmp + '\n' + rm, native_tmp ]
# The upshot of all this is that, if you are using Python 1.5.2,
# you had better have cmd or command.com in your PATH when you run
# scons.
def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
# There is no direct way to do that in python. What we do
# here should work for most cases:
# In case stdout (stderr) is not redirected to a file,
# we redirect it into a temporary file tmpFileStdout
# (tmpFileStderr) and copy the contents of this file
# to stdout (stderr) given in the argument
if not sh:
|
else:
# one temporary file for stdout and stderr
tmpFileStdout = os.path.normpath(tempfile.mktemp())
tmpFileStderr = os.path.normpath(tempfile.mktemp())
# check if output is redirected
stdoutRedirected = 0
stderrRedirected = 0
for arg in args:
# are there more possibilities to redirect stdout ?
if (string.find( arg, ">", 0, 1 ) != -1 or
string.find( arg, "1>", 0, 2 ) != -1):
stdoutRedirected = 1
# are there more possibilities to redirect stderr ?
if string.find( arg, "2>", 0, 2 ) != -1:
stderrRedirected = 1
# redirect output of non-redirected streams to our tempfiles
if stdoutRedirected == 0:
args.append(">" + str(tmpFileStdout))
if stderrRedirected == 0:
args.append("2>" + str(tmpFileStderr))
# actually do the spawn
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
# catch any error
ret = exitvalmap[e[0]]
if stderr != None:
stderr.write("scons: %s: %s\n" % (cmd, e[1]))
# copy child output from tempfiles to our streams
# and do clean up stuff
if stdout != None and stdoutRedirected == 0:
try:
stdout.write(open( tmpFileStdout, "r" ).read())
os.remove( tmpFileStdout )
except (IOError, OSError):
pass
if stderr != None and stderrRedirected == 0:
try:
stderr.write(open( tmpFileStderr, "r" ).read())
os.remove( tmpFileStderr )
except (IOError, OSError):
pass
return ret
def spawn(sh, escape, cmd, args, env):
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
ret = exitvalmap[e[0]]
sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
return ret
# Windows does not allow special characters in file names anyway, so
# no need for a complex escape function, we will just quote the arg.
escape = lambda x: '"' + x + '"'
# Get the windows system directory name
def get_system_root():
# A resonable default if we can't read the registry
try:
val = os.environ['SYSTEMROOT']
except KeyError:
val = "C:/WINDOWS"
pass
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except KeyboardInterrupt:
raise
except:
pass
return val
# Get the location of the program files directory
def get_program_files_dir():
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
except SCons.Util.RegError:
val = ''
pass
if val == '':
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
return val
def generate(env):
# Attempt to find cmd.exe (for WinNT/2k/XP) or
# command.com for Win9x
cmd_interp = ''
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'System32\\cmd.exe')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'command.com')
except KeyboardInterrupt:
raise
except:
pass
# For the special case of not having access to the registry, we
# use a temporary path and pathext to attempt to find the command
# interpreter. If we fail, we try to find the interpreter through
# the env's PATH. The problem with that is that it might not
# contain an ENV and a PATH.
if not cmd_interp:
systemroot = r'C:\Windows'
if os.environ.has_key('SYSTEMROOT'):
systemroot = os.environ['SYSTEMROOT']
tmp_path = systemroot + os.pathsep + \
os.path.join(systemroot,'System32')
tmp_pathext = '.com;.exe;.bat;.cmd'
if os.environ.has_key('PATHEXT'):
tmp_pathext = os.environ['PATHEXT']
cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = env.Detect('cmd')
if not cmd_interp:
cmd_interp = env.Detect('command')
if not env.has_key('ENV'):
env['ENV'] = {}
# Import things from the external environment to the construction
# environment's ENV. This is a potential slippery slope, because we
# *don't* want to make builds dependent on the user's environment by
# default. We're doing this for SYSTEMROOT, though, because it's
# needed for anything that uses sockets, and seldom changes. Weigh
# the impact carefully before adding other variables to this list.
import_env = [ 'SYSTEMROOT' ]
for var in import_env:
v = os.environ.get(var)
if v:
env['ENV'][var] = v
env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ]
env['PSPAWN'] = piped_spawn
env['SPAWN'] = spawn
env['SHELL'] = cmd_interp
env['TEMPFILE'] = TempFileMunge
env['MAXLINELENGTH'] = 2048
env['ESCAPE'] = escape
| sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127 | conditional_block |
win32.py | """SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Platform/win32.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import os
import os.path
import string
import sys
import tempfile
from SCons.Platform.posix import exitvalmap
# XXX See note below about why importing SCons.Action should be
# eventually refactored.
import SCons.Action
import SCons.Util
class TempFileMunge:
"""A callable class. You can set an Environment variable to this,
then call it with a string argument, then it will perform temporary
file substitution on it. This is used to circumvent the win32 long command
line limitation.
Example usage:
env["TEMPFILE"] = TempFileMunge
env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}"
"""
def __init__(self, cmd):
self.cmd = cmd
def __call__(self, target, source, env, for_signature):
|
# The upshot of all this is that, if you are using Python 1.5.2,
# you had better have cmd or command.com in your PATH when you run
# scons.
def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
# There is no direct way to do that in python. What we do
# here should work for most cases:
# In case stdout (stderr) is not redirected to a file,
# we redirect it into a temporary file tmpFileStdout
# (tmpFileStderr) and copy the contents of this file
# to stdout (stderr) given in the argument
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
# one temporary file for stdout and stderr
tmpFileStdout = os.path.normpath(tempfile.mktemp())
tmpFileStderr = os.path.normpath(tempfile.mktemp())
# check if output is redirected
stdoutRedirected = 0
stderrRedirected = 0
for arg in args:
# are there more possibilities to redirect stdout ?
if (string.find( arg, ">", 0, 1 ) != -1 or
string.find( arg, "1>", 0, 2 ) != -1):
stdoutRedirected = 1
# are there more possibilities to redirect stderr ?
if string.find( arg, "2>", 0, 2 ) != -1:
stderrRedirected = 1
# redirect output of non-redirected streams to our tempfiles
if stdoutRedirected == 0:
args.append(">" + str(tmpFileStdout))
if stderrRedirected == 0:
args.append("2>" + str(tmpFileStderr))
# actually do the spawn
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
# catch any error
ret = exitvalmap[e[0]]
if stderr != None:
stderr.write("scons: %s: %s\n" % (cmd, e[1]))
# copy child output from tempfiles to our streams
# and do clean up stuff
if stdout != None and stdoutRedirected == 0:
try:
stdout.write(open( tmpFileStdout, "r" ).read())
os.remove( tmpFileStdout )
except (IOError, OSError):
pass
if stderr != None and stderrRedirected == 0:
try:
stderr.write(open( tmpFileStderr, "r" ).read())
os.remove( tmpFileStderr )
except (IOError, OSError):
pass
return ret
def spawn(sh, escape, cmd, args, env):
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
ret = exitvalmap[e[0]]
sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
return ret
# Windows does not allow special characters in file names anyway, so
# no need for a complex escape function, we will just quote the arg.
escape = lambda x: '"' + x + '"'
# Get the windows system directory name
def get_system_root():
# A resonable default if we can't read the registry
try:
val = os.environ['SYSTEMROOT']
except KeyError:
val = "C:/WINDOWS"
pass
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except KeyboardInterrupt:
raise
except:
pass
return val
# Get the location of the program files directory
def get_program_files_dir():
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
except SCons.Util.RegError:
val = ''
pass
if val == '':
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
return val
def generate(env):
# Attempt to find cmd.exe (for WinNT/2k/XP) or
# command.com for Win9x
cmd_interp = ''
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'System32\\cmd.exe')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'command.com')
except KeyboardInterrupt:
raise
except:
pass
# For the special case of not having access to the registry, we
# use a temporary path and pathext to attempt to find the command
# interpreter. If we fail, we try to find the interpreter through
# the env's PATH. The problem with that is that it might not
# contain an ENV and a PATH.
if not cmd_interp:
systemroot = r'C:\Windows'
if os.environ.has_key('SYSTEMROOT'):
systemroot = os.environ['SYSTEMROOT']
tmp_path = systemroot + os.pathsep + \
os.path.join(systemroot,'System32')
tmp_pathext = '.com;.exe;.bat;.cmd'
if os.environ.has_key('PATHEXT'):
tmp_pathext = os.environ['PATHEXT']
cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = env.Detect('cmd')
if not cmd_interp:
cmd_interp = env.Detect('command')
if not env.has_key('ENV'):
env['ENV'] = {}
# Import things from the external environment to the construction
# environment's ENV. This is a potential slippery slope, because we
# *don't* want to make builds dependent on the user's environment by
# default. We're doing this for SYSTEMROOT, though, because it's
# needed for anything that uses sockets, and seldom changes. Weigh
# the impact carefully before adding other variables to this list.
import_env = [ 'SYSTEMROOT' ]
for var in import_env:
v = os.environ.get(var)
if v:
env['ENV'][var] = v
env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ]
env['PSPAWN'] = piped_spawn
env['SPAWN'] = spawn
env['SHELL'] = cmd_interp
env['TEMPFILE'] = TempFileMunge
env['MAXLINELENGTH'] = 2048
env['ESCAPE'] = escape
| if for_signature:
return self.cmd
cmd = env.subst_list(self.cmd, 0, target, source)[0]
try:
maxline = int(env.subst('$MAXLINELENGTH'))
except ValueError:
maxline = 2048
if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline:
return self.cmd
else:
# We do a normpath because mktemp() has what appears to be
# a bug in Win32 that will use a forward slash as a path
# delimiter. Win32's link mistakes that for a command line
# switch and barfs.
#
# We use the .lnk suffix for the benefit of the Phar Lap
# linkloc linker, which likes to append an .lnk suffix if
# none is given.
tmp = os.path.normpath(tempfile.mktemp('.lnk'))
native_tmp = SCons.Util.get_native_path(tmp)
if env['SHELL'] and env['SHELL'] == 'sh':
# The sh shell will try to escape the backslashes in the
# path, so unescape them.
native_tmp = string.replace(native_tmp, '\\', r'\\\\')
# In Cygwin, we want to use rm to delete the temporary
# file, because del does not exist in the sh shell.
rm = env.Detect('rm') or 'del'
else:
# Don't use 'rm' if the shell is not sh, because rm won't
# work with the win32 shells (cmd.exe or command.com) or
# win32 path names.
rm = 'del'
args = map(SCons.Util.quote_spaces, cmd[1:])
open(tmp, 'w').write(string.join(args, " ") + "\n")
# XXX Using the SCons.Action.print_actions value directly
# like this is bogus, but expedient. This class should
# really be rewritten as an Action that defines the
# __call__() and strfunction() methods and lets the
# normal action-execution logic handle whether or not to
# print/execute the action. The problem, though, is all
# of that is decided before we execute this method as
# part of expanding the $TEMPFILE construction variable.
# Consequently, refactoring this will have to wait until
# we get more flexible with allowing Actions to exist
# independently and get strung together arbitrarily like
# Ant tasks. In the meantime, it's going to be more
# user-friendly to not let obsession with architectural
# purity get in the way of just being helpful, so we'll
# reach into SCons.Action directly.
if SCons.Action.print_actions:
print("Using tempfile "+native_tmp+" for command line:\n"+
str(cmd[0]) + " " + string.join(args," "))
return [ cmd[0], '@' + native_tmp + '\n' + rm, native_tmp ] | identifier_body |
win32.py | """SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Platform/win32.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import os
import os.path
import string
import sys
import tempfile
from SCons.Platform.posix import exitvalmap
# XXX See note below about why importing SCons.Action should be
# eventually refactored.
import SCons.Action
import SCons.Util
class TempFileMunge:
"""A callable class. You can set an Environment variable to this,
then call it with a string argument, then it will perform temporary
file substitution on it. This is used to circumvent the win32 long command
line limitation.
Example usage:
env["TEMPFILE"] = TempFileMunge
env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}"
"""
def __init__(self, cmd):
self.cmd = cmd
def __call__(self, target, source, env, for_signature):
if for_signature:
return self.cmd
cmd = env.subst_list(self.cmd, 0, target, source)[0]
try:
maxline = int(env.subst('$MAXLINELENGTH'))
except ValueError:
maxline = 2048
if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline:
return self.cmd
else:
# We do a normpath because mktemp() has what appears to be
# a bug in Win32 that will use a forward slash as a path
# delimiter. Win32's link mistakes that for a command line
# switch and barfs.
#
# We use the .lnk suffix for the benefit of the Phar Lap
# linkloc linker, which likes to append an .lnk suffix if
# none is given.
tmp = os.path.normpath(tempfile.mktemp('.lnk'))
native_tmp = SCons.Util.get_native_path(tmp)
if env['SHELL'] and env['SHELL'] == 'sh':
# The sh shell will try to escape the backslashes in the
# path, so unescape them.
native_tmp = string.replace(native_tmp, '\\', r'\\\\')
# In Cygwin, we want to use rm to delete the temporary
# file, because del does not exist in the sh shell.
rm = env.Detect('rm') or 'del'
else:
# Don't use 'rm' if the shell is not sh, because rm won't
# work with the win32 shells (cmd.exe or command.com) or
# win32 path names.
rm = 'del'
args = map(SCons.Util.quote_spaces, cmd[1:])
open(tmp, 'w').write(string.join(args, " ") + "\n")
# XXX Using the SCons.Action.print_actions value directly
# like this is bogus, but expedient. This class should
# really be rewritten as an Action that defines the
# __call__() and strfunction() methods and lets the
# normal action-execution logic handle whether or not to
# print/execute the action. The problem, though, is all
# of that is decided before we execute this method as
# part of expanding the $TEMPFILE construction variable.
# Consequently, refactoring this will have to wait until
# we get more flexible with allowing Actions to exist
# independently and get strung together arbitrarily like
# Ant tasks. In the meantime, it's going to be more
# user-friendly to not let obsession with architectural
# purity get in the way of just being helpful, so we'll
# reach into SCons.Action directly.
if SCons.Action.print_actions:
print("Using tempfile "+native_tmp+" for command line:\n"+
str(cmd[0]) + " " + string.join(args," "))
return [ cmd[0], '@' + native_tmp + '\n' + rm, native_tmp ]
# The upshot of all this is that, if you are using Python 1.5.2,
# you had better have cmd or command.com in your PATH when you run
# scons.
def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
# There is no direct way to do that in python. What we do
# here should work for most cases:
# In case stdout (stderr) is not redirected to a file,
# we redirect it into a temporary file tmpFileStdout
# (tmpFileStderr) and copy the contents of this file
# to stdout (stderr) given in the argument
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
# one temporary file for stdout and stderr
tmpFileStdout = os.path.normpath(tempfile.mktemp())
tmpFileStderr = os.path.normpath(tempfile.mktemp())
# check if output is redirected
stdoutRedirected = 0
stderrRedirected = 0
for arg in args:
# are there more possibilities to redirect stdout ?
if (string.find( arg, ">", 0, 1 ) != -1 or
string.find( arg, "1>", 0, 2 ) != -1):
stdoutRedirected = 1
# are there more possibilities to redirect stderr ?
if string.find( arg, "2>", 0, 2 ) != -1:
stderrRedirected = 1
# redirect output of non-redirected streams to our tempfiles
if stdoutRedirected == 0:
args.append(">" + str(tmpFileStdout))
if stderrRedirected == 0:
args.append("2>" + str(tmpFileStderr))
# actually do the spawn
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
# catch any error
ret = exitvalmap[e[0]]
if stderr != None:
stderr.write("scons: %s: %s\n" % (cmd, e[1]))
# copy child output from tempfiles to our streams
# and do clean up stuff
if stdout != None and stdoutRedirected == 0:
try:
stdout.write(open( tmpFileStdout, "r" ).read())
os.remove( tmpFileStdout )
except (IOError, OSError):
pass
if stderr != None and stderrRedirected == 0:
try:
stderr.write(open( tmpFileStderr, "r" ).read())
os.remove( tmpFileStderr )
except (IOError, OSError):
pass
return ret
def | (sh, escape, cmd, args, env):
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
ret = exitvalmap[e[0]]
sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
return ret
# Windows does not allow special characters in file names anyway, so
# no need for a complex escape function, we will just quote the arg.
escape = lambda x: '"' + x + '"'
# Get the windows system directory name
def get_system_root():
# A resonable default if we can't read the registry
try:
val = os.environ['SYSTEMROOT']
except KeyError:
val = "C:/WINDOWS"
pass
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except KeyboardInterrupt:
raise
except:
pass
return val
# Get the location of the program files directory
def get_program_files_dir():
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
except SCons.Util.RegError:
val = ''
pass
if val == '':
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
return val
def generate(env):
# Attempt to find cmd.exe (for WinNT/2k/XP) or
# command.com for Win9x
cmd_interp = ''
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'System32\\cmd.exe')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'command.com')
except KeyboardInterrupt:
raise
except:
pass
# For the special case of not having access to the registry, we
# use a temporary path and pathext to attempt to find the command
# interpreter. If we fail, we try to find the interpreter through
# the env's PATH. The problem with that is that it might not
# contain an ENV and a PATH.
if not cmd_interp:
systemroot = r'C:\Windows'
if os.environ.has_key('SYSTEMROOT'):
systemroot = os.environ['SYSTEMROOT']
tmp_path = systemroot + os.pathsep + \
os.path.join(systemroot,'System32')
tmp_pathext = '.com;.exe;.bat;.cmd'
if os.environ.has_key('PATHEXT'):
tmp_pathext = os.environ['PATHEXT']
cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = env.Detect('cmd')
if not cmd_interp:
cmd_interp = env.Detect('command')
if not env.has_key('ENV'):
env['ENV'] = {}
# Import things from the external environment to the construction
# environment's ENV. This is a potential slippery slope, because we
# *don't* want to make builds dependent on the user's environment by
# default. We're doing this for SYSTEMROOT, though, because it's
# needed for anything that uses sockets, and seldom changes. Weigh
# the impact carefully before adding other variables to this list.
import_env = [ 'SYSTEMROOT' ]
for var in import_env:
v = os.environ.get(var)
if v:
env['ENV'][var] = v
env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ]
env['PSPAWN'] = piped_spawn
env['SPAWN'] = spawn
env['SHELL'] = cmd_interp
env['TEMPFILE'] = TempFileMunge
env['MAXLINELENGTH'] = 2048
env['ESCAPE'] = escape
| spawn | identifier_name |
items.service.ts | import { Injectable, OnDestroy } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
export class Item {
constructor(public id: number, public name: string) { }
}
const ITEMS: Item[] = [
new Item(1, 'Sticky notes'),
new Item(2, 'Dry erase markers'),
new Item(3, 'Erasers'),
new Item(4, 'Whiteboard cleaner'),
];
const FETCH_LATENCY = 500;
/** Simulate a data service that retrieves crises from a server */
@Injectable()
export class ItemService implements OnDestroy {
| () { console.log('ItemService instance created.'); }
ngOnDestroy() { console.log('ItemService instance destroyed.'); }
getItems(): Observable<Item[]> {
return of(ITEMS).pipe(delay(FETCH_LATENCY));
}
getItem(id: number | string): Observable<Item> {
const item$ = of(ITEMS.find(item => item.id === +id));
return item$.pipe(delay(FETCH_LATENCY));
}
}
| constructor | identifier_name |
items.service.ts | import { Injectable, OnDestroy } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
export class Item {
constructor(public id: number, public name: string) { }
}
const ITEMS: Item[] = [
new Item(1, 'Sticky notes'),
new Item(2, 'Dry erase markers'),
new Item(3, 'Erasers'),
new Item(4, 'Whiteboard cleaner'),
];
const FETCH_LATENCY = 500; |
constructor() { console.log('ItemService instance created.'); }
ngOnDestroy() { console.log('ItemService instance destroyed.'); }
getItems(): Observable<Item[]> {
return of(ITEMS).pipe(delay(FETCH_LATENCY));
}
getItem(id: number | string): Observable<Item> {
const item$ = of(ITEMS.find(item => item.id === +id));
return item$.pipe(delay(FETCH_LATENCY));
}
} |
/** Simulate a data service that retrieves crises from a server */
@Injectable()
export class ItemService implements OnDestroy { | random_line_split |
group.rs | extern crate kiss3d;
extern crate nalgebra as na;
use na::Vec3;
use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() | {
let mut window = Window::new("Kiss3d: cube");
let mut g1 = window.add_group();
let mut g2 = window.add_group();
g1.append_translation(&Vec3::new(2.0f32, 0.0, 0.0));
g2.append_translation(&Vec3::new(-2.0f32, 0.0, 0.0));
g1.add_cube(1.0, 5.0, 1.0);
g1.add_cube(5.0, 1.0, 1.0);
g2.add_cube(1.0, 5.0, 1.0);
g2.add_cube(1.0, 1.0, 5.0);
g1.set_color(1.0, 0.0, 0.0);
g2.set_color(0.0, 1.0, 0.0);
window.set_light(Light::StickToCamera);
while window.render() {
g1.prepend_to_local_rotation(&Vec3::new(0.0f32, 0.014, 0.0));
g2.prepend_to_local_rotation(&Vec3::new(0.014f32, 0.0, 0.0));
}
} | identifier_body | |
group.rs | use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() {
let mut window = Window::new("Kiss3d: cube");
let mut g1 = window.add_group();
let mut g2 = window.add_group();
g1.append_translation(&Vec3::new(2.0f32, 0.0, 0.0));
g2.append_translation(&Vec3::new(-2.0f32, 0.0, 0.0));
g1.add_cube(1.0, 5.0, 1.0);
g1.add_cube(5.0, 1.0, 1.0);
g2.add_cube(1.0, 5.0, 1.0);
g2.add_cube(1.0, 1.0, 5.0);
g1.set_color(1.0, 0.0, 0.0);
g2.set_color(0.0, 1.0, 0.0);
window.set_light(Light::StickToCamera);
while window.render() {
g1.prepend_to_local_rotation(&Vec3::new(0.0f32, 0.014, 0.0));
g2.prepend_to_local_rotation(&Vec3::new(0.014f32, 0.0, 0.0));
}
} | extern crate kiss3d;
extern crate nalgebra as na;
use na::Vec3; | random_line_split | |
group.rs | extern crate kiss3d;
extern crate nalgebra as na;
use na::Vec3;
use kiss3d::window::Window;
use kiss3d::light::Light;
fn | () {
let mut window = Window::new("Kiss3d: cube");
let mut g1 = window.add_group();
let mut g2 = window.add_group();
g1.append_translation(&Vec3::new(2.0f32, 0.0, 0.0));
g2.append_translation(&Vec3::new(-2.0f32, 0.0, 0.0));
g1.add_cube(1.0, 5.0, 1.0);
g1.add_cube(5.0, 1.0, 1.0);
g2.add_cube(1.0, 5.0, 1.0);
g2.add_cube(1.0, 1.0, 5.0);
g1.set_color(1.0, 0.0, 0.0);
g2.set_color(0.0, 1.0, 0.0);
window.set_light(Light::StickToCamera);
while window.render() {
g1.prepend_to_local_rotation(&Vec3::new(0.0f32, 0.014, 0.0));
g2.prepend_to_local_rotation(&Vec3::new(0.014f32, 0.0, 0.0));
}
}
| main | identifier_name |
springyui.js | /**
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
jQuery.fn.springy = function(params) {
var graph = this.graph = params.graph || new Springy.Graph();
var nodeFont = "16px Verdana, sans-serif";
var edgeFont = "8px Verdana, sans-serif";
var stiffness = params.stiffness || 400.0;
var repulsion = params.repulsion || 400.0;
var damping = params.damping || 0.5;
var minEnergyThreshold = params.minEnergyThreshold || 0.00001;
var nodeSelected = params.nodeSelected || null;
var nodeImages = {};
var edgeLabelsUpright = true;
var canvas = this[0];
var ctx = canvas.getContext("2d");
var layout = this.layout = new Springy.Layout.ForceDirected(graph, stiffness, repulsion, damping, minEnergyThreshold);
// calculate bounding box of graph layout.. with ease-in
var currentBB = layout.getBoundingBox();
var targetBB = {bottomleft: new Springy.Vector(-2, -2), topright: new Springy.Vector(2, 2)};
// auto adjusting bounding box
Springy.requestAnimationFrame(function adjust() {
targetBB = layout.getBoundingBox();
// current gets 20% closer to target every iteration
currentBB = {
bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
.divide(10)),
topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
.divide(10))
};
Springy.requestAnimationFrame(adjust);
});
// convert to/from screen coordinates
var toScreen = function(p) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
return new Springy.Vector(sx, sy);
};
var fromScreen = function(s) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
return new Springy.Vector(px, py);
};
// half-assed drag and drop
var selected = null;
var nearest = null;
var dragged = null;
// jQuery(canvas).click(function(e) {
// var pos = jQuery(this).offset();
// var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
// selected = layout.nearest(p);
// });
jQuery(canvas).mousedown(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = dragged = layout.nearest(p);
if (dragged.node) {
dragged.point.m = 10000.0;
}
renderer.start();
});
// Basic double click handler
jQuery(canvas).dblclick(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
var selected = layout.nearest(p);
var node = selected.node;
if (node && nodeSelected) {
nodeSelected(node);
}
if (node && node.data && node.data.ondoubleclick) {
node.data.ondoubleclick();
}
renderer.start();
});
jQuery(canvas).mousemove(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = layout.nearest(p);
if (dragged !== null && dragged.node !== null) {
dragged.point.p.x = p.x;
dragged.point.p.y = p.y;
}
renderer.start();
});
jQuery(window).bind('mouseup',function(e) {
dragged = null;
});
var getTextWidth = function(node) {
var text = (node.data.label !== undefined) ? node.data.label : node.id;
if (node._width && node._width[text])
return node._width[text];
ctx.save();
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
var width = ctx.measureText(text).width;
ctx.restore();
node._width || (node._width = {});
node._width[text] = width;
return width;
};
var getTextHeight = function(node) {
return 16;
// In a more modular world, this would actually read the font size, but I think leaving it a constant is sufficient for now.
// If you change the font size, I'd adjust this too.
};
var getImageWidth = function(node) {
var width = (node.data.image.width !== undefined) ? node.data.image.width : nodeImages[node.data.image.src].object.width;
return width;
}
var getImageHeight = function(node) {
var height = (node.data.image.height !== undefined) ? node.data.image.height : nodeImages[node.data.image.src].object.height;
return height;
}
Springy.Node.prototype.getHeight = function() {
var height;
if (this.data.image == undefined) {
height = getTextHeight(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
height = getImageHeight(this);
} else {height = 10;}
}
return height;
}
Springy.Node.prototype.getWidth = function() {
var width;
if (this.data.image == undefined) {
width = getTextWidth(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
width = getImageWidth(this);
} else {width = 10;}
}
return width;
}
var renderer = this.renderer = new Springy.Renderer(layout,
function clear() {
ctx.clearRect(0,0,canvas.width,canvas.height);
},
function drawEdge(edge, p1, p2) {
var x1 = toScreen(p1).x;
var y1 = toScreen(p1).y;
var x2 = toScreen(p2).x;
var y2 = toScreen(p2).y;
var direction = new Springy.Vector(x2-x1, y2-y1);
var normal = direction.normal().normalise();
var from = graph.getEdges(edge.source, edge.target);
var to = graph.getEdges(edge.target, edge.source);
var total = from.length + to.length;
// Figure out edge's position in relation to other edges between the same nodes
var n = 0;
for (var i=0; i<from.length; i++) {
if (from[i].id === edge.id) {
n = i;
}
}
//change default to 10.0 to allow text fit between edges
var spacing = 12.0;
// Figure out how far off center the line should be drawn
var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));
var paddingX = 6;
var paddingY = 6;
var s1 = toScreen(p1).add(offset);
var s2 = toScreen(p2).add(offset);
var boxWidth = edge.target.getWidth() + paddingX;
var boxHeight = edge.target.getHeight() + paddingY;
var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);
if (!intersection) |
var stroke = (edge.data.color !== undefined) ? edge.data.color : '#000000';
var arrowWidth;
var arrowLength;
var weight = (edge.data.weight !== undefined) ? edge.data.weight : 1.0;
ctx.lineWidth = Math.max(weight * 2, 0.1);
arrowWidth = 1 + ctx.lineWidth;
arrowLength = 8;
var directional = (edge.data.directional !== undefined) ? edge.data.directional : true;
// line
var lineEnd;
if (directional) {
lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
} else {
lineEnd = s2;
}
ctx.strokeStyle = stroke;
ctx.beginPath();
ctx.moveTo(s1.x, s1.y);
ctx.lineTo(lineEnd.x, lineEnd.y);
ctx.stroke();
// arrow
if (directional) {
ctx.save();
ctx.fillStyle = stroke;
ctx.translate(intersection.x, intersection.y);
ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
ctx.beginPath();
ctx.moveTo(-arrowLength, arrowWidth);
ctx.lineTo(0, 0);
ctx.lineTo(-arrowLength, -arrowWidth);
ctx.lineTo(-arrowLength * 0.8, -0);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// label
if (edge.data.label !== undefined) {
text = edge.data.label
ctx.save();
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.font = (edge.data.font !== undefined) ? edge.data.font : edgeFont;
ctx.fillStyle = stroke;
var angle = Math.atan2(s2.y - s1.y, s2.x - s1.x);
var displacement = -8;
if (edgeLabelsUpright && (angle > Math.PI/2 || angle < -Math.PI/2)) {
displacement = 8;
angle += Math.PI;
}
var textPos = s1.add(s2).divide(2).add(normal.multiply(displacement));
ctx.translate(textPos.x, textPos.y);
ctx.rotate(angle);
ctx.fillText(text, 0,-2);
ctx.restore();
}
},
function drawNode(node, p) {
var s = toScreen(p);
ctx.save();
// Pulled out the padding aspect sso that the size functions could be used in multiple places
// These should probably be settable by the user (and scoped higher) but this suffices for now
var paddingX = 6;
var paddingY = 6;
var contentWidth = node.getWidth();
var contentHeight = node.getHeight();
var boxWidth = contentWidth + paddingX;
var boxHeight = contentHeight + paddingY;
// clear background
ctx.clearRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
// fill background
if (selected !== null && selected.node !== null && selected.node.id === node.id) {
ctx.fillStyle = node.data.selectedBackgroundColor || params.selectedBackgroundColor || "#FFFFE0";
} else {
ctx.fillStyle = node.data.backgroundColor || params.backgroundColor || "#FFFFFF";
}
ctx.fillRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
if (node.data.image == undefined) {
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
ctx.fillStyle = (node.data.color !== undefined) ? node.data.color : "#000000";
var text = (node.data.label !== undefined) ? node.data.label : node.id;
ctx.fillText(text, s.x - contentWidth/2, s.y - contentHeight/2);
} else {
// Currently we just ignore any labels if the image object is set. One might want to extend this logic to allow for both, or other composite nodes.
var src = node.data.image.src; // There should probably be a sanity check here too, but un-src-ed images aren't exaclty a disaster.
if (src in nodeImages) {
if (nodeImages[src].loaded) {
// Our image is loaded, so it's safe to draw
ctx.drawImage(nodeImages[src].object, s.x - contentWidth/2, s.y - contentHeight/2, contentWidth, contentHeight);
}
}else{
// First time seeing an image with this src address, so add it to our set of image objects
// Note: we index images by their src to avoid making too many duplicates
nodeImages[src] = {};
var img = new Image();
nodeImages[src].object = img;
img.addEventListener("load", function () {
// HTMLImageElement objects are very finicky about being used before they are loaded, so we set a flag when it is done
nodeImages[src].loaded = true;
});
img.src = src;
}
}
ctx.restore();
}
);
renderer.start();
// helpers for figuring out where to draw arrows
function intersect_line_line(p1, p2, p3, p4) {
var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
// lines are parallel
if (denom === 0) {
return false;
}
var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return false;
}
return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
}
function intersect_line_box(p1, p2, p3, w, h) {
var tl = {x: p3.x, y: p3.y};
var tr = {x: p3.x + w, y: p3.y};
var bl = {x: p3.x, y: p3.y + h};
var br = {x: p3.x + w, y: p3.y + h};
var result;
if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
return false;
}
return this;
}
})(); | {
intersection = s2;
} | conditional_block |
springyui.js | /**
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
jQuery.fn.springy = function(params) {
var graph = this.graph = params.graph || new Springy.Graph();
var nodeFont = "16px Verdana, sans-serif";
var edgeFont = "8px Verdana, sans-serif";
var stiffness = params.stiffness || 400.0;
var repulsion = params.repulsion || 400.0;
var damping = params.damping || 0.5;
var minEnergyThreshold = params.minEnergyThreshold || 0.00001;
var nodeSelected = params.nodeSelected || null;
var nodeImages = {};
var edgeLabelsUpright = true;
var canvas = this[0];
var ctx = canvas.getContext("2d");
var layout = this.layout = new Springy.Layout.ForceDirected(graph, stiffness, repulsion, damping, minEnergyThreshold);
// calculate bounding box of graph layout.. with ease-in
var currentBB = layout.getBoundingBox();
var targetBB = {bottomleft: new Springy.Vector(-2, -2), topright: new Springy.Vector(2, 2)};
// auto adjusting bounding box
Springy.requestAnimationFrame(function adjust() {
targetBB = layout.getBoundingBox();
// current gets 20% closer to target every iteration
currentBB = {
bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
.divide(10)),
topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
.divide(10))
};
Springy.requestAnimationFrame(adjust);
});
// convert to/from screen coordinates
var toScreen = function(p) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
return new Springy.Vector(sx, sy);
};
var fromScreen = function(s) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
return new Springy.Vector(px, py);
};
// half-assed drag and drop
var selected = null;
var nearest = null;
var dragged = null;
// jQuery(canvas).click(function(e) {
// var pos = jQuery(this).offset();
// var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
// selected = layout.nearest(p);
// });
jQuery(canvas).mousedown(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = dragged = layout.nearest(p);
if (dragged.node) {
dragged.point.m = 10000.0;
}
renderer.start();
});
// Basic double click handler
jQuery(canvas).dblclick(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
var selected = layout.nearest(p);
var node = selected.node;
if (node && nodeSelected) {
nodeSelected(node);
}
if (node && node.data && node.data.ondoubleclick) {
node.data.ondoubleclick();
}
renderer.start();
});
jQuery(canvas).mousemove(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = layout.nearest(p);
if (dragged !== null && dragged.node !== null) {
dragged.point.p.x = p.x;
dragged.point.p.y = p.y;
}
renderer.start();
});
jQuery(window).bind('mouseup',function(e) {
dragged = null;
});
var getTextWidth = function(node) {
var text = (node.data.label !== undefined) ? node.data.label : node.id;
if (node._width && node._width[text])
return node._width[text];
ctx.save();
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
var width = ctx.measureText(text).width;
ctx.restore();
node._width || (node._width = {});
node._width[text] = width;
return width;
};
var getTextHeight = function(node) {
return 16;
// In a more modular world, this would actually read the font size, but I think leaving it a constant is sufficient for now.
// If you change the font size, I'd adjust this too.
};
var getImageWidth = function(node) {
var width = (node.data.image.width !== undefined) ? node.data.image.width : nodeImages[node.data.image.src].object.width;
return width;
}
var getImageHeight = function(node) {
var height = (node.data.image.height !== undefined) ? node.data.image.height : nodeImages[node.data.image.src].object.height;
return height;
}
Springy.Node.prototype.getHeight = function() {
var height;
if (this.data.image == undefined) {
height = getTextHeight(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
height = getImageHeight(this);
} else {height = 10;}
}
return height;
}
Springy.Node.prototype.getWidth = function() {
var width;
if (this.data.image == undefined) {
width = getTextWidth(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
width = getImageWidth(this);
} else {width = 10;}
}
return width;
}
var renderer = this.renderer = new Springy.Renderer(layout,
function clear() {
ctx.clearRect(0,0,canvas.width,canvas.height);
},
function drawEdge(edge, p1, p2) {
var x1 = toScreen(p1).x;
var y1 = toScreen(p1).y;
var x2 = toScreen(p2).x;
var y2 = toScreen(p2).y;
var direction = new Springy.Vector(x2-x1, y2-y1);
var normal = direction.normal().normalise();
var from = graph.getEdges(edge.source, edge.target);
var to = graph.getEdges(edge.target, edge.source);
var total = from.length + to.length;
// Figure out edge's position in relation to other edges between the same nodes
var n = 0;
for (var i=0; i<from.length; i++) {
if (from[i].id === edge.id) {
n = i;
}
}
//change default to 10.0 to allow text fit between edges
var spacing = 12.0;
// Figure out how far off center the line should be drawn
var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));
var paddingX = 6;
var paddingY = 6;
var s1 = toScreen(p1).add(offset);
var s2 = toScreen(p2).add(offset);
var boxWidth = edge.target.getWidth() + paddingX;
var boxHeight = edge.target.getHeight() + paddingY;
var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);
if (!intersection) {
intersection = s2;
}
var stroke = (edge.data.color !== undefined) ? edge.data.color : '#000000';
var arrowWidth;
var arrowLength;
var weight = (edge.data.weight !== undefined) ? edge.data.weight : 1.0;
ctx.lineWidth = Math.max(weight * 2, 0.1);
arrowWidth = 1 + ctx.lineWidth;
arrowLength = 8;
var directional = (edge.data.directional !== undefined) ? edge.data.directional : true;
// line
var lineEnd;
if (directional) {
lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
} else {
lineEnd = s2;
}
ctx.strokeStyle = stroke;
ctx.beginPath();
ctx.moveTo(s1.x, s1.y);
ctx.lineTo(lineEnd.x, lineEnd.y);
ctx.stroke();
// arrow
if (directional) {
ctx.save(); | ctx.translate(intersection.x, intersection.y);
ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
ctx.beginPath();
ctx.moveTo(-arrowLength, arrowWidth);
ctx.lineTo(0, 0);
ctx.lineTo(-arrowLength, -arrowWidth);
ctx.lineTo(-arrowLength * 0.8, -0);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// label
if (edge.data.label !== undefined) {
text = edge.data.label
ctx.save();
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.font = (edge.data.font !== undefined) ? edge.data.font : edgeFont;
ctx.fillStyle = stroke;
var angle = Math.atan2(s2.y - s1.y, s2.x - s1.x);
var displacement = -8;
if (edgeLabelsUpright && (angle > Math.PI/2 || angle < -Math.PI/2)) {
displacement = 8;
angle += Math.PI;
}
var textPos = s1.add(s2).divide(2).add(normal.multiply(displacement));
ctx.translate(textPos.x, textPos.y);
ctx.rotate(angle);
ctx.fillText(text, 0,-2);
ctx.restore();
}
},
function drawNode(node, p) {
var s = toScreen(p);
ctx.save();
// Pulled out the padding aspect sso that the size functions could be used in multiple places
// These should probably be settable by the user (and scoped higher) but this suffices for now
var paddingX = 6;
var paddingY = 6;
var contentWidth = node.getWidth();
var contentHeight = node.getHeight();
var boxWidth = contentWidth + paddingX;
var boxHeight = contentHeight + paddingY;
// clear background
ctx.clearRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
// fill background
if (selected !== null && selected.node !== null && selected.node.id === node.id) {
ctx.fillStyle = node.data.selectedBackgroundColor || params.selectedBackgroundColor || "#FFFFE0";
} else {
ctx.fillStyle = node.data.backgroundColor || params.backgroundColor || "#FFFFFF";
}
ctx.fillRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
if (node.data.image == undefined) {
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
ctx.fillStyle = (node.data.color !== undefined) ? node.data.color : "#000000";
var text = (node.data.label !== undefined) ? node.data.label : node.id;
ctx.fillText(text, s.x - contentWidth/2, s.y - contentHeight/2);
} else {
// Currently we just ignore any labels if the image object is set. One might want to extend this logic to allow for both, or other composite nodes.
var src = node.data.image.src; // There should probably be a sanity check here too, but un-src-ed images aren't exaclty a disaster.
if (src in nodeImages) {
if (nodeImages[src].loaded) {
// Our image is loaded, so it's safe to draw
ctx.drawImage(nodeImages[src].object, s.x - contentWidth/2, s.y - contentHeight/2, contentWidth, contentHeight);
}
}else{
// First time seeing an image with this src address, so add it to our set of image objects
// Note: we index images by their src to avoid making too many duplicates
nodeImages[src] = {};
var img = new Image();
nodeImages[src].object = img;
img.addEventListener("load", function () {
// HTMLImageElement objects are very finicky about being used before they are loaded, so we set a flag when it is done
nodeImages[src].loaded = true;
});
img.src = src;
}
}
ctx.restore();
}
);
renderer.start();
// helpers for figuring out where to draw arrows
function intersect_line_line(p1, p2, p3, p4) {
var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
// lines are parallel
if (denom === 0) {
return false;
}
var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return false;
}
return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
}
function intersect_line_box(p1, p2, p3, w, h) {
var tl = {x: p3.x, y: p3.y};
var tr = {x: p3.x + w, y: p3.y};
var bl = {x: p3.x, y: p3.y + h};
var br = {x: p3.x + w, y: p3.y + h};
var result;
if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
return false;
}
return this;
}
})(); | ctx.fillStyle = stroke; | random_line_split |
springyui.js | /**
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
jQuery.fn.springy = function(params) {
var graph = this.graph = params.graph || new Springy.Graph();
var nodeFont = "16px Verdana, sans-serif";
var edgeFont = "8px Verdana, sans-serif";
var stiffness = params.stiffness || 400.0;
var repulsion = params.repulsion || 400.0;
var damping = params.damping || 0.5;
var minEnergyThreshold = params.minEnergyThreshold || 0.00001;
var nodeSelected = params.nodeSelected || null;
var nodeImages = {};
var edgeLabelsUpright = true;
var canvas = this[0];
var ctx = canvas.getContext("2d");
var layout = this.layout = new Springy.Layout.ForceDirected(graph, stiffness, repulsion, damping, minEnergyThreshold);
// calculate bounding box of graph layout.. with ease-in
var currentBB = layout.getBoundingBox();
var targetBB = {bottomleft: new Springy.Vector(-2, -2), topright: new Springy.Vector(2, 2)};
// auto adjusting bounding box
Springy.requestAnimationFrame(function adjust() {
targetBB = layout.getBoundingBox();
// current gets 20% closer to target every iteration
currentBB = {
bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
.divide(10)),
topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
.divide(10))
};
Springy.requestAnimationFrame(adjust);
});
// convert to/from screen coordinates
var toScreen = function(p) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
return new Springy.Vector(sx, sy);
};
var fromScreen = function(s) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
return new Springy.Vector(px, py);
};
// half-assed drag and drop
var selected = null;
var nearest = null;
var dragged = null;
// jQuery(canvas).click(function(e) {
// var pos = jQuery(this).offset();
// var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
// selected = layout.nearest(p);
// });
jQuery(canvas).mousedown(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = dragged = layout.nearest(p);
if (dragged.node) {
dragged.point.m = 10000.0;
}
renderer.start();
});
// Basic double click handler
jQuery(canvas).dblclick(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
var selected = layout.nearest(p);
var node = selected.node;
if (node && nodeSelected) {
nodeSelected(node);
}
if (node && node.data && node.data.ondoubleclick) {
node.data.ondoubleclick();
}
renderer.start();
});
jQuery(canvas).mousemove(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = layout.nearest(p);
if (dragged !== null && dragged.node !== null) {
dragged.point.p.x = p.x;
dragged.point.p.y = p.y;
}
renderer.start();
});
jQuery(window).bind('mouseup',function(e) {
dragged = null;
});
var getTextWidth = function(node) {
var text = (node.data.label !== undefined) ? node.data.label : node.id;
if (node._width && node._width[text])
return node._width[text];
ctx.save();
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
var width = ctx.measureText(text).width;
ctx.restore();
node._width || (node._width = {});
node._width[text] = width;
return width;
};
var getTextHeight = function(node) {
return 16;
// In a more modular world, this would actually read the font size, but I think leaving it a constant is sufficient for now.
// If you change the font size, I'd adjust this too.
};
var getImageWidth = function(node) {
var width = (node.data.image.width !== undefined) ? node.data.image.width : nodeImages[node.data.image.src].object.width;
return width;
}
var getImageHeight = function(node) {
var height = (node.data.image.height !== undefined) ? node.data.image.height : nodeImages[node.data.image.src].object.height;
return height;
}
Springy.Node.prototype.getHeight = function() {
var height;
if (this.data.image == undefined) {
height = getTextHeight(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
height = getImageHeight(this);
} else {height = 10;}
}
return height;
}
Springy.Node.prototype.getWidth = function() {
var width;
if (this.data.image == undefined) {
width = getTextWidth(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
width = getImageWidth(this);
} else {width = 10;}
}
return width;
}
var renderer = this.renderer = new Springy.Renderer(layout,
function clear() {
ctx.clearRect(0,0,canvas.width,canvas.height);
},
function drawEdge(edge, p1, p2) {
var x1 = toScreen(p1).x;
var y1 = toScreen(p1).y;
var x2 = toScreen(p2).x;
var y2 = toScreen(p2).y;
var direction = new Springy.Vector(x2-x1, y2-y1);
var normal = direction.normal().normalise();
var from = graph.getEdges(edge.source, edge.target);
var to = graph.getEdges(edge.target, edge.source);
var total = from.length + to.length;
// Figure out edge's position in relation to other edges between the same nodes
var n = 0;
for (var i=0; i<from.length; i++) {
if (from[i].id === edge.id) {
n = i;
}
}
//change default to 10.0 to allow text fit between edges
var spacing = 12.0;
// Figure out how far off center the line should be drawn
var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));
var paddingX = 6;
var paddingY = 6;
var s1 = toScreen(p1).add(offset);
var s2 = toScreen(p2).add(offset);
var boxWidth = edge.target.getWidth() + paddingX;
var boxHeight = edge.target.getHeight() + paddingY;
var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);
if (!intersection) {
intersection = s2;
}
var stroke = (edge.data.color !== undefined) ? edge.data.color : '#000000';
var arrowWidth;
var arrowLength;
var weight = (edge.data.weight !== undefined) ? edge.data.weight : 1.0;
ctx.lineWidth = Math.max(weight * 2, 0.1);
arrowWidth = 1 + ctx.lineWidth;
arrowLength = 8;
var directional = (edge.data.directional !== undefined) ? edge.data.directional : true;
// line
var lineEnd;
if (directional) {
lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
} else {
lineEnd = s2;
}
ctx.strokeStyle = stroke;
ctx.beginPath();
ctx.moveTo(s1.x, s1.y);
ctx.lineTo(lineEnd.x, lineEnd.y);
ctx.stroke();
// arrow
if (directional) {
ctx.save();
ctx.fillStyle = stroke;
ctx.translate(intersection.x, intersection.y);
ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
ctx.beginPath();
ctx.moveTo(-arrowLength, arrowWidth);
ctx.lineTo(0, 0);
ctx.lineTo(-arrowLength, -arrowWidth);
ctx.lineTo(-arrowLength * 0.8, -0);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// label
if (edge.data.label !== undefined) {
text = edge.data.label
ctx.save();
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.font = (edge.data.font !== undefined) ? edge.data.font : edgeFont;
ctx.fillStyle = stroke;
var angle = Math.atan2(s2.y - s1.y, s2.x - s1.x);
var displacement = -8;
if (edgeLabelsUpright && (angle > Math.PI/2 || angle < -Math.PI/2)) {
displacement = 8;
angle += Math.PI;
}
var textPos = s1.add(s2).divide(2).add(normal.multiply(displacement));
ctx.translate(textPos.x, textPos.y);
ctx.rotate(angle);
ctx.fillText(text, 0,-2);
ctx.restore();
}
},
function drawNode(node, p) {
var s = toScreen(p);
ctx.save();
// Pulled out the padding aspect sso that the size functions could be used in multiple places
// These should probably be settable by the user (and scoped higher) but this suffices for now
var paddingX = 6;
var paddingY = 6;
var contentWidth = node.getWidth();
var contentHeight = node.getHeight();
var boxWidth = contentWidth + paddingX;
var boxHeight = contentHeight + paddingY;
// clear background
ctx.clearRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
// fill background
if (selected !== null && selected.node !== null && selected.node.id === node.id) {
ctx.fillStyle = node.data.selectedBackgroundColor || params.selectedBackgroundColor || "#FFFFE0";
} else {
ctx.fillStyle = node.data.backgroundColor || params.backgroundColor || "#FFFFFF";
}
ctx.fillRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
if (node.data.image == undefined) {
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
ctx.fillStyle = (node.data.color !== undefined) ? node.data.color : "#000000";
var text = (node.data.label !== undefined) ? node.data.label : node.id;
ctx.fillText(text, s.x - contentWidth/2, s.y - contentHeight/2);
} else {
// Currently we just ignore any labels if the image object is set. One might want to extend this logic to allow for both, or other composite nodes.
var src = node.data.image.src; // There should probably be a sanity check here too, but un-src-ed images aren't exaclty a disaster.
if (src in nodeImages) {
if (nodeImages[src].loaded) {
// Our image is loaded, so it's safe to draw
ctx.drawImage(nodeImages[src].object, s.x - contentWidth/2, s.y - contentHeight/2, contentWidth, contentHeight);
}
}else{
// First time seeing an image with this src address, so add it to our set of image objects
// Note: we index images by their src to avoid making too many duplicates
nodeImages[src] = {};
var img = new Image();
nodeImages[src].object = img;
img.addEventListener("load", function () {
// HTMLImageElement objects are very finicky about being used before they are loaded, so we set a flag when it is done
nodeImages[src].loaded = true;
});
img.src = src;
}
}
ctx.restore();
}
);
renderer.start();
// helpers for figuring out where to draw arrows
function intersect_line_line(p1, p2, p3, p4) {
var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
// lines are parallel
if (denom === 0) {
return false;
}
var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return false;
}
return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
}
function intersect_line_box(p1, p2, p3, w, h) |
return this;
}
})(); | {
var tl = {x: p3.x, y: p3.y};
var tr = {x: p3.x + w, y: p3.y};
var bl = {x: p3.x, y: p3.y + h};
var br = {x: p3.x + w, y: p3.y + h};
var result;
if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
return false;
} | identifier_body |
springyui.js | /**
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
jQuery.fn.springy = function(params) {
var graph = this.graph = params.graph || new Springy.Graph();
var nodeFont = "16px Verdana, sans-serif";
var edgeFont = "8px Verdana, sans-serif";
var stiffness = params.stiffness || 400.0;
var repulsion = params.repulsion || 400.0;
var damping = params.damping || 0.5;
var minEnergyThreshold = params.minEnergyThreshold || 0.00001;
var nodeSelected = params.nodeSelected || null;
var nodeImages = {};
var edgeLabelsUpright = true;
var canvas = this[0];
var ctx = canvas.getContext("2d");
var layout = this.layout = new Springy.Layout.ForceDirected(graph, stiffness, repulsion, damping, minEnergyThreshold);
// calculate bounding box of graph layout.. with ease-in
var currentBB = layout.getBoundingBox();
var targetBB = {bottomleft: new Springy.Vector(-2, -2), topright: new Springy.Vector(2, 2)};
// auto adjusting bounding box
Springy.requestAnimationFrame(function adjust() {
targetBB = layout.getBoundingBox();
// current gets 20% closer to target every iteration
currentBB = {
bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
.divide(10)),
topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
.divide(10))
};
Springy.requestAnimationFrame(adjust);
});
// convert to/from screen coordinates
var toScreen = function(p) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
return new Springy.Vector(sx, sy);
};
var fromScreen = function(s) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
return new Springy.Vector(px, py);
};
// half-assed drag and drop
var selected = null;
var nearest = null;
var dragged = null;
// jQuery(canvas).click(function(e) {
// var pos = jQuery(this).offset();
// var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
// selected = layout.nearest(p);
// });
jQuery(canvas).mousedown(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = dragged = layout.nearest(p);
if (dragged.node) {
dragged.point.m = 10000.0;
}
renderer.start();
});
// Basic double click handler
jQuery(canvas).dblclick(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
var selected = layout.nearest(p);
var node = selected.node;
if (node && nodeSelected) {
nodeSelected(node);
}
if (node && node.data && node.data.ondoubleclick) {
node.data.ondoubleclick();
}
renderer.start();
});
jQuery(canvas).mousemove(function(e) {
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = layout.nearest(p);
if (dragged !== null && dragged.node !== null) {
dragged.point.p.x = p.x;
dragged.point.p.y = p.y;
}
renderer.start();
});
jQuery(window).bind('mouseup',function(e) {
dragged = null;
});
var getTextWidth = function(node) {
var text = (node.data.label !== undefined) ? node.data.label : node.id;
if (node._width && node._width[text])
return node._width[text];
ctx.save();
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
var width = ctx.measureText(text).width;
ctx.restore();
node._width || (node._width = {});
node._width[text] = width;
return width;
};
var getTextHeight = function(node) {
return 16;
// In a more modular world, this would actually read the font size, but I think leaving it a constant is sufficient for now.
// If you change the font size, I'd adjust this too.
};
var getImageWidth = function(node) {
var width = (node.data.image.width !== undefined) ? node.data.image.width : nodeImages[node.data.image.src].object.width;
return width;
}
var getImageHeight = function(node) {
var height = (node.data.image.height !== undefined) ? node.data.image.height : nodeImages[node.data.image.src].object.height;
return height;
}
Springy.Node.prototype.getHeight = function() {
var height;
if (this.data.image == undefined) {
height = getTextHeight(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
height = getImageHeight(this);
} else {height = 10;}
}
return height;
}
Springy.Node.prototype.getWidth = function() {
var width;
if (this.data.image == undefined) {
width = getTextWidth(this);
} else {
if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
width = getImageWidth(this);
} else {width = 10;}
}
return width;
}
var renderer = this.renderer = new Springy.Renderer(layout,
function clear() {
ctx.clearRect(0,0,canvas.width,canvas.height);
},
function drawEdge(edge, p1, p2) {
var x1 = toScreen(p1).x;
var y1 = toScreen(p1).y;
var x2 = toScreen(p2).x;
var y2 = toScreen(p2).y;
var direction = new Springy.Vector(x2-x1, y2-y1);
var normal = direction.normal().normalise();
var from = graph.getEdges(edge.source, edge.target);
var to = graph.getEdges(edge.target, edge.source);
var total = from.length + to.length;
// Figure out edge's position in relation to other edges between the same nodes
var n = 0;
for (var i=0; i<from.length; i++) {
if (from[i].id === edge.id) {
n = i;
}
}
//change default to 10.0 to allow text fit between edges
var spacing = 12.0;
// Figure out how far off center the line should be drawn
var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));
var paddingX = 6;
var paddingY = 6;
var s1 = toScreen(p1).add(offset);
var s2 = toScreen(p2).add(offset);
var boxWidth = edge.target.getWidth() + paddingX;
var boxHeight = edge.target.getHeight() + paddingY;
var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);
if (!intersection) {
intersection = s2;
}
var stroke = (edge.data.color !== undefined) ? edge.data.color : '#000000';
var arrowWidth;
var arrowLength;
var weight = (edge.data.weight !== undefined) ? edge.data.weight : 1.0;
ctx.lineWidth = Math.max(weight * 2, 0.1);
arrowWidth = 1 + ctx.lineWidth;
arrowLength = 8;
var directional = (edge.data.directional !== undefined) ? edge.data.directional : true;
// line
var lineEnd;
if (directional) {
lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
} else {
lineEnd = s2;
}
ctx.strokeStyle = stroke;
ctx.beginPath();
ctx.moveTo(s1.x, s1.y);
ctx.lineTo(lineEnd.x, lineEnd.y);
ctx.stroke();
// arrow
if (directional) {
ctx.save();
ctx.fillStyle = stroke;
ctx.translate(intersection.x, intersection.y);
ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
ctx.beginPath();
ctx.moveTo(-arrowLength, arrowWidth);
ctx.lineTo(0, 0);
ctx.lineTo(-arrowLength, -arrowWidth);
ctx.lineTo(-arrowLength * 0.8, -0);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// label
if (edge.data.label !== undefined) {
text = edge.data.label
ctx.save();
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.font = (edge.data.font !== undefined) ? edge.data.font : edgeFont;
ctx.fillStyle = stroke;
var angle = Math.atan2(s2.y - s1.y, s2.x - s1.x);
var displacement = -8;
if (edgeLabelsUpright && (angle > Math.PI/2 || angle < -Math.PI/2)) {
displacement = 8;
angle += Math.PI;
}
var textPos = s1.add(s2).divide(2).add(normal.multiply(displacement));
ctx.translate(textPos.x, textPos.y);
ctx.rotate(angle);
ctx.fillText(text, 0,-2);
ctx.restore();
}
},
function drawNode(node, p) {
var s = toScreen(p);
ctx.save();
// Pulled out the padding aspect sso that the size functions could be used in multiple places
// These should probably be settable by the user (and scoped higher) but this suffices for now
var paddingX = 6;
var paddingY = 6;
var contentWidth = node.getWidth();
var contentHeight = node.getHeight();
var boxWidth = contentWidth + paddingX;
var boxHeight = contentHeight + paddingY;
// clear background
ctx.clearRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
// fill background
if (selected !== null && selected.node !== null && selected.node.id === node.id) {
ctx.fillStyle = node.data.selectedBackgroundColor || params.selectedBackgroundColor || "#FFFFE0";
} else {
ctx.fillStyle = node.data.backgroundColor || params.backgroundColor || "#FFFFFF";
}
ctx.fillRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
if (node.data.image == undefined) {
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
ctx.fillStyle = (node.data.color !== undefined) ? node.data.color : "#000000";
var text = (node.data.label !== undefined) ? node.data.label : node.id;
ctx.fillText(text, s.x - contentWidth/2, s.y - contentHeight/2);
} else {
// Currently we just ignore any labels if the image object is set. One might want to extend this logic to allow for both, or other composite nodes.
var src = node.data.image.src; // There should probably be a sanity check here too, but un-src-ed images aren't exaclty a disaster.
if (src in nodeImages) {
if (nodeImages[src].loaded) {
// Our image is loaded, so it's safe to draw
ctx.drawImage(nodeImages[src].object, s.x - contentWidth/2, s.y - contentHeight/2, contentWidth, contentHeight);
}
}else{
// First time seeing an image with this src address, so add it to our set of image objects
// Note: we index images by their src to avoid making too many duplicates
nodeImages[src] = {};
var img = new Image();
nodeImages[src].object = img;
img.addEventListener("load", function () {
// HTMLImageElement objects are very finicky about being used before they are loaded, so we set a flag when it is done
nodeImages[src].loaded = true;
});
img.src = src;
}
}
ctx.restore();
}
);
renderer.start();
// helpers for figuring out where to draw arrows
function | (p1, p2, p3, p4) {
var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
// lines are parallel
if (denom === 0) {
return false;
}
var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return false;
}
return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
}
function intersect_line_box(p1, p2, p3, w, h) {
var tl = {x: p3.x, y: p3.y};
var tr = {x: p3.x + w, y: p3.y};
var bl = {x: p3.x, y: p3.y + h};
var br = {x: p3.x + w, y: p3.y + h};
var result;
if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
return false;
}
return this;
}
})(); | intersect_line_line | identifier_name |
record_backend.rs | extern crate chrono;
extern crate mysql;
use self::chrono::UTC;
use self::chrono::offset::TimeZone;
use self::mysql::conn::MyOpts;
use self::mysql::conn::pool::MyPool;
use self::mysql::error::MyResult;
use self::mysql::value::from_row;
use self::mysql::value::Value;
use std::clone::Clone;
use std::default::Default;
use worker::Record;
pub trait RecordRepository {
fn store (&self, record: Record) -> Result<(), RecordRepositoryError>;
fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError>;
fn fetch_limit (&self, size: u32, offset: u32) -> Result<(Vec<Record>), RecordRepositoryError>;
}
#[derive(Debug)]
pub enum RecordRepositoryError {
CannotStoreRecord,
CannotFetchRecord,
CannotDenormalizeRecord,
RecordNotFound
}
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct MysqlConfig {
address: String,
username: String,
password: String,
database: String
}
impl MysqlConfig {
pub fn to_connection (&self) -> MysqlRepository {
let opts = MyOpts {
tcp_addr: Some(self.address.clone()),
user: Some(self.username.clone()),
pass: Some(self.password.clone()),
db_name: Some(self.database.to_string()),
..Default::default()
};
MysqlRepository::new(MyPool::new(opts).unwrap())
}
}
#[derive(Clone, Debug)]
pub struct MysqlRepository {
pool: MyPool
}
impl MysqlRepository {
pub fn new (pool: MyPool) -> MysqlRepository {
MysqlRepository { pool: pool }
}
fn row_to_record (&self, row: MyResult<Vec<Value>>) -> Record {
let (id, command, cwd, status, stderr, stdout, started_at_col, finished_at_col) = from_row::<(String, String, String, i32, String, String, String, String)>(row.unwrap());
let started_at = UTC.datetime_from_str(&started_at_col, "%Y-%m-%d %H:%M:%S").unwrap();
let finished_at = UTC.datetime_from_str(&finished_at_col, "%Y-%m-%d %H:%M:%S").unwrap();
let optimized_uuid = MysqlOptimizedUuid { uuid: id.to_string() };
Record {
id: optimized_uuid.to_uuid(),
command: command,
cwd: cwd,
status: status,
stderr: stderr,
stdout: stdout, | finished_at: finished_at
}
}
}
#[derive(Clone, Debug)]
pub struct MysqlOptimizedUuid {
uuid: String
}
impl MysqlOptimizedUuid {
pub fn from_uuid (uuid: String) -> MysqlOptimizedUuid {
// the optimized way https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/
let mut ordered_uuid = uuid[14..18].to_string();
ordered_uuid.push_str(&uuid[9..13]);
ordered_uuid.push_str(&uuid[0..8]);
ordered_uuid.push_str(&uuid[19..23]);
ordered_uuid.push_str(&uuid[24..]);
MysqlOptimizedUuid { uuid: ordered_uuid }
}
pub fn to_uuid (&self) -> String {
let mut uuid = self.uuid[8..16].to_string();
uuid.push_str("-");
uuid.push_str(&self.uuid[4..8]);
uuid.push_str("-");
uuid.push_str(&self.uuid[0..4]);
uuid.push_str("-");
uuid.push_str(&self.uuid[16..20]);
uuid.push_str("-");
uuid.push_str(&self.uuid[20..]);
uuid
}
}
impl RecordRepository for MysqlRepository {
fn store (&self, record: Record) -> Result<(), RecordRepositoryError> {
let uuid_optimized = MysqlOptimizedUuid::from_uuid(record.id.clone());
let query = r"INSERT INTO results (id, command, cwd, status, stderr, stdout, started_at, finished_at) VALUES (UNHEX(?), ?, ?, ?, ?, ?, ?, ?)";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotStoreRecord)
};
let result = match stmt.execute(
(uuid_optimized.clone().uuid, record.command, record.cwd, record.status, record.stderr,
record.stdout, record.started_at.format("%Y-%m-%d %H:%M:%S").to_string(), record.finished_at.format("%Y-%m-%d %H:%M:%S").to_string()
)
) {
Ok(_) => Ok(()),
Err(err) => {
error!("[{:?}] error storing in mysql {:?}", uuid_optimized.clone().uuid, err);
return Err(RecordRepositoryError::CannotStoreRecord);
}
};
result
}
fn fetch_limit (&self, size: u32, limit: u32) -> Result<(Vec<Record>), RecordRepositoryError> {
let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char) AS finished_at FROM results ORDER BY started_at DESC LIMIT ? OFFSET ?";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotFetchRecord)
};
let results: Result<(Vec<Record>), RecordRepositoryError> = match stmt
.execute((size, limit))
.map(|result| {
result.map(|row| {
self.row_to_record(row)
}).collect()
})
{
Ok(records) => Ok(records),
Err(err) => {
error!("error fetching from mysql {:?}", err);
return Err(RecordRepositoryError::CannotDenormalizeRecord)
}
};
results
}
fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError> {
let uuid_optimized = MysqlOptimizedUuid::from_uuid(id.clone());
let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char) AS finished_at FROM results WHERE HEX(id) = ?";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotFetchRecord)
};
let results: Result<(Vec<Record>), RecordRepositoryError> = match stmt
.execute((uuid_optimized.uuid, ))
.map(|result| {
result.map(|row| {
self.row_to_record(row)
}).collect()
})
{
Ok(records) => Ok(records),
Err(err) => {
error!("error fetching from mysql {:?}", err);
return Err(RecordRepositoryError::CannotDenormalizeRecord)
}
};
let records: Vec<Record> = results.unwrap();
let result: Result<(Record), RecordRepositoryError> = match records.len() {
1 => {
Ok(records[0].clone())
},
_ => return Err(RecordRepositoryError::RecordNotFound)
};
result
}
}
#[cfg(test)]
mod tests {
use super::MysqlOptimizedUuid;
#[test]
fn optimized_uuid() {
let uuid = String::from("58e0a7d7-eebc-11d8-9669-0800200c9a66");
let optimized_uuid = MysqlOptimizedUuid::from_uuid(uuid);
assert_eq!("11d8eebc58e0a7d796690800200c9a66", optimized_uuid.uuid);
assert_eq!("58e0a7d7-eebc-11d8-9669-0800200c9a66", optimized_uuid.to_uuid());
}
} | started_at: started_at, | random_line_split |
record_backend.rs | extern crate chrono;
extern crate mysql;
use self::chrono::UTC;
use self::chrono::offset::TimeZone;
use self::mysql::conn::MyOpts;
use self::mysql::conn::pool::MyPool;
use self::mysql::error::MyResult;
use self::mysql::value::from_row;
use self::mysql::value::Value;
use std::clone::Clone;
use std::default::Default;
use worker::Record;
pub trait RecordRepository {
fn store (&self, record: Record) -> Result<(), RecordRepositoryError>;
fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError>;
fn fetch_limit (&self, size: u32, offset: u32) -> Result<(Vec<Record>), RecordRepositoryError>;
}
#[derive(Debug)]
pub enum | {
CannotStoreRecord,
CannotFetchRecord,
CannotDenormalizeRecord,
RecordNotFound
}
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct MysqlConfig {
address: String,
username: String,
password: String,
database: String
}
impl MysqlConfig {
pub fn to_connection (&self) -> MysqlRepository {
let opts = MyOpts {
tcp_addr: Some(self.address.clone()),
user: Some(self.username.clone()),
pass: Some(self.password.clone()),
db_name: Some(self.database.to_string()),
..Default::default()
};
MysqlRepository::new(MyPool::new(opts).unwrap())
}
}
#[derive(Clone, Debug)]
pub struct MysqlRepository {
pool: MyPool
}
impl MysqlRepository {
pub fn new (pool: MyPool) -> MysqlRepository {
MysqlRepository { pool: pool }
}
fn row_to_record (&self, row: MyResult<Vec<Value>>) -> Record {
let (id, command, cwd, status, stderr, stdout, started_at_col, finished_at_col) = from_row::<(String, String, String, i32, String, String, String, String)>(row.unwrap());
let started_at = UTC.datetime_from_str(&started_at_col, "%Y-%m-%d %H:%M:%S").unwrap();
let finished_at = UTC.datetime_from_str(&finished_at_col, "%Y-%m-%d %H:%M:%S").unwrap();
let optimized_uuid = MysqlOptimizedUuid { uuid: id.to_string() };
Record {
id: optimized_uuid.to_uuid(),
command: command,
cwd: cwd,
status: status,
stderr: stderr,
stdout: stdout,
started_at: started_at,
finished_at: finished_at
}
}
}
#[derive(Clone, Debug)]
pub struct MysqlOptimizedUuid {
uuid: String
}
impl MysqlOptimizedUuid {
pub fn from_uuid (uuid: String) -> MysqlOptimizedUuid {
// the optimized way https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/
let mut ordered_uuid = uuid[14..18].to_string();
ordered_uuid.push_str(&uuid[9..13]);
ordered_uuid.push_str(&uuid[0..8]);
ordered_uuid.push_str(&uuid[19..23]);
ordered_uuid.push_str(&uuid[24..]);
MysqlOptimizedUuid { uuid: ordered_uuid }
}
pub fn to_uuid (&self) -> String {
let mut uuid = self.uuid[8..16].to_string();
uuid.push_str("-");
uuid.push_str(&self.uuid[4..8]);
uuid.push_str("-");
uuid.push_str(&self.uuid[0..4]);
uuid.push_str("-");
uuid.push_str(&self.uuid[16..20]);
uuid.push_str("-");
uuid.push_str(&self.uuid[20..]);
uuid
}
}
impl RecordRepository for MysqlRepository {
fn store (&self, record: Record) -> Result<(), RecordRepositoryError> {
let uuid_optimized = MysqlOptimizedUuid::from_uuid(record.id.clone());
let query = r"INSERT INTO results (id, command, cwd, status, stderr, stdout, started_at, finished_at) VALUES (UNHEX(?), ?, ?, ?, ?, ?, ?, ?)";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotStoreRecord)
};
let result = match stmt.execute(
(uuid_optimized.clone().uuid, record.command, record.cwd, record.status, record.stderr,
record.stdout, record.started_at.format("%Y-%m-%d %H:%M:%S").to_string(), record.finished_at.format("%Y-%m-%d %H:%M:%S").to_string()
)
) {
Ok(_) => Ok(()),
Err(err) => {
error!("[{:?}] error storing in mysql {:?}", uuid_optimized.clone().uuid, err);
return Err(RecordRepositoryError::CannotStoreRecord);
}
};
result
}
fn fetch_limit (&self, size: u32, limit: u32) -> Result<(Vec<Record>), RecordRepositoryError> {
let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char) AS finished_at FROM results ORDER BY started_at DESC LIMIT ? OFFSET ?";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotFetchRecord)
};
let results: Result<(Vec<Record>), RecordRepositoryError> = match stmt
.execute((size, limit))
.map(|result| {
result.map(|row| {
self.row_to_record(row)
}).collect()
})
{
Ok(records) => Ok(records),
Err(err) => {
error!("error fetching from mysql {:?}", err);
return Err(RecordRepositoryError::CannotDenormalizeRecord)
}
};
results
}
fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError> {
let uuid_optimized = MysqlOptimizedUuid::from_uuid(id.clone());
let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char) AS finished_at FROM results WHERE HEX(id) = ?";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotFetchRecord)
};
let results: Result<(Vec<Record>), RecordRepositoryError> = match stmt
.execute((uuid_optimized.uuid, ))
.map(|result| {
result.map(|row| {
self.row_to_record(row)
}).collect()
})
{
Ok(records) => Ok(records),
Err(err) => {
error!("error fetching from mysql {:?}", err);
return Err(RecordRepositoryError::CannotDenormalizeRecord)
}
};
let records: Vec<Record> = results.unwrap();
let result: Result<(Record), RecordRepositoryError> = match records.len() {
1 => {
Ok(records[0].clone())
},
_ => return Err(RecordRepositoryError::RecordNotFound)
};
result
}
}
#[cfg(test)]
mod tests {
use super::MysqlOptimizedUuid;
#[test]
fn optimized_uuid() {
let uuid = String::from("58e0a7d7-eebc-11d8-9669-0800200c9a66");
let optimized_uuid = MysqlOptimizedUuid::from_uuid(uuid);
assert_eq!("11d8eebc58e0a7d796690800200c9a66", optimized_uuid.uuid);
assert_eq!("58e0a7d7-eebc-11d8-9669-0800200c9a66", optimized_uuid.to_uuid());
}
} | RecordRepositoryError | identifier_name |
record_backend.rs | extern crate chrono;
extern crate mysql;
use self::chrono::UTC;
use self::chrono::offset::TimeZone;
use self::mysql::conn::MyOpts;
use self::mysql::conn::pool::MyPool;
use self::mysql::error::MyResult;
use self::mysql::value::from_row;
use self::mysql::value::Value;
use std::clone::Clone;
use std::default::Default;
use worker::Record;
pub trait RecordRepository {
fn store (&self, record: Record) -> Result<(), RecordRepositoryError>;
fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError>;
fn fetch_limit (&self, size: u32, offset: u32) -> Result<(Vec<Record>), RecordRepositoryError>;
}
#[derive(Debug)]
pub enum RecordRepositoryError {
CannotStoreRecord,
CannotFetchRecord,
CannotDenormalizeRecord,
RecordNotFound
}
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct MysqlConfig {
address: String,
username: String,
password: String,
database: String
}
impl MysqlConfig {
pub fn to_connection (&self) -> MysqlRepository {
let opts = MyOpts {
tcp_addr: Some(self.address.clone()),
user: Some(self.username.clone()),
pass: Some(self.password.clone()),
db_name: Some(self.database.to_string()),
..Default::default()
};
MysqlRepository::new(MyPool::new(opts).unwrap())
}
}
#[derive(Clone, Debug)]
pub struct MysqlRepository {
pool: MyPool
}
impl MysqlRepository {
pub fn new (pool: MyPool) -> MysqlRepository {
MysqlRepository { pool: pool }
}
fn row_to_record (&self, row: MyResult<Vec<Value>>) -> Record {
let (id, command, cwd, status, stderr, stdout, started_at_col, finished_at_col) = from_row::<(String, String, String, i32, String, String, String, String)>(row.unwrap());
let started_at = UTC.datetime_from_str(&started_at_col, "%Y-%m-%d %H:%M:%S").unwrap();
let finished_at = UTC.datetime_from_str(&finished_at_col, "%Y-%m-%d %H:%M:%S").unwrap();
let optimized_uuid = MysqlOptimizedUuid { uuid: id.to_string() };
Record {
id: optimized_uuid.to_uuid(),
command: command,
cwd: cwd,
status: status,
stderr: stderr,
stdout: stdout,
started_at: started_at,
finished_at: finished_at
}
}
}
#[derive(Clone, Debug)]
pub struct MysqlOptimizedUuid {
uuid: String
}
impl MysqlOptimizedUuid {
pub fn from_uuid (uuid: String) -> MysqlOptimizedUuid {
// the optimized way https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/
let mut ordered_uuid = uuid[14..18].to_string();
ordered_uuid.push_str(&uuid[9..13]);
ordered_uuid.push_str(&uuid[0..8]);
ordered_uuid.push_str(&uuid[19..23]);
ordered_uuid.push_str(&uuid[24..]);
MysqlOptimizedUuid { uuid: ordered_uuid }
}
pub fn to_uuid (&self) -> String {
let mut uuid = self.uuid[8..16].to_string();
uuid.push_str("-");
uuid.push_str(&self.uuid[4..8]);
uuid.push_str("-");
uuid.push_str(&self.uuid[0..4]);
uuid.push_str("-");
uuid.push_str(&self.uuid[16..20]);
uuid.push_str("-");
uuid.push_str(&self.uuid[20..]);
uuid
}
}
impl RecordRepository for MysqlRepository {
fn store (&self, record: Record) -> Result<(), RecordRepositoryError> {
let uuid_optimized = MysqlOptimizedUuid::from_uuid(record.id.clone());
let query = r"INSERT INTO results (id, command, cwd, status, stderr, stdout, started_at, finished_at) VALUES (UNHEX(?), ?, ?, ?, ?, ?, ?, ?)";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotStoreRecord)
};
let result = match stmt.execute(
(uuid_optimized.clone().uuid, record.command, record.cwd, record.status, record.stderr,
record.stdout, record.started_at.format("%Y-%m-%d %H:%M:%S").to_string(), record.finished_at.format("%Y-%m-%d %H:%M:%S").to_string()
)
) {
Ok(_) => Ok(()),
Err(err) => {
error!("[{:?}] error storing in mysql {:?}", uuid_optimized.clone().uuid, err);
return Err(RecordRepositoryError::CannotStoreRecord);
}
};
result
}
fn fetch_limit (&self, size: u32, limit: u32) -> Result<(Vec<Record>), RecordRepositoryError> {
let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char) AS finished_at FROM results ORDER BY started_at DESC LIMIT ? OFFSET ?";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotFetchRecord)
};
let results: Result<(Vec<Record>), RecordRepositoryError> = match stmt
.execute((size, limit))
.map(|result| {
result.map(|row| {
self.row_to_record(row)
}).collect()
})
{
Ok(records) => Ok(records),
Err(err) => |
};
results
}
fn fetch_record (&self, id: String) -> Result<(Record), RecordRepositoryError> {
let uuid_optimized = MysqlOptimizedUuid::from_uuid(id.clone());
let query = r"SELECT HEX(id) AS id, command, cwd, status, stderr, stdout, CAST(started_at AS char) AS started_at, CAST(finished_at AS char) AS finished_at FROM results WHERE HEX(id) = ?";
let mut stmt = match self.pool.prepare(query) {
Ok(s) => s,
Err(_) => return Err(RecordRepositoryError::CannotFetchRecord)
};
let results: Result<(Vec<Record>), RecordRepositoryError> = match stmt
.execute((uuid_optimized.uuid, ))
.map(|result| {
result.map(|row| {
self.row_to_record(row)
}).collect()
})
{
Ok(records) => Ok(records),
Err(err) => {
error!("error fetching from mysql {:?}", err);
return Err(RecordRepositoryError::CannotDenormalizeRecord)
}
};
let records: Vec<Record> = results.unwrap();
let result: Result<(Record), RecordRepositoryError> = match records.len() {
1 => {
Ok(records[0].clone())
},
_ => return Err(RecordRepositoryError::RecordNotFound)
};
result
}
}
#[cfg(test)]
mod tests {
use super::MysqlOptimizedUuid;
#[test]
fn optimized_uuid() {
let uuid = String::from("58e0a7d7-eebc-11d8-9669-0800200c9a66");
let optimized_uuid = MysqlOptimizedUuid::from_uuid(uuid);
assert_eq!("11d8eebc58e0a7d796690800200c9a66", optimized_uuid.uuid);
assert_eq!("58e0a7d7-eebc-11d8-9669-0800200c9a66", optimized_uuid.to_uuid());
}
} | {
error!("error fetching from mysql {:?}", err);
return Err(RecordRepositoryError::CannotDenormalizeRecord)
} | conditional_block |
events.js | 'use strict';
var SERVER_ROOT = 'http://localhost:3000';
servicesModule
.factory('Events', function($http){
// helper function to extract data from response
var getData = function(res) {
return res.data;
};
// ---- Export functions ----
var addOne = function(friendId, eventObj){
return $http.post(SERVER_ROOT + '/api/friends/' + friendId + '/events', eventObj)
.then(getData);
};
var getAllForFriend = function(friendId){
return $http.get(SERVER_ROOT + '/api/friends/' + friendId + '/events')
.then(getData);
}
var getOne = function(eventId) {
return $http.get(SERVER_ROOT + '/api/events/' + eventId)
.then(getData);
};
var updateOne = function(eventId, newEventObj){
return $http.put(SERVER_ROOT + '/api/events/' + eventId, newEventObj)
.then(getData);
}
var deleteOne = function(eventId){
return $http.delete(SERVER_ROOT + '/api/events/' + eventId)
.then(getData);
}
var prettifyDate = function(dateStr) { //date is of format TIMESTAMP from sql
var dateObj = new Date(dateStr);
var month = (dateObj.getUTCMonth()+1 % 12);
var date = dateObj.getUTCDate(); | var hours = (dateObj.getHours() + 4) % 24; // 24 hour clock, but then plus 4 for timezone
var minutes = dateObj.getMinutes();
var monthString = month;
var dateString = date;
var yearString = year;
var hoursString = (hours % 12 === 0 ? 12 : hours % 12).toString();
var minutesString = ((minutes <= 10) ? '0' : '') + minutes.toString();
var suffix = (hours <= 12) ? 'am' : 'pm';
console.log(hoursString + ":" + minutesString + suffix);
return monthString + '/' + dateString + '/' + yearString + ', ' + hoursString + ":" + minutesString + suffix;
};
return {
addOne: addOne,
getAllForFriend: getAllForFriend,
getOne: getOne,
updateOne: updateOne,
deleteOne: deleteOne,
prettifyDate: prettifyDate
}
}); | var year = dateObj.getUTCFullYear(); | random_line_split |
BlockedAfDUserExtraction.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@author: Michael Ruster
Extract the timestamp and user of contributions which were authored before the
respecitve user had been blocked. The result can be further processed by
TimeframeCalculations.py.
Requirements: MediaWiki Utilities, WikiWho DiscussionParser
Usage: python BlockedAfDUserExtraction.py -i /path/to/dumps/ -b /path/to/WikiParser/blocks.csv
'''
from mw.xml_dump import Iterator as mwIterator
from mw.xml_dump.functions import open_file
# Our very own little dependency hell:
from sys import path
path.append('../..')
path.append('../../WikiCodeCleaner')
path.append('../../functions')
import WikiWho
import BlockTimeCalculation
import TimeframeCalculations
import csv
import os.path
def extract(path, users, blocks):
output = '../data/blockedAfDUsers.csv'
if os.path.isfile(output):
|
with open(output, 'a') as output:
writer = csv.writer(output, delimiter='\t',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for fileName in WikiWho.extractFileNamesFromPath(path):
print('[I] Now processing the file "%s".' % fileName)
# Access the file.
dumpIterator = mwIterator.from_file(open_file(fileName))
for page in dumpIterator:
for revision in page:
if revision.contributor:
# participated in AfD and was blocked:
if revision.contributor.user_text in users:
secondsToBlock = BlockTimeCalculation.calculateSecondsUntilNextBlock(blocks, revision.contributor.user_text, revision.timestamp)
# If secondsToBlock is -1, the user was once blocked but this post
# belongs to the time after, when she was never blocked again.
if secondsToBlock != -1:
writer.writerow([revision.timestamp,
revision.contributor.id,
revision.contributor.user_text,
int(revision.id),
page.title,
secondsToBlock])
if __name__ == '__main__':
import argparse, pickle, os
parser = argparse.ArgumentParser(description='A method for extracting timestamps of users that have been blocked at least once and have participated in an AfD at least once.',
epilog='''
WikiWho DiscussionParser, Copyright (C) 2015 Fabian Flöck, Maribel Acosta, Michael Ruster (based on wikiwho by Fabian Flöck, Maribel Acosta).
WikiWho DiscussionParser comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. For more information, see the LICENSE and README.md files this program should have been distributed with.
''')
parser.add_argument('-i', dest='pageDumpPath', required=True,
help='Path to the Wikipedia page(s) dump (XML, 7z, bz2…).')
parser.add_argument('-b', dest='blockLog', type=argparse.FileType('r'),
default=None, nargs='?',
help='Path to the block log file produced with 0nse/WikiParser (CSV).'),
args = parser.parse_args()
usersFile = '../data/blockedAfDUserNames_temp.pkl'
TimeframeCalculations.extractLastPostToBlockDeltas(usersOutputFile=usersFile)
# If you stumble upon this code and ask yourself: why pickle? Why not just a
# return parameter? I wanted to try pickle for once. That's all.
with open(usersFile, 'rb') as inputFile:
users = pickle.load(inputFile)
os.remove(usersFile)
blocks = BlockTimeCalculation.createBlockedUsersDict(args.blockLog)
extract(args.pageDumpPath, users, blocks)
| raise IOError('[E] File "%s" already exists. Aborting.' % output) | conditional_block |
BlockedAfDUserExtraction.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@author: Michael Ruster
Extract the timestamp and user of contributions which were authored before the
respecitve user had been blocked. The result can be further processed by
TimeframeCalculations.py.
Requirements: MediaWiki Utilities, WikiWho DiscussionParser
Usage: python BlockedAfDUserExtraction.py -i /path/to/dumps/ -b /path/to/WikiParser/blocks.csv
'''
from mw.xml_dump import Iterator as mwIterator
from mw.xml_dump.functions import open_file
# Our very own little dependency hell:
from sys import path
path.append('../..')
path.append('../../WikiCodeCleaner')
path.append('../../functions')
import WikiWho
import BlockTimeCalculation
import TimeframeCalculations
import csv
import os.path
def extract(path, users, blocks):
output = '../data/blockedAfDUsers.csv'
if os.path.isfile(output):
raise IOError('[E] File "%s" already exists. Aborting.' % output)
with open(output, 'a') as output:
writer = csv.writer(output, delimiter='\t',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for fileName in WikiWho.extractFileNamesFromPath(path):
print('[I] Now processing the file "%s".' % fileName)
# Access the file.
dumpIterator = mwIterator.from_file(open_file(fileName))
for page in dumpIterator:
for revision in page:
if revision.contributor:
# participated in AfD and was blocked:
if revision.contributor.user_text in users:
secondsToBlock = BlockTimeCalculation.calculateSecondsUntilNextBlock(blocks, revision.contributor.user_text, revision.timestamp)
# If secondsToBlock is -1, the user was once blocked but this post
# belongs to the time after, when she was never blocked again.
if secondsToBlock != -1:
writer.writerow([revision.timestamp,
revision.contributor.id,
revision.contributor.user_text,
int(revision.id),
page.title,
secondsToBlock])
if __name__ == '__main__':
import argparse, pickle, os
parser = argparse.ArgumentParser(description='A method for extracting timestamps of users that have been blocked at least once and have participated in an AfD at least once.',
epilog='''
WikiWho DiscussionParser, Copyright (C) 2015 Fabian Flöck, Maribel Acosta, Michael Ruster (based on wikiwho by Fabian Flöck, Maribel Acosta).
WikiWho DiscussionParser comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. For more information, see the LICENSE and README.md files this program should have been distributed with.
''')
parser.add_argument('-i', dest='pageDumpPath', required=True,
help='Path to the Wikipedia page(s) dump (XML, 7z, bz2…).')
parser.add_argument('-b', dest='blockLog', type=argparse.FileType('r'),
default=None, nargs='?',
help='Path to the block log file produced with 0nse/WikiParser (CSV).'),
args = parser.parse_args()
usersFile = '../data/blockedAfDUserNames_temp.pkl'
TimeframeCalculations.extractLastPostToBlockDeltas(usersOutputFile=usersFile)
# If you stumble upon this code and ask yourself: why pickle? Why not just a
# return parameter? I wanted to try pickle for once. That's all. | blocks = BlockTimeCalculation.createBlockedUsersDict(args.blockLog)
extract(args.pageDumpPath, users, blocks) | with open(usersFile, 'rb') as inputFile:
users = pickle.load(inputFile)
os.remove(usersFile)
| random_line_split |
BlockedAfDUserExtraction.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@author: Michael Ruster
Extract the timestamp and user of contributions which were authored before the
respecitve user had been blocked. The result can be further processed by
TimeframeCalculations.py.
Requirements: MediaWiki Utilities, WikiWho DiscussionParser
Usage: python BlockedAfDUserExtraction.py -i /path/to/dumps/ -b /path/to/WikiParser/blocks.csv
'''
from mw.xml_dump import Iterator as mwIterator
from mw.xml_dump.functions import open_file
# Our very own little dependency hell:
from sys import path
path.append('../..')
path.append('../../WikiCodeCleaner')
path.append('../../functions')
import WikiWho
import BlockTimeCalculation
import TimeframeCalculations
import csv
import os.path
def extract(path, users, blocks):
|
if __name__ == '__main__':
import argparse, pickle, os
parser = argparse.ArgumentParser(description='A method for extracting timestamps of users that have been blocked at least once and have participated in an AfD at least once.',
epilog='''
WikiWho DiscussionParser, Copyright (C) 2015 Fabian Flöck, Maribel Acosta, Michael Ruster (based on wikiwho by Fabian Flöck, Maribel Acosta).
WikiWho DiscussionParser comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. For more information, see the LICENSE and README.md files this program should have been distributed with.
''')
parser.add_argument('-i', dest='pageDumpPath', required=True,
help='Path to the Wikipedia page(s) dump (XML, 7z, bz2…).')
parser.add_argument('-b', dest='blockLog', type=argparse.FileType('r'),
default=None, nargs='?',
help='Path to the block log file produced with 0nse/WikiParser (CSV).'),
args = parser.parse_args()
usersFile = '../data/blockedAfDUserNames_temp.pkl'
TimeframeCalculations.extractLastPostToBlockDeltas(usersOutputFile=usersFile)
# If you stumble upon this code and ask yourself: why pickle? Why not just a
# return parameter? I wanted to try pickle for once. That's all.
with open(usersFile, 'rb') as inputFile:
users = pickle.load(inputFile)
os.remove(usersFile)
blocks = BlockTimeCalculation.createBlockedUsersDict(args.blockLog)
extract(args.pageDumpPath, users, blocks)
| output = '../data/blockedAfDUsers.csv'
if os.path.isfile(output):
raise IOError('[E] File "%s" already exists. Aborting.' % output)
with open(output, 'a') as output:
writer = csv.writer(output, delimiter='\t',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for fileName in WikiWho.extractFileNamesFromPath(path):
print('[I] Now processing the file "%s".' % fileName)
# Access the file.
dumpIterator = mwIterator.from_file(open_file(fileName))
for page in dumpIterator:
for revision in page:
if revision.contributor:
# participated in AfD and was blocked:
if revision.contributor.user_text in users:
secondsToBlock = BlockTimeCalculation.calculateSecondsUntilNextBlock(blocks, revision.contributor.user_text, revision.timestamp)
# If secondsToBlock is -1, the user was once blocked but this post
# belongs to the time after, when she was never blocked again.
if secondsToBlock != -1:
writer.writerow([revision.timestamp,
revision.contributor.id,
revision.contributor.user_text,
int(revision.id),
page.title,
secondsToBlock]) | identifier_body |
BlockedAfDUserExtraction.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@author: Michael Ruster
Extract the timestamp and user of contributions which were authored before the
respecitve user had been blocked. The result can be further processed by
TimeframeCalculations.py.
Requirements: MediaWiki Utilities, WikiWho DiscussionParser
Usage: python BlockedAfDUserExtraction.py -i /path/to/dumps/ -b /path/to/WikiParser/blocks.csv
'''
from mw.xml_dump import Iterator as mwIterator
from mw.xml_dump.functions import open_file
# Our very own little dependency hell:
from sys import path
path.append('../..')
path.append('../../WikiCodeCleaner')
path.append('../../functions')
import WikiWho
import BlockTimeCalculation
import TimeframeCalculations
import csv
import os.path
def | (path, users, blocks):
output = '../data/blockedAfDUsers.csv'
if os.path.isfile(output):
raise IOError('[E] File "%s" already exists. Aborting.' % output)
with open(output, 'a') as output:
writer = csv.writer(output, delimiter='\t',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for fileName in WikiWho.extractFileNamesFromPath(path):
print('[I] Now processing the file "%s".' % fileName)
# Access the file.
dumpIterator = mwIterator.from_file(open_file(fileName))
for page in dumpIterator:
for revision in page:
if revision.contributor:
# participated in AfD and was blocked:
if revision.contributor.user_text in users:
secondsToBlock = BlockTimeCalculation.calculateSecondsUntilNextBlock(blocks, revision.contributor.user_text, revision.timestamp)
# If secondsToBlock is -1, the user was once blocked but this post
# belongs to the time after, when she was never blocked again.
if secondsToBlock != -1:
writer.writerow([revision.timestamp,
revision.contributor.id,
revision.contributor.user_text,
int(revision.id),
page.title,
secondsToBlock])
if __name__ == '__main__':
import argparse, pickle, os
parser = argparse.ArgumentParser(description='A method for extracting timestamps of users that have been blocked at least once and have participated in an AfD at least once.',
epilog='''
WikiWho DiscussionParser, Copyright (C) 2015 Fabian Flöck, Maribel Acosta, Michael Ruster (based on wikiwho by Fabian Flöck, Maribel Acosta).
WikiWho DiscussionParser comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. For more information, see the LICENSE and README.md files this program should have been distributed with.
''')
parser.add_argument('-i', dest='pageDumpPath', required=True,
help='Path to the Wikipedia page(s) dump (XML, 7z, bz2…).')
parser.add_argument('-b', dest='blockLog', type=argparse.FileType('r'),
default=None, nargs='?',
help='Path to the block log file produced with 0nse/WikiParser (CSV).'),
args = parser.parse_args()
usersFile = '../data/blockedAfDUserNames_temp.pkl'
TimeframeCalculations.extractLastPostToBlockDeltas(usersOutputFile=usersFile)
# If you stumble upon this code and ask yourself: why pickle? Why not just a
# return parameter? I wanted to try pickle for once. That's all.
with open(usersFile, 'rb') as inputFile:
users = pickle.load(inputFile)
os.remove(usersFile)
blocks = BlockTimeCalculation.createBlockedUsersDict(args.blockLog)
extract(args.pageDumpPath, users, blocks)
| extract | identifier_name |
factories.py | '''
Created on 22/02/2015
@author: Ismail Faizi
'''
import models
class ModelFactory(object):
"""
Factory for creating entities of models
"""
@classmethod
def create_user(cls, name, email, training_journal):
"""
Factory method for creating User entity.
NOTE: you must explicitly call the put() method
"""
user = models.User(parent=models.USER_KEY)
user.name = name
user.email = email
user.training_journal = training_journal.key
return user
@classmethod
def create_training_journal(cls):
"""
Factory method for creating TrainingJournal entity.
NOTE: you must explicitly call the put() method
"""
return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY)
@classmethod
def create_workout_session(cls, started_at, ended_at, training_journal):
|
@classmethod
def create_workout_set(cls, repetitions, weight, workout_session, workout):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY)
workout_set.repetitions = repetitions
workout_set.weight = weight
workout_set.workout_session = workout_session.key
workout_set.workout = workout.key
return workout_set
@classmethod
def create_workout(cls, muscle_group, names=[], description='', images=[]):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout = models.Workout(parent=models.WORKOUT_KEY)
workout.names = names
workout.muscle_group = muscle_group
workout.description = description
workout.images = images
return workout
| """
Factory method for creating WorkoutSession entity.
NOTE: you must explicitly call the put() method
"""
workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY)
workout_session.started_at = started_at
workout_session.ended_at = ended_at
workout_session.training_journal = training_journal.key
return workout_session | identifier_body |
factories.py | '''
Created on 22/02/2015
@author: Ismail Faizi
'''
import models
class ModelFactory(object):
"""
Factory for creating entities of models
"""
@classmethod
def create_user(cls, name, email, training_journal):
"""
Factory method for creating User entity.
NOTE: you must explicitly call the put() method
"""
user = models.User(parent=models.USER_KEY)
user.name = name
user.email = email
user.training_journal = training_journal.key
return user
@classmethod
def create_training_journal(cls):
"""
Factory method for creating TrainingJournal entity.
NOTE: you must explicitly call the put() method
"""
return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY)
@classmethod
def create_workout_session(cls, started_at, ended_at, training_journal):
"""
Factory method for creating WorkoutSession entity.
NOTE: you must explicitly call the put() method
"""
workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY)
workout_session.started_at = started_at
workout_session.ended_at = ended_at
workout_session.training_journal = training_journal.key
return workout_session
@classmethod
def create_workout_set(cls, repetitions, weight, workout_session, workout): | Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY)
workout_set.repetitions = repetitions
workout_set.weight = weight
workout_set.workout_session = workout_session.key
workout_set.workout = workout.key
return workout_set
@classmethod
def create_workout(cls, muscle_group, names=[], description='', images=[]):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout = models.Workout(parent=models.WORKOUT_KEY)
workout.names = names
workout.muscle_group = muscle_group
workout.description = description
workout.images = images
return workout | """ | random_line_split |
factories.py | '''
Created on 22/02/2015
@author: Ismail Faizi
'''
import models
class ModelFactory(object):
"""
Factory for creating entities of models
"""
@classmethod
def create_user(cls, name, email, training_journal):
"""
Factory method for creating User entity.
NOTE: you must explicitly call the put() method
"""
user = models.User(parent=models.USER_KEY)
user.name = name
user.email = email
user.training_journal = training_journal.key
return user
@classmethod
def | (cls):
"""
Factory method for creating TrainingJournal entity.
NOTE: you must explicitly call the put() method
"""
return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY)
@classmethod
def create_workout_session(cls, started_at, ended_at, training_journal):
"""
Factory method for creating WorkoutSession entity.
NOTE: you must explicitly call the put() method
"""
workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY)
workout_session.started_at = started_at
workout_session.ended_at = ended_at
workout_session.training_journal = training_journal.key
return workout_session
@classmethod
def create_workout_set(cls, repetitions, weight, workout_session, workout):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY)
workout_set.repetitions = repetitions
workout_set.weight = weight
workout_set.workout_session = workout_session.key
workout_set.workout = workout.key
return workout_set
@classmethod
def create_workout(cls, muscle_group, names=[], description='', images=[]):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout = models.Workout(parent=models.WORKOUT_KEY)
workout.names = names
workout.muscle_group = muscle_group
workout.description = description
workout.images = images
return workout
| create_training_journal | identifier_name |
verifyCode-validator.directive.ts |
import { Directive, forwardRef, Attribute, Input } from '@angular/core';
import { Validator, FormControl, AbstractControl, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { Observable } from "rxjs";
import { VerifyCodeService } from '../services/verify-code.service'; // 登录服务
@Directive({
selector: '[validateVcode][ngModel]',
providers: [
{
provide: NG_ASYNC_VALIDATORS, // ng2 async validator
useExisting: forwardRef(() => VcodeValidatorDirective),
multi: true
}
]
})
export class VcodeValidatorDirective implements Validator {
constructor(public vCodeService: VerifyCodeService ) {
}
| @Input('validateVcode') mobile: string;
validateVcodeObservable(mobile: string, vcode: string) {
return new Observable(observer => {
this.vCodeService.validateVerifyCode(mobile, vcode).subscribe(responseData => {
console.log(responseData);
// if (responseData.errorCode === 1) {
// // verify error.
// observer.next({ validateVcode: { valid: false }, message="验证码错误,请重新输入。" });
// } else {
// observer.next(null);
// }
});
});
}
validate(c: AbstractControl): Observable<{[key : string] : any}> {
return this.validateVcodeObservable(this.mobile, c.value).first();
}
} | identifier_body | |
verifyCode-validator.directive.ts | import { Directive, forwardRef, Attribute, Input } from '@angular/core';
import { Validator, FormControl, AbstractControl, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { Observable } from "rxjs";
import { VerifyCodeService } from '../services/verify-code.service'; // 登录服务
@Directive({
selector: '[validateVcode][ngModel]',
providers: [
{
provide: NG_ASYNC_VALIDATORS, // ng2 async validator
useExisting: forwardRef(() => VcodeValidatorDirective),
multi: true
}
]
})
export class VcodeValidatorDirective implements Validator {
constructor(public vCodeService: VerifyCodeService ) {
}
@Input('validateVcode') mobile: string;
validateVcodeObservable(mobile: string, vcode: string) {
return new Observable(observer => {
this.vCodeService.validateVerifyCode(mobile, vcode).subscribe(responseData => {
console.log(responseData);
// if (responseData.errorCode === 1) {
// // verify error.
// observer.next({ validateVcode: { valid: false }, message="验证码错误,请重新输入。" });
// } else {
// observer.next(null);
// }
});
});
}
| validate(c: AbstractControl): Observable<{[key : string] : any}> {
return this.validateVcodeObservable(this.mobile, c.value).first();
}
} | random_line_split | |
verifyCode-validator.directive.ts |
import { Directive, forwardRef, Attribute, Input } from '@angular/core';
import { Validator, FormControl, AbstractControl, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { Observable } from "rxjs";
import { VerifyCodeService } from '../services/verify-code.service'; // 登录服务
@Directive({
selector: '[validateVcode][ngModel]',
providers: [
{
provide: NG_ASYNC_VALIDATORS, // ng2 async validator
useExisting: forwardRef(() => VcodeValidatorDirective),
multi: true
}
]
})
export class VcodeValidatorDirective implements Validator {
constructor(public vCodeService: VerifyCodeService ) {
}
@Input('validateVcode') mobile: string;
validate | string, vcode: string) {
return new Observable(observer => {
this.vCodeService.validateVerifyCode(mobile, vcode).subscribe(responseData => {
console.log(responseData);
// if (responseData.errorCode === 1) {
// // verify error.
// observer.next({ validateVcode: { valid: false }, message="验证码错误,请重新输入。" });
// } else {
// observer.next(null);
// }
});
});
}
validate(c: AbstractControl): Observable<{[key : string] : any}> {
return this.validateVcodeObservable(this.mobile, c.value).first();
}
} | VcodeObservable(mobile: | identifier_name |
mozmap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `MozMap` (open-ended dictionary) type.
use dom::bindings::conversions::jsid_to_string;
use dom::bindings::str::DOMString;
use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult};
use js::jsapi::GetPropertyKeys;
use js::jsapi::HandleValue;
use js::jsapi::JSContext;
use js::jsapi::JSITER_OWNONLY;
use js::jsapi::JSPROP_ENUMERATE;
use js::jsapi::JS_DefineUCProperty2;
use js::jsapi::JS_GetPropertyById;
use js::jsapi::JS_NewPlainObject;
use js::jsapi::MutableHandleValue;
use js::jsval::ObjectValue;
use js::jsval::UndefinedValue;
use js::rust::IdVector;
use std::collections::HashMap;
use std::ops::Deref;
/// The `MozMap` (open-ended dictionary) type.
#[derive(Clone)]
pub struct MozMap<T> {
map: HashMap<DOMString, T>,
}
impl<T> MozMap<T> {
/// Create an empty `MozMap`.
pub fn new() -> Self {
MozMap {
map: HashMap::new(),
}
}
}
impl<T> Deref for MozMap<T> {
type Target = HashMap<DOMString, T>;
fn deref(&self) -> &HashMap<DOMString, T> {
&self.map
}
}
impl<T, C> FromJSValConvertible for MozMap<T>
where T: FromJSValConvertible<Config=C>,
C: Clone,
{
type Config = C;
unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C)
-> Result<ConversionResult<Self>, ()> |
}
impl<T: ToJSValConvertible> ToJSValConvertible for MozMap<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rooted!(in(cx) let js_object = JS_NewPlainObject(cx));
assert!(!js_object.handle().is_null());
rooted!(in(cx) let mut js_value = UndefinedValue());
for (key, value) in &self.map {
let key = key.encode_utf16().collect::<Vec<_>>();
value.to_jsval(cx, js_value.handle_mut());
assert!(JS_DefineUCProperty2(cx,
js_object.handle(),
key.as_ptr(),
key.len(),
js_value.handle(),
JSPROP_ENUMERATE,
None,
None));
}
rval.set(ObjectValue(js_object.handle().get()));
}
}
| {
if !value.is_object() {
return Ok(ConversionResult::Failure("MozMap value was not an object".into()));
}
rooted!(in(cx) let object = value.to_object());
let ids = IdVector::new(cx);
assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get()));
let mut map = HashMap::new();
for id in &*ids {
rooted!(in(cx) let id = *id);
rooted!(in(cx) let mut property = UndefinedValue());
if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) {
return Err(());
}
let property = match try!(T::from_jsval(cx, property.handle(), config.clone())) {
ConversionResult::Success(property) => property,
ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)),
};
let key = jsid_to_string(cx, id.handle()).unwrap();
map.insert(key, property);
}
Ok(ConversionResult::Success(MozMap {
map: map,
}))
} | identifier_body |
mozmap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `MozMap` (open-ended dictionary) type.
use dom::bindings::conversions::jsid_to_string;
use dom::bindings::str::DOMString;
use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult};
use js::jsapi::GetPropertyKeys;
use js::jsapi::HandleValue;
use js::jsapi::JSContext;
use js::jsapi::JSITER_OWNONLY;
use js::jsapi::JSPROP_ENUMERATE;
use js::jsapi::JS_DefineUCProperty2;
use js::jsapi::JS_GetPropertyById;
use js::jsapi::JS_NewPlainObject;
use js::jsapi::MutableHandleValue;
use js::jsval::ObjectValue;
use js::jsval::UndefinedValue;
use js::rust::IdVector;
use std::collections::HashMap;
use std::ops::Deref;
/// The `MozMap` (open-ended dictionary) type.
#[derive(Clone)]
pub struct MozMap<T> {
map: HashMap<DOMString, T>,
}
impl<T> MozMap<T> {
/// Create an empty `MozMap`.
pub fn new() -> Self {
MozMap {
map: HashMap::new(),
}
}
}
impl<T> Deref for MozMap<T> {
type Target = HashMap<DOMString, T>;
fn deref(&self) -> &HashMap<DOMString, T> {
&self.map
}
} | where T: FromJSValConvertible<Config=C>,
C: Clone,
{
type Config = C;
unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C)
-> Result<ConversionResult<Self>, ()> {
if !value.is_object() {
return Ok(ConversionResult::Failure("MozMap value was not an object".into()));
}
rooted!(in(cx) let object = value.to_object());
let ids = IdVector::new(cx);
assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get()));
let mut map = HashMap::new();
for id in &*ids {
rooted!(in(cx) let id = *id);
rooted!(in(cx) let mut property = UndefinedValue());
if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) {
return Err(());
}
let property = match try!(T::from_jsval(cx, property.handle(), config.clone())) {
ConversionResult::Success(property) => property,
ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)),
};
let key = jsid_to_string(cx, id.handle()).unwrap();
map.insert(key, property);
}
Ok(ConversionResult::Success(MozMap {
map: map,
}))
}
}
impl<T: ToJSValConvertible> ToJSValConvertible for MozMap<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rooted!(in(cx) let js_object = JS_NewPlainObject(cx));
assert!(!js_object.handle().is_null());
rooted!(in(cx) let mut js_value = UndefinedValue());
for (key, value) in &self.map {
let key = key.encode_utf16().collect::<Vec<_>>();
value.to_jsval(cx, js_value.handle_mut());
assert!(JS_DefineUCProperty2(cx,
js_object.handle(),
key.as_ptr(),
key.len(),
js_value.handle(),
JSPROP_ENUMERATE,
None,
None));
}
rval.set(ObjectValue(js_object.handle().get()));
}
} |
impl<T, C> FromJSValConvertible for MozMap<T> | random_line_split |
mozmap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `MozMap` (open-ended dictionary) type.
use dom::bindings::conversions::jsid_to_string;
use dom::bindings::str::DOMString;
use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult};
use js::jsapi::GetPropertyKeys;
use js::jsapi::HandleValue;
use js::jsapi::JSContext;
use js::jsapi::JSITER_OWNONLY;
use js::jsapi::JSPROP_ENUMERATE;
use js::jsapi::JS_DefineUCProperty2;
use js::jsapi::JS_GetPropertyById;
use js::jsapi::JS_NewPlainObject;
use js::jsapi::MutableHandleValue;
use js::jsval::ObjectValue;
use js::jsval::UndefinedValue;
use js::rust::IdVector;
use std::collections::HashMap;
use std::ops::Deref;
/// The `MozMap` (open-ended dictionary) type.
#[derive(Clone)]
pub struct MozMap<T> {
map: HashMap<DOMString, T>,
}
impl<T> MozMap<T> {
/// Create an empty `MozMap`.
pub fn | () -> Self {
MozMap {
map: HashMap::new(),
}
}
}
impl<T> Deref for MozMap<T> {
type Target = HashMap<DOMString, T>;
fn deref(&self) -> &HashMap<DOMString, T> {
&self.map
}
}
impl<T, C> FromJSValConvertible for MozMap<T>
where T: FromJSValConvertible<Config=C>,
C: Clone,
{
type Config = C;
unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C)
-> Result<ConversionResult<Self>, ()> {
if !value.is_object() {
return Ok(ConversionResult::Failure("MozMap value was not an object".into()));
}
rooted!(in(cx) let object = value.to_object());
let ids = IdVector::new(cx);
assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get()));
let mut map = HashMap::new();
for id in &*ids {
rooted!(in(cx) let id = *id);
rooted!(in(cx) let mut property = UndefinedValue());
if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) {
return Err(());
}
let property = match try!(T::from_jsval(cx, property.handle(), config.clone())) {
ConversionResult::Success(property) => property,
ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)),
};
let key = jsid_to_string(cx, id.handle()).unwrap();
map.insert(key, property);
}
Ok(ConversionResult::Success(MozMap {
map: map,
}))
}
}
impl<T: ToJSValConvertible> ToJSValConvertible for MozMap<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rooted!(in(cx) let js_object = JS_NewPlainObject(cx));
assert!(!js_object.handle().is_null());
rooted!(in(cx) let mut js_value = UndefinedValue());
for (key, value) in &self.map {
let key = key.encode_utf16().collect::<Vec<_>>();
value.to_jsval(cx, js_value.handle_mut());
assert!(JS_DefineUCProperty2(cx,
js_object.handle(),
key.as_ptr(),
key.len(),
js_value.handle(),
JSPROP_ENUMERATE,
None,
None));
}
rval.set(ObjectValue(js_object.handle().get()));
}
}
| new | identifier_name |
testThread.py | from PyQt4 import QtCore
import numpy
from ilastik.core import dataImpex
import shlex
from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray
from ilastik.core.overlays.selectionOverlay import SelectionAccessor
from subprocess import Popen, PIPE
import h5py
# this is the core replacement of the guiThread used to test module functionality
#*******************************************************************************
# T e s t T h r e a d *
#*******************************************************************************
import ilastik.core.jobMachine
def setUp():
if not ilastik.core.jobMachine.GLOBAL_WM:
ilastik.core.jobMachine.GLOBAL_WM = ilastik.core.jobMachine.WorkerManager()
def tearDown():
ilastik.core.jobMachine.GLOBAL_WM.stopWorkers()
del ilastik.core.jobMachine.GLOBAL_WM
ilastik.core.jobMachine.GLOBAL_WM = None
class TestThread(QtCore.QObject):#QtCore.QThread):
def __init__(self, baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
__pyqtSignals__ = ( "done()")
#QtCore.QThread.__init__(self, parent)
QtCore.QObject.__init__(self)
self.baseMgr = baseMgr
self.listOfResultOverlays = listOfResultOverlays
self.listOfFilenames = listOfFilenames
self.tolerance = tolerance
self.passedTest = False
def start(self, input):
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.updateProgress)
# call core function
self.myTestThread = self.baseMgr.computeResults(input)
self.timer.start(200)
def updateProgress(self):
if not self.myTestThread.isRunning():
self.timer.stop()
self.myTestThread.wait()
self.finalize()
def finalize(self):
# call core function
self.baseMgr.finalizeResults()
# compare obtained results with ground truth results
self.passedTest = TestHelperFunctions.compareResultsWithFile(self.baseMgr, self.listOfResultOverlays, self.listOfFilenames, self.tolerance)
# announce that we are done
self.emit(QtCore.SIGNAL("done()"))
'''
# in case you want to create ground truth overlays, use the following code instead of the above
for i in range(len(self.listOfResultOverlays)):
obtained = self.baseMgr.dataMgr[self.baseMgr.dataMgr._activeImageNumber].overlayMgr["Unsupervised/pLSA component %d" % (i+1)]
dataImpex.DataImpex.exportOverlay(self.listOfFilenames[i], "h5", obtained)
'''
#*******************************************************************************
# T e s t H e l p e r F u n c t i o n s *
#*******************************************************************************
class TestHelperFunctions():
@staticmethod
def compareResultsWithFile(baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
equalOverlays = True
for i in range(len(listOfResultOverlays)):
obtained = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[listOfResultOverlays[i]]
prefix = "Ground_Truth/"
dataImpex.DataImpex.importOverlay(baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber], listOfFilenames[i], prefix)
groundTruth = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[prefix + listOfResultOverlays[i]]
equalOverlays = equalOverlays & TestHelperFunctions.compareOverlayData(obtained, groundTruth, tolerance)
print "all ", str(len(listOfResultOverlays)), " compared overlays are equal: ", equalOverlays
return equalOverlays
@staticmethod
# we only compare the data of the overlay, since we want to avoid dependence on color tables etc.
def | (overlay1, overlay2, tolerance = 0):
# overlay1._data._data can be a listOfNDArraysAsNDArray instance, overlay2._data._data is loaded from file, so it should be an NDArray
if isinstance(overlay1._data._data, ListOfNDArraysAsNDArray):
datatemp1 = overlay1._data._data.ndarrays
elif isinstance(overlay1._data._data, SelectionAccessor):
datatemp1 = overlay1._data._data[:]
else:
datatemp1 = overlay1._data._data
datatemp2 = overlay2._data._data
if numpy.all(numpy.abs(datatemp1 - datatemp2) <= tolerance):
return True
else:
return False
@staticmethod
def arrayEqual(a,b):
assert a.shape == b.shape
assert a.dtype == b.dtype
if not numpy.array_equal(a,b):
assert len(a.shape) == 3
for x in range(a.shape[0]):
for y in range(a.shape[1]):
for z in range(a.shape[2]):
if a[x,y,z] != b[x,y,z]:
print x,y,z, "a=", a[x,y,z], "b=", b[x,y,z]
return False
return True
@staticmethod
def compareH5Files(file1, file2):
print "files to compare: ", file1, file2
#have to spawn a subprocess, because h5diff has no wrapper in python
cl = "h5diff -cv '" + file1 + "' '" + file2 + "'"
args = shlex.split(cl)
print args
'''
cl_header1 = "h5dump --header " + file1
args_header1 = shlex.split(cl_header1)
cl_header2 = "h5dump --header " + file2
args_header2 = shlex.split(cl_header2)
try:
p1 = Popen(args_header1, stdout=PIPE, stderr=PIPE)
out1, err1 = p1.communicate()
p2 = Popen(args_header2, stdout=PIPE, stderr=PIPE)
out2, err2 = p2.communicate()
if out1 != out2:
print "different header dumps"
print out1
print ""
print out2
except Exception, e:
print e
return False
#print args
'''
try:
p = Popen(args, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if p.returncode >0:
print stdout
print stderr
return False
else :
return True
except Exception, e:
print e
return False
return True
| compareOverlayData | identifier_name |
testThread.py | from PyQt4 import QtCore
import numpy
from ilastik.core import dataImpex
import shlex
from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray
from ilastik.core.overlays.selectionOverlay import SelectionAccessor
from subprocess import Popen, PIPE
import h5py
# this is the core replacement of the guiThread used to test module functionality
#*******************************************************************************
# T e s t T h r e a d *
#*******************************************************************************
import ilastik.core.jobMachine
def setUp():
if not ilastik.core.jobMachine.GLOBAL_WM:
ilastik.core.jobMachine.GLOBAL_WM = ilastik.core.jobMachine.WorkerManager()
def tearDown():
ilastik.core.jobMachine.GLOBAL_WM.stopWorkers()
del ilastik.core.jobMachine.GLOBAL_WM
ilastik.core.jobMachine.GLOBAL_WM = None
class TestThread(QtCore.QObject):#QtCore.QThread):
def __init__(self, baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
|
def start(self, input):
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.updateProgress)
# call core function
self.myTestThread = self.baseMgr.computeResults(input)
self.timer.start(200)
def updateProgress(self):
if not self.myTestThread.isRunning():
self.timer.stop()
self.myTestThread.wait()
self.finalize()
def finalize(self):
# call core function
self.baseMgr.finalizeResults()
# compare obtained results with ground truth results
self.passedTest = TestHelperFunctions.compareResultsWithFile(self.baseMgr, self.listOfResultOverlays, self.listOfFilenames, self.tolerance)
# announce that we are done
self.emit(QtCore.SIGNAL("done()"))
'''
# in case you want to create ground truth overlays, use the following code instead of the above
for i in range(len(self.listOfResultOverlays)):
obtained = self.baseMgr.dataMgr[self.baseMgr.dataMgr._activeImageNumber].overlayMgr["Unsupervised/pLSA component %d" % (i+1)]
dataImpex.DataImpex.exportOverlay(self.listOfFilenames[i], "h5", obtained)
'''
#*******************************************************************************
# T e s t H e l p e r F u n c t i o n s *
#*******************************************************************************
class TestHelperFunctions():
@staticmethod
def compareResultsWithFile(baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
equalOverlays = True
for i in range(len(listOfResultOverlays)):
obtained = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[listOfResultOverlays[i]]
prefix = "Ground_Truth/"
dataImpex.DataImpex.importOverlay(baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber], listOfFilenames[i], prefix)
groundTruth = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[prefix + listOfResultOverlays[i]]
equalOverlays = equalOverlays & TestHelperFunctions.compareOverlayData(obtained, groundTruth, tolerance)
print "all ", str(len(listOfResultOverlays)), " compared overlays are equal: ", equalOverlays
return equalOverlays
@staticmethod
# we only compare the data of the overlay, since we want to avoid dependence on color tables etc.
def compareOverlayData(overlay1, overlay2, tolerance = 0):
# overlay1._data._data can be a listOfNDArraysAsNDArray instance, overlay2._data._data is loaded from file, so it should be an NDArray
if isinstance(overlay1._data._data, ListOfNDArraysAsNDArray):
datatemp1 = overlay1._data._data.ndarrays
elif isinstance(overlay1._data._data, SelectionAccessor):
datatemp1 = overlay1._data._data[:]
else:
datatemp1 = overlay1._data._data
datatemp2 = overlay2._data._data
if numpy.all(numpy.abs(datatemp1 - datatemp2) <= tolerance):
return True
else:
return False
@staticmethod
def arrayEqual(a,b):
assert a.shape == b.shape
assert a.dtype == b.dtype
if not numpy.array_equal(a,b):
assert len(a.shape) == 3
for x in range(a.shape[0]):
for y in range(a.shape[1]):
for z in range(a.shape[2]):
if a[x,y,z] != b[x,y,z]:
print x,y,z, "a=", a[x,y,z], "b=", b[x,y,z]
return False
return True
@staticmethod
def compareH5Files(file1, file2):
print "files to compare: ", file1, file2
#have to spawn a subprocess, because h5diff has no wrapper in python
cl = "h5diff -cv '" + file1 + "' '" + file2 + "'"
args = shlex.split(cl)
print args
'''
cl_header1 = "h5dump --header " + file1
args_header1 = shlex.split(cl_header1)
cl_header2 = "h5dump --header " + file2
args_header2 = shlex.split(cl_header2)
try:
p1 = Popen(args_header1, stdout=PIPE, stderr=PIPE)
out1, err1 = p1.communicate()
p2 = Popen(args_header2, stdout=PIPE, stderr=PIPE)
out2, err2 = p2.communicate()
if out1 != out2:
print "different header dumps"
print out1
print ""
print out2
except Exception, e:
print e
return False
#print args
'''
try:
p = Popen(args, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if p.returncode >0:
print stdout
print stderr
return False
else :
return True
except Exception, e:
print e
return False
return True
| __pyqtSignals__ = ( "done()")
#QtCore.QThread.__init__(self, parent)
QtCore.QObject.__init__(self)
self.baseMgr = baseMgr
self.listOfResultOverlays = listOfResultOverlays
self.listOfFilenames = listOfFilenames
self.tolerance = tolerance
self.passedTest = False | identifier_body |
testThread.py | from PyQt4 import QtCore
import numpy
from ilastik.core import dataImpex
import shlex
from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray
from ilastik.core.overlays.selectionOverlay import SelectionAccessor
from subprocess import Popen, PIPE
import h5py
# this is the core replacement of the guiThread used to test module functionality
#*******************************************************************************
# T e s t T h r e a d *
#*******************************************************************************
import ilastik.core.jobMachine
def setUp():
if not ilastik.core.jobMachine.GLOBAL_WM:
ilastik.core.jobMachine.GLOBAL_WM = ilastik.core.jobMachine.WorkerManager()
def tearDown():
ilastik.core.jobMachine.GLOBAL_WM.stopWorkers()
del ilastik.core.jobMachine.GLOBAL_WM
ilastik.core.jobMachine.GLOBAL_WM = None
class TestThread(QtCore.QObject):#QtCore.QThread):
def __init__(self, baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
__pyqtSignals__ = ( "done()")
#QtCore.QThread.__init__(self, parent)
QtCore.QObject.__init__(self)
self.baseMgr = baseMgr
self.listOfResultOverlays = listOfResultOverlays
self.listOfFilenames = listOfFilenames
self.tolerance = tolerance
self.passedTest = False
def start(self, input):
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.updateProgress)
# call core function
self.myTestThread = self.baseMgr.computeResults(input)
self.timer.start(200)
def updateProgress(self):
if not self.myTestThread.isRunning():
self.timer.stop()
self.myTestThread.wait()
self.finalize()
def finalize(self):
# call core function
self.baseMgr.finalizeResults()
# compare obtained results with ground truth results
self.passedTest = TestHelperFunctions.compareResultsWithFile(self.baseMgr, self.listOfResultOverlays, self.listOfFilenames, self.tolerance)
# announce that we are done
self.emit(QtCore.SIGNAL("done()"))
'''
# in case you want to create ground truth overlays, use the following code instead of the above
for i in range(len(self.listOfResultOverlays)):
obtained = self.baseMgr.dataMgr[self.baseMgr.dataMgr._activeImageNumber].overlayMgr["Unsupervised/pLSA component %d" % (i+1)]
dataImpex.DataImpex.exportOverlay(self.listOfFilenames[i], "h5", obtained)
'''
#*******************************************************************************
# T e s t H e l p e r F u n c t i o n s *
#*******************************************************************************
class TestHelperFunctions():
@staticmethod
def compareResultsWithFile(baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
equalOverlays = True
for i in range(len(listOfResultOverlays)):
obtained = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[listOfResultOverlays[i]]
prefix = "Ground_Truth/"
dataImpex.DataImpex.importOverlay(baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber], listOfFilenames[i], prefix)
groundTruth = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[prefix + listOfResultOverlays[i]]
equalOverlays = equalOverlays & TestHelperFunctions.compareOverlayData(obtained, groundTruth, tolerance)
print "all ", str(len(listOfResultOverlays)), " compared overlays are equal: ", equalOverlays
return equalOverlays
@staticmethod
# we only compare the data of the overlay, since we want to avoid dependence on color tables etc.
def compareOverlayData(overlay1, overlay2, tolerance = 0):
# overlay1._data._data can be a listOfNDArraysAsNDArray instance, overlay2._data._data is loaded from file, so it should be an NDArray
if isinstance(overlay1._data._data, ListOfNDArraysAsNDArray):
datatemp1 = overlay1._data._data.ndarrays
elif isinstance(overlay1._data._data, SelectionAccessor):
datatemp1 = overlay1._data._data[:]
else:
datatemp1 = overlay1._data._data
datatemp2 = overlay2._data._data
if numpy.all(numpy.abs(datatemp1 - datatemp2) <= tolerance):
return True
else:
return False
@staticmethod
def arrayEqual(a,b):
assert a.shape == b.shape
assert a.dtype == b.dtype
if not numpy.array_equal(a,b):
assert len(a.shape) == 3
for x in range(a.shape[0]):
for y in range(a.shape[1]):
|
return False
return True
@staticmethod
def compareH5Files(file1, file2):
print "files to compare: ", file1, file2
#have to spawn a subprocess, because h5diff has no wrapper in python
cl = "h5diff -cv '" + file1 + "' '" + file2 + "'"
args = shlex.split(cl)
print args
'''
cl_header1 = "h5dump --header " + file1
args_header1 = shlex.split(cl_header1)
cl_header2 = "h5dump --header " + file2
args_header2 = shlex.split(cl_header2)
try:
p1 = Popen(args_header1, stdout=PIPE, stderr=PIPE)
out1, err1 = p1.communicate()
p2 = Popen(args_header2, stdout=PIPE, stderr=PIPE)
out2, err2 = p2.communicate()
if out1 != out2:
print "different header dumps"
print out1
print ""
print out2
except Exception, e:
print e
return False
#print args
'''
try:
p = Popen(args, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if p.returncode >0:
print stdout
print stderr
return False
else :
return True
except Exception, e:
print e
return False
return True
| for z in range(a.shape[2]):
if a[x,y,z] != b[x,y,z]:
print x,y,z, "a=", a[x,y,z], "b=", b[x,y,z] | conditional_block |
testThread.py | from PyQt4 import QtCore
import numpy
from ilastik.core import dataImpex
import shlex
from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray
from ilastik.core.overlays.selectionOverlay import SelectionAccessor
from subprocess import Popen, PIPE
import h5py
# this is the core replacement of the guiThread used to test module functionality
#*******************************************************************************
# T e s t T h r e a d *
#*******************************************************************************
import ilastik.core.jobMachine
def setUp():
if not ilastik.core.jobMachine.GLOBAL_WM:
ilastik.core.jobMachine.GLOBAL_WM = ilastik.core.jobMachine.WorkerManager()
def tearDown():
ilastik.core.jobMachine.GLOBAL_WM.stopWorkers()
del ilastik.core.jobMachine.GLOBAL_WM
ilastik.core.jobMachine.GLOBAL_WM = None
class TestThread(QtCore.QObject):#QtCore.QThread):
def __init__(self, baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
__pyqtSignals__ = ( "done()")
#QtCore.QThread.__init__(self, parent)
QtCore.QObject.__init__(self)
self.baseMgr = baseMgr
self.listOfResultOverlays = listOfResultOverlays
self.listOfFilenames = listOfFilenames
self.tolerance = tolerance
self.passedTest = False
def start(self, input):
self.timer = QtCore.QTimer()
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.updateProgress)
# call core function
self.myTestThread = self.baseMgr.computeResults(input)
self.timer.start(200)
def updateProgress(self):
if not self.myTestThread.isRunning():
self.timer.stop()
self.myTestThread.wait()
self.finalize()
def finalize(self):
# call core function
self.baseMgr.finalizeResults()
# compare obtained results with ground truth results
self.passedTest = TestHelperFunctions.compareResultsWithFile(self.baseMgr, self.listOfResultOverlays, self.listOfFilenames, self.tolerance)
# announce that we are done
self.emit(QtCore.SIGNAL("done()"))
'''
# in case you want to create ground truth overlays, use the following code instead of the above
for i in range(len(self.listOfResultOverlays)):
obtained = self.baseMgr.dataMgr[self.baseMgr.dataMgr._activeImageNumber].overlayMgr["Unsupervised/pLSA component %d" % (i+1)]
dataImpex.DataImpex.exportOverlay(self.listOfFilenames[i], "h5", obtained)
'''
#*******************************************************************************
# T e s t H e l p e r F u n c t i o n s *
#******************************************************************************* | def compareResultsWithFile(baseMgr, listOfResultOverlays, listOfFilenames, tolerance = 0):
equalOverlays = True
for i in range(len(listOfResultOverlays)):
obtained = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[listOfResultOverlays[i]]
prefix = "Ground_Truth/"
dataImpex.DataImpex.importOverlay(baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber], listOfFilenames[i], prefix)
groundTruth = baseMgr.dataMgr[baseMgr.dataMgr._activeImageNumber].overlayMgr[prefix + listOfResultOverlays[i]]
equalOverlays = equalOverlays & TestHelperFunctions.compareOverlayData(obtained, groundTruth, tolerance)
print "all ", str(len(listOfResultOverlays)), " compared overlays are equal: ", equalOverlays
return equalOverlays
@staticmethod
# we only compare the data of the overlay, since we want to avoid dependence on color tables etc.
def compareOverlayData(overlay1, overlay2, tolerance = 0):
# overlay1._data._data can be a listOfNDArraysAsNDArray instance, overlay2._data._data is loaded from file, so it should be an NDArray
if isinstance(overlay1._data._data, ListOfNDArraysAsNDArray):
datatemp1 = overlay1._data._data.ndarrays
elif isinstance(overlay1._data._data, SelectionAccessor):
datatemp1 = overlay1._data._data[:]
else:
datatemp1 = overlay1._data._data
datatemp2 = overlay2._data._data
if numpy.all(numpy.abs(datatemp1 - datatemp2) <= tolerance):
return True
else:
return False
@staticmethod
def arrayEqual(a,b):
assert a.shape == b.shape
assert a.dtype == b.dtype
if not numpy.array_equal(a,b):
assert len(a.shape) == 3
for x in range(a.shape[0]):
for y in range(a.shape[1]):
for z in range(a.shape[2]):
if a[x,y,z] != b[x,y,z]:
print x,y,z, "a=", a[x,y,z], "b=", b[x,y,z]
return False
return True
@staticmethod
def compareH5Files(file1, file2):
print "files to compare: ", file1, file2
#have to spawn a subprocess, because h5diff has no wrapper in python
cl = "h5diff -cv '" + file1 + "' '" + file2 + "'"
args = shlex.split(cl)
print args
'''
cl_header1 = "h5dump --header " + file1
args_header1 = shlex.split(cl_header1)
cl_header2 = "h5dump --header " + file2
args_header2 = shlex.split(cl_header2)
try:
p1 = Popen(args_header1, stdout=PIPE, stderr=PIPE)
out1, err1 = p1.communicate()
p2 = Popen(args_header2, stdout=PIPE, stderr=PIPE)
out2, err2 = p2.communicate()
if out1 != out2:
print "different header dumps"
print out1
print ""
print out2
except Exception, e:
print e
return False
#print args
'''
try:
p = Popen(args, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if p.returncode >0:
print stdout
print stderr
return False
else :
return True
except Exception, e:
print e
return False
return True |
class TestHelperFunctions():
@staticmethod | random_line_split |
15.4.4.16-7-b-11.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.16-7-b-11
description: >
Array.prototype.every - deleting property of prototype causes
prototype index property not to be visited on an Array
includes: [runTestCase.js]
---*/
function | () {
var accessed = false;
function callbackfn(val, idx, obj) {
accessed = true;
return idx !== 1;
}
var arr = [0, , 2];
Object.defineProperty(arr, "0", {
get: function () {
delete Array.prototype[1];
return 0;
},
configurable: true
});
try {
Array.prototype[1] = 1;
return arr.every(callbackfn) && accessed;
} finally {
delete Array.prototype[1];
}
}
runTestCase(testcase);
| testcase | identifier_name |
15.4.4.16-7-b-11.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.16-7-b-11
description: >
Array.prototype.every - deleting property of prototype causes
prototype index property not to be visited on an Array
includes: [runTestCase.js]
---*/
function testcase() { | var arr = [0, , 2];
Object.defineProperty(arr, "0", {
get: function () {
delete Array.prototype[1];
return 0;
},
configurable: true
});
try {
Array.prototype[1] = 1;
return arr.every(callbackfn) && accessed;
} finally {
delete Array.prototype[1];
}
}
runTestCase(testcase); | var accessed = false;
function callbackfn(val, idx, obj) {
accessed = true;
return idx !== 1;
} | random_line_split |
15.4.4.16-7-b-11.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.16-7-b-11
description: >
Array.prototype.every - deleting property of prototype causes
prototype index property not to be visited on an Array
includes: [runTestCase.js]
---*/
function testcase() |
runTestCase(testcase);
| {
var accessed = false;
function callbackfn(val, idx, obj) {
accessed = true;
return idx !== 1;
}
var arr = [0, , 2];
Object.defineProperty(arr, "0", {
get: function () {
delete Array.prototype[1];
return 0;
},
configurable: true
});
try {
Array.prototype[1] = 1;
return arr.every(callbackfn) && accessed;
} finally {
delete Array.prototype[1];
}
} | identifier_body |
control.js | 'use strict';
var hp = require('../modules/hyperpin');
|
exports.actions = function(req, res, ss) {
req.use('session');
require('../modules/announce').registerSocketStream(ss);
return {
/**
* Inserts a coin into the pinball machine.
* @param slot Which slot, 1 or 2
*/
insertCoin: function(slot) {
// access control
if (!req.session.userId) return res(error.unauthorized());
logger.log('info', '[rpc] [control] Inserting coin into slot %s by %s', slot, req.session.user.user);
hp.insertCoin(req.session.user, slot, function(err, result) {
if (err) {
logger.log('error', '[rpc] [hyperpin] [sync] %s', err);
res(error.api(err));
} else {
res(result);
}
});
}
};
}; | var error = require('../modules/error');
var logger = require('winston');
| random_line_split |
test_strings.py | # Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
|
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
| datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "] | identifier_body |
test_strings.py | # Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def | (datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
| test_write_string_table | identifier_name |
test_strings.py | # Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir() | assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def test_write_string_table(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff | src = 'shared-strings-rich.xml'
with open(src) as content: | random_line_split |
recipe-576734.py | import ctypes
class C_struct:
"""Decorator to convert the given class into a C struct."""
# contains a dict of all known translatable types
types = ctypes.__dict__
@classmethod
def register_type(cls, typename, obj):
"""Adds the new class to the dict of understood types."""
cls.types[typename] = obj
def __call__(self, cls):
| """Converts the given class into a C struct.
Usage:
>>> @C_struct()
... class Account:
... first_name = "c_char_p"
... last_name = "c_char_p"
... balance = "c_float"
...
>>> a = Account()
>>> a
<cstruct.Account object at 0xb7c0ee84>
A very important note: while it *is* possible to
instantiate these classes as follows:
>>> a = Account("Geremy", "Condra", 0.42)
This is strongly discouraged, because there is at
present no way to ensure what order the field names
will be read in.
"""
# build the field mapping (names -> types)
fields = []
for k, v in vars(cls).items():
# don't wrap private variables
if not k.startswith("_"):
# if its a pointer
if v.startswith("*"):
field_type = ctypes.POINTER(self.types[v[1:]])
else:
field_type = self.types[v]
new_field = (k, field_type)
fields.append(new_field)
# make our bases tuple
bases = (ctypes.Structure,) + tuple((base for base in cls.__bases__))
# finish up our wrapping dict
class_attrs = {"_fields_": fields, "__doc__": cls.__doc__}
# now create our class
return type(cls.__name__, bases, class_attrs) | identifier_body | |
recipe-576734.py | import ctypes
class C_struct:
"""Decorator to convert the given class into a C struct."""
# contains a dict of all known translatable types
types = ctypes.__dict__
@classmethod
def register_type(cls, typename, obj):
"""Adds the new class to the dict of understood types."""
cls.types[typename] = obj
def __call__(self, cls):
"""Converts the given class into a C struct.
Usage:
>>> @C_struct()
... class Account:
... first_name = "c_char_p"
... last_name = "c_char_p"
... balance = "c_float"
...
>>> a = Account()
>>> a
<cstruct.Account object at 0xb7c0ee84>
A very important note: while it *is* possible to
instantiate these classes as follows:
>>> a = Account("Geremy", "Condra", 0.42)
This is strongly discouraged, because there is at
present no way to ensure what order the field names
will be read in.
"""
# build the field mapping (names -> types)
fields = []
for k, v in vars(cls).items():
# don't wrap private variables
|
# make our bases tuple
bases = (ctypes.Structure,) + tuple((base for base in cls.__bases__))
# finish up our wrapping dict
class_attrs = {"_fields_": fields, "__doc__": cls.__doc__}
# now create our class
return type(cls.__name__, bases, class_attrs)
| if not k.startswith("_"):
# if its a pointer
if v.startswith("*"):
field_type = ctypes.POINTER(self.types[v[1:]])
else:
field_type = self.types[v]
new_field = (k, field_type)
fields.append(new_field) | conditional_block |
recipe-576734.py | import ctypes
class C_struct:
"""Decorator to convert the given class into a C struct."""
# contains a dict of all known translatable types
types = ctypes.__dict__
@classmethod
def register_type(cls, typename, obj):
"""Adds the new class to the dict of understood types."""
cls.types[typename] = obj
def __call__(self, cls):
"""Converts the given class into a C struct.
Usage:
>>> @C_struct()
... class Account:
... first_name = "c_char_p"
... last_name = "c_char_p"
... balance = "c_float"
...
>>> a = Account()
>>> a
<cstruct.Account object at 0xb7c0ee84>
A very important note: while it *is* possible to
instantiate these classes as follows:
>>> a = Account("Geremy", "Condra", 0.42)
This is strongly discouraged, because there is at
present no way to ensure what order the field names
will be read in. | # don't wrap private variables
if not k.startswith("_"):
# if its a pointer
if v.startswith("*"):
field_type = ctypes.POINTER(self.types[v[1:]])
else:
field_type = self.types[v]
new_field = (k, field_type)
fields.append(new_field)
# make our bases tuple
bases = (ctypes.Structure,) + tuple((base for base in cls.__bases__))
# finish up our wrapping dict
class_attrs = {"_fields_": fields, "__doc__": cls.__doc__}
# now create our class
return type(cls.__name__, bases, class_attrs) | """
# build the field mapping (names -> types)
fields = []
for k, v in vars(cls).items(): | random_line_split |
recipe-576734.py | import ctypes
class C_struct:
"""Decorator to convert the given class into a C struct."""
# contains a dict of all known translatable types
types = ctypes.__dict__
@classmethod
def register_type(cls, typename, obj):
"""Adds the new class to the dict of understood types."""
cls.types[typename] = obj
def | (self, cls):
"""Converts the given class into a C struct.
Usage:
>>> @C_struct()
... class Account:
... first_name = "c_char_p"
... last_name = "c_char_p"
... balance = "c_float"
...
>>> a = Account()
>>> a
<cstruct.Account object at 0xb7c0ee84>
A very important note: while it *is* possible to
instantiate these classes as follows:
>>> a = Account("Geremy", "Condra", 0.42)
This is strongly discouraged, because there is at
present no way to ensure what order the field names
will be read in.
"""
# build the field mapping (names -> types)
fields = []
for k, v in vars(cls).items():
# don't wrap private variables
if not k.startswith("_"):
# if its a pointer
if v.startswith("*"):
field_type = ctypes.POINTER(self.types[v[1:]])
else:
field_type = self.types[v]
new_field = (k, field_type)
fields.append(new_field)
# make our bases tuple
bases = (ctypes.Structure,) + tuple((base for base in cls.__bases__))
# finish up our wrapping dict
class_attrs = {"_fields_": fields, "__doc__": cls.__doc__}
# now create our class
return type(cls.__name__, bases, class_attrs)
| __call__ | identifier_name |
__init__.py | """Support for Roku API emulation."""
import voluptuous as vol
from homeassistant import config_entries, util
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from .binding import EmulatedRoku
from .config_flow import configured_servers
from .const import (
CONF_ADVERTISE_IP, CONF_ADVERTISE_PORT, CONF_HOST_IP, CONF_LISTEN_PORT,
CONF_SERVERS, CONF_UPNP_BIND_MULTICAST, DOMAIN)
SERVER_CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_LISTEN_PORT): cv.port,
vol.Optional(CONF_HOST_IP): cv.string,
vol.Optional(CONF_ADVERTISE_IP): cv.string,
vol.Optional(CONF_ADVERTISE_PORT): cv.port,
vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_SERVERS):
vol.All(cv.ensure_list, [SERVER_CONFIG_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up the emulated roku component."""
conf = config.get(DOMAIN)
if conf is None:
return True
existing_servers = configured_servers(hass)
for entry in conf[CONF_SERVERS]:
if entry[CONF_NAME] not in existing_servers:
hass.async_create_task(hass.config_entries.flow.async_init(
DOMAIN,
context={'source': config_entries.SOURCE_IMPORT},
data=entry
))
return True
async def async_setup_entry(hass, config_entry):
"""Set up an emulated roku server from a config entry."""
config = config_entry.data
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
| host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
advertise_ip = config.get(CONF_ADVERTISE_IP)
advertise_port = config.get(CONF_ADVERTISE_PORT)
upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)
server = EmulatedRoku(hass, name, host_ip, listen_port,
advertise_ip, advertise_port, upnp_bind_multicast)
hass.data[DOMAIN][name] = server
return await server.setup()
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
name = entry.data[CONF_NAME]
server = hass.data[DOMAIN].pop(name)
return await server.unload() | name = config[CONF_NAME]
listen_port = config[CONF_LISTEN_PORT] | random_line_split |
__init__.py | """Support for Roku API emulation."""
import voluptuous as vol
from homeassistant import config_entries, util
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from .binding import EmulatedRoku
from .config_flow import configured_servers
from .const import (
CONF_ADVERTISE_IP, CONF_ADVERTISE_PORT, CONF_HOST_IP, CONF_LISTEN_PORT,
CONF_SERVERS, CONF_UPNP_BIND_MULTICAST, DOMAIN)
SERVER_CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_LISTEN_PORT): cv.port,
vol.Optional(CONF_HOST_IP): cv.string,
vol.Optional(CONF_ADVERTISE_IP): cv.string,
vol.Optional(CONF_ADVERTISE_PORT): cv.port,
vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_SERVERS):
vol.All(cv.ensure_list, [SERVER_CONFIG_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up the emulated roku component."""
conf = config.get(DOMAIN)
if conf is None:
return True
existing_servers = configured_servers(hass)
for entry in conf[CONF_SERVERS]:
if entry[CONF_NAME] not in existing_servers:
hass.async_create_task(hass.config_entries.flow.async_init(
DOMAIN,
context={'source': config_entries.SOURCE_IMPORT},
data=entry
))
return True
async def | (hass, config_entry):
"""Set up an emulated roku server from a config entry."""
config = config_entry.data
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
name = config[CONF_NAME]
listen_port = config[CONF_LISTEN_PORT]
host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
advertise_ip = config.get(CONF_ADVERTISE_IP)
advertise_port = config.get(CONF_ADVERTISE_PORT)
upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)
server = EmulatedRoku(hass, name, host_ip, listen_port,
advertise_ip, advertise_port, upnp_bind_multicast)
hass.data[DOMAIN][name] = server
return await server.setup()
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
name = entry.data[CONF_NAME]
server = hass.data[DOMAIN].pop(name)
return await server.unload()
| async_setup_entry | identifier_name |
__init__.py | """Support for Roku API emulation."""
import voluptuous as vol
from homeassistant import config_entries, util
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from .binding import EmulatedRoku
from .config_flow import configured_servers
from .const import (
CONF_ADVERTISE_IP, CONF_ADVERTISE_PORT, CONF_HOST_IP, CONF_LISTEN_PORT,
CONF_SERVERS, CONF_UPNP_BIND_MULTICAST, DOMAIN)
SERVER_CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_LISTEN_PORT): cv.port,
vol.Optional(CONF_HOST_IP): cv.string,
vol.Optional(CONF_ADVERTISE_IP): cv.string,
vol.Optional(CONF_ADVERTISE_PORT): cv.port,
vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_SERVERS):
vol.All(cv.ensure_list, [SERVER_CONFIG_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up the emulated roku component."""
conf = config.get(DOMAIN)
if conf is None:
return True
existing_servers = configured_servers(hass)
for entry in conf[CONF_SERVERS]:
if entry[CONF_NAME] not in existing_servers:
hass.async_create_task(hass.config_entries.flow.async_init(
DOMAIN,
context={'source': config_entries.SOURCE_IMPORT},
data=entry
))
return True
async def async_setup_entry(hass, config_entry):
|
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
name = entry.data[CONF_NAME]
server = hass.data[DOMAIN].pop(name)
return await server.unload()
| """Set up an emulated roku server from a config entry."""
config = config_entry.data
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
name = config[CONF_NAME]
listen_port = config[CONF_LISTEN_PORT]
host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
advertise_ip = config.get(CONF_ADVERTISE_IP)
advertise_port = config.get(CONF_ADVERTISE_PORT)
upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)
server = EmulatedRoku(hass, name, host_ip, listen_port,
advertise_ip, advertise_port, upnp_bind_multicast)
hass.data[DOMAIN][name] = server
return await server.setup() | identifier_body |
__init__.py | """Support for Roku API emulation."""
import voluptuous as vol
from homeassistant import config_entries, util
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from .binding import EmulatedRoku
from .config_flow import configured_servers
from .const import (
CONF_ADVERTISE_IP, CONF_ADVERTISE_PORT, CONF_HOST_IP, CONF_LISTEN_PORT,
CONF_SERVERS, CONF_UPNP_BIND_MULTICAST, DOMAIN)
SERVER_CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_LISTEN_PORT): cv.port,
vol.Optional(CONF_HOST_IP): cv.string,
vol.Optional(CONF_ADVERTISE_IP): cv.string,
vol.Optional(CONF_ADVERTISE_PORT): cv.port,
vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_SERVERS):
vol.All(cv.ensure_list, [SERVER_CONFIG_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up the emulated roku component."""
conf = config.get(DOMAIN)
if conf is None:
return True
existing_servers = configured_servers(hass)
for entry in conf[CONF_SERVERS]:
if entry[CONF_NAME] not in existing_servers:
|
return True
async def async_setup_entry(hass, config_entry):
"""Set up an emulated roku server from a config entry."""
config = config_entry.data
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
name = config[CONF_NAME]
listen_port = config[CONF_LISTEN_PORT]
host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
advertise_ip = config.get(CONF_ADVERTISE_IP)
advertise_port = config.get(CONF_ADVERTISE_PORT)
upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)
server = EmulatedRoku(hass, name, host_ip, listen_port,
advertise_ip, advertise_port, upnp_bind_multicast)
hass.data[DOMAIN][name] = server
return await server.setup()
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
name = entry.data[CONF_NAME]
server = hass.data[DOMAIN].pop(name)
return await server.unload()
| hass.async_create_task(hass.config_entries.flow.async_init(
DOMAIN,
context={'source': config_entries.SOURCE_IMPORT},
data=entry
)) | conditional_block |
Layout.js | // Generated by CoffeeScript 1.9.3
var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth;
Block = require('./layout/Block');
object = require('utila').object;
SpecialString = require('./layout/SpecialString');
terminalWidth = require('./tools').getCols();
module.exports = Layout = (function() {
var self;
self = Layout;
Layout._rootBlockDefaultConfig = {
linePrependor: {
options: {
amount: 0
}
},
lineAppendor: {
options: {
amount: 0
}
},
blockPrependor: {
options: {
amount: 0
}
},
blockAppendor: {
options: {
amount: 0
}
}
};
Layout._defaultConfig = {
terminalWidth: terminalWidth
};
function Layout(config, rootBlockConfig) |
Layout.prototype.getRootBlock = function() {
return this._root;
};
Layout.prototype._append = function(text) {
return this._written.push(text);
};
Layout.prototype._appendLine = function(text) {
var s;
this._append(text);
s = SpecialString(text);
if (s.length < this._config.terminalWidth) {
this._append('<none>\n</none>');
}
return this;
};
Layout.prototype.get = function() {
this._ensureClosed();
if (this._written[this._written.length - 1] === '<none>\n</none>') {
this._written.pop();
}
return this._written.join("");
};
Layout.prototype._ensureClosed = function() {
if (this._activeBlock !== this._root) {
throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks.");
}
if (this._root.isOpen()) {
this._root.close();
}
};
return Layout;
})();
ref = ['openBlock', 'write'];
fn = function() {
var method;
method = prop;
return Layout.prototype[method] = function() {
return this._root[method].apply(this._root, arguments);
};
};
for (i = 0, len = ref.length; i < len; i++) {
prop = ref[i];
fn();
}
| {
var rootConfig;
if (config == null) {
config = {};
}
if (rootBlockConfig == null) {
rootBlockConfig = {};
}
this._written = [];
this._activeBlock = null;
this._config = object.append(self._defaultConfig, config);
rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig);
this._root = new Block(this, null, rootConfig, '__root');
this._root._open();
} | identifier_body |
Layout.js | // Generated by CoffeeScript 1.9.3
var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth;
Block = require('./layout/Block');
object = require('utila').object;
SpecialString = require('./layout/SpecialString');
terminalWidth = require('./tools').getCols();
module.exports = Layout = (function() {
var self;
self = Layout;
Layout._rootBlockDefaultConfig = {
linePrependor: {
options: {
amount: 0
}
},
lineAppendor: {
options: {
amount: 0
}
},
blockPrependor: {
options: {
amount: 0
}
},
blockAppendor: {
options: {
amount: 0
}
}
};
Layout._defaultConfig = {
terminalWidth: terminalWidth
};
function | (config, rootBlockConfig) {
var rootConfig;
if (config == null) {
config = {};
}
if (rootBlockConfig == null) {
rootBlockConfig = {};
}
this._written = [];
this._activeBlock = null;
this._config = object.append(self._defaultConfig, config);
rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig);
this._root = new Block(this, null, rootConfig, '__root');
this._root._open();
}
Layout.prototype.getRootBlock = function() {
return this._root;
};
Layout.prototype._append = function(text) {
return this._written.push(text);
};
Layout.prototype._appendLine = function(text) {
var s;
this._append(text);
s = SpecialString(text);
if (s.length < this._config.terminalWidth) {
this._append('<none>\n</none>');
}
return this;
};
Layout.prototype.get = function() {
this._ensureClosed();
if (this._written[this._written.length - 1] === '<none>\n</none>') {
this._written.pop();
}
return this._written.join("");
};
Layout.prototype._ensureClosed = function() {
if (this._activeBlock !== this._root) {
throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks.");
}
if (this._root.isOpen()) {
this._root.close();
}
};
return Layout;
})();
ref = ['openBlock', 'write'];
fn = function() {
var method;
method = prop;
return Layout.prototype[method] = function() {
return this._root[method].apply(this._root, arguments);
};
};
for (i = 0, len = ref.length; i < len; i++) {
prop = ref[i];
fn();
}
| Layout | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.