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
ActionPanel.ts
import sf, { IOptionToGrab, ISpiralFramework } from '@spiral-toolkit/core'; import { ACTION_PANEL_CLASS_NAME, SelectionType } from '../constants'; import type Datagrid from '../datagrid/Datagrid'; import type { IActionDescriptor, IActionPanelOptions, IActionPanelState } from '../types'; export type FlexibleRenderDefin...
else { el.appendChild(rendered); } } else { el.appendChild(definition); } } renderAction(actionId: string, action: IActionDescriptor, options: IActionPanelOptions) { const el = document.createElement('div'); if (options.actionClassName) { if (typeof options.actionClassNam...
{ // eslint-disable-next-line no-param-reassign el.innerHTML = rendered; }
conditional_block
ActionPanel.ts
import sf, { IOptionToGrab, ISpiralFramework } from '@spiral-toolkit/core'; import { ACTION_PANEL_CLASS_NAME, SelectionType } from '../constants'; import type Datagrid from '../datagrid/Datagrid'; import type { IActionDescriptor, IActionPanelOptions, IActionPanelState } from '../types'; export type FlexibleRenderDefin...
(options: Partial<IActionPanelOptions>, datagrid: Datagrid) { // console.log('reconfigure', datagrid); this.datagrid = datagrid; this.options = { ...this.options, ...options, }; this.state = { hasSelection: false, selectedCount: 0, selectedItems: [], selectedKeys:...
reconfigure
identifier_name
ActionPanel.ts
import sf, { IOptionToGrab, ISpiralFramework } from '@spiral-toolkit/core'; import { ACTION_PANEL_CLASS_NAME, SelectionType } from '../constants'; import type Datagrid from '../datagrid/Datagrid'; import type { IActionDescriptor, IActionPanelOptions, IActionPanelState } from '../types'; export type FlexibleRenderDefin...
if (!this.el) { this.el = document.createElement('div'); this.node.appendChild(this.el); } else { this.el.innerHTML = ''; // TODO: dont rerender } const el = this.el!; if (this.options.className) { el.className = ''; if (typeof this.options.className === 'string') { ...
} render() {
random_line_split
ActionPanel.ts
import sf, { IOptionToGrab, ISpiralFramework } from '@spiral-toolkit/core'; import { ACTION_PANEL_CLASS_NAME, SelectionType } from '../constants'; import type Datagrid from '../datagrid/Datagrid'; import type { IActionDescriptor, IActionPanelOptions, IActionPanelState } from '../types'; export type FlexibleRenderDefin...
renderAs(el: Element, definition: FlexibleRenderDefinition) { if (typeof definition === 'string') { // eslint-disable-next-line no-param-reassign el.innerHTML = definition; } else if (typeof definition === 'function') { const rendered = definition(this.state); if (typeof rendered ===...
{ this.state = { ...this.state, selectedKeys, selectedItems, selectedCount: selectedKeys.size, hasSelection: !!selectedKeys.size, }; this.render(); }
identifier_body
hidrawpure.py
""" from https://github.com/vpelletier/python-hidraw copied and renamed due to the existence of another 'hidraw' package on pypi which seems to conflict in some way. """ from __future__ import absolute_import from __future__ import print_function import ctypes import struct import collections import fcntl import ioc...
else: import codecs def b(x): return codecs.latin_1_encode(x)[0] # hidraw.h class _hidraw_report_descriptor(ctypes.Structure): _fields_ = [ ('size', ctypes.c_uint), ('value', ctypes.c_ubyte * _HID_MAX_DESCRIPTOR_SIZE), ] class _hidraw_devinfo(ctypes.Structure): _fields...
def b(x): return x
conditional_block
hidrawpure.py
""" from https://github.com/vpelletier/python-hidraw copied and renamed due to the existence of another 'hidraw' package on pypi which seems to conflict in some way. """ from __future__ import absolute_import from __future__ import print_function import ctypes import struct import collections import fcntl import ioc...
def getRawReportDescriptor(self): """ Return a binary string containing the raw HID report descriptor. """ descriptor = _hidraw_report_descriptor() size = ctypes.c_uint() self._ioctl(_HIDIOCGRDESCSIZE, size, True) descriptor.size = size self._ioctl(_...
result = fcntl.ioctl(self._device, func, arg, mutate_flag) if result < 0: raise IOError(result)
identifier_body
hidrawpure.py
""" from https://github.com/vpelletier/python-hidraw copied and renamed due to the existence of another 'hidraw' package on pypi which seems to conflict in some way. """ from __future__ import absolute_import from __future__ import print_function import ctypes import struct import collections import fcntl import ioc...
def getInfo(self): """ Returns a DevInfo instance, a named tuple with the following items: - bustype: one of BUS_USB, BUS_HIL, BUS_BLUETOOTH or BUS_VIRTUAL - vendor: device's vendor number - product: device's product number """ devinfo = _hidraw_devinfo() ...
random_line_split
hidrawpure.py
""" from https://github.com/vpelletier/python-hidraw copied and renamed due to the existence of another 'hidraw' package on pypi which seems to conflict in some way. """ from __future__ import absolute_import from __future__ import print_function import ctypes import struct import collections import fcntl import ioc...
(ctypes.Structure): _fields_ = [ ('bustype', ctypes.c_uint), ('vendor', ctypes.c_short), ('product', ctypes.c_short), ] _HIDIOCGRDESCSIZE = ioctl_opt.IOR(ord('H'), 0x01, ctypes.c_int) _HIDIOCGRDESC = ioctl_opt.IOR(ord('H'), 0x02, _hidraw_report_descriptor) _HIDIOCGRAWINFO = ioctl_op...
_hidraw_devinfo
identifier_name
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] #[should_fail] fn test_option_too_much_dance() { let mut y = Some(marker::NoCopy); let _y2 = y.take().unwrap(); let _y3 = y.take().unwrap(); } #[test] fn test_and() { let x: Option<int> = Some(1i); assert_eq!(x.and(Some(2i)), Some(2)); assert_eq!(x.and(None::<int>), None); let x: O...
assert_eq!(y2, 5); assert!(y.is_none()); }
random_line_split
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
None => assert!(false), } assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } assert_eq!(x, Some(new_val)); } #[test] fn test_ord() { let small = Some(1.0f64); let big = Some(5.0f64); let nan = Some(0.0f64/0.0); assert!(!(nan < big)); ...
{ assert_eq!(*interior, val); *interior = new_val; }
conditional_block
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x: Option<int> = Some(1); assert_eq!(x.or_else(|| Some(2)), Some(1)); assert_eq!(x.or_else(|| None), Some(1)); let x: Option<int> = None; assert_eq!(x.or_else(|| Some(2)), Some(2)); assert_eq!(x.or_else(|| None), None); } #[test] fn test_unwrap() { assert_eq!(Some(1i).unwrap(), 1)...
test_or_else
identifier_name
Log.py
# -*- coding:utf-8 -*- """ Provide log related functions. You need to Initialize the logger and use the logger to make logs. Example: >>> logger = Initialize() Use logger.level(\*msg) to log like: >>> logger.error("Pickle data writing Failed.") >>> logger.info("Pickle data of ", foo, " written successfu...
(self, *args, **kwargs): super().critical("".join([str(arg) for arg in args]), **kwargs) def log(self, level, *args, **kwargs): super().log(level, "".join([str(arg) for arg in args]), **kwargs) def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): super(...
critical
identifier_name
Log.py
# -*- coding:utf-8 -*- """ Provide log related functions. You need to Initialize the logger and use the logger to make logs. Example: >>> logger = Initialize() Use logger.level(\*msg) to log like: >>> logger.error("Pickle data writing Failed.") >>> logger.info("Pickle data of ", foo, " written successfu...
def warning(self, *args, **kwargs): super().warning("".join([str(arg) for arg in args]), **kwargs) def warn(self, *args, **kwargs): super().warn("".join([str(arg) for arg in args]), **kwargs) def error(self, *args, **kwargs): super().error("".join([str(arg) for arg in ar...
super().info("".join([str(arg) for arg in args]), **kwargs)
identifier_body
Log.py
# -*- coding:utf-8 -*- """ Provide log related functions. You need to Initialize the logger and use the logger to make logs. Example: >>> logger = Initialize() Use logger.level(\*msg) to log like: >>> logger.error("Pickle data writing Failed.") >>> logger.info("Pickle data of ", foo, " written successfu...
logger.setLevel(logging.DEBUG) if LogLevel == "INFO": streamHandler = logging.StreamHandler(stream = sys.stdout) streamHandler.setLevel(logging.INFO) fileHandler.setLevel(logging.INFO) logger.setLevel(logging.INFO) if LogLevel == "ERROR": streamHandler = lo...
streamHandler.setLevel(logging.DEBUG) fileHandler.setLevel(logging.DEBUG)
random_line_split
Log.py
# -*- coding:utf-8 -*- """ Provide log related functions. You need to Initialize the logger and use the logger to make logs. Example: >>> logger = Initialize() Use logger.level(\*msg) to log like: >>> logger.error("Pickle data writing Failed.") >>> logger.info("Pickle data of ", foo, " written successfu...
logging.Logger.manager.setLoggerClass(Logger) logger = logging.getLogger(__name__) #__name__ == CommonModules.Log handlers = logger.handlers[:] for handler in handlers: handler.close() logger.removeHandler(handler) fileHandler = logging.FileHandler(FileName) fileHandler....
raise ValueError("LogLevel is not correctly set.")
conditional_block
workspace.ts
concatMap, first, map, tap } from 'rxjs/operators'; import { BaseException } from '../../exception'; import { JsonObject, JsonParseMode, parseJson, schema, } from '../../json'; import { SchemaValidatorResult } from '../../json/schema/interface'; import { Path, basename, dirname, isAbsolute, join, n...
else { this._registry = new schema.CoreSchemaRegistry(); this._registry.addPostTransform(schema.transforms.addUndefinedDefaults); } } static async findWorkspaceFile(host: virtualFs.Host<{}>, path: Path): Promise<Path | null> { return await _findUp(host, this._workspaceFileNames, path); } s...
{ this._registry = registry; }
conditional_block
workspace.ts
Map, first, map, tap } from 'rxjs/operators'; import { BaseException } from '../../exception'; import { JsonObject, JsonParseMode, parseJson, schema, } from '../../json'; import { SchemaValidatorResult } from '../../json/schema/interface'; import { Path, basename, dirname, isAbsolute, join, normaliz...
} export class WorkspaceNotYetLoadedException extends BaseException { constructor() { super(`Workspace needs to be loaded before it is used.`); } } export class AmbiguousProjectPathException extends BaseException { constructor(public readonly path: Path, public readonly projects: ReadonlyArray<string>) { sup...
{ super(`Tool ${name} could not be found in project.`); }
identifier_body
workspace.ts
concatMap, first, map, tap } from 'rxjs/operators'; import { BaseException } from '../../exception'; import { JsonObject, JsonParseMode, parseJson, schema, } from '../../json'; import { SchemaValidatorResult } from '../../json/schema/interface'; import { Path, basename, dirname, isAbsolute, join, n...
return Object.keys(this._workspace.projects); } getProject(projectName: string): WorkspaceProject { this._assertLoaded(); const workspaceProject = this._workspace.projects[projectName]; if (!workspaceProject) { throw new ProjectNotFoundException(projectName); } // Return only the p...
return this._workspace.newProjectRoot; } listProjectNames(): string[] {
random_line_split
workspace.ts
concatMap, first, map, tap } from 'rxjs/operators'; import { BaseException } from '../../exception'; import { JsonObject, JsonParseMode, parseJson, schema, } from '../../json'; import { SchemaValidatorResult } from '../../json/schema/interface'; import { Path, basename, dirname, isAbsolute, join, n...
(host: virtualFs.Host, names: string[], from: Path): Promise<Path | null> { if (!Array.isArray(names)) { names = [names]; } do { for (const name of names) { const p = join(from, name); if (await host.exists(p).toPromise()) { return p; } } from = dirname(from); } while...
_findUp
identifier_name
global.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut maybe_clone: Option<T> = None; do global_data_modify(key) |current| { match &current { &Some(~ref value) => { maybe_clone = Some(value.clone()); } &None => () } current } return maybe_clone; } // GlobalState is a map fr...
random_line_split
global.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}; match maybe_new_value { Some(value) => { let data: *c_void = transmute(value); let dtor: ~fn() = match maybe_dtor { Some(dtor) => dtor, None => { let dtor: ~fn() = || { ...
{ (op(None), None) }
conditional_block
global.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_modify() { fn key(_v: UnsafeAtomicRcBox<int>) { } unsafe { do global_data_modify(key) |v| { match v { None => { Some(~UnsafeAtomicRcBox::new(10)) } _ => fail!() } } do global_data_modify(key) |v| { ma...
{ fn key(_v: UnsafeAtomicRcBox<int>) { } for uint::range(0, 100) |_| { do spawn { unsafe { let val = do global_data_clone_create(key) { ~UnsafeAtomicRcBox::new(10) }; assert!(val.get() == &10); } } ...
identifier_body
global.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> Exclusive<GlobalState> { static POISON: int = -1; // FIXME #4728: Doing atomic_cxchg to initialize the global state // lazily, which wouldn't be necessary with a runtime written // in Rust let global_ptr = unsafe { rust_get_global_data_ptr() }; if unsafe { *global_ptr } == 0 { /...
get_global_state
identifier_name
test_cargo_clean.rs
use support::{project, execs, main_file, basic_bin_manifest, cargo_dir}; use hamcrest::{assert_that, existing_dir, is_not}; fn setup()
test!(cargo_clean_simple { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()...
{ }
identifier_body
test_cargo_clean.rs
use support::{project, execs, main_file, basic_bin_manifest, cargo_dir}; use hamcrest::{assert_that, existing_dir, is_not}; fn
() { } test!(cargo_clean_simple { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()); assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing...
setup
identifier_name
test_cargo_clean.rs
use support::{project, execs, main_file, basic_bin_manifest, cargo_dir}; use hamcrest::{assert_that, existing_dir, is_not}; fn setup() { } test!(cargo_clean_simple { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am ...
execs().with_status(0)); assert_that(&p.build_dir(), is_not(existing_dir())); }) test!(different_dir { let p = project("foo") .file("Cargo.toml", basic_bin_manifest("foo").as_slice()) .file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice()) .file(...
assert_that(p.cargo_process("build"), execs().with_status(0)); assert_that(&p.build_dir(), existing_dir()); assert_that(p.process(cargo_dir().join("cargo")).arg("clean"),
random_line_split
autoderef-method-priority.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl double for Box<uint> { fn double(self) -> uint { *self * 2_usize } } pub fn main() { let x = box 3_usize; assert_eq!(x.double(), 6_usize); }
{ self }
identifier_body
autoderef-method-priority.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
trait double { fn double(self) -> uint; } impl double for uint { fn double(self) -> uint { self } } impl double for Box<uint> { fn double(self) -> uint { *self * 2_usize } } pub fn main() { let x = box 3_usize; assert_eq!(x.double(), 6_usize); }
random_line_split
autoderef-method-priority.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(self) -> uint { self } } impl double for Box<uint> { fn double(self) -> uint { *self * 2_usize } } pub fn main() { let x = box 3_usize; assert_eq!(x.double(), 6_usize); }
double
identifier_name
Money.js
/** * @file * Money is a value object representing a monetary value. It does not use * floating point numbers, so it avoids rounding errors. * The only operation that may cause stray cents is split, it assures that no * cents vanish by distributing as evenly as possible among the parts it splits into. * * Money ...
else { throw new Error("Money:fromString: BUG: RegExp should have prevent this from happening."); } }; /** * @param int amount * @return Money */ Money._fromAmount = function (amount) { if (amount > 0) { return new Money(Math.floor(amount / 100), amount % 100); } else { re...
{ return new Money(parseInt(a[0], 10), parseInt(a[1], 10)); }
conditional_block
Money.js
/** * @file * Money is a value object representing a monetary value. It does not use * floating point numbers, so it avoids rounding errors. * The only operation that may cause stray cents is split, it assures that no * cents vanish by distributing as evenly as possible among the parts it splits into. * * Money ...
if (this.gt(new Money(-1, 0))) { var cents = (-this.getCents()) < 10 ? "0" + (-this.getCents()) : (-this.getCents()); return "-0." + cents; } } var cents = this.getCents() < 10 ? "0" + this.getCents() : this.getCents(); return t...
if (this.isNegative()) {
random_line_split
app-controller.js
/** * App Control * * Central controller attached to the top level <html> * element */ "use strict"; ( function ( angular, app ) { // get user profile data app.controller( "AppCtrl", [ '$rootScope', '$scope', '$state', 'UserService', function ( $rootScope, $scope, $state, UserService ) { // // bodyCl...
] ); } )( angular, SimplySocial );
random_line_split
always_circular_stereo.py
""" Custom Boundary Shape --------------------- This example demonstrates how a custom shape geometry may be used instead of the projection's default boundary. In this instance, we define the boundary as a circle in axes coordinates. This means that no matter the extent of the map itself, the boundary will always be ...
# Limit the map to -60 degrees latitude and below. ax1.set_extent([-180, 180, -90, -60], ccrs.PlateCarree()) ax1.add_feature(cfeature.LAND) ax1.add_feature(cfeature.OCEAN) ax1.gridlines() ax2.gridlines() ax2.add_feature(cfeature.LAND) ax2.add_feature(cfeature.OCEAN) # Compute a ...
fig.subplots_adjust(bottom=0.05, top=0.95, left=0.04, right=0.95, wspace=0.02)
random_line_split
always_circular_stereo.py
""" Custom Boundary Shape --------------------- This example demonstrates how a custom shape geometry may be used instead of the projection's default boundary. In this instance, we define the boundary as a circle in axes coordinates. This means that no matter the extent of the map itself, the boundary will always be ...
(): fig = plt.figure(figsize=[10, 5]) ax1 = fig.add_subplot(1, 2, 1, projection=ccrs.SouthPolarStereo()) ax2 = fig.add_subplot(1, 2, 2, projection=ccrs.SouthPolarStereo(), sharex=ax1, sharey=ax1) fig.subplots_adjust(bottom=0.05, top=0.95, left=0.04, righ...
main
identifier_name
always_circular_stereo.py
""" Custom Boundary Shape --------------------- This example demonstrates how a custom shape geometry may be used instead of the projection's default boundary. In this instance, we define the boundary as a circle in axes coordinates. This means that no matter the extent of the map itself, the boundary will always be ...
# for the map. We can pan/zoom as much as we like - the boundary will be # permanently circular. theta = np.linspace(0, 2*np.pi, 100) center, radius = [0.5, 0.5], 0.5 verts = np.vstack([np.sin(theta), np.cos(theta)]).T circle = mpath.Path(verts * radius + center) ax2.set_boundary(circle, tr...
fig = plt.figure(figsize=[10, 5]) ax1 = fig.add_subplot(1, 2, 1, projection=ccrs.SouthPolarStereo()) ax2 = fig.add_subplot(1, 2, 2, projection=ccrs.SouthPolarStereo(), sharex=ax1, sharey=ax1) fig.subplots_adjust(bottom=0.05, top=0.95, left=0.04, right=0.95, ...
identifier_body
always_circular_stereo.py
""" Custom Boundary Shape --------------------- This example demonstrates how a custom shape geometry may be used instead of the projection's default boundary. In this instance, we define the boundary as a circle in axes coordinates. This means that no matter the extent of the map itself, the boundary will always be ...
main()
conditional_block
MicOffTwoTone.js
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12 3.7c-.66 0-1.2.54-1.2 1.2v1.51l2.39 2.39.01-3.9c0-.66-.54-1.2-1.2-1.2z" opacity=".3" /><path d="M19 11h-1.7c0 .58-.1 1.13-.27 1.64l1.27 1.27c.44-.88.7-1.87.7-2.91zM4.41 2.86L3 4.27l6 6V11c0 1.66 1.34 3 3 3 ....
random_line_split
tessellation.rs
#[macro_use] extern crate glium; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod support; fn
() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new(); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &event_loop).unwrap(); // building the vertex buffer, which c...
main
identifier_name
tessellation.rs
#[macro_use] extern crate glium; #[allow(unused_imports)] use glium::{glutin, Surface}; use glium::index::PrimitiveType; mod support; fn main() { // building the display, ie. the main object let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new(); let cb =...
}
});
random_line_split
md3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007 by Kai Blin # # Plunger 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; version 2 of the License. # # This program is distributed in the hop...
for vert in self.vertices: pack_str += vert.pack() class MD3Object: def __init__(self): self.ident = MD3_IDENT self.version = MD3_VERSION self.name = "" self.num_frames = 0 self.num_tags = 0 self.num_surfaces = 0 self.num_skins = 0 ...
pack_str += texcoord.pack()
conditional_block
md3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007 by Kai Blin # # Plunger 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; version 2 of the License. # # This program is distributed in the hop...
(self): return struct.calcsize(self.fmt) def pack(self): return struct.pack("iii", self.indices.split()) class Md3TexCoord: def __init__(self): self.uv_coords = [0,0] self.fmt = "ff" def packSize(self): return struct.calcsize(self.fmt) def pack(self): ...
packSize
identifier_name
md3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007 by Kai Blin # # Plunger 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; version 2 of the License. # # This program is distributed in the hop...
def packSize(self): return struct.calcsize(self.fmt) def pack(self): pack_str = "" pack_str += struct.pack("64s", self.name) pack_str += struct.pack("fff", self.origin.split()) for row in self.axis: pack_str += struct.pack("fff", row.split()) return...
self.name = "" self.origin = [0,0,0] self.axis = [[1,0,0], [0,1,0], [0,0,1]] self.fmt = "64s fff fff fff fff"
identifier_body
md3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007 by Kai Blin # # Plunger 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; version 2 of the License. # # This program is distributed in the hop...
MD3_MAX_TAGS = 16 MD3_MAX_SURFACES = 32 MD3_MAX_SHADERS = 256 MD3_MAX_VERTS = 4096 MD3_MAX_TRIANGLES = 8192 class Md3Frame: def __init__(self): self.min_bounds = [0,0,0] self.max_bounds = [0,0,0] self.local_origin = [0,0,0] self.radius = 0.0 self.name = "" self.fmt =...
# Augmented by the libmodelfile headers by Alistair Riddoch, as the specfile # is kind of inaccurate. MD3_IDENT = "IDP3" MD3_VERSION = 15 MD3_MAX_FRAMES = 1024
random_line_split
setup_metrics.py
#!/usr/bin/python # Copyright 2014 IBM Corp # # 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 i...
MOLD = {"name": "name1", "timestamp": '2014-12-01', "value": 100 } MOLD_DIMENSIONS = {"key1": None} def setup_metrics(argv): for a in range(100): MOLD_DIMENSIONS['key1'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key2'] = ( ...
import time
random_line_split
setup_metrics.py
#!/usr/bin/python # Copyright 2014 IBM Corp # # 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 i...
# Generate unique 100 metrics for i in range(100): MOLD['name'] = ''.join(random.sample(string.ascii_uppercase * 6, 6)) for j in range(10): MOLD['value'] = round((i + 1) * j * random.random(), 2) th...
MOLD_DIMENSIONS['key1'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key2'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key_' + str(a)] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) "...
conditional_block
setup_metrics.py
#!/usr/bin/python # Copyright 2014 IBM Corp # # 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 i...
print('starting round %s' % a) # Generate unique 100 metrics for i in range(100): MOLD['name'] = ''.join(random.sample(string.ascii_uppercase * 6, 6)) for j in range(10): MOLD['value'] = round((i + 1) * j *...
for a in range(100): MOLD_DIMENSIONS['key1'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key2'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key_' + str(a)] = ( ''.join(random.sample(string.ascii_u...
identifier_body
setup_metrics.py
#!/usr/bin/python # Copyright 2014 IBM Corp # # 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 i...
(argv): for a in range(100): MOLD_DIMENSIONS['key1'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key2'] = ( ''.join(random.sample(string.ascii_uppercase * 6, 6))) MOLD_DIMENSIONS['key_' + str(a)] = ( ''.join(random.sample(s...
setup_metrics
identifier_name
tests.py
# coding: utf-8 # # This file is part of Progdupeupl. # # Progdupeupl is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Progdu...
self.assertEqual(result, [1, 2, None, 10]) def test_big_start_limit(self): result = paginator_range(3, 10) self.assertEqual(result, [1, 2, 3, 4, None, 10]) def test_big_middle(self): result = paginator_range(5, 10) self.assertEqual(result, [1, None, 4, 5, 6, None, 10]) ...
def test_big_start(self): result = paginator_range(1, 10)
random_line_split
tests.py
# coding: utf-8 # # This file is part of Progdupeupl. # # Progdupeupl is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Progdu...
(self): recipients = ['test1@localhost'] result = mail.send_templated_mail( subject='Fake subject', template='base.txt', context={}, recipients=recipients ) self.assertEqual(result, 1) def test_send_mail_to_confirm_registration(self)...
test_send_templated_mail
identifier_name
tests.py
# coding: utf-8 # # This file is part of Progdupeupl. # # Progdupeupl is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Progdu...
def test_big_middle(self): result = paginator_range(5, 10) self.assertEqual(result, [1, None, 4, 5, 6, None, 10]) def test_big_end(self): result = paginator_range(10, 10) self.assertEqual(result, [1, None, 9, 10]) def test_big_end_limit(self): result = paginator_r...
result = paginator_range(3, 10) self.assertEqual(result, [1, 2, 3, 4, None, 10])
identifier_body
serializers.py
# -*- coding: utf-8 -*- from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User from go_green.badge.serializers import BadgeViewSetSerializer class UserViewSetSerial...
: model = User fields = (u'id', u'username', u'email', u'first_name', u'last_name', u'clean_count', u'status', u'is_volunteer', u'volunteer_group_name', u'show_contact', u'contact_email', u'contact_phone', u'contact_url', u'badges',...
Meta
identifier_name
serializers.py
# -*- coding: utf-8 -*- from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User from go_green.badge.serializers import BadgeViewSetSerializer class UserViewSetSerial...
contact_email = attrs if contact_email: emailset = Q(contact_email__icontains=contact_email) emailres = User.objects.filter(emailset) if emailres: msg = _('The email address is already taken') raise serializers.Valid...
identifier_body
serializers.py
# -*- coding: utf-8 -*-
from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User from go_green.badge.serializers import BadgeViewSetSerializer class UserViewSetSerializer(serializers.ModelSerializer): badges = BadgeViewSetSerializer(many=True, read_only=True) email = ser...
from django.db.models import Q from django.utils.translation import ugettext_lazy as _
random_line_split
serializers.py
# -*- coding: utf-8 -*- from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User from go_green.badge.serializers import BadgeViewSetSerializer class UserViewSetSerial...
else: return attrs
msg = _('The email address is already taken') raise serializers.ValidationError(msg)
conditional_block
GirlComponent.js
/** * Created by TC on 2016/10/10. */ import React, { Component, } from 'react' import { Image, View, ToastAndroid, ActivityIndicator, } from 'react-native' import PixelRatio from "react-native/Libraries/Utilities/PixelRatio"; class GirlComponent extends Component { constructor(props)...
() { this.setState({imgUrl: ''}); this.getImage(); } componentWillMount() { this.getImage(); } getImage() { fetch('http://gank.io/api/data/福利/100/1')//异步请求图片 .then((response) => { return response.json(); }) .then((re...
loadImage
identifier_name
GirlComponent.js
/** * Created by TC on 2016/10/10. */ import React, { Component, } from 'react' import { Image, View, ToastAndroid, ActivityIndicator, } from 'react-native' import PixelRatio from "react-native/Libraries/Utilities/PixelRatio"; class GirlComponent extends Component { constructor(props)...
Component;
<View style={{flexDirection: 'column', flex: 1}}> <Image source={{uri: this.state.imgUrl}} style={{width: 200 * PixelRatio.get(), height: 200 * PixelRatio.get()}}/> </View> ); } } } export default Girl
conditional_block
GirlComponent.js
/** * Created by TC on 2016/10/10. */ import React, { Component, } from 'react' import { Image, View, ToastAndroid, ActivityIndicator, } from 'react-native' import PixelRatio from "react-native/Libraries/Utilities/PixelRatio"; class GirlComponent extends Component { constructor(props)...
getImage() { fetch('http://gank.io/api/data/福利/100/1')//异步请求图片 .then((response) => { return response.json(); }) .then((responseJson) => { if (responseJson.results) { const index = Math.ceil(Math.random() * 100 - 1);//...
{ this.getImage(); }
identifier_body
GirlComponent.js
/** * Created by TC on 2016/10/10. */ import React, { Component, } from 'react' import { Image, View, ToastAndroid, ActivityIndicator, } from 'react-native' import PixelRatio from "react-native/Libraries/Utilities/PixelRatio"; class GirlComponent extends Component { constructor(props)...
</View> ); } } } export default GirlComponent;
<View style={{flexDirection: 'column', flex: 1}}> <Image source={{uri: this.state.imgUrl}} style={{width: 200 * PixelRatio.get(), height: 200 * PixelRatio.get()}}/>
random_line_split
payload-github-status.ts
import {https} from 'firebase-functions'; import {verifyToken} from './jwt/verify-token'; import {setGithubStatus} from './github/github-status'; export const payloadGithubStatus = https.onRequest(async (request, response) => { const authToken = request.header('auth-token'); const commitSha = request.header('commi...
(word: string) { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }
capitalizeFirstLetter
identifier_name
payload-github-status.ts
import {https} from 'firebase-functions'; import {verifyToken} from './jwt/verify-token'; import {setGithubStatus} from './github/github-status'; export const payloadGithubStatus = https.onRequest(async (request, response) => { const authToken = request.header('auth-token'); const commitSha = request.header('commi...
{ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }
identifier_body
payload-github-status.ts
import {https} from 'firebase-functions'; import {verifyToken} from './jwt/verify-token'; import {setGithubStatus} from './github/github-status'; export const payloadGithubStatus = https.onRequest(async (request, response) => { const authToken = request.header('auth-token'); const commitSha = request.header('commi...
if (isNaN(packageSize)) { return response.status(400).json({message: 'No full size of the package has been specified.'}); } if (!packageName) { return response.status(400).json({message: 'No package name has been specified.'}); } if (packageDiff === 0) { return response.status(400).json({messa...
{ return response.status(400).json({message: 'No valid package difference has been specified.'}); }
conditional_block
payload-github-status.ts
import {https} from 'firebase-functions'; import {verifyToken} from './jwt/verify-token'; import {setGithubStatus} from './github/github-status'; export const payloadGithubStatus = https.onRequest(async (request, response) => { const authToken = request.header('auth-token'); const commitSha = request.header('commi...
return response.status(400).json({message: 'No package name has been specified.'}); } if (packageDiff === 0) { return response.status(400).json({message: `The difference equals zero. Status won't be set.`}); } // Better message about the diff that shows whether the payload increased or decreased. co...
if (isNaN(packageSize)) { return response.status(400).json({message: 'No full size of the package has been specified.'}); } if (!packageName) {
random_line_split
create-quest.component.ts
import { Component, OnInit } from '@angular/core'; import { flyInOutTrigger } from '../animations/flyInOutTrigger-animation'; import { hostConfig } from '../animations/flyInOutTrigger-animation'; import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms'; import 'rxjs/add/...
extends AbstractDemoComponent implements OnInit { public disableForm = false; public form: FormGroup; public questName; // = new FormControl('Quest Name'); public stageName; // = new FormControl('Stage Name'); public description; // = new FormControl('Description'); public cost; // = new FormControl('Cost...
CreateQuest
identifier_name
create-quest.component.ts
import { Component, OnInit } from '@angular/core'; import { flyInOutTrigger } from '../animations/flyInOutTrigger-animation'; import { hostConfig } from '../animations/flyInOutTrigger-animation'; import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms'; import 'rxjs/add/...
]); this.form = new FormGroup({ questName: new FormControl(''), stages: this.stages }); } public makeStage() { return new FormGroup({ 'Stage Name': new FormControl(''), 'Description': new FormControl(''), 'Cost': new FormControl(''), }) } // public onSubmit(...
// this.makeStage()
random_line_split
create-quest.component.ts
import { Component, OnInit } from '@angular/core'; import { flyInOutTrigger } from '../animations/flyInOutTrigger-animation'; import { hostConfig } from '../animations/flyInOutTrigger-animation'; import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms'; import 'rxjs/add/...
}
{ console.log("CREATE_STAGE"); // this.stages.push(this.makeStage()); this.stages.push(new FormControl('')); // const control = < any > this.form.controls['stages']; // control.push(this.addStage()); // this.form = control; }
identifier_body
sanitizer.py
'fill', 'fill-opacity', 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'h...
return match.end()
conditional_block
sanitizer.py
'aqua', 'auto', 'black', 'block', 'blue', 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted', 'fuchsia', 'gray', 'green', 'italic', 'left', 'li...
super(_HTMLSanitizer, self).__init__(encoding, _type) self.unacceptablestack = 0 self.mathmlOK = 0 self.svgOK = 0
identifier_body
sanitizer.py
'ideographic', 'k', 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end', 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'mathematical', 'max', 'min', 'name...
return data
random_line_split
sanitizer.py
'rquote', 'rspace', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'shift', 'side', 'src', 'stackalign', 'stretchy', 'subscriptshift', 'superscriptshift', ...
handle_data
identifier_name
PastebinCom.py
# -*- coding: utf-8 -*- ############################################################################ # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of...
TITLE_PATTERN = r'<div class="paste_box_line1" title="(?P<title>[^"]+)">'
random_line_split
PastebinCom.py
# -*- coding: utf-8 -*- ############################################################################ # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of...
(SimpleCrypter): __name__ = "PastebinCom" __type__ = "crypter" __pattern__ = r"http://(?:w{3}.)?pastebin\.com/\w+" __version__ = "0.01" __description__ = """Pastebin.com Plugin""" __author_name__ = ("stickell") __author_mail__ = ("l.stickell@yahoo.it") LINK_PATTERN = r'<div class="de\d+...
PastebinCom
identifier_name
PastebinCom.py
# -*- coding: utf-8 -*- ############################################################################ # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of...
__name__ = "PastebinCom" __type__ = "crypter" __pattern__ = r"http://(?:w{3}.)?pastebin\.com/\w+" __version__ = "0.01" __description__ = """Pastebin.com Plugin""" __author_name__ = ("stickell") __author_mail__ = ("l.stickell@yahoo.it") LINK_PATTERN = r'<div class="de\d+">(https?://[^ <]+)(?...
identifier_body
knn.py
#-*- coding: UTF-8 -*- from numpy import * import operator def classifyPerson(): resultList = ['not at all','in small doses','in large doses'] percentTats = float(raw_input("percentage of time spent playing video games?")) ffMiles = float(raw_input("frequent filter miles earned per year?")) iceCream = float(raw_in...
createDataSet(): group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) labels = ['A','A','B','B'] return group,labels def classify0(inX, dataSet, labels, k): # 获取数据集的大小, 4 dataSetSize = dataSet.shape[0] # 复制输入的向量,然后做减法 diffMat = tile(inX, (dataSetSize,1)) - dataSet # print diffMat sqDiffMat = diffMat**2 sqDis...
0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 # returnMat 返回全部的值 # classLabelVector 数据对应的标签 return returnMat,classLabelVector def
conditional_block
knn.py
#-*- coding: UTF-8 -*- from numpy import * import operator def classifyPerson(): resultList = ['not at all','in small doses','in large doses'] percentTats = float(raw_input("percentage of time spent playing video games?")) ffMiles = float(raw_input("frequent filter miles earned per year?")) iceCream = float(raw_in...
fy0(inX, dataSet, labels, k): # 获取数据集的大小, 4 dataSetSize = dataSet.shape[0] # 复制输入的向量,然后做减法 diffMat = tile(inX, (dataSetSize,1)) - dataSet # print diffMat sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) distances = sqDistances**0.5 sortedDistIndices = distances.argsort() classCount = {} for i in r...
s def classi
identifier_name
knn.py
#-*- coding: UTF-8 -*- from numpy import * import operator def classifyPerson(): resultList = ['not at all','in small doses','in large doses'] percentTats = float(raw_input("percentage of time spent playing video games?")) ffMiles = float(raw_input("frequent filter miles earned per year?")) iceCream = float(raw_in...
classLabelVector.append(int(listFromLine[-1])) index += 1 # returnMat 返回全部的值 # classLabelVector 数据对应的标签 return returnMat,classLabelVector def createDataSet(): group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) labels = ['A','A','B','B'] return group,labels def classify0(inX, dataSet, labels, k): # 获取数据集的...
index = 0 for line in arrayOLines: line = line.strip() listFromLine = line.split('\t') returnMat[index,:] = listFromLine[0:3]
random_line_split
knn.py
#-*- coding: UTF-8 -*- from numpy import * import operator def classifyPerson(): resultList = ['not at all','in small doses','in large doses'] percentTats = float(raw_input("percentage of time spent playing video games?")) ffMiles = float(raw_input("frequent filter miles earned per year?")) iceCream = float(raw_in...
p,labels def classify0(inX, dataSet, labels, k): # 获取数据集的大小, 4 dataSetSize = dataSet.shape[0] # 复制输入的向量,然后做减法 diffMat = tile(inX, (dataSetSize,1)) - dataSet # print diffMat sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) distances = sqDistances**0.5 sortedDistIndices = distances.argsort() classCo...
berOfLines = len(arrayOLines) # 获得总的记录条数 returnMat = zeros((numberOfLines,3)) # 初始化矩阵,全都置为0 classLabelVector = [] index = 0 for line in arrayOLines: line = line.strip() listFromLine = line.split('\t') returnMat[index,:] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 # retu...
identifier_body
__init__.py
import time from xml.etree import ElementTree from PyQt5 import QtWidgets import gremlin import gremlin.ui.common import gremlin.ui.input_item class DoubleTapContainerWidget(gremlin.ui.input_item.AbstractContainerWidget): """DoubleTap container for actions for double or single taps.""" def __init__(self,...
self.activate_combined.toggled.connect(self._activation_changed_cb) self.activate_exclusive.toggled.connect(self._activation_changed_cb) self.options_layout.addWidget(self.activate_exclusive) self.options_layout.addWidget(self.activate_combined) self.action_layout.addLayout(sel...
self.activate_exclusive.setChecked(True)
conditional_block
__init__.py
# 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, # bu...
random_line_split
__init__.py
, profile_data, parent=None): """Creates a new instance. :param profile_data the profile data represented by this widget :param parent the parent of this widget """ super().__init__(profile_data, parent) def _create_action_ui(self): """Creates the UI components.""" ...
"""A container with two actions which are triggered based on the delay between the taps. A single tap will run the first action while a double tap will run the second action. """ name = "Double Tap" tag = "double_tap" functor = DoubleTapContainerFunctor widget = DoubleTapContainerWidge...
identifier_body
__init__.py
import time from xml.etree import ElementTree from PyQt5 import QtWidgets import gremlin import gremlin.ui.common import gremlin.ui.input_item class DoubleTapContainerWidget(gremlin.ui.input_item.AbstractContainerWidget): """DoubleTap container for actions for double or single taps.""" def __init__(self,...
(self, index, label, layout, view_type): """Creates a new action widget. :param index the index at which to store the created action :param label the name of the action to create """ widget = self._create_action_set_widget( self.profile_data.action_sets[index], ...
_create_action_widget
identifier_name
nav.js
var Backbone = require('backbone'), $ = require('jquery'), lang = require('../lang'), template = require('../templates/nav.hbs') module.exports = Backbone.View.extend({ events: { 'click .js-nav': 'navigate' }, initialize: function (options) {
lang: lang })) this.$navLis = this.$('.js-li') this.setActivePage() this.listenTo(options.router, 'route', this.setActivePage) return this }, setActivePage: function () { var pathname = window.location.pathname this.$navLis.removeClass('active'...
this.$el.html(template({ name: window.app.name,
random_line_split
react-native-scrollable-tab-view-tests.tsx
import * as React from 'react'; import { Text, TextStyle, View, ViewStyle } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, TabProps, DefaultTabBar } from 'react-native-scrollable-tab-view'; interface MyTextProps { style?: TextStyle | undefined; } const MyText: React.SFC<TabProps<MyTextProps>> ...
} const TabView1 = () => ( <ScrollableTabView style={{ marginTop: 20, }} initialPage={0} renderTabBar={() => <ScrollableTabBar />} > <MyText tabLabel='Tab #1'>My</MyText> <MyText tabLabel='Tab #2 word word'>favorite</MyText> <MyText tabLabel='Tab #3 word word wo...
{ return ( <View style={this.props.style}>{this.props.children}</View> ); }
identifier_body
react-native-scrollable-tab-view-tests.tsx
import * as React from 'react'; import { Text, TextStyle, View, ViewStyle } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, TabProps, DefaultTabBar } from 'react-native-scrollable-tab-view'; interface MyTextProps { style?: TextStyle | undefined; } const MyText: React.SFC<TabProps<MyTextProps>> ...
extends React.Component<TabProps<MyViewProps>> { render() { return ( <View style={this.props.style}>{this.props.children}</View> ); } } const TabView1 = () => ( <ScrollableTabView style={{ marginTop: 20, }} initialPage={0} renderTabBar={() => <Scrollable...
MyView
identifier_name
react-native-scrollable-tab-view-tests.tsx
import * as React from 'react'; import { Text, TextStyle, View, ViewStyle } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, TabProps, DefaultTabBar } from 'react-native-scrollable-tab-view'; interface MyTextProps { style?: TextStyle | undefined; } const MyText: React.SFC<TabProps<MyTextProps>> ...
style={{ marginTop: 20, }} initialPage={0} renderTabBar={() => <ScrollableTabBar />} > <MyText tabLabel='Tab #1'>My</MyText> <MyText tabLabel='Tab #2 word word'>favorite</MyText> <MyText tabLabel='Tab #3 word word word'>project</MyText> <MyView tabLabel='Tab #...
random_line_split
mediaquerylistevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindi...
} impl MediaQueryListEventMethods for MediaQueryListEvent { // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-media fn Media(&self) -> DOMString { self.media.clone() } // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches fn Matches(&self) -> bool { ...
{ let global = window.upcast::<GlobalScope>(); Ok(MediaQueryListEvent::new( global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.media.clone(), init.matches, )) }
identifier_body
mediaquerylistevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindi...
( global: &GlobalScope, media: DOMString, matches: bool, ) -> DomRoot<MediaQueryListEvent> { let ev = Box::new(MediaQueryListEvent { event: Event::new_inherited(), media: media, matches: Cell::new(matches), }); reflect_dom_object(ev...
new_initialized
identifier_name
mediaquerylistevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindi...
fn Matches(&self) -> bool { self.matches.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.upcast::<Event>().IsTrusted() } }
self.media.clone() } // https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches
random_line_split
pages_per_sheet_settings_test.ts
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'chrome://print/print_preview.js'; import {PrintPreviewPagesPerSheetSettingsElement} from 'chrome://print/print_preview.js'; import {assertEquals, ...
suite('PagesPerSheetSettingsTest', function() { let pagesPerSheetSection: PrintPreviewPagesPerSheetSettingsElement; setup(function() { document.body.innerHTML = ''; const model = document.createElement('print-preview-model'); document.body.appendChild(model); pagesPerSheetSection = docume...
random_line_split
sale_order.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
# fetch the partner's id and subscribe the partner to the sale order assert len(ids) == 1 order = self.browse(cr, uid, ids[0], context=context) add_delivery_method = True only_service = True delivery_method = self.pool.get('delivery.carrier').search(cr, uid, [('default_i...
class sale_order(osv.osv): _inherit = 'sale.order' def action_button_confirm(self, cr, uid, ids, context=None):
random_line_split
sale_order.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
(self, cr, uid, ids, context=None): # fetch the partner's id and subscribe the partner to the sale order assert len(ids) == 1 order = self.browse(cr, uid, ids[0], context=context) add_delivery_method = True only_service = True delivery_method = self.pool.get('delivery.ca...
action_button_confirm
identifier_name
sale_order.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
break elif order_line.product_id.type != 'service': only_service = False if only_service: add_delivery_method = False if add_delivery_method: delivery_met...
_inherit = 'sale.order' def action_button_confirm(self, cr, uid, ids, context=None): # fetch the partner's id and subscribe the partner to the sale order assert len(ids) == 1 order = self.browse(cr, uid, ids[0], context=context) add_delivery_method = True only_service = True...
identifier_body
sale_order.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
if add_delivery_method: delivery_method = delivery_method.id self.write(cr, uid, ids[0], {'carrier_id': delivery_method}) return super(sale_order, self).action_button_confirm(cr, uid, ids, context=context)
add_delivery_method = False
conditional_block
toolbar.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { letProto } from 'rxjs/operator/let';
@Component({ selector: 'app-toolbar', templateUrl: './toolbar.component.html', styleUrls: ['./toolbar.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ToolbarComponent implements OnChanges { @Output() openMenu = new EventEmitter<void>(); @Input() tooltipMsg: string; @Outpu...
random_line_split
toolbar.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { letProto } from 'rxjs/operator/let'; @Component({ selector: 'app-toolbar', templateUrl: './toolbar.compo...
}
{ for (const propName in changes) { if (propName === 'avatarUrl' && changes[propName].currentValue) { this.backgroundImg = this.sanitizer .bypassSecurityTrustStyle(`url(${this.avatarUrl})`); } } }
identifier_body
toolbar.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { letProto } from 'rxjs/operator/let'; @Component({ selector: 'app-toolbar', templateUrl: './toolbar.compo...
} } }
{ this.backgroundImg = this.sanitizer .bypassSecurityTrustStyle(`url(${this.avatarUrl})`); }
conditional_block
toolbar.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { letProto } from 'rxjs/operator/let'; @Component({ selector: 'app-toolbar', templateUrl: './toolbar.compo...
(private sanitizer: DomSanitizer) { } ngOnChanges(changes: SimpleChanges) { for (const propName in changes) { if (propName === 'avatarUrl' && changes[propName].currentValue) { this.backgroundImg = this.sanitizer .bypassSecurityTrustStyle(`url(${this.avatarUrl})`); ...
constructor
identifier_name
first_lab.py
"" if len(filling_string) != 4: result = filling_string else: return filling_string while len(result) != 4: result = "0" + result return result def prettify_table(table, table_type, report_file=None): out_table = { "values_table": [], "pretty_table": [] ...
delta_A) report.write("\n\ndC table for %s:\n" % table_count) prettify_table(delta_C, "delta_C_table", report) result = block_analysis_table(delta_C, table) delta_A_summary.append(result['bytes']) return result S1_table = [[6, 3, 1, 7, 1, 4, 7, 3], [3, 2, 5, 4, 6, 7, 2, 5]] S2_table = [[6, 2, 3, ...
ables(S_value,
identifier_name
first_lab.py
"" if len(filling_string) != 4: result = filling_string else: return filling_string while len(result) != 4: result = "0" + result return result def prettify_table(table, table_type, report_file=None): out_table = { "values_table": [], "pretty_table": [] ...
def gen_delta_C_tables(S_block_table, delta_A_table): values = [] for i in delta_A_table["inputs"]: input_data = { "input_1": i["first"], "input_2": i["second"], } output_data = { "output_1": S_block_table[input_data["input_1"]], "output_...
values = { "outputs": [], "inputs": [] } for i in range(0, 16): values["outputs"].append(i) for j in range(0, 16): data = { "first": j, "second": i ^ j } values["inputs"].append(data) return values
identifier_body
first_lab.py
= "" if len(filling_string) != 4: result = filling_string else: return filling_string while len(result) != 4: result = "0" + result return result def prettify_table(table, table_type, report_file=None): out_table = { "values_table": [], "pretty_table": [] ...
# максимальная вероятность } index = 0 j_divider = 0 # Устанавливаем граничное значение для заполнения таблиц # вероятностей и количества значений if t_type == "S1" or t_type == "S2": j_divider = 8 elif t_type == "S3": j_divid...
# которых встречается
random_line_split
first_lab.py
"" if len(filling_string) != 4: result = filling_string else: return filling_string while len(result) != 4: result = "0" + result return result def prettify_table(table, table_type, report_file=None): out_table = { "values_table": [], "pretty_table": [] ...
ValueError: pass index += 1 report.write("\n=====================\n") index = 0 arr = [] for i in values['bytes']: if i != None: report.write("|\t%s\t|\t%s\t|\n" % (to_bin(index), to_bin(i))) arr.append(to_bin(index)) index += 1 report.writ...
arr2.append(value / 16) values['table'].update({i : arr1}) values['probability'].update({i : arr2}) index += 1 m = max(arr2) values['max'].append(m) values['max'] = max(values['max']) if debug: print("Maximum is %.4f" % values['ma...
conditional_block