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 |
|---|---|---|---|---|
filters.tsx | import * as React from 'react';
import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/';
import { defaultColumns, partyList, sampledata } from './shared';
// //if coming in from DTO
// const availDTO = [
// { fieldName: 'number... | onst data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' }));
//const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName);
//availableFiltersMap.number.operations.gt.displayN... | // tslint:disable-next-line:no-bitwise
targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (str.length >= targetLength) {
return String(str);
} else {
targetLength = targetLengt... | identifier_body |
dscNodeReportListResult.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | () {
super();
}
/**
* Defines the metadata of DscNodeReportListResult
*
* @returns {object} metadata of DscNodeReportListResult
*
*/
mapper() {
return {
required: false,
serializedName: 'DscNodeReportListResult',
type: {
name: 'Composite',
className: 'DscN... | constructor | identifier_name |
dscNodeReportListResult.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... |
/**
* Defines the metadata of DscNodeReportListResult
*
* @returns {object} metadata of DscNodeReportListResult
*
*/
mapper() {
return {
required: false,
serializedName: 'DscNodeReportListResult',
type: {
name: 'Composite',
className: 'DscNodeReportListResult',... | {
super();
} | identifier_body |
dscNodeReportListResult.js | * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use... | /* | random_line_split | |
cors_cache.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/. */
//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For n... | (&mut self, request: &Request, method: Method) -> bool {
self.find_entry_by_method(&request, method).is_some()
}
/// Updates max age if an entry for
/// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found.
///
/// If not, it will insert an equivalent entr... | match_method | identifier_name |
cors_cache.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/. */
//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For n... |
impl CorsCacheEntry {
fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool,
header_or_method: HeaderOrMethod) -> CorsCacheEntry {
CorsCacheEntry {
origin: origin,
url: url,
max_age: max_age,
credentials: credentials,
h... | pub max_age: u32,
pub credentials: bool,
pub header_or_method: HeaderOrMethod,
created: Timespec
} | random_line_split |
cors_cache.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/. */
//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For n... |
/// A simple, vector-based CORS Cache
#[derive(Clone)]
pub struct CorsCache(Vec<CorsCacheEntry>);
impl CorsCache {
pub fn new() -> CorsCache {
CorsCache(vec![])
}
fn find_entry_by_header<'a>(&'a mut self, request: &Request,
header_name: &str) -> Option<&'a mut Cor... | {
cors_cache.origin == cors_req.origin &&
cors_cache.url == cors_req.current_url() &&
(cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include)
} | identifier_body |
index.js | import React, { PropTypes as T } from 'react';
import ReactModal2 from 'react-modal2';
export default class Modal extends React.Component {
static propTypes = {
children: T.node,
onClose: T.func.isRequired,
closeOnEsc: T.bool,
closeOnBackdropClick: T.bool,
};
static defaultProps = {
closeOnEsc: true,
... |
}
render() {
const {
onClose,
closeOnEsc,
closeOnBackdropClick,
children,
} = this.props;
return (
<ReactModal2
onClose={onClose}
closeOnEsc={closeOnEsc}
closeOnBackdropClick={closeOnBackdropClick}
backdropClassName="Modal"
modalClassName="Modal-content"
>
<div clas... | {
onClose();
} | conditional_block |
index.js | import React, { PropTypes as T } from 'react';
import ReactModal2 from 'react-modal2';
export default class Modal extends React.Component {
static propTypes = {
children: T.node,
onClose: T.func.isRequired,
closeOnEsc: T.bool,
closeOnBackdropClick: T.bool,
};
static defaultProps = {
closeOnEsc: true,
... | () {
const { onClose, closeOnBackdropClick } = this.props;
if (closeOnBackdropClick) {
onClose();
}
}
render() {
const {
onClose,
closeOnEsc,
closeOnBackdropClick,
children,
} = this.props;
return (
<ReactModal2
onClose={onClose}
closeOnEsc={closeOnEsc}
closeOnBackdropClic... | handleBackdropClick | identifier_name |
index.js | import React, { PropTypes as T } from 'react';
import ReactModal2 from 'react-modal2';
export default class Modal extends React.Component {
static propTypes = {
children: T.node,
onClose: T.func.isRequired,
closeOnEsc: T.bool,
closeOnBackdropClick: T.bool,
};
static defaultProps = {
closeOnEsc: true,
... |
render() {
const {
onClose,
closeOnEsc,
closeOnBackdropClick,
children,
} = this.props;
return (
<ReactModal2
onClose={onClose}
closeOnEsc={closeOnEsc}
closeOnBackdropClick={closeOnBackdropClick}
backdropClassName="Modal"
modalClassName="Modal-content"
>
<div classNa... | {
const { onClose, closeOnBackdropClick } = this.props;
if (closeOnBackdropClick) {
onClose();
}
} | identifier_body |
index.js | import React, { PropTypes as T } from 'react';
import ReactModal2 from 'react-modal2';
export default class Modal extends React.Component {
static propTypes = {
children: T.node,
onClose: T.func.isRequired,
closeOnEsc: T.bool,
closeOnBackdropClick: T.bool,
};
static defaultProps = {
closeOnEsc: true,
... | <ReactModal2
onClose={onClose}
closeOnEsc={closeOnEsc}
closeOnBackdropClick={closeOnBackdropClick}
backdropClassName="Modal"
modalClassName="Modal-content"
>
<div className="Modal-close" onClick={this.handleBackdropClick}>
{children}
</div>
</ReactModal2>
);
}
} | closeOnBackdropClick,
children,
} = this.props;
return ( | random_line_split |
kd_tree_edges_mk2.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | ():
bpy.utils.register_class(SvKDTreeEdgesNodeMK2)
def unregister():
bpy.utils.unregister_class(SvKDTreeEdgesNodeMK2)
| register | identifier_name |
kd_tree_edges_mk2.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | name='maxNum', description='max edge count',
default=4, min=1, update=updateNode)
skip = IntProperty(
name='skip', description='skip first n',
default=0, min=0, update=updateNode)
def sv_init(self, context):
self.inputs.new('VerticesSocket', 'Verts')
self.inputs... | name='maxdist', description='Maximum dist', min=0.0,
default=2.0, update=updateNode)
maxNum = IntProperty( | random_line_split |
kd_tree_edges_mk2.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
if (dist <= abs(mindist)) or (i == index):
continue
edge = tuple(sorted([i, index]))
if not edge in e:
e.add(edge)
num_edges += 1
if num_edges == maxNum:
break
se... | continue | conditional_block |
kd_tree_edges_mk2.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | def sv_init(self, context):
self.inputs.new('VerticesSocket', 'Verts')
self.inputs.new('StringsSocket', 'mindist').prop_name = 'mindist'
self.inputs.new('StringsSocket', 'maxdist').prop_name = 'maxdist'
self.inputs.new('StringsSocket', 'maxNum').prop_name = 'maxNum'
self.inpu... | bl_idname = 'SvKDTreeEdgesNodeMK2'
bl_label = 'KDT Closest Edges MK2'
bl_icon = 'OUTLINER_OB_EMPTY'
mindist = FloatProperty(
name='mindist', description='Minimum dist', min=0.0,
default=0.1, update=updateNode)
maxdist = FloatProperty(
name='maxdist', description='Maximum dist',... | identifier_body |
ContactCanvas.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at>
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Matplotlib
try:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as Navig... | (self, parent=None):
super(ContactCanvas, self).__init__(parent)
self.setText(self.tr("Matplotlib not found - Please install it."))
| __init__ | identifier_name |
ContactCanvas.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at>
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Matplotlib
try:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as Navig... |
if USE_MATPLOTLIB:
class ContactCanvas(FigureCanvas):
def __init__(self, parent=None, width = 10, height = 3, dpi = 100, sharex = None, sharey = None):
self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
self.ax = self.fig.add_subplot(11... | USE_MATPLOTLIB= True | conditional_block |
ContactCanvas.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at>
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Matplotlib
try:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as Navig... | def __init__(self, parent=None):
super(ContactCanvas, self).__init__(parent)
self.setText(self.tr("Matplotlib not found - Please install it.")) | identifier_body | |
ContactCanvas.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at>
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Matplotlib
try:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as Navig... | class ContactCanvas(QLabel):
def __init__(self, parent=None):
super(ContactCanvas, self).__init__(parent)
self.setText(self.tr("Matplotlib not found - Please install it.")) | random_line_split | |
cross-global-eval-is-indirect.js | // |reftest| skip-if(!xulRuntime.shell) -- needs newGlobal()
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
//-----------------------------------------------------------------------------
var BUGNUMBER = 608473;
var summary =
'|var eval = otherWindow.e... | **************/
var originalEval = eval;
var res;
function f()
{
return [this, eval("this")];
}
var otherGlobalSameCompartment = newGlobal("same-compartment");
eval = otherGlobalSameCompartment.eval;
res = new f();
assertEq(res[0] !== res[1], true);
assertEq(res[0] !== this, true);
assertEq(res[0] instanceof f, ... | * BEGIN TEST * | random_line_split |
cross-global-eval-is-indirect.js | // |reftest| skip-if(!xulRuntime.shell) -- needs newGlobal()
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
//-----------------------------------------------------------------------------
var BUGNUMBER = 608473;
var summary =
'|var eval = otherWindow.e... | ()
{
return [this, eval("this")];
}
var otherGlobalSameCompartment = newGlobal("same-compartment");
eval = otherGlobalSameCompartment.eval;
res = new f();
assertEq(res[0] !== res[1], true);
assertEq(res[0] !== this, true);
assertEq(res[0] instanceof f, true);
assertEq(res[1], otherGlobalSameCompartment);
res = f()... | f | identifier_name |
cross-global-eval-is-indirect.js | // |reftest| skip-if(!xulRuntime.shell) -- needs newGlobal()
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
//-----------------------------------------------------------------------------
var BUGNUMBER = 608473;
var summary =
'|var eval = otherWindow.e... |
var otherGlobalSameCompartment = newGlobal("same-compartment");
eval = otherGlobalSameCompartment.eval;
res = new f();
assertEq(res[0] !== res[1], true);
assertEq(res[0] !== this, true);
assertEq(res[0] instanceof f, true);
assertEq(res[1], otherGlobalSameCompartment);
res = f();
assertEq(res[0] !== res[1], true);
... | {
return [this, eval("this")];
} | identifier_body |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs:... |
};
let sandbox_fn = master_cfg.parent().unwrap()
.join(&master.sandboxes_dir)
.join(&(sandbox_name.clone() + ".yaml"));
let sandbox: SandboxConfig = match parse_config(&sandbox_fn,
&SandboxConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
... | {
return Err(format!("Can't parse master config: {}", e));
} | conditional_block |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs:... | pid_file.display());
}
};
return Ok(());
}
fn main() {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_... | }
None => {
warn!("Can't read pid file {}. Probably daemon is not running.", | random_line_split |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs:... | "Verbose configuration");
ap.refer(&mut sandbox_name)
.add_argument("sandbox", Parse,
"Name of the sandbox which configuration will be switched for")
.required()
.metavar("NAME");
ap.refer(&mut config_file)
.add_argument("new_config", Parse... | {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
let m... | identifier_body |
lithos_switch.rs | extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs:... | () {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
le... | main | identifier_name |
tests.py | import datetime
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase, skipIfDBFeature
from django.utils import tzinfo
from models import Donut, RumBaba
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
... |
@skipIfDBFeature('supports_timezones')
def test_error_on_timezone(self):
"""Regression test for #8354: the MySQL and Oracle backends should raise
an error if given a timezone-aware datetime object."""
dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0))
d =... | """Regression test for #10238: TextField values returned from the
database should be unicode."""
d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding')
newd = Donut.objects.get(id=d.id)
self.assert_(isinstance(newd.review, unicode)) | identifier_body |
tests.py | import datetime
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase, skipIfDBFeature
from django.utils import tzinfo
from models import Donut, RumBaba
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
... | (self):
"""Year boundary tests (ticket #3689)"""
d = Donut.objects.create(name='Date Test 2007',
baked_date=datetime.datetime(year=2007, month=12, day=31),
consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59))
d1 = Donut.objects.crea... | test_year_boundaries | identifier_name |
tests.py | import datetime
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase, skipIfDBFeature
from django.utils import tzinfo
from models import Donut, RumBaba
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
... | d2 = Donut.objects.get(name='Apple Fritter')
self.assertFalse(d2.is_frosted)
self.assertTrue(d2.has_sprinkles)
def test_date_type(self):
d = Donut(name='Apple Fritter')
d.baked_date = datetime.date(year=1938, month=6, day=4)
d.baked_time = datetime.time(hour=5, minut... | self.assertTrue(d.has_sprinkles)
d.save()
| random_line_split |
fs.rs | if start < self.i {
let ret = DirEntry {
name: self.data[start .. i].to_owned().into_boxed_slice(),
root: self.root.clone()
};
if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
return Some(Ok(ret))
... | syscall::O_CLOEXEC | syscall::O_STAT | syscall::O_NOFOLLOW))?; | random_line_split | |
fs.rs | {
tv_sec: self.stat.st_atime as i64,
tv_nsec: self.stat.st_atime_nsec as i32,
}))
}
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_ctime as i64,
tv_nsec: self.stat.st_ctime_nsec as i... |
pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
pub fn create(&mut self, create: bool) { self.create = create; }
pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
pub f... | { self.append = append; } | identifier_body |
fs.rs | {
tv_sec: self.stat.st_atime as i64,
tv_nsec: self.stat.st_atime_nsec as i32,
}))
}
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(syscall::TimeSpec {
tv_sec: self.stat.st_ctime as i64,
tv_nsec: self.stat.st_ctime_nsec as i... | (&self) -> io::Result<File> {
self.0.duplicate().map(File)
}
pub fn dup(&self, buf: &[u8]) -> io::Result<File> {
let fd = cvt(syscall::dup(*self.fd().as_inner() as usize, buf))?;
Ok(File(FileDesc::new(fd)))
}
pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()... | duplicate | identifier_name |
event_event.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.addons.http_routing.models.ir_http import slug
class EventEvent(models.Model):
_inherit = "event.event"
community_menu = fields.Boolean(
"Community Men... | (self):
""" See website_event_track._get_track_menu_entries() """
self.ensure_one()
return [(_('Talk Proposals'), '/event/%s/track_proposal' % slug(self), False, 15, 'track_proposal')]
| _get_track_proposal_menu_entries | identifier_name |
event_event.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.addons.http_routing.models.ir_http import slug
class EventEvent(models.Model):
_inherit = "event.event"
community_menu = fields.Boolean(
"Community Men... |
def _get_community_menu_entries(self):
self.ensure_one()
return [(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community')]
def _get_track_menu_entries(self):
""" Remove agenda as this is now managed separately """
self.ensure_one()
return [
... | res = super(EventEvent, self)._get_menu_type_field_matching()
res['community'] = 'community_menu'
return res | random_line_split |
event_event.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.addons.http_routing.models.ir_http import slug
class EventEvent(models.Model):
_inherit = "event.event"
community_menu = fields.Boolean(
"Community Men... |
# ------------------------------------------------------------
# WEBSITE MENU MANAGEMENT
# ------------------------------------------------------------
# OVERRIDES: ADD SEQUENCE
def _get_menu_update_fields(self):
update_fields = super(EventEvent, self)._get_menu_update_fields()
u... | if event.event_type_id and event.event_type_id != event._origin.event_type_id:
event.community_menu = event.event_type_id.community_menu
elif event.website_menu and event.website_menu != event._origin.website_menu or not event.community_menu:
event.community_menu = True
... | conditional_block |
event_event.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.addons.http_routing.models.ir_http import slug
class EventEvent(models.Model):
_inherit = "event.event"
community_menu = fields.Boolean(
"Community Men... |
def _get_community_menu_entries(self):
self.ensure_one()
return [(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community')]
def _get_track_menu_entries(self):
""" Remove agenda as this is now managed separately """
self.ensure_one()
return [
... | res = super(EventEvent, self)._get_menu_type_field_matching()
res['community'] = 'community_menu'
return res | identifier_body |
login.component.ts | import { FormBuilder } from '@angular/forms';
import { Http } from '@angular/http';
import { FormGroup } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { SecurityService } from 'app/security.service';
@Component({
selector: 'cf-login',
template: `
<form [formGroup]="loginForm"... |
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: '',
password: ''
});
}
onRegister() {
const credentials = this.loginForm.value;
this.security
.registerUser(credentials)
}
onLogIn() {
const credentials = this.loginForm.value;
this.security
.logIn... | { } | identifier_body |
login.component.ts | import { FormBuilder } from '@angular/forms';
import { Http } from '@angular/http';
import { FormGroup } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { SecurityService } from 'app/security.service';
@Component({
selector: 'cf-login',
template: `
<form [formGroup]="loginForm"... | () {
this.loginForm = this.formBuilder.group({
email: '',
password: ''
});
}
onRegister() {
const credentials = this.loginForm.value;
this.security
.registerUser(credentials)
}
onLogIn() {
const credentials = this.loginForm.value;
this.security
.logInUser(credent... | ngOnInit | identifier_name |
login.component.ts | import { FormBuilder } from '@angular/forms';
import { Http } from '@angular/http';
import { FormGroup } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { SecurityService } from 'app/security.service';
@Component({
selector: 'cf-login',
template: `
<form [formGroup]="loginForm"... | </form>
`,
styles: []
})
export class LoginComponent implements OnInit {
public loginForm: FormGroup
constructor(public security: SecurityService, public formBuilder: FormBuilder) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: '',
password: ''
});
}
onRegister... | <button (click)="onRegister()"
[disabled]="loginForm.invalid">Register</button>
<button (click)="onLogIn()"
[disabled]="loginForm.invalid">Log In</button> | random_line_split |
mkfifo.rs | #![crate_name = "uu_mkfifo"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
#[macro_use]
ext... | (args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.p... | uumain | identifier_name |
mkfifo.rs | #![crate_name = "uu_mkfifo"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
#[macro_use]
ext... | Usage:
{0} [OPTIONS] NAME...
Create a FIFO with the given name.", NAME, VERSION);
print!("{}", opts.usage(&msg));
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match matches.opt_str("m") {
Some(m) => match usize::from_str_radix(&m, 8) {
... | {
let mut opts = getopts::Options::new();
opts.optopt("m", "mode", "file permissions for the fifo", "(default 0666)");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
... | identifier_body |
mkfifo.rs | #![crate_name = "uu_mkfifo"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
#[macro_use]
ext... |
let mode = match matches.opt_str("m") {
Some(m) => match usize::from_str_radix(&m, 8) {
Ok(m) => m,
Err(e)=> {
show_error!("invalid mode: {}", e);
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for ... | {
let msg = format!("{0} {1}
Usage:
{0} [OPTIONS] NAME...
Create a FIFO with the given name.", NAME, VERSION);
print!("{}", opts.usage(&msg));
if matches.free.is_empty() {
return 1;
}
return 0;
} | conditional_block |
terraindisplay.py | """Module for displaying Terrain, both in 2D and 3D.
(Not accessible outside of package; use display methods of Terrain instead.)
"""
from Tkinter import Tk, Canvas, Frame, BOTH
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
class Terrain2D(Frame):
"""2D graphical re... | (cls, terrain):
"""Display a Terrain in 2D.
Args:
terrain (Terrain): Terrain to display.
"""
root = Tk()
dimensions = "{0}x{1}".format(terrain.width * Terrain2D.SQUARE_SIDE,
terrain.length * Terrain2D.SQUARE_SIDE)
root.g... | display_terrain | identifier_name |
terraindisplay.py | """Module for displaying Terrain, both in 2D and 3D.
(Not accessible outside of package; use display methods of Terrain instead.)
"""
from Tkinter import Tk, Canvas, Frame, BOTH
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
class Terrain2D(Frame):
"""2D graphical re... | def __init__(self, terrain):
self.terrain = terrain
self.x_grid, self.y_grid = np.meshgrid(range(self.terrain.width),
range(self.terrain.length))
z_vals = np.array([self.terrain[x, y] for x, y in zip(np.ravel(self.x_grid), np.ravel(self.y_grid))... | random_line_split | |
terraindisplay.py | """Module for displaying Terrain, both in 2D and 3D.
(Not accessible outside of package; use display methods of Terrain instead.)
"""
from Tkinter import Tk, Canvas, Frame, BOTH
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
class Terrain2D(Frame):
"""2D graphical re... |
def display_terrain(self):
"""Display 3D surface of terrain."""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(self.x_grid, self.y_grid, self.z_grid)
ax.set_zlim(0.0, 1.0)
plt.show()
| self.terrain = terrain
self.x_grid, self.y_grid = np.meshgrid(range(self.terrain.width),
range(self.terrain.length))
z_vals = np.array([self.terrain[x, y] for x, y in zip(np.ravel(self.x_grid), np.ravel(self.y_grid))])
self.z_grid = z_vals.reshape(s... | identifier_body |
terraindisplay.py | """Module for displaying Terrain, both in 2D and 3D.
(Not accessible outside of package; use display methods of Terrain instead.)
"""
from Tkinter import Tk, Canvas, Frame, BOTH
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
class Terrain2D(Frame):
"""2D graphical re... |
canvas.pack(fill=BOTH, expand=1)
class Terrain3D(object):
"""A 3D representation of a Terrain.
Consists of a 3D surface mesh, shown at an angle. Can be seen at different angles.
Uses matplotlib.mplot3d to display rudimentary 3D version of terrain.
Notes:
Is somewhat guaranteed to be... | x_pos = x * Terrain2D.SQUARE_SIDE
y_pos = y * Terrain2D.SQUARE_SIDE
color = int(self.terrain[x, y] * 15)
hex_color = "#" + "0123456789abcdef"[color] * 3
canvas.create_rectangle(x_pos, y_pos,
x_pos + Terrain2D.SQUARE_... | conditional_block |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets ... | )
}
}
| {
f(i)
} | conditional_block |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets ... |
/// Call closure for each available choice.
#[inline(always)]
pub fn with_choices(&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Cal... | random_line_split | |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets ... |
/// Call closure for each available choice.
#[inline(always)]
pub fn with_choices(&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Ca... | {
BinNode {
state: pairs.iter().map(|&(a, _)| a).collect(),
choices: pairs.iter().map(|&(_, b)| b).collect()
}
} | identifier_body |
binnode.rs | use std::collections::Bitv;
use BinGraph;
/// Contains a binary state and the choices.
#[deriving(PartialEq, Eq, Show, Clone)]
pub struct BinNode {
/// The state composed of bits.
pub state: Bitv,
/// The choices represented as bits that can be flipped.
pub choices: Bitv
}
impl BinNode {
/// Gets ... | (&self, f: |i: uint|) {
for i in range(0, self.choices.len())
.zip(self.choices.iter())
.filter(|&(_, v)| v)
.map(|(i, _)| i
) {
f(i)
}
}
/// Calls closure for all choices that are not in graph.
#[inline(always)]
pub fn with_choice... | with_choices | identifier_name |
[postID].tsx | import { css } from "@emotion/react";
import styled from "@emotion/styled";
import { GetStaticPaths, GetStaticProps } from "next";
import { IMDXSource } from "next-mdx-remote";
import hydrate from "next-mdx-remote/hydrate";
import renderToString from "next-mdx-remote/render-to-string";
import Head from "next/head";
imp... |
const mdxSource = await renderToString(post.content, {
components: mdxComponents,
mdxOptions: {
remarkPlugins: [remarkMath],
rehypePlugins: [rehypeKatex],
},
});
return { props: { source: mdxSource, post } };
};
export default Post;
| {
return {
redirect: {
permanent: true,
destination: post.path,
},
};
} | conditional_block |
[postID].tsx | import { css } from "@emotion/react";
import styled from "@emotion/styled";
import { GetStaticPaths, GetStaticProps } from "next";
import { IMDXSource } from "next-mdx-remote";
import hydrate from "next-mdx-remote/hydrate";
import renderToString from "next-mdx-remote/render-to-string";
import Head from "next/head";
imp... | </>
) : (
// If no banner is present, still display a card
<meta name="twitter:card" content="summary" />
)}
</Head>
<h1
css={css`
margin-bottom: 30px;
${mobileOnly(css`
text-align: center;
`)}
`}
>... | <meta property="og:image:url" content={post.banner.src} />
<meta property="twitter:image" content={post.banner.src} />
<meta property="twitter:image:alt" content={post.banner.alt} />
<meta property="twitter:card" content="summary_large_image" /> | random_line_split |
Shop.js | import React from 'react'
import { moneyFormat } from '../../../modules/helpers'
import './shop.scss'
import { Link } from 'react-router'
const Product = ({id, price, name, description, onAddToCart}) => (
<div className="product-box">
<h3>{name}</h3>
<p>{description}</p>
<section className="bottom">
... | )
export default class Shop extends React.Component{
constructor(props){
super(props);
props.getProducts();
props.getUsers();
}
componentDidUpdate(){
if(this.props.state.shop.displayNotice){
setTimeout(
() => this.props.destroyNoticeMsg(),
3500
)
}
}
selectUs... | random_line_split | |
Shop.js | import React from 'react'
import { moneyFormat } from '../../../modules/helpers'
import './shop.scss'
import { Link } from 'react-router'
const Product = ({id, price, name, description, onAddToCart}) => (
<div className="product-box">
<h3>{name}</h3>
<p>{description}</p>
<section className="bottom">
... |
}
render(){
const {products, users, displayNotice, noticeMsg} = this.props.state.shop;
// console.log(this.props.state.shop);
return (
<div className="shop">
{users && (
<div className="test-user-select">
Test As:
<select value={this.props.state.shop.us... | {
if(users[i].id === e.target.value){
this.props.setActiveUser(users[i])
break
}
} | conditional_block |
Shop.js | import React from 'react'
import { moneyFormat } from '../../../modules/helpers'
import './shop.scss'
import { Link } from 'react-router'
const Product = ({id, price, name, description, onAddToCart}) => (
<div className="product-box">
<h3>{name}</h3>
<p>{description}</p>
<section className="bottom">
... | <Link to="/checkout" className="checkout-btn">Checkout Now</Link>
</div>
<div className="products-wrapper center-block">
{products && products.map((p) => (
<Product key={p.id} {...p} onAddToCart={ this.props.addToCart }/>
))}
</div>
</div>
);
... | {
const {products, users, displayNotice, noticeMsg} = this.props.state.shop;
// console.log(this.props.state.shop);
return (
<div className="shop">
{users && (
<div className="test-user-select">
Test As:
<select value={this.props.state.shop.user.id} onChange=... | identifier_body |
Shop.js | import React from 'react'
import { moneyFormat } from '../../../modules/helpers'
import './shop.scss'
import { Link } from 'react-router'
const Product = ({id, price, name, description, onAddToCart}) => (
<div className="product-box">
<h3>{name}</h3>
<p>{description}</p>
<section className="bottom">
... | (props){
super(props);
props.getProducts();
props.getUsers();
}
componentDidUpdate(){
if(this.props.state.shop.displayNotice){
setTimeout(
() => this.props.destroyNoticeMsg(),
3500
)
}
}
selectUser = (e) => {
const { users } = this.props.state.shop;
for... | constructor | identifier_name |
node_void_ptr.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/. */
//! CSS library requires that DOM nodes be convertable to *c_void through this trait
extern mod netsurfcss;
use d... | (node: *libc::c_void) -> AbstractNode {
assert!(node.is_not_null());
unsafe {
cast::transmute(node)
}
}
fn to_void_ptr(&self) -> *libc::c_void {
unsafe {
cast::transmute(*self)
}
}
}
| from_void_ptr | identifier_name |
node_void_ptr.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/. */
//! CSS library requires that DOM nodes be convertable to *c_void through this trait
extern mod netsurfcss;
use d... |
}
| {
unsafe {
cast::transmute(*self)
}
} | identifier_body |
node_void_ptr.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/. */
//! CSS library requires that DOM nodes be convertable to *c_void through this trait
extern mod netsurfcss;
use d... | fn from_void_ptr(node: *libc::c_void) -> AbstractNode {
assert!(node.is_not_null());
unsafe {
cast::transmute(node)
}
}
fn to_void_ptr(&self) -> *libc::c_void {
unsafe {
cast::transmute(*self)
}
}
} |
impl VoidPtrLike for AbstractNode { | random_line_split |
lmmsg.rs | // Copyright © 2015-2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied,... | pub type LPMSG_INFO_1 = *mut MSG_INFO_1;
pub const MSGNAME_NOT_FORWARDED: DWORD = 0;
pub const MSGNAME_FORWARDED_TO: DWORD = 0x04;
pub const MSGNAME_FORWARDED_FROM: DWORD = 0x10; | }}
pub type PMSG_INFO_1 = *mut MSG_INFO_1; | random_line_split |
my-children-controller.js | /* global _, angular */
'use strict';
function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) {
$scope.parentProfileData = ownProfile.data;
$scope.tabs = [];
function loadChildrenTabs () {
$scope.tabs = [];
cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, fun... |
}
});
}
angular.module('cpZenPlatform')
.controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
| {
loadChildrenTabs();
} | conditional_block |
my-children-controller.js | /* global _, angular */
'use strict';
function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) {
$scope.parentProfileData = ownProfile.data;
$scope.tabs = [];
function | () {
$scope.tabs = [];
cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) {
$scope.children = _.sortBy(children, [
function (child) {
return child.name.toLowerCase();
}
]);
$scope.tabs = $scope.children.map(function (child) {
... | loadChildrenTabs | identifier_name |
my-children-controller.js | /* global _, angular */
'use strict';
function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) {
$scope.parentProfileData = ownProfile.data;
$scope.tabs = [];
function loadChildrenTabs () | state: 'my-children.add',
tabImage: '/img/avatars/avatar.png',
tabTitle: $translate.instant('Add Child')
});
});
}
loadChildrenTabs();
$scope.$on('$stateChangeStart', function (e, toState, params) {
if (toState.name === 'my-children.child') {
var childLoaded = _.some... | {
$scope.tabs = [];
cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) {
$scope.children = _.sortBy(children, [
function (child) {
return child.name.toLowerCase();
}
]);
$scope.tabs = $scope.children.map(function (child) {
... | identifier_body |
my-children-controller.js | /* global _, angular */
'use strict';
function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) {
$scope.parentProfileData = ownProfile.data;
$scope.tabs = [];
function loadChildrenTabs () {
$scope.tabs = [];
cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, fun... | if (!childLoaded) {
loadChildrenTabs();
}
}
});
}
angular.module('cpZenPlatform')
.controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]); | return child.userId === params.id;
}); | random_line_split |
qr_scanner.py | from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', )
def on_symbols(self, instance, value):
instance.stop()
sel... | #separator_height: '1.2dp'
#title_color: .437, .437, .437, 1
#background: 'atlas://electrum/gui/kivy/theming/light/dialog'
on_activate:
qrscr.start()
qrscr.size = self.size
on_deactivate: qrscr.stop()
QRScanner:
id: qrscr
on_symbols: root.on_symbols(*args)
''') | random_line_split | |
qr_scanner.py | from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
__events__ = ('on_complete', )
def | (self, instance, value):
instance.stop()
self.dismiss()
data = value[0].data
self.dispatch('on_complete', data)
def on_complete(self, x):
''' Default Handler for on_complete event.
'''
print(x)
Builder.load_string('''
<QrScannerDialog>
title:
_(... | on_symbols | identifier_name |
qr_scanner.py | from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner')
class QrScannerDialog(Factory.AnimatedPopup):
|
Builder.load_string('''
<QrScannerDialog>
title:
_(\
'[size=18dp]Hold your QRCode up to the camera[/size][size=7dp]\\n[/size]')
title_size: '24sp'
border: 7, 7, 7, 7
size_hint: None, None
size: '340dp', '290dp'
pos_hint: {'center_y': .53}
#separator_color: .89, .89, .89, 1... | __events__ = ('on_complete', )
def on_symbols(self, instance, value):
instance.stop()
self.dismiss()
data = value[0].data
self.dispatch('on_complete', data)
def on_complete(self, x):
''' Default Handler for on_complete event.
'''
print(x) | identifier_body |
test_events.py | """This module tests events that are invoked by Cloud/Infra VMs."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.gce import GCEProvider
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provi... |
Polarion:
assignee: jdupuy
casecomponent: Events
caseimportance: high
initialEstimate: 1/8h
"""
action = appliance.collections.actions.create(
fauxfactory.gen_alpha(),
"Tag",
dict(tag=("My Company Tags", "Environment", "Development")))
request.add... | * Assert the tag appears.
Metadata:
test_flag: provision, events | random_line_split |
test_events.py | """This module tests events that are invoked by Cloud/Infra VMs."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.gce import GCEProvider
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provi... |
wait_for(_check, num_sec=300, delay=15, message="tags to appear")
| return any(tag.category.display_name == "Environment" and tag.display_name == "Development"
for tag in vm_crud.get_tags()) | identifier_body |
test_events.py | """This module tests events that are invoked by Cloud/Infra VMs."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.gce import GCEProvider
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provi... | ():
return any(tag.category.display_name == "Environment" and tag.display_name == "Development"
for tag in vm_crud.get_tags())
wait_for(_check, num_sec=300, delay=15, message="tags to appear")
| _check | identifier_name |
util.js | //@ sourceMappingURL=util.map
// Generated by CoffeeScript 1.6.1
var Util, semver;
semver = require('semver');
Util = (function() {
function Util() {}
Util.convertObjectKeysToUnderscores = function(obj) {
var item, key, newKey, newObj, value;
newObj = {};
for (key in obj) {
value = obj[key];
... | newArray = [];
for (key in obj) {
value = obj[key];
if (key !== '@') {
if (value instanceof Array) {
for (_i = 0, _len = value.length; _i < _len; _i++) {
item = value[_i];
newArray.push(this.convertNodeToObject(item));
... | var item, key, newArray, newObj, value, _i, _j, _len, _len1, _results;
if (typeof obj === 'object' && obj['@']) {
if (obj['@'].type === 'array') { | random_line_split |
util.js | //@ sourceMappingURL=util.map
// Generated by CoffeeScript 1.6.1
var Util, semver;
semver = require('semver');
Util = (function() {
function Util() {}
Util.convertObjectKeysToUnderscores = function(obj) {
var item, key, newKey, newObj, value;
newObj = {};
for (key in obj) {
value = obj[key];
... | else if (obj['@'].type === 'boolean') {
return obj['#'] === 'true';
} else {
return obj['#'];
}
} else if (obj instanceof Array) {
_results = [];
for (_j = 0, _len1 = obj.length; _j < _len1; _j++) {
item = obj[_j];
_results.push(this.convertNodeToObject(item)... | {
return parseInt(obj['#']);
} | conditional_block |
util.js | //@ sourceMappingURL=util.map
// Generated by CoffeeScript 1.6.1
var Util, semver;
semver = require('semver');
Util = (function() {
function | () {}
Util.convertObjectKeysToUnderscores = function(obj) {
var item, key, newKey, newObj, value;
newObj = {};
for (key in obj) {
value = obj[key];
newKey = Util.toUnderscore(key);
if (value instanceof Array) {
newObj[newKey] = (function() {
var _i, _len, _results;
... | Util | identifier_name |
util.js | //@ sourceMappingURL=util.map
// Generated by CoffeeScript 1.6.1
var Util, semver;
semver = require('semver');
Util = (function() {
function Util() |
Util.convertObjectKeysToUnderscores = function(obj) {
var item, key, newKey, newObj, value;
newObj = {};
for (key in obj) {
value = obj[key];
newKey = Util.toUnderscore(key);
if (value instanceof Array) {
newObj[newKey] = (function() {
var _i, _len, _results;
... | {} | identifier_body |
reseeding.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 ... |
/// Reseed the internal RNG if the number of bytes that have been
/// generated exceed the threshold.
pub fn reseed_if_necessary(&mut self) {
if self.bytes_generated >= self.generation_threshold {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
}
... | {
ReseedingRng {
rng: rng,
generation_threshold: generation_threshold,
bytes_generated: 0,
reseeder: reseeder
}
} | identifier_body |
reseeding.rs | // 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.
//! A wrapper aroun... | // 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.
// | random_line_split | |
reseeding.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<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
fn next_u32(&mut self) -> u32 {
self.reseed_if_necessary();
self.bytes_generated += 4;
self.rng.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.reseed_if_necessary();
self.bytes_generated +=... | {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
} | conditional_block |
reseeding.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 ... | <R, Rsdr> {
rng: R,
generation_threshold: usize,
bytes_generated: usize,
/// Controls the behaviour when reseeding the RNG.
pub reseeder: Rsdr,
}
impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
/// Create a new `ReseedingRng` with the given parameters.
///
/// # Arguments
//... | ReseedingRng | identifier_name |
error.rs | use std::error::Error as StdError;
use std::string;
use std::{fmt, io};
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhilePars... | (&self) -> &str { "encoder error" }
}
impl fmt::Display for EncoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<fmt::Error> for EncoderError {
fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
}
| description | identifier_name |
error.rs | use std::error::Error as StdError;
use std::string;
use std::{fmt, io};
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhilePars... | NotUtf8,
}
#[derive(Debug)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::Error),
}
impl PartialEq for ParserError {
fn eq(&self, other: &ParserError) -> bool {
match (self, other) {
(&ParserError::SyntaxError(msg0, line0, col0), &P... | UnexpectedEndOfHexEscape,
UnrecognizedHex,
NotFourDigit,
ControlCharacterInString, | random_line_split |
error.rs | use std::error::Error as StdError;
use std::string;
use std::{fmt, io};
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhilePars... | }
}
#[derive(PartialEq, Debug)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
MissingFieldError(string::String),
UnknownVariantError(string::String),
ApplicationError(string::String),
EOF,
}
#[derive(Copy, Debug)]
pub enum EncoderError {
... | {
match error {
ErrorCode::InvalidSyntax => "invalid syntax",
ErrorCode::InvalidNumber => "invalid number",
ErrorCode::EOFWhileParsingObject => "EOF While parsing object",
ErrorCode::EOFWhileParsingArray => "EOF While parsing array",
ErrorCode::EOFWhileParsingValue => "EOF Wh... | identifier_body |
traits.rs | // Copyright (C) 2017-2020 Free Software Foundation, Inc.
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Thi... | {
let d = 23.5f64;
let u = 23u8;
let td = &d as &T;
let tu = &u as &T;
println!(""); // set breakpoint here
} | identifier_body | |
traits.rs | // Copyright (C) 2017-2020 Free Software Foundation, Inc.
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Thi... | } | println!(""); // set breakpoint here | random_line_split |
traits.rs | // Copyright (C) 2017-2020 Free Software Foundation, Inc.
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Thi... | () {
let d = 23.5f64;
let u = 23u8;
let td = &d as &T;
let tu = &u as &T;
println!(""); // set breakpoint here
}
| main | identifier_name |
index.js | var run_tl = new TimelineLite({
onComplete: function() {
run_tl.play(0);
},
}),
jump_tl = new TimelineLite({
paused:true,
onComplete:function() {
run_tl.play(0);
}
}),
dur = 0.125;
TweenLite.defaultEase = Linear.easeNone;
run_tl.timeScale(1.25);
run_tl.add("Step")
.add(bodyTl(), "Step")
.add(ar... | ease: Power1.easeInOut
}, "Return")
console.log("Arms TL", arms_tl.totalDuration());
return arms_tl;
}
function bodyTl() {
var body_tl = new TimelineLite();
body_tl.add(bodyBounce())
.add(bodyBounce())
console.log("Body TL", body_tl.totalDuration());
return body_tl;
}
function bodyBounce() {
var t... | {
var arms_tl = new TimelineLite();
arms_tl.add("Start")
.to(armR, dur * 3, {
x: "150",
ease: Power1.easeInOut
}, "Start")
.to(armL, dur * 2.75, {
x: "-100",
ease: Power1.easeInOut
}, "Start")
.add("Return")
.to(armR, dur * 2.5, {
x: "0",
ease: Power1.easeInOut
}, "Return")
.to(armL... | identifier_body |
index.js | var run_tl = new TimelineLite({
onComplete: function() {
run_tl.play(0);
},
}),
jump_tl = new TimelineLite({
paused:true,
onComplete:function() {
run_tl.play(0);
}
}),
dur = 0.125;
TweenLite.defaultEase = Linear.easeNone;
run_tl.timeScale(1.25);
run_tl.add("Step")
.add(bodyTl(), "Step")
.add(ar... | var tl = new TimelineLite();
tl.add("Start").set(legL, {x: "-30",y: "10"})
.to(legL, dur * 2, {
y: "-30",
rotation: "30",
transformOrigin: "50% 0"
})
.to(legL, dur, {
x: 0,
y: 0,
rotation: 0
})
.to(legL, dur, {
x: "80",
y: "10",
rotation: 0
})
.to(legL, dur * 2, {
x: "-30"... |
function legLTl() { | random_line_split |
index.js | var run_tl = new TimelineLite({
onComplete: function() {
run_tl.play(0);
},
}),
jump_tl = new TimelineLite({
paused:true,
onComplete:function() {
run_tl.play(0);
}
}),
dur = 0.125;
TweenLite.defaultEase = Linear.easeNone;
run_tl.timeScale(1.25);
run_tl.add("Step")
.add(bodyTl(), "Step")
.add(ar... |
})
// BUTTON BEHAVIOUR
var btn = document.querySelector('button');
btn.addEventListener('click', function(e) {
if(!jump_tl.isActive()) {
jump_tl.play(0);
jumpFx.play();
run_tl.pause();
}
// if (run_tl.isActive()) {
// } else {
// run_tl.play();
// }
}); | {
audio.play();
} | conditional_block |
index.js | var run_tl = new TimelineLite({
onComplete: function() {
run_tl.play(0);
},
}),
jump_tl = new TimelineLite({
paused:true,
onComplete:function() {
run_tl.play(0);
}
}),
dur = 0.125;
TweenLite.defaultEase = Linear.easeNone;
run_tl.timeScale(1.25);
run_tl.add("Step")
.add(bodyTl(), "Step")
.add(ar... | () {
var tl = new TimelineLite();
tl.add("Up")
.to(momo, dur, {
y: "-50",
ease: Power2.easeInOut
}, "Up")
.to(shadow, dur, {scale: 0.98, opacity: 0.9, transformOrigin: "50% 50%", ease: Power2.easeInOut}, "Up")
.add("Down")
.to(momo, dur, {
y: "0",
ease: Power2.easeIn
}, "Down")
.to(shadow, ... | bodyBounce | identifier_name |
create_objects.py | # -*- coding: utf-8 -*-
# Demandlib
import logging
import oemof.solph as solph
import reegis_hp.berlin_hp.electricity as electricity
import pandas as pd
import demandlib.bdew as bdew
import demandlib.particular_profiles as pprofiles
import reegis_hp.berlin_hp.prepare_data as prepare_data
def heating_systems(esyst... |
for b in dfull[h].keys():
if b.upper() in p.bdew_types:
bc = 0
if b.upper() in ['EFH', 'MFH']:
bc = 1
hd[h] += bdew.HeatBuilding(
time_index, temperature=temperature, shlp_type=b,
building_cl... | power_plants = prepare_data.chp_berlin(p)
time_index = esystem.time_idx
temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples'
temperature_file = temperature_path + '/example_data.csv'
temperature = pd.read_csv(temperature_file)['temperature']
sli = pd.Series(list(temperature.loc[:23]... | identifier_body |
create_objects.py | # -*- coding: utf-8 -*-
# Demandlib
import logging
import oemof.solph as solph
import reegis_hp.berlin_hp.electricity as electricity
import pandas as pd
import demandlib.bdew as bdew
import demandlib.particular_profiles as pprofiles
import reegis_hp.berlin_hp.prepare_data as prepare_data
def | (esystem, dfull, add_elec, p):
power_plants = prepare_data.chp_berlin(p)
time_index = esystem.time_idx
temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples'
temperature_file = temperature_path + '/example_data.csv'
temperature = pd.read_csv(temperature_file)['temperature']
sli = ... | heating_systems | identifier_name |
create_objects.py | # -*- coding: utf-8 -*-
# Demandlib
import logging
import oemof.solph as solph
import reegis_hp.berlin_hp.electricity as electricity
import pandas as pd
import demandlib.bdew as bdew
import demandlib.particular_profiles as pprofiles
import reegis_hp.berlin_hp.prepare_data as prepare_data
def heating_systems(esyst... |
heatbus[h] = solph.Bus(label=lbus)
solph.Sink(label=lsink, inputs={heatbus[h]: solph.Flow(
actual_value=hd[h].div(hd[h].max()), fixed=True,
nominal_value=hd[h].max())})
if 'district' not in h:
if lres_bus not in esystem.groups:
solph.Bus(lab... | logging.error('Demandlib typ "{0}" not found.'.format(b)) | conditional_block |
create_objects.py | # -*- coding: utf-8 -*-
# Demandlib
import logging
import oemof.solph as solph
import reegis_hp.berlin_hp.electricity as electricity
import pandas as pd
import demandlib.bdew as bdew
import demandlib.particular_profiles as pprofiles
import reegis_hp.berlin_hp.prepare_data as prepare_data
def heating_systems(esyst... | esystem.groups['bus_el']: solph.Flow(
nominal_value=power_plants[h]['power_el'][pp]),
heatbus[h]: solph.Flow(
nominal_value=power_plants[h]['power_th'][pp])},
conversion_factors={esystem.groups['b... | solph.LinearTransformer(
label='pp_chp_{0}_{1}'.format(h, pp),
inputs={esystem.groups[lres_bus]: solph.Flow()},
outputs={ | random_line_split |
test_local.py | import numpy as np
def test_prepare_abi_connectivity_maps():
from samri.fetch.local import prepare_abi_connectivity_maps
prepare_abi_connectivity_maps('Ventral_tegmental_area',
invert_lr_experiments=[
"127651139",
"127796728",
"127798146",
"127867804",
"156314762",
"160539283",
"160540751",
... |
def test_summary_atlas():
from samri.fetch.local import summary_atlas
mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv'
atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii'
summary={
1:{
'structure':'Hippocampus',
'summarize':['CA'],
'laterality':'right',
},
2:{
'str... | from samri.fetch.local import prepare_feature_map
prepare_feature_map('/usr/share/ABI-connectivity-data/Ventral_tegmental_area-127651139/',
invert_lr=True,
save_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz',
) | identifier_body |
test_local.py | import numpy as np
def test_prepare_abi_connectivity_maps():
from samri.fetch.local import prepare_abi_connectivity_maps
prepare_abi_connectivity_maps('Ventral_tegmental_area',
invert_lr_experiments=[
"127651139",
"127796728",
"127798146",
"127867804",
"156314762",
"160539283",
"160540751",
... |
mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv'
atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii'
summary={
1:{
'structure':'Hippocampus',
'summarize':['CA'],
'laterality':'right',
},
2:{
'structure':'Hippocampus',
'summarize':['CA'],
'laterality':'left',
... | save_as='/var/tmp/samri_testing/pytest/vta_127651139.nii.gz',
)
def test_summary_atlas():
from samri.fetch.local import summary_atlas | random_line_split |
test_local.py | import numpy as np
def test_prepare_abi_connectivity_maps():
from samri.fetch.local import prepare_abi_connectivity_maps
prepare_abi_connectivity_maps('Ventral_tegmental_area',
invert_lr_experiments=[
"127651139",
"127796728",
"127798146",
"127867804",
"156314762",
"160539283",
"160540751",
... | ():
from samri.fetch.local import roi_from_atlaslabel
mapping='/usr/share/mouse-brain-templates/dsurqe_labels.csv'
atlas='/usr/share/mouse-brain-templates/dsurqec_40micron_labels.nii'
my_roi = roi_from_atlaslabel(atlas,
mapping=mapping,
label_names=['cortex'],
)
roi_data = my_roi.get_data()
output_labels ... | test_roi_from_atlaslabel | identifier_name |
test_gamma.py | from pytest import approx, raises
from fastats.maths.gamma import gammaln
def test_gamma_ints():
assert gammaln(10) == approx(12.801827480081469, rel=1e-6)
assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
def test_gamma_floats():
as... | pytest.main([__file__]) |
if __name__ == '__main__':
import pytest | random_line_split |
test_gamma.py |
from pytest import approx, raises
from fastats.maths.gamma import gammaln
def test_gamma_ints():
assert gammaln(10) == approx(12.801827480081469, rel=1e-6)
assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
def test_gamma_floats():
a... |
if __name__ == '__main__':
import pytest
pytest.main([__file__])
| raises(AssertionError, gammaln, -1)
raises(AssertionError, gammaln, -0.023)
raises(AssertionError, gammaln, -10.9) | identifier_body |
test_gamma.py |
from pytest import approx, raises
from fastats.maths.gamma import gammaln
def test_gamma_ints():
assert gammaln(10) == approx(12.801827480081469, rel=1e-6)
assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
def test_gamma_floats():
a... | import pytest
pytest.main([__file__]) | conditional_block | |
test_gamma.py |
from pytest import approx, raises
from fastats.maths.gamma import gammaln
def | ():
assert gammaln(10) == approx(12.801827480081469, rel=1e-6)
assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
def test_gamma_floats():
assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6)
assert gammaln(8.8129) == approx... | test_gamma_ints | identifier_name |
transmute_int_to_float.rs | use super::TRANSMUTE_INT_TO_FLOAT;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
/// Checks for `transmute_int_to_float` lint.
/// Returns `true` if it's triggered, otherwis... | match (&from_ty.kind(), &to_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => {
span_lint_and_then(
cx,
TRANSMUTE_INT_TO_FLOAT,
e.span,
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
... | from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
args: &'tcx [Expr<'_>],
const_context: bool,
) -> bool { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.