file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
seh.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ unsafe { ((*(*eh_ptrs).ExceptionRecord).ExceptionCode == RUST_PANIC) as i32 } }
identifier_body
seh.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{} const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; pub unsafe fn panic(data: Box<Any + Send + 'static>) -> ! { // See module docs above for an explanation of why `data` is stored in a // thread local instead of being passed as an argument to the // `RaiseException` function (which can in theory carry alo...
_EXCEPTION_RECORD
identifier_name
workspace.py
from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(object): log = logging.getLogger('wo...
(self, command, *args, **kwargs): kwargs['stdout'] = PIPE kwargs['stderr'] = STDOUT proc = self._run_process(command, *args, **kwargs) (stdout, stderr) = proc.communicate() if proc.returncode != 0: raise CommandError(command, proc.returncode, stdout, stderr) ...
capture
identifier_name
workspace.py
from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(object):
self.path = path if log is not None: self.log = log def whereis(self, program, env): for path in env.get('PATH', '').split(':'): if os.path.exists(os.path.join(path, program)) and \ not os.path.isdir(os.path.join(path, program)): return...
log = logging.getLogger('workspace') def __init__(self, path, log=None):
random_line_split
workspace.py
from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(object): log = logging.getLogger('wo...
else: msg = traceback.format_exc() raise CommandError(command, 1, stdout=None, stderr=msg) return proc def capture(self, command, *args, **kwargs): kwargs['stdout'] = PIPE kwargs['stderr'] = STDOUT proc = self._run_process(command, *args, **...
msg = 'ERROR: Command not found: {}'.format(command[0])
conditional_block
workspace.py
from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(object): log = logging.getLogger('wo...
class TemporaryWorkspace(Workspace): def __init__(self, *args, **kwargs): path = os.path.join( current_app.config['WORKSPACE_ROOT'], 'freight-workspace-{}'.format(uuid1().hex), ) super(TemporaryWorkspace, self).__init__(path, *args, **kwargs)
if os.path.exists(self.path): shutil.rmtree(self.path)
identifier_body
globals.d.ts
declare module 'meteor/react-meteor-data' {
} export var ReactMeteorData: IReactMeteorData; // param `component:ComponentClass<P>` causes problem if the componet // when the component has `static propTypes` function createContainer<P>(propsfn: (props: P) => any, component:any): ComponentClass<P>; export { createContainer }; } declare mo...
import ComponentClass = __React.ComponentClass; interface IReactMeteorData { data: any;
random_line_split
imageGradientStructureTensor.py
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageGradientStructureTensor(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_...
def config_to_view(self): pass def execute_module(self): self._imageGradientStructureTensor.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
pass
identifier_body
imageGradientStructureTensor.py
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageGradientStructureTensor(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_...
def execute_module(self): self._imageGradientStructureTensor.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
def config_to_view(self): pass
random_line_split
imageGradientStructureTensor.py
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageGradientStructureTensor(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_...
(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(sel...
close
identifier_name
imageGradientStructureTensor.py
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageGradientStructureTensor(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_...
self._viewFrame.Raise()
conditional_block
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct
{ gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectan...
App
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
if let Some(u) = e.update_args() { app.update(&u); } } }
{ app.render(&r); }
conditional_block
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. // let opengl = OpenGL::V3_2; let opengl = Ope...
{ use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as...
identifier_body
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
} } fn main() { // Change this to OpenGL::V2_1 if not working. // let opengl = OpenGL::V3_2; let opengl = OpenGL::V2_1; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_o...
// Rotate 2 radians per second. self.rotation += 2.0 * args.dt;
random_line_split
index.ts
import type { Locale } from '../types' import formatDistance from './_lib/formatDistance/index' import formatLong from './_lib/formatLong/index' import formatRelative from './_lib/formatRelative/index' import localize from './_lib/localize/index' import match from './_lib/match/index' /** * @type {Locale} * @categor...
match: match, options: { weekStartsOn: 1 /* Monday */, firstWeekContainsDate: 1 /* First week of new year contains Jan 1st */, }, } export default locale
formatRelative: formatRelative, localize: localize,
random_line_split
TestResitiveNetwork-circuits.py
as np import networkx as nx from pyunicorn import ResNetwork from .ResistiveNetwork_utils import * debug = 0 """ Test for basic sanity, parallel and serial circiuts """ def testParallelTrivial(): r""" Trivial parallel case: a) 0 --- 1 --- 2 /---- 3 ---\ b) 0 --- 1 --- 2 c) /---- 3 ---...
for i, j, v in zip(idI, idJ, val): nw1[i, j] = v nw1[j, i] = v # construct nw2 idI = idI + [2, 3] idJ = idJ + [3, 4] val = val + [1, 1] nw2 = np.zeros((5, 5)) for i, j, v in zip(idI, idJ, val): nw2[i, j] = v nw2[j, i] = v # init ResNetworks rnw1 = R...
nw1 = np.zeros((3, 3)) G1 = nx.DiGraph()
random_line_split
TestResitiveNetwork-circuits.py
as np import networkx as nx from pyunicorn import ResNetwork from .ResistiveNetwork_utils import * debug = 0 """ Test for basic sanity, parallel and serial circiuts """ def testParallelTrivial(): r""" Trivial parallel case: a) 0 --- 1 --- 2 /---- 3 ---\ b) 0 --- 1 --- 2 c) /---- 3 ---...
assert abs(ER[0]/2-ER[1]) < .1E-6 assert abs(ER[0]/3-ER[2]) < .1E-6 def testParallelLessTrivial(): """ Less Trivial Parallel Case: |--- 1 --- 0 a) 2 | |--- 3 ----4 |--- 1 --- 0 --- 5 --- | b) 2 | | 7 |--- 3 ----4 --- ...
rnw = ResNetwork(nw) ER.append(rnw.effective_resistance(0, 2))
conditional_block
TestResitiveNetwork-circuits.py
as np import networkx as nx from pyunicorn import ResNetwork from .ResistiveNetwork_utils import * debug = 0 """ Test for basic sanity, parallel and serial circiuts """ def
(): r""" Trivial parallel case: a) 0 --- 1 --- 2 /---- 3 ---\ b) 0 --- 1 --- 2 c) /---- 3 ---\ 0 --- 1 --- 2 \____ 4 ___/ ER(a) = 2*ER(b) = 3*ER(c) """ nws = [] # construct nw1 idI, idJ = [0, 1], [1, 2] nws.append(makeNW(idI, idJ, [.1])) # const...
testParallelTrivial
identifier_name
TestResitiveNetwork-circuits.py
case: a) 0 --- 1 --- 2 /---- 3 ---\ b) 0 --- 1 --- 2 c) /---- 3 ---\ 0 --- 1 --- 2 \____ 4 ___/ ER(a) = 2*ER(b) = 3*ER(c) """ nws = [] # construct nw1 idI, idJ = [0, 1], [1, 2] nws.append(makeNW(idI, idJ, [.1])) # construct nw2 idI += [0, 3] ...
""" 50 Random serial test cases """ N = 10 p = .7 runs = 0 while runs < 50: # a random graph G = nx.fast_gnp_random_graph(N, p) try: nx.shortest_path(G, source=0, target=N-1) except RuntimeError: continue # convert to plain ndarray ...
identifier_body
module.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnnotationsQueryCtrl = exports.QueryOptionsCtrl = exports.ConfigCtrl = exports.QueryCtrl = exports.Datasource = undefined; var _datasource = require('./datasource'); var _query_ctrl = require('./query_ctrl'); require('./netxms_ob...
(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var NetXMSConfigCtrl = function NetXMSConfigCtrl() { _classCallCheck(this, NetXMSConfigCtrl); }; NetXMSConfigCtrl.templateUrl = 'partials/config.html'; var NetXMSQueryOptionsCtrl = func...
_classCallCheck
identifier_name
module.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnnotationsQueryCtrl = exports.QueryOptionsCtrl = exports.ConfigCtrl = exports.QueryCtrl = exports.Datasource = undefined; var _datasource = require('./datasource'); var _query_ctrl = require('./query_ctrl'); require('./netxms_ob...
} var NetXMSConfigCtrl = function NetXMSConfigCtrl() { _classCallCheck(this, NetXMSConfigCtrl); }; NetXMSConfigCtrl.templateUrl = 'partials/config.html'; var NetXMSQueryOptionsCtrl = function NetXMSQueryOptionsCtrl() { _classCallCheck(this, NetXMSQueryOptionsCtrl); }; NetXMSQueryOptionsCtrl.templateUrl = 'part...
{ throw new TypeError("Cannot call a class as a function"); }
conditional_block
module.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnnotationsQueryCtrl = exports.QueryOptionsCtrl = exports.ConfigCtrl = exports.QueryCtrl = exports.Datasource = undefined; var _datasource = require('./datasource'); var _query_ctrl = require('./query_ctrl'); require('./netxms_ob...
NetXMSConfigCtrl.templateUrl = 'partials/config.html'; var NetXMSQueryOptionsCtrl = function NetXMSQueryOptionsCtrl() { _classCallCheck(this, NetXMSQueryOptionsCtrl); }; NetXMSQueryOptionsCtrl.templateUrl = 'partials/query.options.html'; var NetXMSAnnotationsQueryCtrl = function NetXMSAnnotationsQueryCtrl() { _c...
random_line_split
module.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnnotationsQueryCtrl = exports.QueryOptionsCtrl = exports.ConfigCtrl = exports.QueryCtrl = exports.Datasource = undefined; var _datasource = require('./datasource'); var _query_ctrl = require('./query_ctrl'); require('./netxms_ob...
var NetXMSConfigCtrl = function NetXMSConfigCtrl() { _classCallCheck(this, NetXMSConfigCtrl); }; NetXMSConfigCtrl.templateUrl = 'partials/config.html'; var NetXMSQueryOptionsCtrl = function NetXMSQueryOptionsCtrl() { _classCallCheck(this, NetXMSQueryOptionsCtrl); }; NetXMSQueryOptionsCtrl.templateUrl = 'partia...
{ if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
identifier_body
8e0f791e-b273-4267-8605-b7c2f55a68ab-de_DE.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="de_DE"> <context> <name>NetworkDetector</name> <message> <location filename="../plugininfo.h" line="32"/> <source>NetworkDetector</source> <extracomment>The name of the plugin NetworkDetector (8e0f791e-b273-...
</message> </context> </TS>
<translation type="unfinished"></translation>
random_line_split
mesh.py
vec4 pos_front = $scene2doc(pos_scene); pos_front.z += 0.01; pos_front = $doc2scene(pos_front); pos_front /= pos_front.w; vec4 pos_back = $scene2doc(pos_scene); pos_back.z -= 0.01; pos_back = $doc2scene(pos_back); pos_back /= pos_back.w; vec3 eye = normalize(pos_front.xyz - pos_back.x...
(self): """The uniform color for this mesh. This value is only used if per-vertex or per-face colors are not specified. """ return self._color @color.setter def color(self, c): self.set_data(color=c) def mesh_data_changed(self): self._data_changed =...
color
identifier_name
mesh.py
vec4(xyz, 1.0); } """) vec2to4 = Function(""" vec4 vec2to4(vec2 xyz) { return vec4(xyz, 0.0, 1.0); } """) class MeshVisual(Visual): """Mesh visual Parameters ---------- vertices : array-like | None The vertices. faces : array-like | None The faces. vertex_colors : array-...
def _prepare_draw(self, view): if self._data_changed: if self._update_data() is False: return False self._data_changed = False
random_line_split
mesh.py
vec4 pos_front = $scene2doc(pos_scene); pos_front.z += 0.01; pos_front = $doc2scene(pos_front); pos_front /= pos_front.w; vec4 pos_back = $scene2doc(pos_scene); pos_back.z -= 0.01; pos_back = $doc2scene(pos_back); pos_back /= pos_back.w; vec3 eye = normalize(pos_front.xyz - pos_back.x...
@property def mesh_data(self): """The mesh data""" return self._meshdata @property def color(self): """The uniform color for this mesh. This value is only used if per-vertex or per-face colors are not specified. """ return self._color @col...
modes = ['triangles', 'triangle_strip', 'triangle_fan'] if m not in modes: raise ValueError("Mesh mode must be one of %s" % ', '.join(modes)) self._draw_mode = m
identifier_body
mesh.py
v_light_vec = light; //VARYING COPY gl_Position = $transform($to_vec4($position)); } """ shading_fragment_template = """ varying vec3 v_normal_vec; varying vec3 v_light_vec; varying vec3 v_eye_vec; varying vec4 v_ambientk; varying vec4 v_light_color; varying vec4 v_base_color; void main() { //DIFFUSE ...
self.shared_program.vert['to_vec4'] = vec2to4
conditional_block
test_probe_count.py
#!/usr/bin/env python # Copyright (c) Suchakra Sharma <suchakrapani.sharma@polymtl.ca> # Licensed under the Apache License, Version 2.0 (the "License") from bcc import BPF, _get_num_open_probes, TRACEFS import os import sys from unittest import main, TestCase class TestKprobeCnt(TestCase): def setUp(self): ...
class TestProbeQuota(TestCase): def setUp(self): self.b = BPF(text="""int count(void *ctx) { return 0; }""") def test_probe_quota(self): with self.assertRaises(Exception): self.b.attach_kprobe(event_re=".*", fn_name="count") def test_uprobe_quota(self): with self.asser...
random_line_split
test_probe_count.py
#!/usr/bin/env python # Copyright (c) Suchakra Sharma <suchakrapani.sharma@polymtl.ca> # Licensed under the Apache License, Version 2.0 (the "License") from bcc import BPF, _get_num_open_probes, TRACEFS import os import sys from unittest import main, TestCase class TestKprobeCnt(TestCase): def setUp(self): ...
(TestCase): def setUp(self): self.b = BPF(text="""int count(void *ctx) { return 0; }""") def test_not_exist(self): with self.assertRaises(Exception): b.attach_kprobe(event="___doesnotexist", fn_name="count") def tearDown(self): self.b.cleanup() if __name__ == "__main_...
TestProbeNotExist
identifier_name
test_probe_count.py
#!/usr/bin/env python # Copyright (c) Suchakra Sharma <suchakrapani.sharma@polymtl.ca> # Licensed under the Apache License, Version 2.0 (the "License") from bcc import BPF, _get_num_open_probes, TRACEFS import os import sys from unittest import main, TestCase class TestKprobeCnt(TestCase): def setUp(self): ...
def tearDown(self): self.b.cleanup() class TestProbeGlobalCnt(TestCase): def setUp(self): self.b1 = BPF(text="""int count(void *ctx) { return 0; }""") self.b2 = BPF(text="""int count(void *ctx) { return 0; }""") def test_probe_quota(self): self.b1.attach_kprobe(event="sc...
actual_cnt = 0 with open("%s/available_filter_functions" % TRACEFS, "rb") as f: for line in f: if line.startswith(b"vfs_"): actual_cnt += 1 open_cnt = self.b.num_open_kprobes() self.assertEqual(actual_cnt, open_cnt)
identifier_body
test_probe_count.py
#!/usr/bin/env python # Copyright (c) Suchakra Sharma <suchakrapani.sharma@polymtl.ca> # Licensed under the Apache License, Version 2.0 (the "License") from bcc import BPF, _get_num_open_probes, TRACEFS import os import sys from unittest import main, TestCase class TestKprobeCnt(TestCase): def setUp(self): ...
main()
conditional_block
primitive_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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, inc...
<'a, T> where T: PrimitiveElement { marker : ::std::marker::PhantomData<T>, builder : ListBuilder<'a> } impl <'a, T> Builder<'a, T> where T: PrimitiveElement { pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> { Builder { builder : builder, marker : ::std::marker::PhantomData } } pub...
Builder
identifier_name
primitive_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: //
// 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 WAR...
// 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
random_line_split
primitive_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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, inc...
} pub struct Builder<'a, T> where T: PrimitiveElement { marker : ::std::marker::PhantomData<T>, builder : ListBuilder<'a> } impl <'a, T> Builder<'a, T> where T: PrimitiveElement { pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> { Builder { builder : builder, marker : ::std::marker::Phanto...
{ assert!(index < self.len()); PrimitiveElement::get(&self.reader, index) }
identifier_body
test.py
#Unused def fail(): for t in [TypeA, TypeB]: x = TypeA() run_test(x) #OK by name def OK1(seq): for _ in seq: do_something() print("Hi") #OK counting def OK2(seq): i = 3 for x in seq: i += 1 return i #OK check emptiness def OK3(seq): for thing in seq: ...
def fail4(coll, sequence): while coll: x = coll.pop() for s in sequence: do_something(x+1) #OK See ODASA-4153 and ODASA-4533 def fail5(t): x, y = t return x class OK9(object): cls_attr = 0 def __init__(self): self.attr = self.cls_attr __all__ = [ 'hello' ] __all__.e...
for x in sequence: do_something(x+1) for y in sequence: do_something(x+1)
identifier_body
test.py
#Unused def fail(): for t in [TypeA, TypeB]: x = TypeA() run_test(x) #OK by name def OK1(seq): for _ in seq: do_something() print("Hi") #OK counting def OK2(seq): i = 3 for x in seq: i += 1 return i #OK check emptiness def OK3(seq): for thing in seq: ...
(seq, queue): for x in seq: queue.add(None) def OK8(seq, output): for x in seq: output.append("</item>") #Not OK -- Use a constant, but also a variable def fail2(sequence): for x in sequence: for y in sequence: do_something(x+1) def fail3(sequence): for x in sequen...
OK7
identifier_name
test.py
#Unused def fail(): for t in [TypeA, TypeB]: x = TypeA() run_test(x) #OK by name def OK1(seq): for _ in seq: do_something() print("Hi") #OK counting def OK2(seq): i = 3 for x in seq:
#OK check emptiness def OK3(seq): for thing in seq: return "Not empty" return "empty" #OK iteration over range def OK4(n): r = range(n) for i in r: print("x") #OK named as unused def OK5(seq): for unused_x in seq: print("x") #ODASA-3794 def OK6(seq): for thing in seq:...
i += 1 return i
random_line_split
test.py
#Unused def fail(): for t in [TypeA, TypeB]:
#OK by name def OK1(seq): for _ in seq: do_something() print("Hi") #OK counting def OK2(seq): i = 3 for x in seq: i += 1 return i #OK check emptiness def OK3(seq): for thing in seq: return "Not empty" return "empty" #OK iteration over range def OK4(n): r ...
x = TypeA() run_test(x)
conditional_block
eg-enum-use.rs
#![allow(dead_code)] enum HTTPGood { HTTP200, HTTP300, } enum HTTPBad { HTTP400, HTTP500, } fn server_debug() { use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping use HTTPBad::*; // automatically use each name let good = HTTP200; // equivalent to HTTPGood::H...
match bad { HTTP400 => println!("bad client"), HTTP500 => println!("bad server"), } } enum BrowserEvent { // may be unit like Render, Clear, // tuple structs KeyPress(char), LoadFrame(String), // or structs Click { x: i64, y: i64 }, } fn browser_debug(event: Bro...
match good { HTTP200 => println!("okay"), HTTP300 => println!("redirect"), }
random_line_split
eg-enum-use.rs
#![allow(dead_code)] enum HTTPGood { HTTP200, HTTP300, } enum HTTPBad { HTTP400, HTTP500, } fn server_debug() { use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping use HTTPBad::*; // automatically use each name let good = HTTP200; // equivalent to HTTPGood::H...
{ // may be unit like Render, Clear, // tuple structs KeyPress(char), LoadFrame(String), // or structs Click { x: i64, y: i64 }, } fn browser_debug(event: BrowserEvent) { match event { BrowserEvent::Render => println!("render page"), BrowserEvent::Clear => println!(...
BrowserEvent
identifier_name
eg-enum-use.rs
#![allow(dead_code)] enum HTTPGood { HTTP200, HTTP300, } enum HTTPBad { HTTP400, HTTP500, } fn server_debug() { use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping use HTTPBad::*; // automatically use each name let good = HTTP200; // equivalent to HTTPGood::H...
{ server_debug(); let render = BrowserEvent::Render; let clear = BrowserEvent::Clear; let keypress = BrowserEvent::KeyPress('z'); let frame = BrowserEvent::LoadFrame("example.com".to_owned()); // creates an owned String from string slice let click = BrowserEvent::Click {x: 120, y: 240}; bro...
identifier_body
settings.py
# -*- coding: utf-8 -*- # Scrapy settings for spider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/...
NEWSPIDER_MODULE = 'spider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'spider (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5' # Configure max...
BOT_NAME = 'spider' SPIDER_MODULES = ['spider.spiders']
random_line_split
alarm.py
is reached."), default='true', update_allowed=True ) } NOVA_METERS = ['instance', 'memory', 'memory.usage', 'cpu', 'cpu_util', 'vcpus', 'disk.read.requests', 'disk.read.requests.rate', 'disk.write.requests', 'disk.write.requests.rate', '...
handle_update
identifier_name
alarm.py
else: if act: kwargs[k].append(act) else: kwargs[k] = v return kwargs class CeilometerAlarm(resource.Resource): PROPERTIES = ( COMPARISON_OPERATOR, EVALUATION_PERIODS, METER_NAME, PERIOD, STATISTIC, THRESHOLD, MAT...
return { 'OS::Ceilometer::Alarm': CeilometerAlarm, 'OS::Ceilometer::CombinationAlarm': CombinationAlarm, }
identifier_body
alarm.py
, _('Description for the alarm.'), update_allowed=True ), ENABLED: properties.Schema( properties.Schema.BOOLEAN, _('True if alarm evaluation/actioning is enabled.'), default='true', update_allowed=True ), ALARM_ACTIONS: properties.Schema( propertie...
elif m_k.startswith(prefix): key = 'metadata.%s' % m_k else: key = 'metadata.%s%s' % (prefix, m_k) # NOTE(prazumovsky): type of query value must be a string, but # matching_metadata value type can not be a string, so we # must ...
key = m_k
conditional_block
alarm.py
[act].FnGetAtt('AlarmUrl') kwargs[k].append(url) else: if act: kwargs[k].append(act) else: kwargs[k] = v return kwargs class CeilometerAlarm(resource.Resource): PROPERTIES = ( COMPARISON_OPERATOR, EVAL...
'OS::Ceilometer::Alarm': CeilometerAlarm,
random_line_split
create-db-connection.ts
import { knex, Knex } from 'knex'; import path from 'path'; import { promisify } from 'util'; export type Credentials = { filename?: string; host?: string; port?: number; database?: string; user?: string; password?: string; ssl?: boolean; options__encrypt?: boolean; }; export default function
( client: 'sqlite3' | 'mysql' | 'pg' | 'oracledb' | 'mssql' | 'cockroachdb', credentials: Credentials ): Knex<any, unknown[]> { let connection: Knex.Config['connection'] = {}; if (client === 'sqlite3') { const { filename } = credentials; connection = { filename: filename as string, }; } else { const {...
createDBConnection
identifier_name
create-db-connection.ts
import { knex, Knex } from 'knex'; import path from 'path'; import { promisify } from 'util'; export type Credentials = { filename?: string; host?: string; port?: number; database?: string; user?: string; password?: string; ssl?: boolean; options__encrypt?: boolean; }; export default function createDBConnectio...
const db = knex(knexConfig); return db; }
{ knexConfig.pool!.afterCreate = async (conn: any, callback: any) => { const run = promisify(conn.query.bind(conn)); await run('SET serial_normalization = "sql_sequence"'); await run('SET default_int_size = 4'); callback(null, conn); }; }
conditional_block
create-db-connection.ts
import { knex, Knex } from 'knex'; import path from 'path'; import { promisify } from 'util'; export type Credentials = { filename?: string; host?: string; port?: number; database?: string; user?: string; password?: string; ssl?: boolean; options__encrypt?: boolean; }; export default function createDBConnectio...
if (client === 'pg' || client === 'cockroachdb') { const { ssl } = credentials as Credentials; connection['ssl'] = ssl; } if (client === 'mssql') { const { options__encrypt } = credentials as Credentials; (connection as Knex.MsSqlConnectionConfig)['options'] = { encrypt: options__encrypt, }; ...
{ let connection: Knex.Config['connection'] = {}; if (client === 'sqlite3') { const { filename } = credentials; connection = { filename: filename as string, }; } else { const { host, port, database, user, password } = credentials as Credentials; connection = { host: host, port: Number(port), ...
identifier_body
create-db-connection.ts
import { knex, Knex } from 'knex'; import path from 'path'; import { promisify } from 'util'; export type Credentials = { filename?: string; host?: string; port?: number; database?: string; user?: string; password?: string; ssl?: boolean; options__encrypt?: boolean; }; export default function createDBConnectio...
}, pool: {}, }; if (client === 'sqlite3') { knexConfig.useNullAsDefault = true; } if (client === 'cockroachdb') { knexConfig.pool!.afterCreate = async (conn: any, callback: any) => { const run = promisify(conn.query.bind(conn)); await run('SET serial_normalization = "sql_sequence"'); await run('...
directory: path.resolve(__dirname, '../../database/seeds/'),
random_line_split
app.e2e-spec.ts
/** * @license * Todo Storage for wifeys Todo app. * Copyright (C) 2017 Simon Wendel * * 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 opt...
import {TodoAdminClientPage} from './app.po'; describe('e2e: Authentication admin page', () => { let adminPage: TodoAdminClientPage; let numberOfSecrets: number; beforeEach(async () => { adminPage = new TodoAdminClientPage(); await adminPage.navigateTo(); }); it('should have a da...
* * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */
random_line_split
pratparser.rs
enum
{ Atom(String), Cons(String, Vec<S>), } impl std::fmt::Display for S { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { S::Atom(i) => write!(f, "{}", i), S::Cons(head, rest) => { write!(f, "({}", head)?; for s...
S
identifier_name
pratparser.rs
enum S { Atom(String), Cons(String, Vec<S>), } impl std::fmt::Display for S { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { S::Atom(i) => write!(f, "{}", i), S::Cons(head, rest) => { write!(f, "({}", head)?; ...
'[' => { let rhs = expr_bp(lexer, 0); assert_eq!(lexer.next(), Token::Op(']')); S::Cons(op.to_string(), vec![lhs, rhs]) } '(' => { let mut args = vec![expr_bp(lexer, 0)]; w...
lexer.next(); lhs = match op {
random_line_split
java.security.KeyPairGenerator.d.ts
declare namespace java { namespace security { abstract class KeyPairGenerator extends java.security.KeyPairGeneratorSpi { provider: java.security.Provider protected constructor(arg0: java.lang.String | string) public getAlgorithm(): java.lang.String
public initialize(arg0: number | java.lang.Integer): void public initialize(arg0: number | java.lang.Integer, arg1: java.security.SecureRandom): void public initialize(arg0: java.security.spec.AlgorithmParameterSpec): void public initialize(arg0: java.security.spec.AlgorithmParameterSpec, arg1: ...
public static getInstance(arg0: java.lang.String | string): java.security.KeyPairGenerator public static getInstance(arg0: java.lang.String | string, arg1: java.lang.String | string): java.security.KeyPairGenerator public static getInstance(arg0: java.lang.String | string, arg1: java.security.Provider...
random_line_split
login.component.ts
/** * Created by pohodnaivan on 05.06.17. */ import {Component, OnInit} from '@angular/core'; import {FormBuilder} from '@angular/forms'; import {FormGroup} from '@angular/forms'; import {User} from '../../../models/Model'; import AuthService = require('../../../service/web/auth.service'); import {MdDialogRef, MdSnac...
if (this.dialogRef) { this.snackBar.open(`successful login! as ${user.name}`, null, { duration: 1000 }); this.dialogRef.close(user); } }); } }
{ this.snackBar.open(`wrong login or password!`, null, { duration: 1000 }); return; }
conditional_block
login.component.ts
/** * Created by pohodnaivan on 05.06.17. */ import {Component, OnInit} from '@angular/core'; import {FormBuilder} from '@angular/forms'; import {FormGroup} from '@angular/forms'; import {User} from '../../../models/Model'; import AuthService = require('../../../service/web/auth.service'); import {MdDialogRef, MdSnac...
this.dialogRef = dialogRef; } ngOnInit() { this.loginForm = this.fb.group(new User()); } login(): void { this.authService.login(this.loginForm.get('login').value, this.loginForm.get('password').value).then((user) => { if (!user) { this.snackBar.open(`wrong login or password!`, null, ...
constructor(fb: FormBuilder, authService: AuthService, dialogRef: MdDialogRef<LoginComponent>, private snackBar: MdSnackBar) { this.fb = fb; this.authService = authService;
random_line_split
login.component.ts
/** * Created by pohodnaivan on 05.06.17. */ import {Component, OnInit} from '@angular/core'; import {FormBuilder} from '@angular/forms'; import {FormGroup} from '@angular/forms'; import {User} from '../../../models/Model'; import AuthService = require('../../../service/web/auth.service'); import {MdDialogRef, MdSnac...
(fb: FormBuilder, authService: AuthService, dialogRef: MdDialogRef<LoginComponent>, private snackBar: MdSnackBar) { this.fb = fb; this.authService = authService; this.dialogRef = dialogRef; } ngOnInit() { this.loginForm = this.fb.group(new User()); } login(): void { this.auth...
constructor
identifier_name
config.js
var path = require('path'), fs = require('fs'), Source = require(hexo.lib_dir + '/core/source'), config_dir = path.dirname(hexo.configfile), config = hexo.config; function testver(){ var ver = hexo.env.version.split('.'); var test = true; if (ver[0] < 2) test = false; else if (ver[0] == 2 &...
}) hexo.source = new Source(); } var load_default_usercfg = function(){ var cfg = global.usercfg = { ajax_widgets: true, updated: true, cache d_widgets:true }; cfg.twbs_style = ['primary','success','info','warning','danger']; var user_cfg = hexo.source_dir + '_' + hexo.config.theme...
path.sep; return str; }; var custom = config.CustomDir; ['public_dir','source_dir','scaffold_dir'].forEach(function(p){ if (!custom[p]) return; if (custom[p] == 'auto'){ hexo.constant(p,joinPath(config_dir,p)); } else { var test = custom[p].match(/^:config(.*)$/); ...
conditional_block
config.js
var path = require('path'), fs = require('fs'), Source = require(hexo.lib_dir + '/core/source'), config_dir = path.dirname(hexo.configfile),
config = hexo.config; function testver(){ var ver = hexo.env.version.split('.'); var test = true; if (ver[0] < 2) test = false; else if (ver[0] == 2 && ver[1] < 5) test = false; if (test) return; var hexo_curver = 'hexo'.red + (' V' + hexo.env.version).green; var theme_curver = 'chenal...
random_line_split
config.js
var path = require('path'), fs = require('fs'), Source = require(hexo.lib_dir + '/core/source'), config_dir = path.dirname(hexo.configfile), config = hexo.config; function testver(){ var ver = hexo.env.version.split('.'); var test = true; if (ver[0] < 2) test = false; else if (ver[0] == 2 &...
'ejs']) error += '\tnpm install hexo-renderer-ejs\n'; if (!store['md']) error += '\tnpm install hexo-renderer-marked\n'; if (!store['styl']) error +='\tnpm install hexo-renderer-stylus\n'; if (error){ hexo.log.e('\t主题使用环境检测失败\n\n\t缺少必要插件,请使用以下命令安装:\n\n',error); process.exit(1); } } testver()...
(!store[
identifier_name
config.js
var path = require('path'), fs = require('fs'), Source = require(hexo.lib_dir + '/core/source'), config_dir = path.dirname(hexo.configfile), config = hexo.config; function testver(){ var ver = hexo.env.version.split('.'); var test = true; if (ver[0] < 2) test = false; else if (ver[0] == 2 &...
hexo.__dump = function(obj){ var cache = []; return JSON.stringify(obj,function(key, value){ if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } cache.push(value); } return v...
js']) error += '\tnpm install hexo-renderer-ejs\n'; if (!store['md']) error += '\tnpm install hexo-renderer-marked\n'; if (!store['styl']) error +='\tnpm install hexo-renderer-stylus\n'; if (error){ hexo.log.e('\t主题使用环境检测失败\n\n\t缺少必要插件,请使用以下命令安装:\n\n',error); process.exit(1); } } testver(); ...
identifier_body
group.metadata.comp.ts
import { Location } from '@angular/common'; import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { throwError as observableThrowError, of as observableOf, Observab...
(private readonly fb: FormBuilder, private readonly location: Location, private readonly router: Router, private readonly groupHttp: GroupHttpService, private readonly permissionHttp: PermissionHttpService, private readonly alertService: AlertService...
constructor
identifier_name
group.metadata.comp.ts
import { Location } from '@angular/common'; import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { throwError as observableThrowError, of as observableOf, Observab...
constructor(private readonly fb: FormBuilder, private readonly location: Location, private readonly router: Router, private readonly groupHttp: GroupHttpService, private readonly permissionHttp: PermissionHttpService, private readonly alertService...
private _groupSub: Subscription;
random_line_split
group.metadata.comp.ts
import { Location } from '@angular/common'; import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { throwError as observableThrowError, of as observableOf, Observab...
}
{ this.location.back(); }
identifier_body
group.metadata.comp.ts
import { Location } from '@angular/common'; import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { throwError as observableThrowError, of as observableOf, Observab...
else { return this.groupHttp.saveGroup(groupToSave) } })).subscribe( () => { this.alertService.success(`Successfully saved user group '${groupName}'.`); this.userGroupForm.reset(); if (this.mode === this.modes.NEW) { this.router.navigate(['/group', groupName])...
{ return observableThrowError(`A user group named '${groupName}' already exists!`); }
conditional_block
task.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/delay'; import 'rxjs/add/operator/map'; import { ITask } from '../../models/task/task.model'; // mock data const testTasks: Array<ITask> = [ { id: '1', ...
}
{ // send the new task-item to the server return Observable.of(task).delay(2000) .map(result => result); }
identifier_body
task.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/delay'; import 'rxjs/add/operator/map'; import { ITask } from '../../models/task/task.model'; // mock data const testTasks: Array<ITask> = [ { id: '1', ...
} addTask(task: ITask) { // send the new task-item to the server return Observable.of(task).delay(2000) .map(result => result); } }
.map(result => result);
random_line_split
task.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/delay'; import 'rxjs/add/operator/map'; import { ITask } from '../../models/task/task.model'; // mock data const testTasks: Array<ITask> = [ { id: '1', ...
(): Observable<Array<ITask>> { return Observable.of(testTasks).delay(2000) .map(result => result); } addTask(task: ITask) { // send the new task-item to the server return Observable.of(task).delay(2000) .map(result => result); } }
getTasks
identifier_name
plot_queue.py
''' Plot queue occupancy over time ''' from helper import * import plot_defaults parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', help="Queue timeseries output to one plot", required=True, action="store", nargs='+',...
(i): if i == 0: return {'color': 'red'} else: return {'color': 'black', 'ls': '-.'} for i, f in enumerate(args.files): data = read_list(f) xaxis = map(float, col(0, data)) start_time = xaxis[0] xaxis = map(lambda x: x - start_time, xaxis) qlens = map(float, col(1, data)) ...
get_style
identifier_name
plot_queue.py
''' Plot queue occupancy over time ''' from helper import * import plot_defaults parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', help="Queue timeseries output to one plot", required=True, action="store", nargs='+',...
for i, f in enumerate(args.files): data = read_list(f) xaxis = map(float, col(0, data)) start_time = xaxis[0] xaxis = map(lambda x: x - start_time, xaxis) qlens = map(float, col(1, data)) if args.summarise or args.cdf: to_plot.append(qlens[10:-10]) else: plt.plot(xaxis, qle...
if i == 0: return {'color': 'red'} else: return {'color': 'black', 'ls': '-.'}
identifier_body
plot_queue.py
''' Plot queue occupancy over time ''' from helper import * import plot_defaults parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', help="Queue timeseries output to one plot", required=True, action="store", nargs='+',...
plt.annotate(s, (x,y+1), xycoords='data', xytext=offset, textcoords='offset points', arrowprops=dict(arrowstyle="->")) elif args.cdf: for i,data in enumerate(to_plot): xs, ys = cdf(map(int, data)) plt.plot(xs, ys, label=args.legend[i], lw=2, **get_style(i)) ...
s = str(y) offset = (-10, 20)
conditional_block
plot_queue.py
''' Plot queue occupancy over time ''' from helper import * import plot_defaults parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', help="Queue timeseries output to one plot", required=True, action="store", nargs='+',...
dest="legend") parser.add_argument('--out', '-o', help="Output png file for the plot.", default=None, # Will show the plot dest="out") parser.add_argument('-s', '--summarise', help="Summarise the time series plot (boxp...
random_line_split
utils_selenium.py
# ONLY FOR DOCUMANTATION PURPOSE # #import os #import re # #class CommandsLinuxSelenium(Commands): # # def run_selenium(self, ssn): # """Some general info. # There are ways to define Firefox options globaly: # # * /usr/lib64/firefox/defaults/preferences/<anyname>.js # * /etc/firef...
# """ # selenium = download_asset("selenium", # section=self.cfg_vm.selenium_ver) # fname = os.path.basename(selenium) # dst_fname = os.path.join(self.workdir(), fname) # self.vm.copy_files_to(selenium, dst_fname) # defs = [] # opts = [] ...
# # firefox -CreateProfile <profile name> #
random_line_split
index.d.ts
// Type definitions for Popcorn 1.3.0 // Project: https://github.com/mozilla/popcorn-js // Definitions by: grapswiz <https://github.com/grapswiz> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var Popcorn:PopcornStatic; interface PopcornStatic { (callback:Function):PopcornImpl; (se...
(pluginName:string, info:PopcornPlugin, manifest?:any); debug:boolean; errors:any[]; }; util:{ toSeconds(smpte:string, fps?:number):number; }; destroy(insntace:PopcornImpl); extend(target:string, source, ...rest:any[]); forEach( object:any, callback:Function, con...
random_line_split
PriorityQueue.d.ts
import * as util from './util'; export default class PriorityQueue<T> { private heap; /** * Creates an empty priority queue. * @class <p>In a priority queue each element is associated with a "priority", * elements are dequeued in highest-priority-first order (the elements with the * highest ...
*/ add(element: T): boolean; /** * Retrieves and removes the highest priority element of this queue. * @return {*} the the highest priority element of this queue, * or undefined if this queue is empty. */ dequeue(): T; /** * Retrieves, but does not remove, the highest prio...
* @param {Object} element the element to insert. * @return {boolean} true if the element was inserted, or false if it is undefined.
random_line_split
PriorityQueue.d.ts
import * as util from './util'; export default class
<T> { private heap; /** * Creates an empty priority queue. * @class <p>In a priority queue each element is associated with a "priority", * elements are dequeued in highest-priority-first order (the elements with the * highest priority are dequeued first). Priority Queues are implemented as h...
PriorityQueue
identifier_name
domtokenlist.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 dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { let attr = attr.r(); Some(a...
random_line_split
domtokenlist.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 dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
} element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_token...
{ atoms.push(token); }
conditional_block
domtokenlist.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 dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), GlobalRef::Window(window.r()), DOMTokenListBinding...
{ DOMTokenList { reflector_: Reflector::new(), element: JS::from_ref(element), local_name: local_name, } }
identifier_body
domtokenlist.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 dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindin...
(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr...
Length
identifier_name
strmap_helper.py
""" This module contains a helper to extract various kinds of primitive data types from a dictionary of strings. """ class StringDictHelper: """ Helper class to extract primitive types from a dictionary of strings. This is a port of Java robotutils class StringmapHelper. The special values 'true' an...
(self, key, default, pattern=None): """ Returns a string - either parsed from map of {key} or {defaultValue}. param key -- key to lookup. default -- default value to use if the key did not exist, the value was not parseable or did not match {pattern}. This value does ...
get_as_str
identifier_name
strmap_helper.py
""" This module contains a helper to extract various kinds of primitive data types from a dictionary of strings. """ class StringDictHelper: """ Helper class to extract primitive types from a dictionary of strings. This is a port of Java robotutils class StringmapHelper. The special values 'true' an...
{minval} and {maxval}. NOTE: The *type* of this default value is used to determine the type of return value. So, if a floating point value is expected, specify a float default value! [minval] -- Optional inclusive minimum to accept. [maxva...
Returns a number - either parsed from map of {key} or {default}. key -- key to lookup. default -- default value to use if the key did exist, the value was not parseable or out of bounds. This value does not need to be between
random_line_split
strmap_helper.py
""" This module contains a helper to extract various kinds of primitive data types from a dictionary of strings. """ class StringDictHelper: """ Helper class to extract primitive types from a dictionary of strings. This is a port of Java robotutils class StringmapHelper. The special values 'true' an...
def get_as_bool(self, key, default): """ Returns a bool - either parsed from map of {key} or {default}. key -- key to lookup. default -- default value to use if the key did not exist or the value was not parseable. """ val = self._dct.get(k...
""" Returns a string - either parsed from map of {key} or {defaultValue}. param key -- key to lookup. default -- default value to use if the key did not exist, the value was not parseable or did not match {pattern}. This value does not need match {pattern}. ...
identifier_body
strmap_helper.py
""" This module contains a helper to extract various kinds of primitive data types from a dictionary of strings. """ class StringDictHelper: """ Helper class to extract primitive types from a dictionary of strings. This is a port of Java robotutils class StringmapHelper. The special values 'true' an...
D = dict(a='abc', b='true', c=42, d=1.5) H = StringDictHelper(D) AV = H.get_as_str('a', '') BV = H.get_as_bool('b', False) CV = H.get_as_num('c', 100) DV = H.get_as_num('d', 0.0) assert AV == 'abc' assert BV is True assert CV == 42 assert abs(DV-1.5) < 1E-10 print("StringDictHelp...
conditional_block
Item.web.tsx
import React from 'react'; import classNames from 'classnames'; import Touchable from 'rc-touchable'; export default class Item extends React.Component<any, any> { static defaultProps = { prefixCls: 'am-popover', disabled: false, }; static myName = 'PopoverItem'; render() { const { children, clas...
return ( <Touchable disabled={disabled} activeClassName={activeClass} activeStyle={activeStyle} > <div className={classNames(cls)} {...restProps}> <div className={`${prefixCls}-item-container`}> {icon ? <span className={`${prefixCls}-item-icon`}>{icon}</span> : null} ...
{ activeClass += `${prefixCls}-item-fix-active-arrow`; }
conditional_block
Item.web.tsx
import React from 'react'; import classNames from 'classnames'; import Touchable from 'rc-touchable'; export default class Item extends React.Component<any, any> { static defaultProps = { prefixCls: 'am-popover', disabled: false, }; static myName = 'PopoverItem'; render()
</div> </div> </Touchable> ); } }
{ const { children, className, prefixCls, icon, disabled, firstItem, activeStyle, ...restProps } = this.props; const cls = { [className as string]: !!className, [`${prefixCls}-item`]: true, [`${prefixCls}-item-disabled`]: disabled, }; let activeClass = `${prefixCls}-item-active `; ...
identifier_body
Item.web.tsx
import React from 'react'; import classNames from 'classnames'; import Touchable from 'rc-touchable'; export default class
extends React.Component<any, any> { static defaultProps = { prefixCls: 'am-popover', disabled: false, }; static myName = 'PopoverItem'; render() { const { children, className, prefixCls, icon, disabled, firstItem, activeStyle, ...restProps } = this.props; const cls = { [className as str...
Item
identifier_name
Item.web.tsx
import React from 'react'; import classNames from 'classnames'; import Touchable from 'rc-touchable'; export default class Item extends React.Component<any, any> { static defaultProps = { prefixCls: 'am-popover', disabled: false, }; static myName = 'PopoverItem'; render() { const { children, clas...
</div> </Touchable> ); } }
<div className={`${prefixCls}-item-container`}> {icon ? <span className={`${prefixCls}-item-icon`}>{icon}</span> : null} <span className={`${prefixCls}-item-content`}>{children}</span> </div>
random_line_split
ReopenResizeTest.ts
import { Pipeline, RawAssertions, Step, Waiter, Logger, Log } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock'; import { TinyLoader, TinyUi } from '@ephox/mcagar'; import Plugin from 'tinymce/plugins/media/Plugin'; import Theme from 'tinymce/themes/silver/Theme'; import Utils from '../module/test/Utils';...
// Hacky way to assert that the placeholder image is in // the correct place that works cross browser // assertContentStructure did not work because some // browsers insert BRs and some do not return Logger.t('Assert image is present', Step.sync(function () { const actualCount = editor.dom.sel...
RawAssertions.assertEq('Resize handle should exist', editor.dom.select('#mceResizeHandlenw').length, 1); })); }; const sRawAssertImagePresence = function (editor) {
random_line_split
restart-cluster-manager-callout.tsx
/* * Wazuh app - React component for registering agents. * Copyright (C) 2015-2021 Wazuh, Inc. *
* 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. * * Find more information about this on the LICENSE file. */ import React, { Component, Fragment } from 'react'; // Eui components im...
* This program is free software; you can redistribute it and/or modify
random_line_split
restart-cluster-manager-callout.tsx
/* * Wazuh app - React component for registering agents. * Copyright (C) 2015-2021 Wazuh, Inc. * * 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 ...
(props){ super(props); this.state = { warningRestarting: false, warningRestartModalVisible: false, isCluster: false }; } toggleWarningRestartModalVisible(){ this.setState({ warningRestartModalVisible: !this.state.warningRestartModalVisible }) } showToast(color, title, text = ''...
constructor
identifier_name
restart-cluster-manager-callout.tsx
/* * Wazuh app - React component for registering agents. * Copyright (C) 2015-2021 Wazuh, Inc. * * 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 ...
toggleWarningRestartModalVisible(){ this.setState({ warningRestartModalVisible: !this.state.warningRestartModalVisible }) } showToast(color, title, text = '', time = 3000){ getToasts().add({ color, title, text, toastLifeTimeMs: time }); } restartClusterOrManager = async ()...
{ super(props); this.state = { warningRestarting: false, warningRestartModalVisible: false, isCluster: false }; }
identifier_body
vacuum.py
"""Shark IQ Wrapper.""" from __future__ import annotations import logging from typing import Iterable from sharkiqpy import OperatingModes, PowerModes, Properties, SharkIqVacuum from homeassistant.components.vacuum import ( STATE_CLEANING, STATE_DOCKED, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, ...
"""Clean a spot. Not yet implemented.""" raise NotImplementedError() def send_command(self, command, params=None, **kwargs): """Send a command to the vacuum. Not yet implemented.""" raise NotImplementedError() @property def is_online(self) -> bool: """Tell us if the...
def clean_spot(self, **kwargs):
random_line_split
vacuum.py
"""Shark IQ Wrapper.""" from __future__ import annotations import logging from typing import Iterable from sharkiqpy import OperatingModes, PowerModes, Properties, SharkIqVacuum from homeassistant.components.vacuum import ( STATE_CLEANING, STATE_DOCKED, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, ...
@property def unique_id(self) -> str: """Return the unique id of the vacuum cleaner.""" return self.serial_number @property def available(self) -> bool: """Determine if the sensor is available based on API results.""" # If the last update was successful... retu...
""" Get the current vacuum state. NB: Currently, we do not return an error state because they can be very, very stale. In the app, these are (usually) handled by showing the robot as stopped and sending the user a notification. """ if self.is_docked: return S...
identifier_body
vacuum.py
"""Shark IQ Wrapper.""" from __future__ import annotations import logging from typing import Iterable from sharkiqpy import OperatingModes, PowerModes, Properties, SharkIqVacuum from homeassistant.components.vacuum import ( STATE_CLEANING, STATE_DOCKED, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, ...
return self.sharkiq.error_text @property def operating_mode(self) -> str | None: """Operating mode..""" op_mode = self.sharkiq.get_property_value(Properties.OPERATING_MODE) return OPERATING_STATE_MAP.get(op_mode) @property def recharging_to_resume(self) -> int | None: ...
return None
conditional_block
vacuum.py
"""Shark IQ Wrapper.""" from __future__ import annotations import logging from typing import Iterable from sharkiqpy import OperatingModes, PowerModes, Properties, SharkIqVacuum from homeassistant.components.vacuum import ( STATE_CLEANING, STATE_DOCKED, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, ...
(self) -> int | None: """Get the WiFi RSSI.""" return self.sharkiq.get_property_value(Properties.RSSI) @property def low_light(self): """Let us know if the robot is operating in low-light mode.""" return self.sharkiq.get_property_value(Properties.LOW_LIGHT_MISSION) @propert...
rssi
identifier_name
test_graphrbac.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. #---------------------------------------------------------------------...
ittest.main()
conditional_block
test_graphrbac.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. #---------------------------------------------------------------------...
) ) self.assertEqual(user.display_name, 'Test Buddy') user = self.graphrbac_client.users.get(user.object_id) self.assertEqual(user.display_name, 'Test Buddy') users = self.graphrbac_client.users.list( filter="displayName eq 'Test Buddy'" ) ...
f setUp(self): super(GraphRbacTest, self).setUp() self.graphrbac_client = self.create_basic_client( azure.graphrbac.GraphRbacManagementClient, tenant_id=self.settings.AD_DOMAIN ) @record def test_graphrbac_users(self): user = self.graphrbac_client.users....
identifier_body