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 |
|---|---|---|---|---|
switch.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Components, registerComponent } from "@reactioncommerce/reaction-components";
class Switch extends Component {
static defaultProps = {
checked: false
}
static propTypes = {
checked... | else if (this.props.label) {
labelElement = (
<Components.Translation defaultValue={this.props.label} i18nKey={this.props.i18nKeyLabel} />
);
}
if (labelElement) {
return (
<div className="control-label">
{labelElement}
</div>
);
}
return null... | {
labelElement = (
<Components.Translation defaultValue={this.props.onLabel} i18nKey={this.props.i18nKeyOnLabel} />
);
} | conditional_block |
switch.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Components, registerComponent } from "@reactioncommerce/reaction-components";
class Switch extends Component {
static defaultProps = {
checked: false
}
static propTypes = {
checked... | (props) {
super(props);
this.state = {
checked: false
};
}
handleChange = (event) => {
if (this.props.onChange) {
const isInputChecked = !this.props.checked;
this.props.onChange(event, isInputChecked, this.props.name);
}
}
renderLabel() {
let labelElement;
if (t... | constructor | identifier_name |
firmware_test.tsx | const mockDevice = {
rebootFirmware: jest.fn(() => Promise.resolve()),
flashFirmware: jest.fn((_) => Promise.resolve()),
};
jest.mock("../../../device", () => ({ getDevice: () => mockDevice }));
import React from "react";
import { mount } from "enzyme";
import { Firmware } from "../firmware";
import { FirmwareProp... | const wrapper = mount(<Firmware {...p} />);
expect(wrapper.text().toLowerCase())
.toContain("Restart Firmware".toLowerCase());
clickButton(wrapper, 3, "restart");
expect(mockDevice.rebootFirmware).toHaveBeenCalled();
});
it("flashes firmware", () => {
const p = fakeProps();
p.controlP... | p.controlPanelState.firmware = true; | random_line_split |
f_expression.py | #######################################################################
#
# Author: Gabi Roeger
# Modified by: Silvia Richter (silvia.richter@nicta.com.au)
# (C) Copyright 2008: Gabi Roeger and NICTA
#
# This file is part of LAMA.
#
# LAMA is free software; you can redistribute it and/or
# modify it under the terms of ... |
def _dump(self):
return str(self)
def instantiate(self, var_mapping, init_facts):
args = [conditions.ObjectTerm(var_mapping.get(arg.name, arg.name)) for arg in self.args]
pne = PrimitiveNumericExpression(self.symbol, args)
assert not self.symbol == "total-cost"
# We kno... | print "%s%s" % (indent, self._dump())
for arg in self.args:
arg.dump(indent + " ") | identifier_body |
f_expression.py | #######################################################################
#
# Author: Gabi Roeger
# Modified by: Silvia Richter (silvia.richter@nicta.com.au)
# (C) Copyright 2008: Gabi Roeger and NICTA
#
# This file is part of LAMA.
#
# LAMA is free software; you can redistribute it and/or
# modify it under the terms of ... |
def _dump(self):
return self.__class__.__name__
def instantiate(self, var_mapping, init_facts):
raise ValueError("Cannot instantiate condition: not normalized")
class NumericConstant(FunctionalExpression):
parts = ()
def __init__(self, value):
self.value = value
def __eq__(... | part.dump(indent + " ") | conditional_block |
f_expression.py | #######################################################################
#
# Author: Gabi Roeger
# Modified by: Silvia Richter (silvia.richter@nicta.com.au) | # (C) Copyright 2008: Gabi Roeger and NICTA
#
# This file is part of LAMA.
#
# LAMA 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.
#
#... | random_line_split | |
f_expression.py | #######################################################################
#
# Author: Gabi Roeger
# Modified by: Silvia Richter (silvia.richter@nicta.com.au)
# (C) Copyright 2008: Gabi Roeger and NICTA
#
# This file is part of LAMA.
#
# LAMA is free software; you can redistribute it and/or
# modify it under the terms of ... | (self, other):
if not (self.__class__ == other.__class__ and self.symbol == other.symbol
and len(self.args) == len(other.args)):
return False
else:
for s,o in zip(self.args, other.args):
if not s == o:
return False
r... | __eq__ | identifier_name |
editorUI.events.js | $(window).load(function() {
$(window).on('keydown', function(evt) {
console.log('keycode', evt.which);
// slice down
if (evt.which === 38) { // down arrow
var sliceZ = Session.get('sliceZ');
sliceZ = Math.min(Math.max(sliceZ + 1, 1), Session.get('gridSizeZ'));
Session.set('sliceZ', sli... | var sliceZ = Session.get('sliceZ');
sliceZ = Math.min(Math.max(sliceZ - 1, 1), Session.get('gridSizeZ'));
Session.set('sliceZ', sliceZ);
console.log('slice up', sliceZ);
}
// rotate left
if (evt.which === 37) {
var currentRotationIndex = Session.get('rotationIndex');
va... | if (evt.which === 40) { // up arrow | random_line_split |
editorUI.events.js | $(window).load(function() {
$(window).on('keydown', function(evt) {
console.log('keycode', evt.which);
// slice down
if (evt.which === 38) { // down arrow
var sliceZ = Session.get('sliceZ');
sliceZ = Math.min(Math.max(sliceZ + 1, 1), Session.get('gridSizeZ'));
Session.set('sliceZ', sli... |
// rotate left
if (evt.which === 37) {
var currentRotationIndex = Session.get('rotationIndex');
var newRotationIndex = (currentRotationIndex + 3) % 4
Session.set('rotationIndex', newRotationIndex);
console.log('rotate left', newRotationIndex);
}
// rotate right
if (evt.w... | { // up arrow
var sliceZ = Session.get('sliceZ');
sliceZ = Math.min(Math.max(sliceZ - 1, 1), Session.get('gridSizeZ'));
Session.set('sliceZ', sliceZ);
console.log('slice up', sliceZ);
} | conditional_block |
models.py | from django.db import models
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from tagging.utils import parse_tag_input
from django.contrib.auth.models import User
from django.conf import settings
import uuid,os
import datetime
# Create your models here.
def slugify_uniquely(value... |
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (instance.uuid, ext)
return os.path.join(settings.LOCAL_PHOTO_STORAGE_FOLDER, filename)
class TrovePhoto(models.Model):
user = models.ForeignKey(User)
full_size = models.URLField(max_length=255)
thumbnai... | if suffix:
potential = "-".join([base, str(suffix)])
if not model.objects.filter(**{slugfield: potential}).count():
return potential
# we hit a conflicting slug, so bump the suffix & try again
suffix += 1 | conditional_block |
models.py | from django.db import models
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from tagging.utils import parse_tag_input
from django.contrib.auth.models import User
from django.conf import settings
import uuid,os
import datetime
# Create your models here.
def slugify_uniquely(value... | slug is determined and when the object with that slug is saved.
It's also not exactly database friendly if there is a high
likelyhood of common slugs being attempted.
A good usage pattern for this code would be to add a custom save()
method to a model with a slug field along the... | This code suffers a race condition between when a unique | random_line_split |
models.py | from django.db import models
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from tagging.utils import parse_tag_input
from django.contrib.auth.models import User
from django.conf import settings
import uuid,os
import datetime
# Create your models here.
def slugify_uniquely(value... |
class SuperAlbum(models.Model):
user = models.ForeignKey(User)
album_name = models.CharField(max_length=100)
slug = models.SlugField(max_length=255,unique=True)
def save(self, *args, **kw):
if not self.slug:
self.slug = slugify_uniquely(self.album_name,self.__class__)
... | trove_photo = models.ForeignKey(TrovePhoto,related_name='superalbum_trove_photo')
album = models.ForeignKey('SuperAlbum')
order = models.IntegerField() | identifier_body |
models.py | from django.db import models
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from tagging.utils import parse_tag_input
from django.contrib.auth.models import User
from django.conf import settings
import uuid,os
import datetime
# Create your models here.
def slugify_uniquely(value... | (models.Model):
user = models.ForeignKey(User)
uuid = models.CharField(max_length=200)
title = models.CharField(max_length=100,null=True,blank=True)
description = models.CharField(max_length=200,null=True,blank=True)
photo = models.ImageField(upload_to=get_file_path,null=True,blank=True)
date_up... | LocalPhoto | identifier_name |
launcher.py | #
# Copyright (C) 2014
# Sean Poyser (seanpoyser@gmail.com)
# | # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This Program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY o... | # This Program is free software; you can redistribute it and/or modify | random_line_split |
admin-page.constants.ajs.ts | // Copyright 2019 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at | //
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the Licen... | //
// http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
Globals.js | var jsface = require('jsface');
var packageVersion = require('../../package.json').version;
/**
* @name Globals
* @namespace
* @classdesc Globals to be used throught Newman.
*/
var Globals = jsface.Class({
$singleton: true,
newmanVersion: packageVersion,
/**
* Used to add the Globals used throug... |
}
});
module.exports = Globals;
| {
this.recurseLimit = options.recurseLimit;
} | conditional_block |
Globals.js | var jsface = require('jsface');
var packageVersion = require('../../package.json').version;
/**
* @name Globals
* @namespace
* @classdesc Globals to be used throught Newman.
*/
var Globals = jsface.Class({
$singleton: true,
newmanVersion: packageVersion, | * @param {Object} requestJSON Request JSON.
* @param {Object} options Newman Options.
*/
addEnvironmentGlobals: function (requestJSON, options) {
this.requestJSON = requestJSON;
this.envJson = options.envJson || {};
this.iterationNumber = 1;
this.outputFile = options.o... |
/**
* Used to add the Globals used through out the app | random_line_split |
stylearc.rs | impl.
let $container { $field: _, .. };
// Create an (invalid) instance of the container and calculate the offset to its
// field. Using a null pointer might be UB if `&(*(0 as *const T)).field` is interpreted to
// be nullptr deref.
let invalid: $container = ::std::mem::uninit... |
// FIXME(bholley): Use the updated comment when [2] is merged.
//
// This load is needed to prevent reordering of use of the data and
// deletion of the data. Because it is marked `Release`, the decreasing
// of the reference count synchronizes with this `Acquire` load. This
... | {
return;
} | conditional_block |
stylearc.rs | impl.
let $container { $field: _, .. };
// Create an (invalid) instance of the container and calculate the offset to its
// field. Using a null pointer might be UB if `&(*(0 as *const T)).field` is interpreted to
// be nullptr deref.
let invalid: $container = ::std::mem::uninit... |
#[inline]
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr == other.ptr
}
}
impl<T: ?Sized> Clone for Arc<T> {
#[inline]
fn clone(&self) -> Self {
// Using a relaxed ordering is alright here, as knowledge of the
// original reference prevents other threads from... | {
let _ = Box::from_raw(self.ptr);
} | identifier_body |
stylearc.rs | impl.
let $container { $field: _, .. };
// Create an (invalid) instance of the container and calculate the offset to its
// field. Using a null pointer might be UB if `&(*(0 as *const T)).field` is interpreted to
// be nullptr deref.
let invalid: $container = ::std::mem::uninit... | (data: T) -> Self {
let x = Box::new(ArcInner {
count: atomic::AtomicUsize::new(1),
data: data,
});
Arc { ptr: Box::into_raw(x) }
}
pub fn into_raw(this: Self) -> *const T {
let ptr = unsafe { &((*this.ptr).data) as *const _ };
mem::forget(this);
... | new | identifier_name |
stylearc.rs | uniquely owned
unsafe { &mut (*self.0.ptr).data }
}
}
unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
struct ArcInner<T: ?Sized> {
count: atomic::AtomicUsize,
data: T,
}
unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
u... | random_line_split | ||
highq_power_sweep_0813f12.py | import matplotlib
from kid_readout.roach import baseband
matplotlib.use('agg')
import numpy as np
import time
import sys
from kid_readout.utils import data_file,sweeps
from kid_readout.analysis.resonator import fit_best_resonator
ri = baseband.RoachBasebandWide()
ri.initialize()
#ri.set_fft_gain(6)
#f0s = np.load('/... | print "using this fit"
meas_cfs.append(res.f_0)
idx = np.unravel_index(abs(measured_freqs - meas_cfs[-1]).argmin(),measured_freqs.shape)
idxs.append(idx)
delay = np.median(delays)
print "median delay is ",delay
nsamp = 2**22
step = 1
f0binned_mea... | fr,s21,errors = sweep_data.select_by_freq(f0s[m])
thiscf = f0s[m]
res = fit_best_resonator(fr[1:-1],s21[1:-1],errors=errors[1:-1]) #Resonator(fr,s21,errors=errors)
delay = res.delay
delays.append(delay)
s21 = s21*np.exp(2j*np.pi*res.delay*fr)
res = fit_best_resonator(fr,s... | conditional_block |
highq_power_sweep_0813f12.py | import matplotlib
from kid_readout.roach import baseband
matplotlib.use('agg')
import numpy as np
import time
import sys
from kid_readout.utils import data_file,sweeps
from kid_readout.analysis.resonator import fit_best_resonator
ri = baseband.RoachBasebandWide()
ri.initialize()
#ri.set_fft_gain(6)
#f0s = np.load('/... | meas_cfs.append(res.f_0)
idx = np.unravel_index(abs(measured_freqs - meas_cfs[-1]).argmin(),measured_freqs.shape)
idxs.append(idx)
delay = np.median(delays)
print "median delay is ",delay
nsamp = 2**22
step = 1
f0binned_meas = np.round(f0s*nsamp/512.0)*512.0/nsam... | print "using this fit" | random_line_split |
jquery.horizontalNav.js | /**
* jQuery Horizontal Navigation 1.0
* https://github.com/sebnitu/horizontalNav
*
* By Sebastian Nitu - Copyright 2012 - All rights reserved
* Author URL: http://sebnitu.com
*/
(function($) {
$.fn.horizontalNav = function(options) {
// Extend our default options with those provided.
var op... |
}
if ($('.clearHorizontalNav').length ) {
ul_wrap.css({ 'zoom' : '1' });
} else {
ul_wrap.css({ 'zoom' : '1' }).append('<div class="clearHorizontalNav">');
// let's append a clearfixing element to the ul wrapper
$('.cl... | {
resizeTrigger( _construct, o.responsiveDelay );
} | conditional_block |
jquery.horizontalNav.js | /**
* jQuery Horizontal Navigation 1.0
* https://github.com/sebnitu/horizontalNav
*
* By Sebastian Nitu - Copyright 2012 - All rights reserved
* Author URL: http://sebnitu.com
*/
(function($) {
$.fn.horizontalNav = function(options) {
// Extend our default options with those provided.
var op... | } else {
var ul_wrap = $this;
}
// Grab elements we'll need and add some default styles
var ul = $this.is('ul') ? $this : ul_wrap.find('> ul'), // The unordered list element
li = ul.find('> li'), // All list items
li_last =... | // we figure out what the full width should be
if ($this.is('ul')) {
var ul_wrap = $this.parent(); | random_line_split |
jquery.horizontalNav.js | /**
* jQuery Horizontal Navigation 1.0
* https://github.com/sebnitu/horizontalNav
*
* By Sebastian Nitu - Copyright 2012 - All rights reserved
* Author URL: http://sebnitu.com
*/
(function($) {
$.fn.horizontalNav = function(options) {
// Extend our default options with those provided.
var op... |
// Cycle through the list items and give them widths
li.each(function(index) {
var li_width = trueInnerWidth( $(this) );
$(this).css({ 'width' : (li_width + li_padding) + 'px' });
});
// Get... | {
if ( (o.tableDisplay != true) || (navigator.userAgent.match(/msie [6]/i)) ) {
// IE7 doesn't support the "display: table" method
// so we need to do it the hard way.
// Add some styles
ul.css({ 'float' : 'left' });
... | identifier_body |
jquery.horizontalNav.js | /**
* jQuery Horizontal Navigation 1.0
* https://github.com/sebnitu/horizontalNav
*
* By Sebastian Nitu - Copyright 2012 - All rights reserved
* Author URL: http://sebnitu.com
*/
(function($) {
$.fn.horizontalNav = function(options) {
// Extend our default options with those provided.
var op... | (callback, delay) {
// Delay before function is called
delay = delay || 100;
// Call function on resize
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeo... | resizeTrigger | identifier_name |
closures.rs | /*
* MIT License
*
* Copyright (c) 2016 Johnathan Fercher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy... | {
// closures are anonymous functions.
let sum = |i: f64, j: f64| -> f64 { i + j };
let print_hi = || println!("Hi");
let i = 4.0;
let j = 3.0;
println!("{}", sum(i, j));
print_hi();
} | identifier_body | |
closures.rs | /*
* MIT License
*
* Copyright (c) 2016 Johnathan Fercher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy... | print_hi();
} | println!("{}", sum(i, j)); | random_line_split |
closures.rs | /*
* MIT License
*
* Copyright (c) 2016 Johnathan Fercher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy... | () {
// closures are anonymous functions.
let sum = |i: f64, j: f64| -> f64 { i + j };
let print_hi = || println!("Hi");
let i = 4.0;
let j = 3.0;
println!("{}", sum(i, j));
print_hi();
} | main | identifier_name |
tokeniser.rs | _word: bool,
/// The current closing quote character and quote mode, if any.
quote: Option<( char, QuoteMode )>,
/// The current escape scheme in use, if any.
escape: Option<S>,
/// Maps from quote openers to quote closers.
quote_map: Q,
/// Map from escape leader characters to their sch... | self.escape = self.escape_map.find(&c).map(|a| a.clone());
self.in_word = true;
}
| identifier_body | |
tokeniser.rs | , a Tokeniser can be consumed to produce the vector of words
/// it has read, using the `into_strings` method. This method may fail if the
/// Tokeniser ended in a bad state (in the middle of a quoted string, or in
/// the middle of an escape sequence).
#[deriving(Clone)]
pub struct Tokeniser<Q, E, S> {
/// The cu... | // -> Begin escape (and word if not in one already)
( c, Tokeniser { escape: None,
quote: None,
escape_map: ref e, .. } ) if e.contains_key(&c) =>
new.start_escaping(c),
// Escape leader, in escape-permitti... | // ESCAPE LEADER
// Escape leader, not in quotes | random_line_split |
tokeniser.rs | a Tokeniser can be consumed to produce the vector of words
/// it has read, using the `into_strings` method. This method may fail if the
/// Tokeniser ended in a bad state (in the middle of a quoted string, or in
/// the middle of an escape sequence).
#[deriving(Clone)]
pub struct Tokeniser<Q, E, S> {
/// The cur... | f, chr: char) -> Tokeniser<Q, E, S> {
let mut new = self.clone();
match (chr, self) {
// ERROR
// Found an error
// -> Ignore input
( _, Tokeniser { error: Some(_), .. } ) => (),
// ESCAPE SEQUENCES
// Currently escaping
... | char(sel | identifier_name |
calendar.js | /*!
* Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
*/
import {WebexPlugin} from '@webex/webex-core';
const Calendar = WebexPlugin.extend({
namespace: 'Calendar',
/**
* Decrypts an encrypted incoming calendar event
* @param {Object} event
* @returns {Promise} Resolves with a decrypted ... | (options) {
options = options || {};
return this.webex.request({
method: 'GET',
service: 'calendar',
resource: 'calendarEvents',
qs: options
})
.then((res) => res.body.items);
}
});
export default Calendar;
| list | identifier_name |
calendar.js | /*!
* Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
*/
import {WebexPlugin} from '@webex/webex-core';
const Calendar = WebexPlugin.extend({
namespace: 'Calendar',
/**
* Decrypts an encrypted incoming calendar event
* @param {Object} event
* @returns {Promise} Resolves with a decrypted ... | * @returns {Promise} Resolves with an array of meetings
*/
list(options) {
options = options || {};
return this.webex.request({
method: 'GET',
service: 'calendar',
resource: 'calendarEvents',
qs: options
})
.then((res) => res.body.items);
}
});
export default Calend... | * @param {Date} options.toDate the end of the time range | random_line_split |
calendar.js | /*!
* Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
*/
import {WebexPlugin} from '@webex/webex-core';
const Calendar = WebexPlugin.extend({
namespace: 'Calendar',
/**
* Decrypts an encrypted incoming calendar event
* @param {Object} event
* @returns {Promise} Resolves with a decrypted ... |
});
export default Calendar;
| {
options = options || {};
return this.webex.request({
method: 'GET',
service: 'calendar',
resource: 'calendarEvents',
qs: options
})
.then((res) => res.body.items);
} | identifier_body |
astropy_models.py | try:
from astropy.models import ParametricModel,Parameter,_convert_input,_convert_output
import numpy as np
class PowerLawModel(ParametricModel):
param_names = ['scale', 'alpha']
def __init__(self, scale, alpha, param_dim=1):
self._scale = Parameter(name='scale', val=scale, mcl... | (self, xvals, params):
return params[0]*((xvals)**(-params[1]))
def noderiv(self, params, xvals, yvals):
deriv_dict = {
'scale': ((xvals)**(-params[1])),
'alpha': params[0]*((xvals)**(-params[1]))*np.log(xvals)}
derivval = [deriv_dict[... | eval | identifier_name |
astropy_models.py | try:
from astropy.models import ParametricModel,Parameter,_convert_input,_convert_output
import numpy as np
class PowerLawModel(ParametricModel):
param_names = ['scale', 'alpha']
def __init__(self, scale, alpha, param_dim=1):
self._scale = Parameter(name='scale', val=scale, mcl... | Parameters
--------------
x : array, of minimum dimensions 1
Notes
-----
See the module docstring for rules for model evaluation.
"""
x, fmt = _convert_input(x, self.param_dim)
result = self.eval(x,... | random_line_split | |
astropy_models.py | try:
from astropy.models import ParametricModel,Parameter,_convert_input,_convert_output
import numpy as np
class PowerLawModel(ParametricModel):
| """
Transforms data using this model.
Parameters
--------------
x : array, of minimum dimensions 1
Notes
-----
See the module docstring for rules for model evaluation.
"""
x... | param_names = ['scale', 'alpha']
def __init__(self, scale, alpha, param_dim=1):
self._scale = Parameter(name='scale', val=scale, mclass=self, param_dim=param_dim)
self._alpha = Parameter(name='alpha', val=alpha, mclass=self, param_dim=param_dim)
super(ParametricModel,self)._... | identifier_body |
vec.rs | //! Vector primitive.
use prelude::*;
use core::{mem, ops, ptr, slice};
use leak::Leak;
/// A low-level vector primitive.
///
/// This does not perform allocation nor reallaction, thus these have to be done manually.
/// Moreover, no destructors are called, making it possible to leak memory.
pub struct Vec<T: Leak>... | (&mut self) -> Option<T> {
if self.len == 0 {
None
} else {
unsafe {
// LAST AUDIT: 2016-08-21 (Ticki).
// Decrement the length. This won't underflow due to the conditional above.
self.len -= 1;
// We use `ptr::rea... | pop | identifier_name |
vec.rs | //! Vector primitive.
use prelude::*;
use core::{mem, ops, ptr, slice};
use leak::Leak;
/// A low-level vector primitive.
///
/// This does not perform allocation nor reallaction, thus these have to be done manually.
/// Moreover, no destructors are called, making it possible to leak memory.
pub struct Vec<T: Leak>... | else {
// Place the element in the end of the vector.
unsafe {
// LAST AUDIT: 2016-08-21 (Ticki).
// By the invariants of this type (the size is bounded by the address space), this
// conversion isn't overflowing.
ptr::write((self... | {
Err(())
} | conditional_block |
vec.rs | //! Vector primitive.
use prelude::*;
use core::{mem, ops, ptr, slice};
use leak::Leak;
/// A low-level vector primitive.
///
/// This does not perform allocation nor reallaction, thus these have to be done manually.
/// Moreover, no destructors are called, making it possible to leak memory.
pub struct Vec<T: Leak>... | // LAST AUDIT: 2016-08-21 (Ticki).
// Due to the invariants of `Block`, this copy is safe (the pointer is valid and
// unaliased).
ptr::copy_nonoverlapping(old.ptr.get(), self.ptr.get(), old.len);
}
Block::from(old)
}
/// Get the capacity of th... | {
log!(INTERNAL, "Refilling vector...");
// Calculate the new capacity.
let new_cap = block.size() / mem::size_of::<T>();
// Make some assertions.
assert!(
self.len <= new_cap,
"Block not large enough to cover the vector."
);
assert!(bloc... | identifier_body |
vec.rs | //! Vector primitive.
use prelude::*;
use core::{mem, ops, ptr, slice};
use leak::Leak;
/// A low-level vector primitive.
///
/// This does not perform allocation nor reallaction, thus these have to be done manually.
/// Moreover, no destructors are called, making it possible to leak memory.
pub struct Vec<T: Leak>... | // By the invariants of this type (the size is bounded by the address space), this
// conversion isn't overflowing.
ptr::write((self.ptr.get()).offset(self.len as isize), elem);
}
// Increment the length.
self.len += 1;
Ok(... | random_line_split | |
iot_lcd.py | #!/usr/bin/env python
from __future__ import print_function
import time
import pyupm_grove as grove
import pyupm_i2clcd as lcd
import pyupm_th02 as th02
import pyupm_guvas12d as upmUV
import pyupm_grovemoisture as upmMoisture
from phant import Phant
import requests
from iot_utils import *
__author__ = 'KT Kirk'
# Ini... |
#data = p.get()
#print(data['temp'])
time.sleep(60 * 5)
| myLcd.setColor(53, 39, 249) # Bl
myLcd.write("Sent Bytes: {}".format(p.remaining_bytes)) | conditional_block |
iot_lcd.py | #!/usr/bin/env python
from __future__ import print_function
import time
import pyupm_grove as grove
import pyupm_i2clcd as lcd
import pyupm_th02 as th02
import pyupm_guvas12d as upmUV | from phant import Phant
import requests
from iot_utils import *
__author__ = 'KT Kirk'
# Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS)
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
myLcd.setColor(53, 249, 39 ) # Green
myLcd.setCursor(0,0)
myLcd.write('IoT')
# Instantiate a Grove Moisture sensor on analog ... | import pyupm_grovemoisture as upmMoisture | random_line_split |
create_table_snr.py | ]) * 0.5 + 1)*40.
snr_ids = n.searchsorted(SNR_w_max, wl_40)
print(SNR_keys[snr_ids])
out_dir = os.path.join(os.environ['OBS_REPO'], 'spm', 'results')
#path_2_MAG_cat = os.path.join( os.environ['HOME'], 'SDSS', "dr14_specphot_gri.fits" )
#hd = fits.open(path_2_MAG_cat)
#path_2_sdss_cat = os.path.join( os.environ['... |
all_galaxies = n.array(all_galaxies)
tpps = n.array(tpps)
ids = n.argsort(all_galaxies)[::-1]
out_file = os.path.join(os.environ['OBS_REPO'], 'spm', 'results', "table_comp_"+survey+"_snr_all_sourcetype_SNR_moments.tex")
f=open(out_file, 'w')
#f.write('source type & N & \multicolumn{c}{2}{N galaxies} && \multicolum... | all_galaxies.append(n_all)
all_out = []
for z_Min, z_Max, snr_key in zip(z_bins[:-1], z_bins[1:], SNR_keys[snr_ids]):
s_z = sel_all &(catalog[z_name] >= z_Min) & (catalog[z_name] < z_Max)
n_z = length(s_z)
#print(z_Min, z_Max, n_z)
if n_z > 0 :
#print(n.min(catalog[snr_key][s_z]), n.max(catalog[snr_... | conditional_block |
create_table_snr.py | #hd = fits.open(path_2_MAG_cat)
#path_2_sdss_cat = os.path.join( os.environ['HOME'], 'SDSS', '26', 'catalogs', "FireFly.fits" )
#path_2_eboss_cat = os.path.join( os.environ['HOME'], 'SDSS', 'v5_10_0', 'catalogs', "FireFly.fits" )
path_2_sdss_cat = os.path.join( os.environ['OBS_REPO'], 'SDSS', '26', 'catalogs', "Fir... | for IMF in imfs :
prf = IMF.split('_')[0]+' & '+IMF.split('_')[1]
l2w = get_basic_stat_deep2(deep2, 'ZBEST', 'ZQUALITY', prf, 2., IMF, o2=False)
f.write(l2w + " \n") | random_line_split | |
lib.rs | `Browser`, along with a generic client
//! implementing the `WindowMethods` trait, to create a working web
//! browser.
//!
//! The `Browser` type is responsible for configuring a
//! `Constellation`, which does the heavy lifting of coordinating all
//! of Servo's internal subsystems, including the `ScriptThread` and ... |
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::Devtool... | {
self.compositor.title_for_main_frame()
} | identifier_body |
lib.rs | crate devtools;
pub extern crate devtools_traits;
pub extern crate euclid;
pub extern crate gfx;
pub extern crate ipc_channel;
pub extern crate layout_thread;
pub extern crate msg;
pub extern crate net;
pub extern crate net_traits;
pub extern crate profile;
pub extern crate profile_traits;
pub extern crate script;
pub... | create_sandbox | identifier_name | |
lib.rs | type `Browser`, along with a generic client
//! implementing the `WindowMethods` trait, to create a working web
//! browser.
//!
//! The `Browser` type is responsible for configuring a | //! of Servo's internal subsystems, including the `ScriptThread` and the
//! `LayoutThread`, as well maintains the navigation context.
//!
//! The `Browser` is fed events from a generic type that implements the
//! `WindowMethods` trait.
#[cfg(not(target_os = "windows"))]
extern crate gaol;
#[macro_use]
extern crate g... | //! `Constellation`, which does the heavy lifting of coordinating all | random_line_split |
lib.rs | `Browser`, along with a generic client
//! implementing the `WindowMethods` trait, to create a working web
//! browser.
//!
//! The `Browser` type is responsible for configuring a
//! `Constellation`, which does the heavy lifting of coordinating all
//! of Servo's internal subsystems, including the `ScriptThread` and ... |
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = IOCompositor::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
cons... | {
webdriver(port, constellation_chan.clone());
} | conditional_block |
popup.js | /*======================================================
************ Picker ************
======================================================*/
/* global $:true */
+ function($) {
"use strict";
//Popup 和 picker 之类的不要共用一个弹出方法,因为这样会导致 在 popup 中再弹出 picker 的时候会有问题。
$.openPopup = function(popup, className) ... |
var modal = popup.find(".weui-popup-modal");
modal.width();
modal.addClass("weui-popup-modal-visible");
}
$.closePopup = function(container, remove) {
$(".weui-popup-modal-visible").removeClass("weui-popup-modal-visible").transitionEnd(function() {
$(this).parent().removeClass("weui-popu... |
popup.addClass("weui-popup-container-visible"); | random_line_split |
scikit_radon.py | # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL 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.
#... | (scikit_range, sinogram):
"""Interpolate in a possibly smaller space
Sets all points that would be outside ofthe domain to match the boundary
values.
"""
min_x = scikit_range.domain.min()[1]
max_x = scikit_range.domain.max()[1]
def interpolation_wrapper(x):
x = (x[0], np.maximum(mi... | clamped_interpolation | identifier_name |
scikit_radon.py | # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL 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.
#... |
scale = volume.space.cell_sides[0]
out *= scale
return out
def scikit_radon_back_projector(sinogram, geometry, range, out=None):
"""Calculate forward projection using scikit
Parameters
----------
sinogram : `DiscreteLpElement`
Sinogram (projections) to backproject.
geometry... | random_line_split | |
scikit_radon.py | # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL 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.
#... |
def scikit_sinogram_space(geometry, volume_space, sinogram_space):
"""Create a range adapted to the scikit radon geometry."""
padded_size = int(np.ceil(volume_space.shape[0] * np.sqrt(2)))
det_width = volume_space.domain.extent()[0] * np.sqrt(2)
scikit_detector_part = uniform_partition(-det_width / ... | """Calculate angles in degrees with ODL scikit conventions."""
return np.asarray(geometry.motion_grid).squeeze() * 180.0 / np.pi | identifier_body |
scikit_radon.py | # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL 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.
#... |
out[:] = iradon(scikit_sinogram.asarray().T, theta,
output_size=range.shape[0], filter=None)
# Empirically determined value, gives correct scaling
scale = 4.0 * float(geometry.motion_params.length) / (2 * np.pi)
out *= scale
return out
| assert out in range | conditional_block |
component_registrator.js | /**
* DevExtreme (core/component_registrator.js)
* Version: 16.2.5
* Build date: Mon Feb 27 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
errors = require("./errors"),
... |
var member = instance[memberName],
memberValue = member.apply(instance, memberArgs);
if (void 0 === result) {
result = memberValue
}
})
} else {
this.each(function() {
var instance = ... | {
throw errors.Error("E0009", name)
} | conditional_block |
component_registrator.js | /**
* DevExtreme (core/component_registrator.js)
* Version: 16.2.5
* Build date: Mon Feb 27 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
errors = require("./errors"),
... | module.exports = registerComponent; | callbacks.add(registerJQueryComponent); | random_line_split |
gather_op_test.py | from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.platform import test
_TEST_TYPES = (dtypes.int64, dtypes.float32,
dtypes.complex64, dtypes.complex128)
class GatherTest(test.TestCase):
def _buildParams(self, data, dtype):
data =... | (self):
for unsigned_type in (dtypes.uint32, dtypes.uint64):
params = self._buildParams(
np.array([[1, 2, 3], [7, 8, 9]]), unsigned_type)
with self.cached_session():
self.assertAllEqual([7, 8, 9],
array_ops.gather(params, 1, axis=0).eval())
self.asse... | testUInt32AndUInt64 | identifier_name |
gather_op_test.py | from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.platform import test
_TEST_TYPES = (dtypes.int64, dtypes.float32,
dtypes.complex64, dtypes.complex128)
class GatherTest(test.TestCase):
def _buildParams(self, data, dtype):
data =... |
def testBadIndicesCPU(self):
with self.session(use_gpu=False):
params = [[0, 1, 2], [3, 4, 5]]
with self.assertRaisesOpError(r"indices\[0,0\] = 7 is not in \[0, 2\)"):
array_ops.gather(params, [[7]], axis=0).eval()
with self.assertRaisesOpError(r"indices\[0,0\] = 7 is not in \[0, 3\)")... | params = constant_op.constant([[0, 1, 2]])
indices = constant_op.constant([[0, 0], [0, 0]])
axis = array_ops.placeholder(dtypes.int32)
gather_t = array_ops.gather(params, indices, axis=axis)
# Rank 2 params with rank 2 indices results in a rank 3 shape.
self.assertEqual([None, None, None], gather_t.... | identifier_body |
gather_op_test.py | from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.platform import test
_TEST_TYPES = (dtypes.int64, dtypes.float32,
dtypes.complex64, dtypes.complex128)
class GatherTest(test.TestCase):
def _buildParams(self, data, dtype):
data =... |
# Test gradients
gather_grad = np.random.randn(
*gather.get_shape().as_list()).astype(dtype.as_numpy_dtype)
if dtype.is_complex:
gather_grad -= 1j * gather_grad
params_grad, indices_grad, axis_grad = gradients_impl.gradients(
... | params = self._buildParams(np.random.randn(*shape), dtype)
indices = np.random.randint(shape[axis], size=indices_shape)
with self.cached_session(use_gpu=True) as sess:
tf_params = constant_op.constant(params)
tf_indices = constant_op.constant(indices)
# Check that... | conditional_block |
gather_op_test.py | from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.platform import test
_TEST_TYPES = (dtypes.int64, dtypes.float32,
dtypes.complex64, dtypes.complex128)
class GatherTest(test.TestCase):
def _buildParams(self, data, dtype):
data =... | *gather.get_shape().as_list()).astype(dtype.as_numpy_dtype)
if dtype.is_complex:
gather_grad -= 1j * gather_grad
params_grad, indices_grad, axis_grad = gradients_impl.gradients(
gather, [tf_params, tf_indices, tf_axis], gather_grad)
self.... | self.assertEqual(expected_shape, gather.shape)
self.assertEqual(expected_shape, gather_negative_axis.shape)
# Test gradients
gather_grad = np.random.randn( | random_line_split |
parse_ana_dump.py | #!/usr/bin/python2
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All... |
def InitDecisions():
decisions = {}
event = debug_dump_pb2.Event()
for decision in event.encoder_runtime_config.DESCRIPTOR.fields:
decisions[decision.name] = {'time': [], 'value': []}
return decisions
def ParseAnaDump(dump_file_to_parse):
with open(dump_file_to_parse, 'rb') as file_to_parse:
metr... | metrics = {}
event = debug_dump_pb2.Event()
for metric in event.network_metrics.DESCRIPTOR.fields:
metrics[metric.name] = {'time': [], 'value': []}
return metrics | identifier_body |
parse_ana_dump.py | #!/usr/bin/python2
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All... | parser.print_help()
exit()
(metrics, decisions) = ParseAnaDump(options.dump_file_to_parse)
metric_keys = options.metric_keys
decision_keys = options.decision_keys
plot_count = len(metric_keys) + len(decision_keys)
if plot_count == 0:
print "You have to set at least one metric or decision to plot.\... | if options.dump_file_to_parse == None:
print "No dump file to parse is set.\n" | random_line_split |
parse_ana_dump.py | #!/usr/bin/python2
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All... | ():
metrics = {}
event = debug_dump_pb2.Event()
for metric in event.network_metrics.DESCRIPTOR.fields:
metrics[metric.name] = {'time': [], 'value': []}
return metrics
def InitDecisions():
decisions = {}
event = debug_dump_pb2.Event()
for decision in event.encoder_runtime_config.DESCRIPTOR.fields:
... | InitMetrics | identifier_name |
parse_ana_dump.py | #!/usr/bin/python2
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All... |
return struct.unpack('<I', data)[0]
def GetNextMessageFromFile(file_to_parse):
message_size = GetNextMessageSize(file_to_parse)
if message_size == 0:
return None
try:
event = debug_dump_pb2.Event()
event.ParseFromString(file_to_parse.read(message_size))
except IOError:
print 'Invalid messag... | return 0 | conditional_block |
size.rs | use std::{io, mem};
use super::cvt;
use super::libc::{c_ushort, ioctl, STDOUT_FILENO, TIOCGWINSZ};
#[repr(C)]
struct TermSize { | y: c_ushort,
}
/// Get the size of the terminal.
pub fn terminal_size() -> io::Result<(u16, u16)> {
unsafe {
let mut size: TermSize = mem::zeroed();
cvt(ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size as *mut _))?;
Ok((size.col as u16, size.row as u16))
}
}
/// Get the size of the... | row: c_ushort,
col: c_ushort,
x: c_ushort, | random_line_split |
size.rs | use std::{io, mem};
use super::cvt;
use super::libc::{c_ushort, ioctl, STDOUT_FILENO, TIOCGWINSZ};
#[repr(C)]
struct TermSize {
row: c_ushort,
col: c_ushort,
x: c_ushort,
y: c_ushort,
}
/// Get the size of the terminal.
pub fn terminal_size() -> io::Result<(u16, u16)> |
/// Get the size of the terminal, in pixels
pub fn terminal_size_pixels() -> io::Result<(u16, u16)> {
unsafe {
let mut size: TermSize = mem::zeroed();
cvt(ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size as *mut _))?;
Ok((size.x as u16, size.y as u16))
}
}
| {
unsafe {
let mut size: TermSize = mem::zeroed();
cvt(ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size as *mut _))?;
Ok((size.col as u16, size.row as u16))
}
} | identifier_body |
size.rs | use std::{io, mem};
use super::cvt;
use super::libc::{c_ushort, ioctl, STDOUT_FILENO, TIOCGWINSZ};
#[repr(C)]
struct | {
row: c_ushort,
col: c_ushort,
x: c_ushort,
y: c_ushort,
}
/// Get the size of the terminal.
pub fn terminal_size() -> io::Result<(u16, u16)> {
unsafe {
let mut size: TermSize = mem::zeroed();
cvt(ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size as *mut _))?;
Ok((size.col ... | TermSize | identifier_name |
logging_resource.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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
# versio... |
def clean(self, resource):
resource.tearDown() | random_line_split | |
logging_resource.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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
# versio... | (self, attr):
if attr == '_dirty':
return True
return object.__getattribute__(self, attr)
def make(self, dep_resources):
new_root = logging.RootLogger(logging.WARNING)
new_manager = logging.Manager(new_root)
new_manager.emittedNoHandlerWarning = 1
return ... | __getattribute__ | identifier_name |
logging_resource.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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
# versio... |
def isDirty(self):
return True
def clean(self, resource):
resource.tearDown()
| new_root = logging.RootLogger(logging.WARNING)
new_manager = logging.Manager(new_root)
new_manager.emittedNoHandlerWarning = 1
return OldState([monkeypatch('logging.root', new_root),
monkeypatch('logging.Logger.root', new_root),
monkeypatch('logging.Logger.manager', new_m... | identifier_body |
logging_resource.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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
# versio... |
return object.__getattribute__(self, attr)
def make(self, dep_resources):
new_root = logging.RootLogger(logging.WARNING)
new_manager = logging.Manager(new_root)
new_manager.emittedNoHandlerWarning = 1
return OldState([monkeypatch('logging.root', new_root),
monke... | return True | conditional_block |
abdt_rbranchnaming__t.py | """Test suite for abdt_rbranchnaming."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which te... |
import abdt_namingtester
import abdt_rbranchnaming
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def make_naming(self):
return abdt_rbranchnaming.Naming()
def test_A_Breathing(self):
pass
def test_XA_Breathing(self):
abd... |
from __future__ import absolute_import
import unittest | random_line_split |
abdt_rbranchnaming__t.py | """Test suite for abdt_rbranchnaming."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which te... |
def tearDown(self):
pass
def make_naming(self):
return abdt_rbranchnaming.Naming()
def test_A_Breathing(self):
pass
def test_XA_Breathing(self):
abdt_namingtester.check_XA_Breathing(self)
def test_XB_globally_invalid_review_tracker_names(self):
abdt_nami... | pass | identifier_body |
abdt_rbranchnaming__t.py | """Test suite for abdt_rbranchnaming."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which te... | (self):
pass
def tearDown(self):
pass
def make_naming(self):
return abdt_rbranchnaming.Naming()
def test_A_Breathing(self):
pass
def test_XA_Breathing(self):
abdt_namingtester.check_XA_Breathing(self)
def test_XB_globally_invalid_review_tracker_names(self... | setUp | identifier_name |
abdt_rbranchnaming__t.py | """Test suite for abdt_rbranchnaming."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which te... |
abdt_namingtester.check_XD_valid_reviews(
self, self.make_naming(), names_to_properties)
# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may ... | name = 'r/{base}/{description}'.format(
description=properties.description,
base=properties.base)
assert name not in names_to_properties
names_to_properties[name] = properties | conditional_block |
smallintmap.rs | use std::collections::SmallIntMap;
struct Tenant<'a> {
name: &'a str,
phone: &'a str,
}
fn main() | apartments.pop(&1);
match apartments.find_mut(&3) {
Some(henrietta) => henrietta.name = "David and Henrietta Smith",
_ => println!("Oh no! Where did David and Henrietta go?"),
}
apartments.insert(0, Tenant {
name: "Phillip Davis",
phone: "5555-7869",
});
for (ke... | {
// Start with 5 apartments
let mut apartments = SmallIntMap::with_capacity(5);
// The compiler infers 1 as uint
apartments.insert(1, Tenant {
name: "John Smith",
phone: "555-1234",
});
apartments.insert(3, Tenant {
name: "Henrietta George",
phone: "555-2314",
... | identifier_body |
smallintmap.rs | use std::collections::SmallIntMap;
struct Tenant<'a> {
name: &'a str,
phone: &'a str,
}
fn main() {
// Start with 5 apartments
let mut apartments = SmallIntMap::with_capacity(5);
// The compiler infers 1 as uint
apartments.insert(1, Tenant {
name: "John Smith",
phone: "555-123... | name: "David Rogers",
phone: "555-5467",
});
apartments.pop(&1);
match apartments.find_mut(&3) {
Some(henrietta) => henrietta.name = "David and Henrietta Smith",
_ => println!("Oh no! Where did David and Henrietta go?"),
}
apartments.insert(0, Tenant {
name:... | });
apartments.insert(5, Tenant { | random_line_split |
smallintmap.rs | use std::collections::SmallIntMap;
struct Tenant<'a> {
name: &'a str,
phone: &'a str,
}
fn | () {
// Start with 5 apartments
let mut apartments = SmallIntMap::with_capacity(5);
// The compiler infers 1 as uint
apartments.insert(1, Tenant {
name: "John Smith",
phone: "555-1234",
});
apartments.insert(3, Tenant {
name: "Henrietta George",
phone: "555-2314... | main | identifier_name |
custom.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import * as fromEvent from 'rxjs/add/observable/fromEvent';
@Component({
selector: 'async',
templateUrl: './custom.component.html'
})
export class CustomComponent implements AfterViewInit {
$start_click: Observable<an... | }
reset() {
this.arr = this.arr.slice();
}
} | this.newVal = ''; | random_line_split |
custom.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import * as fromEvent from 'rxjs/add/observable/fromEvent';
@Component({
selector: 'async',
templateUrl: './custom.component.html'
})
export class CustomComponent implements AfterViewInit {
$start_click: Observable<an... | () {
this.$start_click = Observable.fromEvent(document.getElementById('start_btn'), 'click');
this.$stop_click = Observable.fromEvent(document.getElementById('stop_btn'), 'click');
this.$num_stream = this.$start_click.switchMap(() => {
return Observable.interval(500).takeUntil(this.$stop_click);
}... | ngAfterViewInit | identifier_name |
custom.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import * as fromEvent from 'rxjs/add/observable/fromEvent';
@Component({
selector: 'async',
templateUrl: './custom.component.html'
})
export class CustomComponent implements AfterViewInit {
$start_click: Observable<an... | else {
this.arr = this.arr.concat(item);
}
this.newVal = '';
}
reset() {
this.arr = this.arr.slice();
}
}
| {
this.arr.push(item);
} | conditional_block |
custom.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import * as fromEvent from 'rxjs/add/observable/fromEvent';
@Component({
selector: 'async',
templateUrl: './custom.component.html'
})
export class CustomComponent implements AfterViewInit {
$start_click: Observable<an... |
reset() {
this.arr = this.arr.slice();
}
}
| {
let item = {
name: this.newVal,
isFruit: this.isFruit
};
if (this.mutate) {
this.arr.push(item);
} else {
this.arr = this.arr.concat(item);
}
this.newVal = '';
} | identifier_body |
logging_mixin.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | _logger = None | conditional_block | |
logging_mixin.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | # under the License.
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import sys
import warnings
import six
from builtins import object
from contextlib import contextmanager
from logging import Handle... | # KIND, either express or implied. See the License for the
# specific language governing permissions and limitations | random_line_split |
logging_mixin.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | (object):
encoding = False
"""
Allows to redirect stdout and stderr to logger
"""
def __init__(self, logger, level):
"""
:param log: The log level method to write to, ie. log.debug, log.warning
:return:
"""
self.logger = logger
self.level = level
... | StreamLogWriter | identifier_name |
logging_mixin.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | For compatibility with the io.IOBase interface.
"""
return False
def write(self, message):
"""
Do whatever it takes to actually log the specified logging record
:param message: message to log
"""
if not message.endswith("\n"):
self._buffer... | encoding = False
"""
Allows to redirect stdout and stderr to logger
"""
def __init__(self, logger, level):
"""
:param log: The log level method to write to, ie. log.debug, log.warning
:return:
"""
self.logger = logger
self.level = level
self._buff... | identifier_body |
route.ts | /**
* parse url
* @private
*/
const RULE_RE = /([^<]*)<(?:([a-zA-Z_][a-zA-Z0-9_]*):)?([a-zA-Z_][a-zA-Z0-9_]*)>/g;
/**
* parse url rule
* @param rule
* @private
*/
function* _parse_rule(rule: string) {
let pos = 0;
let end = rule.length;
let usedNames = new Set();
RULE_RE.lastIndex = 0;
whil... | () {
let self = this;
self._variable = [];
let regexParts: string[] = [];
function _build_regex(rule: string) {
for (let [converter, variable] of _parse_rule(rule)) {
if (converter === null) {
// static part
regexParts.... | complie | identifier_name |
route.ts | /**
* parse url
* @private
*/
const RULE_RE = /([^<]*)<(?:([a-zA-Z_][a-zA-Z0-9_]*):)?([a-zA-Z_][a-zA-Z0-9_]*)>/g;
/**
* parse url rule
* @param rule
* @private
*/
function* _parse_rule(rule: string) {
let pos = 0;
let end = rule.length;
let usedNames = new Set();
RULE_RE.lastIndex = 0;
whil... | break;
case 'int':
result = { regex: '(\\d+)', weight: 50 };
break;
case 'float':
result = { regex: '(\\d+\\.\\d+)', weight: 50 };
break;
case 'default':
result = { regex: '(\\w+)', weight: 100 };
break;
}
... | result = { regex: '(\\w+)', weight: 100 };
break;
case 'path':
result = { regex: '(.*?)', weight: 200 }; | random_line_split |
route.ts | /**
* parse url
* @private
*/
const RULE_RE = /([^<]*)<(?:([a-zA-Z_][a-zA-Z0-9_]*):)?([a-zA-Z_][a-zA-Z0-9_]*)>/g;
/**
* parse url rule
* @param rule
* @private
*/
function* _parse_rule(rule: string) {
let pos = 0;
let end = rule.length;
let usedNames = new Set();
RULE_RE.lastIndex = 0;
whil... | result = { regex: '(\\w+)', weight: 100 };
break;
}
return result;
}
/**
* Route class
* @private
*/
export class Route {
rule: string;
endpoint: string;
methods: string[];
weight: number;
private _regex: RegExp;
private _variable: string[];
constructor... | {
let converterTypes = ['str', 'int', 'float', 'path', 'default'];
if (converterTypes.indexOf(type) === -1)
throw TypeError('converter type ' + type + ' is undefined');
let result = { regex: '', weight: 0 };
switch (type) {
case 'str':
result = { regex: '(\\w+)', weight: 100... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import django.utils.timezone
import model_utils.fields
from django.db import migrations, models
from opaque_keys.edx.django.models import CourseKeyField, UsageKeyField
from lms.djangoapps.courseware.fields import UnsignedBigIntAutoField
... | ),
migrations.CreateModel(
name='VisibleBlocks',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('blocks_json', models.TextField()),
('hashed', models.CharField(unique=Tru... | dependencies = [
]
operations = [
migrations.CreateModel(
name='PersistentSubsectionGrade',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),
('modified', model_ut... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import django.utils.timezone
import model_utils.fields
from django.db import migrations, models
from opaque_keys.edx.django.models import CourseKeyField, UsageKeyField
from lms.djangoapps.courseware.fields import UnsignedBigIntAutoField
... | (migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='PersistentSubsectionGrade',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),
... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import django.utils.timezone
import model_utils.fields
from django.db import migrations, models
from opaque_keys.edx.django.models import CourseKeyField, UsageKeyField
from lms.djangoapps.courseware.fields import UnsignedBigIntAutoField
... | ('course_version', models.CharField(max_length=255, verbose_name=b'guid of latest course version', blank=True)),
('earned_all', models.FloatField()),
('possible_all', models.FloatField()),
('earned_graded', models.FloatField()),
('possible_... | ('course_id', CourseKeyField(max_length=255)),
('usage_key', UsageKeyField(max_length=255)),
('subtree_edited_date', models.DateTimeField(verbose_name=b'last content edit timestamp')), | random_line_split |
SimRepAnaligRMSD.py | import MDAnalysis
import matplotlib.pyplot as plt
import numpy as np
from MDAnalysis.analysis.align import *
from MDAnalysis.analysis.rms import rmsd
def ligRMSD(u,ref):
"""
This function produces RMSD data and plots for ligand.
:input
1) Universe of Trajectory
2) reference universe
:... | ligandRMSD = []
fig,ligandRMSD = ligRMSD(u,ref)
#print caRMSD
np.savetxt(args.jobname+"_ligRMSD.data", ligandRMSD)
fig.figure.savefig(args.jobname+"_ligRMSD.pdf") | random_line_split | |
SimRepAnaligRMSD.py | import MDAnalysis
import matplotlib.pyplot as plt
import numpy as np
from MDAnalysis.analysis.align import *
from MDAnalysis.analysis.rms import rmsd
def ligRMSD(u,ref):
| #print RMSD_lig
import matplotlib.pyplot as plt
ax = plt.subplot(111)
ax.plot(RMSD_lig[:,0], RMSD_lig[:,1], 'r--', lw=2, label=r"$R_G$")
ax.set_xlabel("Frame")
ax.set_ylabel(r"RMSD of ligand ($\AA$)")
#ax.figure.savefig("RMSD_ligand.pdf")
#plt.draw()
handles, labels = ax.get_legend_h... | """
This function produces RMSD data and plots for ligand.
:input
1) Universe of Trajectory
2) reference universe
:return
1) matplot object
2) array for RMSD data.
"""
RMSD_lig = []
ligand = u.select_atoms("(resid 142:146) and not name H*") ## include s... | identifier_body |
SimRepAnaligRMSD.py | import MDAnalysis
import matplotlib.pyplot as plt
import numpy as np
from MDAnalysis.analysis.align import *
from MDAnalysis.analysis.rms import rmsd
def ligRMSD(u,ref):
"""
This function produces RMSD data and plots for ligand.
:input
1) Universe of Trajectory
2) reference universe
:... | import argparse
parser = argparse.ArgumentParser(description='This function will plot RMSD for a given universe (trajectory).')
parser.add_argument('-j', '--jobname', help='Enter your job name and it will appear as first coloumn in the result file', default='Test')
parser.add_argument('-trj', '--trajectory'... | conditional_block | |
SimRepAnaligRMSD.py | import MDAnalysis
import matplotlib.pyplot as plt
import numpy as np
from MDAnalysis.analysis.align import *
from MDAnalysis.analysis.rms import rmsd
def | (u,ref):
"""
This function produces RMSD data and plots for ligand.
:input
1) Universe of Trajectory
2) reference universe
:return
1) matplot object
2) array for RMSD data.
"""
RMSD_lig = []
ligand = u.select_atoms("(resid 142:146) and not name H*")... | ligRMSD | identifier_name |
views.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | (tabs.TabbedTableView):
tab_group_class = project_tabs.SystemInfoTabs
template_name = constants.INFO_TEMPLATE_NAME
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
try:
context["version"] = version.version_info.version_string()
... | IndexView | identifier_name |
views.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | context = super(IndexView, self).get_context_data(**kwargs)
try:
context["version"] = version.version_info.version_string()
except Exception:
exceptions.handle(self.request,
_('Unable to retrieve version information.'))
return context | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.