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
hash_join.rs
// http://rosettacode.org/wiki/Hash_join use std::collections::HashMap; type LeftTable<'a> = Vec<(i64, &'a str)>; type RightTable<'a> = Vec<(&'a str, &'a str)>; type ResultTable<'a> = Vec<(i64, &'a str, &'a str)>; fn hash_join<'a>(s: LeftTable<'a>, r: RightTable<'a>) -> ResultTable<'a> { let mut hash_map: HashMa...
let mut result = vec![]; //join phase for (age, name) in s { if let Some(v) = hash_map.get(name) { for nemesis in v { result.push((age, name, *nemesis)); } } } return result; } #[cfg(not(test))] pub fn main() { let table1 = vec![(27, "Jonah")...
} }
random_line_split
hash_join.rs
// http://rosettacode.org/wiki/Hash_join use std::collections::HashMap; type LeftTable<'a> = Vec<(i64, &'a str)>; type RightTable<'a> = Vec<(&'a str, &'a str)>; type ResultTable<'a> = Vec<(i64, &'a str, &'a str)>; fn hash_join<'a>(s: LeftTable<'a>, r: RightTable<'a>) -> ResultTable<'a> { let mut hash_map: HashMa...
} let mut result = vec![]; //join phase for (age, name) in s { if let Some(v) = hash_map.get(name) { for nemesis in v { result.push((age, name, *nemesis)); } } } return result; } #[cfg(not(test))] pub fn main() { let table1 = vec![(27, ...
{ hash_map.insert(name, vec![nemesis]); }
conditional_block
v1.py
from .base import * class
(object): cache = {} @classmethod def Add(cls, object): t = object.type cls.cache[t] = object @classmethod def Lookup(cls, type): return cls.cache[type] @classmethod def Define(cls, pt): cls.Add(pt) return pt class OpRecord(pstruct.type): def __...
OpStash
identifier_name
v1.py
from .base import * class OpStash(object): cache = {} @classmethod def Add(cls, object): t = object.type cls.cache[t] = object @classmethod def Lookup(cls, type): return cls.cache[type] @classmethod def Define(cls, pt): cls.Add(pt) return pt class ...
class pixMap(pstruct.type): _fields_ = [ (Long, 'baseAddr'), (Integer, 'rowBytes'), (bounds, 'bounds'), (Integer, 'pmVersion'), (Integer, 'packType'), (Long, 'packSize'), (Long, 'hRes'), (Long, 'vRes'), (Integer, 'pixelType'), (Integer,...
random_line_split
v1.py
from .base import * class OpStash(object): cache = {} @classmethod def Add(cls, object): t = object.type cls.cache[t] = object @classmethod def Lookup(cls, type): return cls.cache[type] @classmethod def Define(cls, pt): cls.Add(pt) return pt class ...
class File(parray.terminated): _object_ = OpRecord def isTerminator(self, value): return int(value['code']) == 0xff
opcode = 0x009a _fields_ = [ (pixMap, 'pixMap'), (bounds, 'srcRect'), (bounds, 'dstRect'), (Integer, 'mode'), ]
identifier_body
gstreamer.py
from threading import Lock from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from Log import log try: import pygst pygst.require('0.10') import gst except ImportError, e: log.error("Unable to import gstreamer. All sound will be mute.\n%s" % e) class Player (GObject): __gsignals__ = ...
else: class Player (GObject): __gsignals__ = { 'end': (SIGNAL_RUN_FIRST, TYPE_NONE, ()), 'error': (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)) } def __init__(self): GObject.__init__(self) self.player = gst.element_factory_make("playbin")...
pass
identifier_body
gstreamer.py
from threading import Lock from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from Log import log try: import pygst pygst.require('0.10') import gst except ImportError, e: log.error("Unable to import gstreamer. All sound will be mute.\n%s" % e) class Player (GObject): __gsignals__ = ...
elif message.type == gst.MESSAGE_EOS: #self.emit("end") return True def play(self, uri): self.player.set_state(gst.STATE_READY) self.player.set_property("uri", uri) self.player.set_state(gst.STATE_PLAYING) def...
simpleMessage, advMessage = message.parse_error() log.warn("Gstreamer error '%s': %s" % (simpleMessage, advMessage)) self.__del__()
conditional_block
gstreamer.py
from threading import Lock from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from Log import log try: import pygst pygst.require('0.10') import gst except ImportError, e: log.error("Unable to import gstreamer. All sound will be mute.\n%s" % e) class Player (GObject): __gsignals__ = ...
self.player.set_state(gst.STATE_READY) self.player.set_property("uri", uri) self.player.set_state(gst.STATE_PLAYING) def __del__ (self): self.player.set_state(gst.STATE_NULL)
return True def play(self, uri):
random_line_split
gstreamer.py
from threading import Lock from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from Log import log try: import pygst pygst.require('0.10') import gst except ImportError, e: log.error("Unable to import gstreamer. All sound will be mute.\n%s" % e) class Player (GObject): __gsignals__ = ...
(self): GObject.__init__(self) self.player = gst.element_factory_make("playbin") self.player.get_bus().add_watch(self.onMessage) def onMessage(self, bus, message): if message.type == gst.MESSAGE_ERROR: # Sound seams sometimes to work, even...
__init__
identifier_name
plugin.py
import ana import weakref default_plugins = { } # This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They # are intended to be used for things such as tracking open files, tracking heap details, and providing storage and persistence for SimProc...
# Should return a copy of the state plugin. def copy(self): raise Exception("copy() not implement for %s", self.__class__.__name__) def merge(self, others, merge_flag, flag_values): # pylint: disable=W0613 ''' Should merge the state plugin with the provided others. oth...
self.state = weakref.proxy(state)
conditional_block
plugin.py
import ana import weakref default_plugins = { } # This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They # are intended to be used for things such as tracking open files, tracking heap details, and providing storage and persistence for SimProc...
(self): self.state = None # Sets a new state (for example, if the state has been branched) def set_state(self, state): if state is None or type(state).__name__ == 'weakproxy': self.state = state else: self.state = weakref.proxy(state) # Should return a copy ...
__init__
identifier_name
plugin.py
import ana import weakref default_plugins = { } # This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They # are intended to be used for things such as tracking open files, tracking heap details, and providing storage and persistence for SimProc...
@staticmethod def register_default(name, cls): if name in default_plugins: raise Exception("%s is already set as the default for %s" % (default_plugins[name], name)) default_plugins[name] = cls
""" The widening operation for plugins. """ raise Exception('widen() not implemented for %s', self.__class__.__name__)
identifier_body
plugin.py
import ana import weakref default_plugins = { } # This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They # are intended to be used for things such as tracking open files, tracking heap details, and providing storage and persistence for SimProc...
''' Should merge the state plugin with the provided others. others - the other state plugin merge_flag - a symbolic expression for the merge flag flag_values - the values to compare against to check which content should be used. self.symbolic_content = s...
raise Exception("copy() not implement for %s", self.__class__.__name__) def merge(self, others, merge_flag, flag_values): # pylint: disable=W0613
random_line_split
FullscreenView.tsx
import * as React from 'react'; import { DummySlide } from 'modules'; import { EDirection } from 'constants/slides.enums'; import './fullscreen-view.scss'; const ReactTransitions = require('react-transitions'); require('react-transitions/dist/animations.css'); interface FullScreenViewProps { deviceDimension: { ...
isFullscreen, slide }: FullScreenViewProps) => { const { r, g, b, a } = slide.state.backgroundColor; const { state: { transition } } = slide; return ( <div id="fullscreen-view"> <ReactTransitions width={deviceDimension.width} height={deviceDimension.height} transition={ ...
direction,
random_line_split
config.rs
use alloc::boxed::Box; use fs::{KScheme, Resource, SliceResource, SliceMutResource}; use network::common::{DNS_ADDR, IP_ADDR, IP_ROUTER_ADDR, IP_SUBNET, MAC_ADDR}; use system::error::{Error, ENOENT, Result}; use system::syscall::{MODE_DIR, MODE_FILE}; /// Network configuration scheme pub struct
; impl KScheme for NetConfigScheme { fn scheme(&self) -> &str { "netcfg" } fn open(&mut self, url: &str, _: usize) -> Result<Box<Resource>> { match url.splitn(2, ":").nth(1).unwrap_or("") { "dns" => Ok(Box::new(SliceMutResource::new("netcfg:dns", unsafe { &mut DNS_ADDR.bytes },...
NetConfigScheme
identifier_name
config.rs
use alloc::boxed::Box; use fs::{KScheme, Resource, SliceResource, SliceMutResource}; use network::common::{DNS_ADDR, IP_ADDR, IP_ROUTER_ADDR, IP_SUBNET, MAC_ADDR}; use system::error::{Error, ENOENT, Result}; use system::syscall::{MODE_DIR, MODE_FILE}; /// Network configuration scheme
"netcfg" } fn open(&mut self, url: &str, _: usize) -> Result<Box<Resource>> { match url.splitn(2, ":").nth(1).unwrap_or("") { "dns" => Ok(Box::new(SliceMutResource::new("netcfg:dns", unsafe { &mut DNS_ADDR.bytes }, MODE_FILE))), "ip" => Ok(Box::new(SliceMutResource::new(...
pub struct NetConfigScheme; impl KScheme for NetConfigScheme { fn scheme(&self) -> &str {
random_line_split
config.rs
use alloc::boxed::Box; use fs::{KScheme, Resource, SliceResource, SliceMutResource}; use network::common::{DNS_ADDR, IP_ADDR, IP_ROUTER_ADDR, IP_SUBNET, MAC_ADDR}; use system::error::{Error, ENOENT, Result}; use system::syscall::{MODE_DIR, MODE_FILE}; /// Network configuration scheme pub struct NetConfigScheme; impl ...
fn open(&mut self, url: &str, _: usize) -> Result<Box<Resource>> { match url.splitn(2, ":").nth(1).unwrap_or("") { "dns" => Ok(Box::new(SliceMutResource::new("netcfg:dns", unsafe { &mut DNS_ADDR.bytes }, MODE_FILE))), "ip" => Ok(Box::new(SliceMutResource::new("netcfg:ip", unsafe { ...
{ "netcfg" }
identifier_body
vga.rs
//! VGA helpers use core::fmt::Write; use log::*; use spin::Mutex; const ROWS: usize = 25; const COLS: usize = 80; pub struct VgaWriter { vmem: *mut u8, offset: usize, } impl VgaWriter { pub unsafe fn new(vmem: *mut u8) -> VgaWriter { let mut vga_writer = VgaWriter { vmem, offset: 0 }; v...
let b = if c.is_ascii() { c as u8 } else { '?' as u8 }; unsafe { *self.vmem.offset(2 * self.offset as isize) = b; } self.offset += 1; } Ok(()) } } pub struct VgaLog { writer: Mutex<VgaWriter>, } impl VgaLog { pub fn new(w...
{ self.offset = ((self.offset + COLS) / COLS) * COLS; continue; }
conditional_block
vga.rs
//! VGA helpers use core::fmt::Write; use log::*; use spin::Mutex; const ROWS: usize = 25; const COLS: usize = 80; pub struct VgaWriter { vmem: *mut u8, offset: usize, } impl VgaWriter { pub unsafe fn new(vmem: *mut u8) -> VgaWriter { let mut vga_writer = VgaWriter { vmem, offset: 0 }; v...
self.clear_line(i); } self.offset = self.offset.saturating_sub(lines * COLS); } } unsafe impl Send for VgaWriter {} impl Write for VgaWriter { fn write_str(&mut self, s: &str) -> core::fmt::Result { for c in s.chars() { if self.offset >= ROWS * COLS { ...
{ if lines == 0 { return; } let lines = core::cmp::min(lines, ROWS); if lines == ROWS { self.clear(); return; } unsafe { core::ptr::copy( self.vmem.offset((lines * COLS * 2) as isize), self....
identifier_body
vga.rs
//! VGA helpers use core::fmt::Write; use log::*;
const ROWS: usize = 25; const COLS: usize = 80; pub struct VgaWriter { vmem: *mut u8, offset: usize, } impl VgaWriter { pub unsafe fn new(vmem: *mut u8) -> VgaWriter { let mut vga_writer = VgaWriter { vmem, offset: 0 }; vga_writer.clear(); vga_writer } pub fn clear(&mut se...
use spin::Mutex;
random_line_split
vga.rs
//! VGA helpers use core::fmt::Write; use log::*; use spin::Mutex; const ROWS: usize = 25; const COLS: usize = 80; pub struct VgaWriter { vmem: *mut u8, offset: usize, } impl VgaWriter { pub unsafe fn new(vmem: *mut u8) -> VgaWriter { let mut vga_writer = VgaWriter { vmem, offset: 0 }; v...
(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { let mut writer = self.writer.lock(); let _ = writeln!( &mut writer, "[{}] {}: {}", level_as_string(record.level()), record.target(), record.args() ...
enabled
identifier_name
includes.ts
/// <reference path="../d.ts/node.d.ts" /> /// <reference path="../d.ts/express.d.ts" /> /// <reference path="../d.ts/form-data.d.ts" /> /// <reference path="../d.ts/request.d.ts" /> /// <reference path="../d.ts/logger.d.ts" /> /// <reference path="../d.ts/lodash.d.ts" /> /// <reference path="../d.ts/underscore.string....
var conf = require(configFile); _.assign(config, conf); } logger.useDefaults(config.logLevel); if (runningAsScript) { logger.get('hawtio-backend').info("Running as script"); }
if (fs.existsSync(configFile)) {
random_line_split
includes.ts
/// <reference path="../d.ts/node.d.ts" /> /// <reference path="../d.ts/express.d.ts" /> /// <reference path="../d.ts/form-data.d.ts" /> /// <reference path="../d.ts/request.d.ts" /> /// <reference path="../d.ts/logger.d.ts" /> /// <reference path="../d.ts/lodash.d.ts" /> /// <reference path="../d.ts/underscore.string....
logger.useDefaults(config.logLevel); if (runningAsScript) { logger.get('hawtio-backend').info("Running as script"); }
{ var conf = require(configFile); _.assign(config, conf); }
conditional_block
index.js
/** * Module dependencies. */ var express = require('../..'); var logger = require('morgan'); var vhost = require('vhost'); /* edit /etc/hosts: 127.0.0.1 foo.example.com 127.0.0.1 bar.example.com 127.0.0.1 example.com
// Main server app var main = express(); main.use(logger('dev')); main.get('/', function(req, res){ res.send('Hello from main app!'); }); main.get('/:sub', function(req, res){ res.send('requested ' + req.params.sub); }); // Redirect app var redirect = express(); redirect.all('*', function(req, res){ consol...
*/
random_line_split
sensor.py
"""Support for monitoring emoncms feeds.""" from __future__ import annotations from datetime import timedelta from http import HTTPStatus import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, SensorState...
@property def native_unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def native_value(self): """Return the state of the device.""" return self._state @property def extra_state_att...
def name(self): """Return the name of the sensor.""" return self._name
random_line_split
sensor.py
"""Support for monitoring emoncms feeds.""" from __future__ import annotations from datetime import timedelta from http import HTTPStatus import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, SensorState...
(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def native_value(self): """Return the state of the device.""" return self._state @property def extra_state_attributes(self): """Return the attributes ...
native_unit_of_measurement
identifier_name
sensor.py
"""Support for monitoring emoncms feeds.""" from __future__ import annotations from datetime import timedelta from http import HTTPStatus import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, SensorState...
else: self._state = round(float(elem["value"]), DECIMALS) class EmonCmsData: """The class for handling the data retrieval.""" def __init__(self, hass, url, apikey, interval): """Initialize the data object.""" self._apikey = apikey self._url = f"{url}/feed/list.jso...
self._state = self._value_template.render_with_possible_json_value( elem["value"], STATE_UNKNOWN )
conditional_block
sensor.py
"""Support for monitoring emoncms feeds.""" from __future__ import annotations from datetime import timedelta from http import HTTPStatus import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, SensorState...
self._data = data self._value_template = value_template self._unit_of_measurement = unit_of_measurement self._sensorid = sensorid self._elem = elem if unit_of_measurement == "kWh": self._attr_device_class = SensorDeviceClass.ENERGY self._attr_stat...
"""Implementation of an Emoncms sensor.""" def __init__( self, hass, data, name, value_template, unit_of_measurement, sensorid, elem ): """Initialize the sensor.""" if name is None: # Suppress ID in sensor name if it's 1, since most people won't # have more than ...
identifier_body
visit-table.component.ts
import { Component, Input, ChangeDetectionStrategy, OnChanges } from '@angular/core'; import { FORM_DIRECTIVES } from '@angular/forms'; import { CORE_DIRECTIVES } from '@angular/common'; import { Router } from '@angular/router'; import { PAGINATION_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap'; import { NG_TABLE_D...
implements OnChanges { public rows:Array<any> = []; public columns:Array<{[key: string]: string}> = [ {title: 'Name', name: 'name', pipe: 'name'}, {title: 'Status', name: 'status', pipe: 'Status'}, {title: 'Time', name: 'last_message_time', pipe: 'DatePipe'}, {title: 'Message', name: 'last_message...
VisitTableComponent
identifier_name
visit-table.component.ts
import { Component, Input, ChangeDetectionStrategy, OnChanges } from '@angular/core'; import { FORM_DIRECTIVES } from '@angular/forms'; import { CORE_DIRECTIVES } from '@angular/common'; import { Router } from '@angular/router'; import { PAGINATION_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap'; import { NG_TABLE_D...
}
{ this.chatUtilService.isSelectedChat = true; this.socketService.markThreadAsRead(new Thread({id: row.id, type: Thread.THREAD_TYPE_SERVE})); var sub1 = this.threadsService.threads.subscribe(threads => { var foundThread = _.find(threads, t => {return t.id === row.id;}); if(foundThread !== null)...
identifier_body
visit-table.component.ts
import { Component, Input, ChangeDetectionStrategy, OnChanges } from '@angular/core'; import { FORM_DIRECTIVES } from '@angular/forms'; import { CORE_DIRECTIVES } from '@angular/common'; import { Router } from '@angular/router'; import { PAGINATION_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap'; import { NG_TABLE_D...
if (config.sorting) { Object.assign(this.config.sorting, config.sorting); } let filteredData = this.changeFilter(this.data, this.config); let sortedData = this.changeSort(filteredData, this.config); this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData; this....
{ Object.assign(this.config.filtering, config.filtering); }
conditional_block
visit-table.component.ts
import { Component, Input, ChangeDetectionStrategy, OnChanges } from '@angular/core'; import { FORM_DIRECTIVES } from '@angular/forms'; import { CORE_DIRECTIVES } from '@angular/common'; import { Router } from '@angular/router'; import { PAGINATION_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap';
@Component({ moduleId: module.id, selector: 'visit-table', templateUrl: 'visit-table.component.html', directives: [NG_TABLE_DIRECTIVES, PAGINATION_DIRECTIVES, CORE_DIRECTIVES, FORM_DIRECTIVES], changeDetection: ChangeDetectionStrategy.OnPush }) export class VisitTableComponent implements OnChanges ...
import { NG_TABLE_DIRECTIVES } from '../../shared/ng2-table/index'; import { TextService } from '../../shared/index'; import { ChatUtilService, ThreadService, SocketService, Thread } from '../../shared/index';
random_line_split
move-in-guard-1.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_synt...
// http://rust-lang.org/COPYRIGHT. //
random_line_split
move-in-guard-1.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 ...
{ false }
identifier_body
move-in-guard-1.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 ...
() { let x: Box<_> = box 1; let v = (1, 2); match v { (1, _) if take(x) => (), (_, 2) if take(x) => (), //~ ERROR use of moved value: `x` _ => (), } } fn take<T>(_: T) -> bool { false }
main
identifier_name
logic.js
const fs = require('fs'); const util = require('../../util'); // test equality function equal(a, b, options) { if (a === b) { return options.fn(this); } return options.inverse(this); } // great than function
(a, b, options) { if (a >= b) { return options.fn(this); } return options.inverse(this); } // between function between(a, b, c, options) { if (a >= b && a <= c) { return options.fn(this); } return options.inverse(this); } // less than function lt(a, b, options) { if (a < b) { return options....
gt
identifier_name
logic.js
const fs = require('fs'); const util = require('../../util'); // test equality function equal(a, b, options) { if (a === b) { return options.fn(this); } return options.inverse(this); } // great than function gt(a, b, options) { if (a >= b) { return options.fn(this); } return options.inverse(this);...
return options.inverse(this); } // less than function lt(a, b, options) { if (a < b) { return options.fn(this); } return options.inverse(this); } function ignoreNan(val, symbol) { const isNumber = (val >= 0 || val < 0); return isNumber ? `${util.roundDecimal(val, 2)} ${symbol}` : ''; } // test inequ...
{ return options.fn(this); }
conditional_block
logic.js
const fs = require('fs'); const util = require('../../util'); // test equality function equal(a, b, options) { if (a === b) { return options.fn(this); } return options.inverse(this); } // great than function gt(a, b, options) { if (a >= b) { return options.fn(this); } return options.inverse(this);...
// test File Exit function fileExist(a, b, options) { try { fs.statSync(`${a}${b}`); return options.fn(this); } catch (err) { return options.inverse(this); } } exports.equal = equal; exports.gt = gt; exports.lt = lt; exports.between = between; exports.ignoreNan = ignoreNan; exports.inequal = inequa...
return options.fn(this); } return options.inverse(this); }
random_line_split
logic.js
const fs = require('fs'); const util = require('../../util'); // test equality function equal(a, b, options) { if (a === b) { return options.fn(this); } return options.inverse(this); } // great than function gt(a, b, options) { if (a >= b) { return options.fn(this); } return options.inverse(this);...
// test File Exit function fileExist(a, b, options) { try { fs.statSync(`${a}${b}`); return options.fn(this); } catch (err) { return options.inverse(this); } } exports.equal = equal; exports.gt = gt; exports.lt = lt; exports.between = between; exports.ignoreNan = ignoreNan; exports.inequal = inequ...
{ if (a !== b) { return options.fn(this); } return options.inverse(this); }
identifier_body
restful.gateway.ts
import { Injectable } from '@angular/core'; import { Response, ResponseOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Observer } from 'rxjs/Observer'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/merge'; import { GAME_TEXT } from '../../config/config'; import { R...
extends Gateway { private _lastText = ''; private _lastTime = 0; send(command: RestfulCommand): Observable<any> { return Observable.create((observer: Observer<any>) => { const currentText = (command.payload as any).text; const currentTime = (command.payload as any).time; let status = 200;...
RestfulGateway
identifier_name
restful.gateway.ts
import { Injectable } from '@angular/core'; import { Response, ResponseOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Observer } from 'rxjs/Observer'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/merge'; import { GAME_TEXT } from '../../config/config'; import { R...
this._lastText = currentText; this._lastTime = currentTime; if (GAME_TEXT === this._lastText) { this._lastText = ''; } const response = new Response(new ResponseOptions({ body: null, status, headers: null, statusText: null, type: null, ...
{ status = 403; }
conditional_block
restful.gateway.ts
import { Injectable } from '@angular/core'; import { Response, ResponseOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Observer } from 'rxjs/Observer'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/merge'; import { GAME_TEXT } from '../../config/config';
@Injectable() export class RestfulGateway extends Gateway { private _lastText = ''; private _lastTime = 0; send(command: RestfulCommand): Observable<any> { return Observable.create((observer: Observer<any>) => { const currentText = (command.payload as any).text; const currentTime = (command.paylo...
import { RestfulCommand } from '../commands/restful.command'; import { Gateway } from './base.gateway'; // Mocking backend validation behavior.
random_line_split
toolbar-example.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CameraService, CesiumService, CirclesEditorService, EllipsesEditorService, HippodromeEditorService, PointsEditorService, PolygonsEditorService, PolylineEditorObservable, RangeAndBearingComponent, RectanglesEditorService, ZoomToRe...
() { } createRangeAndBearing() { if (this.rnb) { this.rnb.dispose(); } this.rnb = this.rangeAndBearing.create(); } zoomToRectangle() { this.zoomToRectangleService.activate(); } goHome() { this.cameraService.cameraFlyTo({ destination: Cesium.Cartesian3.fromDegrees(35.21, 31.77, ...
ngOnInit
identifier_name
toolbar-example.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CameraService, CesiumService, CirclesEditorService, EllipsesEditorService, HippodromeEditorService, PointsEditorService, PolygonsEditorService, PolylineEditorObservable, RangeAndBearingComponent, RectanglesEditorService, ZoomToRe...
this.rnb = this.rangeAndBearing.create(); } zoomToRectangle() { this.zoomToRectangleService.activate(); } goHome() { this.cameraService.cameraFlyTo({ destination: Cesium.Cartesian3.fromDegrees(35.21, 31.77, 200000) }); } drawCircle() { this.circlesEditor.create(); } drawEllipse() {...
{ this.rnb.dispose(); }
conditional_block
toolbar-example.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CameraService, CesiumService, CirclesEditorService, EllipsesEditorService, HippodromeEditorService, PointsEditorService, PolygonsEditorService, PolylineEditorObservable, RangeAndBearingComponent, RectanglesEditorService, ZoomToRe...
], }) export class ToolbarExampleComponent implements OnInit { rnb: PolylineEditorObservable; @ViewChild('rangeAndBearing') private rangeAndBearing: RangeAndBearingComponent; constructor( private cameraService: CameraService, private zoomToRectangleService: ZoomToRectangleService, private cesiumSer...
PolygonsEditorService, RectanglesEditorService, HippodromeEditorService, PointsEditorService,
random_line_split
toolbar-example.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CameraService, CesiumService, CirclesEditorService, EllipsesEditorService, HippodromeEditorService, PointsEditorService, PolygonsEditorService, PolylineEditorObservable, RangeAndBearingComponent, RectanglesEditorService, ZoomToRe...
drawEllipse() { this.ellipsesEditor.create(); } drawPolygon() { this.polygonsEditor.create(); } drawRectangle() { this.rectanglesEditor.create({ rectangleProps: { height: undefined, extrudedHeight: undefined } }); } drawHippodrome() { this.hippodromesEditor.create({ hippodromeProps: {...
{ this.circlesEditor.create(); }
identifier_body
builtin-superkinds-self-type.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 ...
} impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182.foo(tx); assert!(rx.recv() == 1193182); }
{ }
identifier_body
builtin-superkinds-self-type.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 ...
use std::sync::mpsc::{channel, Sender}; trait Foo : Sync+'static { fn foo(self, mut chan: Sender<Self>) { } } impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182.foo(tx); assert!(rx.recv() == 1193182); }
// Tests (negatively) the ability for the Self type in default methods // to use capabilities granted by builtin kinds as supertraits.
random_line_split
builtin-superkinds-self-type.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 (tx, rx) = channel(); 1193182.foo(tx); assert!(rx.recv() == 1193182); }
main
identifier_name
index.js
// Component TrunkTable [[INCLUDE component=Trunk]] [[INCLUDE component=TrunkInputButton]] [[INCLUDE component=Ajax]] (function() { function
() { this.name = null; this.fields = {}; this.rows = {}; this.dom = document.createElement('div'); this.search = trunk.create('InputButton'); this.search.dom.classList.add('search'); this.dom.appendChild(this.search.dom); this.table = document.createElement('table'); this.dom.appendChild(this.table...
TrunkTable
identifier_name
index.js
// Component TrunkTable [[INCLUDE component=Trunk]] [[INCLUDE component=TrunkInputButton]] [[INCLUDE component=Ajax]] (function() { function TrunkTable()
// this.table.foot = document.createElement('tfoot'); // this.table.appendChild(this.table.foot); this.pagination = document.createElement('div'); this.pagination.classList.add('pagination') this.pagination.innerHTML = 'pagination'; this.dom.appendChild(this.pagination); } TrunkTable.prototype.load = f...
{ this.name = null; this.fields = {}; this.rows = {}; this.dom = document.createElement('div'); this.search = trunk.create('InputButton'); this.search.dom.classList.add('search'); this.dom.appendChild(this.search.dom); this.table = document.createElement('table'); this.dom.appendChild(this.table); ...
identifier_body
index.js
// Component TrunkTable [[INCLUDE component=Trunk]] [[INCLUDE component=TrunkInputButton]] [[INCLUDE component=Ajax]] (function() { function TrunkTable() { this.name = null; this.fields = {}; this.rows = {}; this.dom = document.createElement('div'); this.search = trunk.create('InputButton'); this.sea...
// this.table.foot.appendChild(tr.cloneNode(true)); }; TrunkTable.prototype.repaintRows = function() { // TODO: improve this: this.table.body.innerHTML = ''; var fields = this.fields; for(var i in this.rows) { var row = this.rows[i]; var tr = document.createElement('tr'); for (var field in f...
td.innerHTML = '<div class="a"><div class="c"><div class="f">'+i+'</div></div><div class="b">'+i+'</div></div>'; tr.appendChild(td); field.dom = tr; }
random_line_split
mainserver.py
import os import pwd import grp import argparse import shutil from twisted.web import server, resource, static, script from twisted.internet import reactor from zope.interface import Interface, Attribute, implements from twisted.python.components import registerAdapter from twisted.web.server import Sessio...
# Try setting the new uid/gid os.setgid(running_gid) os.setuid(running_uid) # Ensure a very conservative umask old_umask = os.umask(077) def startServer(): ap = argparse.ArgumentParser(description='Server options') ap.add_argument('--clean',action='store_true',default=False) ...
# Remove group privileges os.setgroups([])
random_line_split
mainserver.py
import os import pwd import grp import argparse import shutil from twisted.web import server, resource, static, script from twisted.internet import reactor from zope.interface import Interface, Attribute, implements from twisted.python.components import registerAdapter from twisted.web.server import Sessio...
# Get the uid/gid from the name running_uid = pwd.getpwnam(uid_name).pw_uid running_gid = grp.getgrnam(gid_name).gr_gid # Remove group privileges os.setgroups([]) # Try setting the new uid/gid os.setgid(running_gid) os.setuid(running_uid) # Ensure a very conservativ...
return
conditional_block
mainserver.py
import os import pwd import grp import argparse import shutil from twisted.web import server, resource, static, script from twisted.internet import reactor from zope.interface import Interface, Attribute, implements from twisted.python.components import registerAdapter from twisted.web.server import Sessio...
def drop_privileges(uid_name='nobody', gid_name='nogroup'): if os.getuid() != 0: # We're not root so, like, whatever dude return # Get the uid/gid from the name running_uid = pwd.getpwnam(uid_name).pw_uid running_gid = grp.getgrnam(gid_name).gr_gid # Remove group privi...
global startedSession if not startedSession: print "Started session adapter" registerAdapter(User, Session, IUser) startedSession = True
identifier_body
mainserver.py
import os import pwd import grp import argparse import shutil from twisted.web import server, resource, static, script from twisted.internet import reactor from zope.interface import Interface, Attribute, implements from twisted.python.components import registerAdapter from twisted.web.server import Sessio...
(): global startedSession if not startedSession: print "Started session adapter" registerAdapter(User, Session, IUser) startedSession = True def drop_privileges(uid_name='nobody', gid_name='nogroup'): if os.getuid() != 0: # We're not root so, like, whatever dude ...
startSession
identifier_name
traces.py
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
elif "sort_asc" in raw_filters and raw_filters["sort_asc"] == "True": query_options = {"sort": ["+start_timestamp", "trace_tag"]} return self._get_all( exclude_fields=exclude_attributes, include_fields=include_attributes, sort=sort, offset=off...
query_options = {"sort": ["-start_timestamp", "trace_tag"]}
conditional_block
traces.py
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
"trigger_instance": "trigger_instances.object_id", } query_options = {"sort": ["-start_timestamp", "trace_tag"]} def get_all( self, exclude_attributes=None, include_attributes=None, sort=None, offset=0, limit=None, requester_user=None, ...
supported_filters = { "trace_tag": "trace_tag", "execution": "action_executions.object_id", "rule": "rules.object_id",
random_line_split
traces.py
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
(self, id, requester_user): return self._get_one_by_id( id, requester_user=requester_user, permission_type=PermissionType.TRACE_VIEW ) traces_controller = TracesController()
get_one
identifier_name
traces.py
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
traces_controller = TracesController()
return self._get_one_by_id( id, requester_user=requester_user, permission_type=PermissionType.TRACE_VIEW )
identifier_body
load.js
import Promise from 'bluebird'; import fs from 'fs'; Promise.promisifyAll(fs); const RAW_DATA_FILE = 'data'; /** * Include any raw compilation data as a 'data' file */ function includeRawDataFile(includedFiles, files, entryFilename, data) { let orderedFiles = includedFiles; if(entryFilename === RAW_DATA_FILE ...
return { compiledFiles: files, orderedFiles, }; } /** * Async load a file from filename */ function load(filename, encoding = 'utf8') { return fs.readFileAsync(filename, encoding); } /** * Sync load a file from filename */ function loadSync(filename, encoding = 'utf8') { return fs.readFileSync(f...
{ orderedFiles = [...orderedFiles.slice(1), orderedFiles[0]]; }
conditional_block
load.js
import Promise from 'bluebird'; import fs from 'fs'; Promise.promisifyAll(fs); const RAW_DATA_FILE = 'data'; /** * Include any raw compilation data as a 'data' file */ function includeRawDataFile(includedFiles, files, entryFilename, data) { let orderedFiles = includedFiles; if(entryFilename === RAW_DATA_FILE ...
/** * Synchronously load all files included in a sass compilations including potential raw data input */ export function loadCompiledFilesSync(includedFiles, entryFilename, data) { const files = {}; includedFiles.forEach(filename => { files[filename] = loadSync(filename); }); return includeRawDataFile...
{ const files = {}; return Promise.all(includedFiles.map(filename => { return load(filename) .then(data => { files[filename] = data; }); })) .then(() => { return includeRawDataFile(includedFiles, files, entryFilename, data); }); }
identifier_body
load.js
import Promise from 'bluebird'; import fs from 'fs'; Promise.promisifyAll(fs); const RAW_DATA_FILE = 'data'; /** * Include any raw compilation data as a 'data' file */ function includeRawDataFile(includedFiles, files, entryFilename, data) { let orderedFiles = includedFiles; if(entryFilename === RAW_DATA_FILE ...
(filename, encoding = 'utf8') { return fs.readFileSync(filename, encoding); } /** * Load all files included in a sass compilations including potential raw data input */ export function loadCompiledFiles(includedFiles, entryFilename, data) { const files = {}; return Promise.all(includedFiles.map(filename => { ...
loadSync
identifier_name
load.js
import Promise from 'bluebird'; import fs from 'fs'; Promise.promisifyAll(fs); const RAW_DATA_FILE = 'data'; /** * Include any raw compilation data as a 'data' file */ function includeRawDataFile(includedFiles, files, entryFilename, data) { let orderedFiles = includedFiles; if(entryFilename === RAW_DATA_FILE ...
*/ export function loadCompiledFiles(includedFiles, entryFilename, data) { const files = {}; return Promise.all(includedFiles.map(filename => { return load(filename) .then(data => { files[filename] = data; }); })) .then(() => { return includeRawDataFile(includedFiles, files, entryFilen...
random_line_split
lib.rs
`. #[inline(always)] pub fn inf<T: POrd>(a: &T, b: &T) -> T { POrd::inf(a, b) } /// Returns the supremum of `a` and `b`. #[inline(always)] pub fn sup<T: POrd>(a: &T, b: &T) -> T { POrd::sup(a, b) } /// Compare `a` and `b` using a partial ordering relation. #[inline(always)] pub fn partial_cmp<T: POrd>(a: &T, ...
, M: Translate<P>>(m: &M, p: &P) -> P { m.inv_translate(p) } /* * Rotation<V> */ /// Gets the rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::...
v_translate<P
identifier_name
lib.rs
`. #[inline(always)] pub fn inf<T: POrd>(a: &T, b: &T) -> T { POrd::inf(a, b) } /// Returns the supremum of `a` and `b`. #[inline(always)] pub fn sup<T: POrd>(a: &T, b: &T) -> T { POrd::sup(a, b) } /// Compare `a` and `b` using a partial ordering relation. #[inline(always)] pub fn partial_cmp<T: POrd>(a: &T, ...
/// Returns the squared distance between two points. #[inline(always)] pub fn sqdist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N { a.sqdist(b) } /* * Translation<V> */ /// Gets the translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /...
a.dist(b) }
identifier_body
lib.rs
`. #[inline(always)] pub fn inf<T: POrd>(a: &T, b: &T) -> T { POrd::inf(a, b) } /// Returns the supremum of `a` and `b`. #[inline(always)] pub fn sup<T: POrd>(a: &T, b: &T) -> T { POrd::sup(a, b) } /// Compare `a` and `b` using a partial ordering relation. #[inline(always)] pub fn partial_cmp<T: POrd>(a: &T, ...
/// } /// ``` #[inline(always)] pub fn translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.translate(p) } /// Applies an inverse translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::...
random_line_split
lib.rs
else { max } } else { min } } /// Same as `cmp::max`. #[inline(always)] pub fn max<T: Ord>(a: T, b: T) -> T { cmp::max(a, b) } /// Same as `cmp::min`. #[inline(always)] pub fn min<T: Ord>(a: T, b: T) -> T { cmp::min(a, b) } /// Returns the infimum of `a` and `b`...
val }
conditional_block
ViewContainer.tsx
import { BaseComponent, setRef } from './vdom-util' import { ComponentChildren, Ref, createElement } from './vdom' import { CssDimValue } from './scrollgrid/util' export interface ViewContainerProps { labeledById: string liquid?: boolean height?: CssDimValue aspectRatio?: number elRef?: Ref<HTMLDivElement> ...
componentWillUnmount() { this.context.removeResizeHandler(this.handleResize) } handleEl = (el: HTMLElement | null) => { this.el = el setRef(this.props.elRef, el) this.updateAvailableWidth() } handleResize = () => { this.updateAvailableWidth() } updateAvailableWidth() { if ( ...
{ this.context.addResizeHandler(this.handleResize) }
identifier_body
ViewContainer.tsx
import { BaseComponent, setRef } from './vdom-util' import { ComponentChildren, Ref, createElement } from './vdom' import { CssDimValue } from './scrollgrid/util' export interface ViewContainerProps { labeledById: string liquid?: boolean height?: CssDimValue aspectRatio?: number elRef?: Ref<HTMLDivElement> ...
} else { height = props.height || '' } return ( <div aria-labelledby={props.labeledById} ref={this.handleEl} className={classNames.join(' ')} style={{ height, paddingBottom }} > {props.children} </div> ) } componentDidMount() { t...
{ // while waiting to know availableWidth, we can't set height to *zero* // because will cause lots of unnecessary scrollbars within scrollgrid. // BETTER: don't start rendering ANYTHING yet until we know container width // NOTE: why not always use paddingBottom? Causes height oscillatio...
conditional_block
ViewContainer.tsx
import { BaseComponent, setRef } from './vdom-util' import { ComponentChildren, Ref, createElement } from './vdom' import { CssDimValue } from './scrollgrid/util' export interface ViewContainerProps { labeledById: string liquid?: boolean height?: CssDimValue aspectRatio?: number elRef?: Ref<HTMLDivElement> ...
if (state.availableWidth !== null) { height = state.availableWidth / aspectRatio } else { // while waiting to know availableWidth, we can't set height to *zero* // because will cause lots of unnecessary scrollbars within scrollgrid. // BETTER: don't start rendering ANYTHING y...
if (aspectRatio) {
random_line_split
ViewContainer.tsx
import { BaseComponent, setRef } from './vdom-util' import { ComponentChildren, Ref, createElement } from './vdom' import { CssDimValue } from './scrollgrid/util' export interface ViewContainerProps { labeledById: string liquid?: boolean height?: CssDimValue aspectRatio?: number elRef?: Ref<HTMLDivElement> ...
() { if ( this.el && // needed. but why? this.props.aspectRatio // aspectRatio is the only height setting that needs availableWidth ) { this.setState({ availableWidth: this.el.offsetWidth }) } } }
updateAvailableWidth
identifier_name
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStream...
(name: impl ToString) -> Vertex { Vertex::copy_from(name.to_string().as_bytes()) } }
v
identifier_name
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStream...
to_visit.push(p); } } } false } } let state: Mutex<State> = Default::default(); move |v: Vertex| -> Result<Vec<Vertex>> { let mut state = state.lock().unwrap(); if let Some(parents) = state.known.ge...
{ return true; }
conditional_block
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStream...
return true; } to_visit.push(p); } } } false } } let state: Mutex<State> = Default::default(); move |v: Vertex| -> Result<Vec<Vertex>> { let mut state = st...
if let Some(parents) = self.known.get(&v) { for p in parents { if p == ancestor {
random_line_split
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStream...
#[test] fn test_break_parent_func_cycle_linear() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { let list = "0123456789".chars().map(|c| v(c)).collect::<Vec<_>>(); let parents = match list.iter().position(|x| x == &n) { Some(i) if i > 0 =>...
{ let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { Ok(vec![n, v("1"), v("2")]) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("A"))?, vec![v("1"), v("2")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("2")]); asser...
identifier_body
loading.component.spec.ts
/* * Copyright 2019-present Open Networking Foundation * * 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 appli...
describe('LoadingComponent', () => { let log: LogService; let component: LoadingComponent; let fixture: ComponentFixture<LoadingComponent>; beforeEach(async(() => { log = new ConsoleLoggerService(); TestBed.configureTestingModule({ imports: [ BrowserAnimationsModule ], ...
import { LoadingComponent } from './loading.component'; import {LogService} from '../../log.service'; import {ConsoleLoggerService} from '../../consolelogger.service'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
random_line_split
object_header.rs
//! A generic header for every Git object. use object_type::ObjectType; use object_type; use reader::Reader; use std::str::FromStr; use error::GitError; use error::GitError::CorruptObject; #[deriving(PartialEq, Show, Clone)] pub struct ObjectHeader { pub typ: ObjectType, pub length: uint } imp...
{ let mut reader = Reader::from_data(bytes); let typ = try!(object_type::from_text(reader.take_string_while(|c| *c != 32).unwrap_or(""))); reader.skip(1); let length: uint = try!( FromStr::from_str(reader.take_string_while(|c| *c != 0).unwrap_or("")) .ok_or(CorruptObject(...
identifier_body
object_header.rs
//! A generic header for every Git object. use object_type::ObjectType; use object_type; use reader::Reader; use std::str::FromStr; use error::GitError; use error::GitError::CorruptObject; #[deriving(PartialEq, Show, Clone)] pub struct ObjectHeader { pub typ: ObjectType, pub length: uint } imp...
reader.skip(1); let length: uint = try!( FromStr::from_str(reader.take_string_while(|c| *c != 0).unwrap_or("")) .ok_or(CorruptObject("invalid header length".into_cow())) ); Ok(ObjectHeader { typ: typ, length: length }) }
random_line_split
object_header.rs
//! A generic header for every Git object. use object_type::ObjectType; use object_type; use reader::Reader; use std::str::FromStr; use error::GitError; use error::GitError::CorruptObject; #[deriving(PartialEq, Show, Clone)] pub struct ObjectHeader { pub typ: ObjectType, pub length: uint } imp...
(&self) -> Vec<u8> { let mut buff = Vec::new(); buff.push_all(format!("{} ", self.typ.to_text()).into_bytes().as_slice()); buff.push_all(format!("{}", self.length).into_bytes().as_slice()); buff.push(0x00); buff } } pub fn decode(bytes: &[u8]) -> Result<ObjectHe...
encode
identifier_name
data_manager_functions.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE import lxml ''' A set of functions related to Data Manager and the <data_manager> node in Opus Project Configuration files. ''' def get_tool_nodes(projec...
return project.find('data_manager/tool_library') def get_path_to_tool_modules(project): ''' Get the path to the tool modules @param project (OpusProject) project to operate on @return the text representing the path or None if not found ''' node = project.find('data_manager/path_to_tool_mod...
return project
conditional_block
data_manager_functions.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE
''' A set of functions related to Data Manager and the <data_manager> node in Opus Project Configuration files. ''' def get_tool_nodes(project): ''' Retrieve a list of all nodes that represent tools in the given project @param project (OpusProject) project to fetch nodes from @return a list of nodes re...
import lxml
random_line_split
data_manager_functions.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE import lxml ''' A set of functions related to Data Manager and the <data_manager> node in Opus Project Configuration files. ''' def get_tool_nodes(projec...
def get_tool_node_by_name(project, tool_name): ''' Fetch a node representing a tool based in it's name. @param project (OpusProject) project to fetch node from @param tool_name (str) name of the tool to fetch @return the node (Element) or None if the node was not found ''' for node in get_...
''' Retrieve a list of all nodes that represent tools in the given project @param project (OpusProject) project to fetch nodes from @return a list of nodes representing the tools (list(Element)) ''' tool_nodes = [] tool_group_nodes = get_tool_library_node(project).findall("tool_group") for t...
identifier_body
data_manager_functions.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE import lxml ''' A set of functions related to Data Manager and the <data_manager> node in Opus Project Configuration files. ''' def get_tool_nodes(projec...
(project, tool_name): ''' Fetch a node representing a tool based in it's name. @param project (OpusProject) project to fetch node from @param tool_name (str) name of the tool to fetch @return the node (Element) or None if the node was not found ''' for node in get_tool_nodes(project): ...
get_tool_node_by_name
identifier_name
List.tsx
import React, { MouseEvent, PureComponent, ReactElement } from 'react'; import { IProject } from 'Projects'; import Tile from '../Tile'; export default class List extends PureComponent<{ projects: IProject[], olderCommercial: boolean, olderNoncommercial: boolean, onToggleOlderCommercial: (event: Mouse...
(): ReactElement<{}> { const commercialTiles = this.props.projects .filter((project) => project.type === 'commercial' && (!project.archived || this.props.olderCommercial)) .map(this.tileRender.bind(this)); const noncommercialTiles = this.props.projects ...
render
identifier_name
List.tsx
import React, { MouseEvent, PureComponent, ReactElement } from 'react'; import { IProject } from 'Projects'; import Tile from '../Tile'; export default class List extends PureComponent<{
olderCommercial: boolean, olderNoncommercial: boolean, onToggleOlderCommercial: (event: MouseEvent<HTMLButtonElement>) => void, onToggleOlderNoncommercial: (event: MouseEvent<HTMLButtonElement>) => void, onOpen: (projectId: string) => void, }, {}> { constructor(props) { super(props); ...
projects: IProject[],
random_line_split
CitationView.js
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless requir...
function pickNameProperty() { var prop = this.model.getFeature('label') || this.model.getFeature('name'); if (!prop) { var props = this.model.getRuntimeProperties(); var stringProps = []; for (var i = 0; i < props.length; i++) { var p = props[i]; if (! p.hidde...
], methods: [
random_line_split
CitationView.js
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless requir...
} for (var i = 0; i < stringProps.length; i++) { var p = stringProps[i]; var pname = p.name.toLowerCase(); if (pname.indexOf('name') > -1 || pname.indexOf('label') > -1) { prop = p; break; } } if (!prop && stringProps.lengt...
{ stringProps.push(p); }
conditional_block
error.rs
/* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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....
} impl From<BuildError> for Error { fn from(err: BuildError) -> Error { Error::Build(err) } } impl error::Error for Error { #[allow(warnings)] fn description(&self) -> &str { match *self { Error::Build(ref err) => err.description(), Error::Lib(ref err) => err, ...
{ Error::Lib(err.to_string()) }
identifier_body
error.rs
/* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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....
(err: reqwest::Error) -> Error { Error::Http(err) } } impl From<serde_json::error::Error> for Error { fn from(err: serde_json::error::Error) -> Error { Error::Json(err) } } impl From<url::ParseError> for Error { fn from(err: url::ParseError) -> Error { Error::Lib(err.to_string(...
from
identifier_name
error.rs
/* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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....
Lib(String), /// HTTP library error Http(reqwest::Error), /// IO error Io(io::Error), /// JSON error Json(serde_json::error::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<reqwest::Error> for Error { fn from...
/// A general error from this library
random_line_split
data-shopping.ts
type ShoppingItem = { type: string; name: string; price: number; qty: number; } interface ShoppingItemWithId extends ShoppingItem { id: number; }; const shoppingData: ShoppingItemWithId[] = [ { type: 'Clothes', name: 'Socks', price: 1.00, qty: 5, id: 421801449988 }, { type: 'Clothes', name: 'Trousers', price: ...
{ type: 'Food', name: 'Chips', price: 3.50, qty: 4, id: 206058323583 }, { type: 'Food', name: 'Fish', price: 8.75, qty: 2, id: 837318618873 }, { type: 'Food', name: 'Beer', price: 2.80, qty: 12, id: 611830716982 }, ]; type ShoppingItemsDictionary = { [idx: number]: ShoppingItem; } const shoppingDataDictionary: Sh...
random_line_split
defs.rs
Hex, UpperHex, Debug, Display, Formatter, Error }; use core::str::FromStr; use vec::Vec; use num::PrimInt; use net::Packet; /// Type of the ether_type pub type EtherType = u16; /// Type that represent a protocol id pub type ProtocolIdType = u8; /// Type that represent a port pub type PortType =...
let mut ret = Self::empty(); for (i, b) in split.iter().enumerate() { let bytes = b.as_bytes(); if bytes.len() != 2 { return Err(()) } let d1 = try!(b.char_at(0).to_digit(16).ok_or(())) * 16; let d2 = try!(b.char_at(1).to_d...
{ return Err(()) }
conditional_block
defs.rs
Hex, UpperHex, Debug, Display, Formatter, Error }; use core::str::FromStr; use vec::Vec; use num::PrimInt; use net::Packet; /// Type of the ether_type pub type EtherType = u16; /// Type that represent a protocol id pub type ProtocolIdType = u8; /// Type that represent a port pub type PortType =...
/// Construct from an integer represented using host's endianness pub fn from_host(i: T) -> Self { Int(i.to_be()) } /// Returns the contained integer using host's endianness pub fn as_host(&self) -> T { T::from_be(self.0.clone()) } /// Returns the contained integer using ne...
random_line_split
defs.rs
Hex, UpperHex, Debug, Display, Formatter, Error }; use core::str::FromStr; use vec::Vec; use num::PrimInt; use net::Packet; /// Type of the ether_type pub type EtherType = u16; /// Type that represent a protocol id pub type ProtocolIdType = u8; /// Type that represent a port pub type PortType =...
(&self) -> bool { *self == Self::broadcast() } /// Create an hardware address from bytes. /// /// This method is unsafe because the slice *MUST* contain at least 6 /// elements. pub unsafe fn from_bytes(bytes: &[u8]) -> Self { let mut ret = Self::empty(); ret.bytes[0] =...
is_broadcast
identifier_name
htmlselectelement.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::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; u...
} }
{ node.check_disabled_attribute(); }
conditional_block
htmlselectelement.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::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; u...
fn after_set_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_sta...
random_line_split
htmlselectelement.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::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; u...
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods...
new
identifier_name
cards.js
import React from 'react'; import PropTypes from 'prop-types'; import { Table, Alert } from 'react-bootstrap'; import Card from './card'; import Loader from '../ui/loader'; const ProfileCards = (props) => { const renderCards = (cards) => { if (cards)
return []; }; const renderMessage = () => { const { message } = props; return (message && message.type === 'card') && ( <div> <Alert bsStyle={message.status === 'success' ? 'success' : 'error'} onDismiss={() => { props.clearMessage(); }} > <p>{ m...
{ return Object.keys(cards).map(key => ( <Card card={cards[key]} key={cards[key].id} deleteCard={props.deleteCard} setCardDefault={props.setCardDefault} /> ) ); }
conditional_block
cards.js
import React from 'react'; import PropTypes from 'prop-types'; import { Table, Alert } from 'react-bootstrap'; import Card from './card'; import Loader from '../ui/loader'; const ProfileCards = (props) => { const renderCards = (cards) => { if (cards) { return Object.keys(cards).map(key => ( ...
); } return []; }; const renderMessage = () => { const { message } = props; return (message && message.type === 'card') && ( <div> <Alert bsStyle={message.status === 'success' ? 'success' : 'error'} onDismiss={() => { props.clearMessage(); }} > ...
/> )
random_line_split