file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
readme.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
| {
return content.replace(
/version = "~> [\d]+.[\d]+"/,
`version = "~> ${this.version.major}.${this.version.minor}"`
);
} | identifier_body |
readme.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | export class ReadMe extends DefaultUpdater {
/**
* Given initial file contents, return updated contents.
* @param {string} content The initial content
* @returns {string} The updated content
*/
updateContent(content: string): string {
return content.replace(
/version = "~> [\d]+.[\d]+"/,
... | */ | random_line_split |
readme.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | extends DefaultUpdater {
/**
* Given initial file contents, return updated contents.
* @param {string} content The initial content
* @returns {string} The updated content
*/
updateContent(content: string): string {
return content.replace(
/version = "~> [\d]+.[\d]+"/,
`version = "~> ${t... | ReadMe | identifier_name |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stacko... | return False
def get_token(self, obj):
try:
return obj.accesstoken_set.first().token
except AttributeError:
return None
def is_superuser(self, obj):
return obj.is_superuser
class Meta:
model = models.ShareUser
fields = (
'user... | obj.is_robot
| conditional_block |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stacko... | ss ChangeSetSerializer(ShareModelSerializer):
# changes = ChangeSerializer(many=True)
change_count = serializers.SerializerMethodField()
self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
source = ShareUserSerializer(source='normalized_data.source')
status = serializers.Se... | def __init__(self, *args, token=None, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
if token:
self.fields.update({
'token': serializers.SerializerMethodField()
})
self.fields.update({
'π¦': serializers.SerializerMethodFi... | identifier_body |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
|
class ShareModelSerializer(serializers.ModelSerializer):
# http://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
def to_representation(self, instance):
def not_none(value):
return value is not None
ret = super(ShareModelSerializer, self)... | from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
| random_line_split |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stacko... | j):
return obj.username.replace('providers.', '')
class Meta:
model = models.ShareUser
fields = ('home_page', 'long_title', 'date_joined', 'gravatar')
| name(self, ob | identifier_name |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
matc... | () -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <joris.guisson@gmail.com>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ... | run | identifier_name |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
matc... | {
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
} | identifier_body | |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
matc... | build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.... | } else if let Some(matches) = matches.subcommand_matches("build") { | random_line_split |
encryptData.js | function hashPassword(password) | ;
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var en... | {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
} | identifier_body |
encryptData.js | function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=nu... | ;
return encryptedData;
};
// AJAX for posting
function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
//... | {
encryptedData.push({date: date2Str(data[i0].x), value: encryptValue(data[i0].y, encrypt)});
} | conditional_block |
encryptData.js | function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function | (value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var encrypted = cipher.output.... | encryptValue | identifier_name |
encryptData.js | function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=nu... | function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
// handle a successful response
success : functio... | random_line_split | |
edits.ts | import {letters} from './letters'
| results.push(word.slice(0, i) + word.slice(i+1));
// transposition
for (i=0; i < word.length-1; i+=1)
results.push(word.slice(0, i) + word.slice(i+1, i+2) + word.slice(i, i+1) + word.slice(i+2));
// alteration
for (i=0; i < word.length; i+=1)
letters.forEach(function (l) {
results.push(word.sl... | export function edits(word): string[] {
let i, results: string[] = [];
// deletion
for (i=0; i < word.length; i+=1) | random_line_split |
edits.ts | import {letters} from './letters'
export function | (word): string[] {
let i, results: string[] = [];
// deletion
for (i=0; i < word.length; i+=1)
results.push(word.slice(0, i) + word.slice(i+1));
// transposition
for (i=0; i < word.length-1; i+=1)
results.push(word.slice(0, i) + word.slice(i+1, i+2) + word.slice(i, i+1) + word.slice(i+2));
// altera... | edits | identifier_name |
edits.ts | import {letters} from './letters'
export function edits(word): string[] | {
let i, results: string[] = [];
// deletion
for (i=0; i < word.length; i+=1)
results.push(word.slice(0, i) + word.slice(i+1));
// transposition
for (i=0; i < word.length-1; i+=1)
results.push(word.slice(0, i) + word.slice(i+1, i+2) + word.slice(i, i+1) + word.slice(i+2));
// alteration
for (i=0; ... | identifier_body | |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn main() {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let... | // 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
} | random_line_split | |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn main() | {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec... | identifier_body | |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn | () {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = ... | main | identifier_name |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | """
info ID
Get information about an advert.
"""
if not _id:
print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
return 2
job_advert = self.get_object(_id, 'get_job_advert')
if not job_advert:
... | identifier_body | |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... |
return result.strip('\n\t')
class Handjoob(ReplApplication):
APPNAME = 'handjoob'
VERSION = '0.i'
COPYRIGHT = 'Copyright(C) 2012 Bezleputh'
DESCRIPTION = "Console application to search for a job."
SHORT_DESCRIPTION = "search for a job"
CAPS = ICapJob
EXTRA_FORMATTERS = {'job_adver... | result += '\tContract : %s\n' % obj.contract_type | conditional_block |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | (PrettyFormatter):
MANDATORY_FIELDS = ('id', 'title')
def get_title(self, obj):
return '%s' % (obj.title)
def get_description(self, obj):
result = u''
if hasattr(obj, 'publication_date') and obj.publication_date:
result += '\tPublication date : %s\n' % obj.publication_d... | JobAdvertListFormatter | identifier_name |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | for backend, job_advert in self.do('advanced_search_job'):
self.cached_format(job_advert)
def complete_info(self, text, line, *ignored):
args = line.split(' ')
if len(args) == 2:
return self._complete_object()
def do_info(self, _id):
"""
info ID
... | """
self.change_path([u'advanced']) | random_line_split |
lib.rs | // Copyright TUNTAP, 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use base::{ioctl_ior_nr, ioctl_iow_nr};
// genera... | ioctl_iow_nr!(TUNSETIFINDEX, TUNTAP, 218, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETFILTER, TUNTAP, 219, sock_fprog);
ioctl_iow_nr!(TUNSETVNETLE, TUNTAP, 220, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETVNETLE, TUNTAP, 221, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETVNETBE, TUNTAP, 222, ::std::os::raw::c_int);
ioct... | ioctl_iow_nr!(TUNSETQUEUE, TUNTAP, 217, ::std::os::raw::c_int); | random_line_split |
cube-portfolio-2-ns.js | (function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridC... | else {
filtersCallback = function(me) {
me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active');
};
}
filtersContainer.on('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/click.cbp', '.cbp-filter-item', function() {
... | {
wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap');
wrap.on({
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseover.cbp': function() {
wrap.addClass('cbp-l-filters-dropdownWrap-open');
},
'http://htmlst... | conditional_block |
cube-portfolio-2-ns.js | (function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridC... | cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
/*********************************
add listener for filters
*********************************/
if (filtersContainer.hasClass('cbp-l-filters-dropdown')) {
... | cols: 2
}, {
width: 320,
| random_line_split |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable... | return angle;
};
PosePredictor.prototype.getAxisAngularSpeedFromRotationRate_ = function(rotationRate) {
if (!rotationRate) {
return null;
}
var screenRotationRate;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
// iOS: angular speed in deg/s.
var screenRotationRate = this.getScreenAdjustedRot... | angle -= 2 * Math.PI;
}
| conditional_block |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable... |
PosePredictor.prototype.setScreenOrientation = function(screenOrientation) {
this.screenOrientation = screenOrientation;
};
PosePredictor.prototype.getAxis_ = function(quat) {
// x = qx / sqrt(1-qw*qw)
// y = qy / sqrt(1-qw*qw)
// z = qz / sqrt(1-qw*qw)
var d = Math.sqrt(1 - quat.w * quat.w);
return new T... | random_line_split | |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable... | () {
this.lastQ = new THREE.Quaternion();
this.lastTimestamp = null;
this.outQ = new THREE.Quaternion();
this.deltaQ = new THREE.Quaternion();
}
PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) {
// If there's no previous quaternion, output the current one and save for
/... | PosePredictor | identifier_name |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable... |
PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) {
// If there's no previous quaternion, output the current one and save for
// later.
if (!this.lastTimestamp) {
this.lastQ.copy(currentQ);
this.lastTimestamp = timestamp;
return currentQ;
}
// DEBUG ONLY: Try w... | {
this.lastQ = new THREE.Quaternion();
this.lastTimestamp = null;
this.outQ = new THREE.Quaternion();
this.deltaQ = new THREE.Quaternion();
} | identifier_body |
mod.rs | // Copyright (C) 2020 Sebastian DrΓΆge <sebastian@centricular.com>
//
// 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... | // the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
} | // Registers the type for our element, and then registers in GStreamer under | random_line_split |
mod.rs | // Copyright (C) 2020 Sebastian DrΓΆge <sebastian@centricular.com>
//
// 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... | plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
}
| egister( | identifier_name |
mod.rs | // Copyright (C) 2020 Sebastian DrΓΆge <sebastian@centricular.com>
//
// 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... |
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
}
| identifier_body | |
driver.py | #! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes the test cases from the answers/question_name file
and executes each test case. The output of each execution
will be compared and the program outputs a binary string.
Eg : 1110111 mea... | print s | s+="1"
else:
s+="0"
| random_line_split |
driver.py | #! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes the test cases from the answers/question_name file
and executes each test case. The output of each execution
will be compared and the program outputs a binary string.
Eg : 1110111 mea... |
else:
s+="0"
else:
if cases[number_of_cases+i] == solution.answer(cases[i]):
s+="1"
else:
s+="0"
print s
| s+="1" | conditional_block |
tests.py | from django.test import TestCase
from finance.models import Banking_Account |
def test_iban_converter(self):
"""BBAN to IBAN conversion"""
self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE34091000277790')
self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE48679200550227')
self.assertEqual(Banking_Account.i... |
class IBANTestCase(TestCase):
def setUp(self):
pass | random_line_split |
tests.py | from django.test import TestCase
from finance.models import Banking_Account
class IBANTestCase(TestCase):
| def setUp(self):
pass
def test_iban_converter(self):
"""BBAN to IBAN conversion"""
self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE34091000277790')
self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE48679200550227')
self... | identifier_body | |
tests.py | from django.test import TestCase
from finance.models import Banking_Account
class | (TestCase):
def setUp(self):
pass
def test_iban_converter(self):
"""BBAN to IBAN conversion"""
self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE34091000277790')
self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE4867920055022... | IBANTestCase | identifier_name |
makeDummyReport.js | /*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http:... |
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps[bucketSize];
return {
fromDate: startDate.format(DATE_FORMAT),
toDate: endDate.format(DATE_FOR... | {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
} | identifier_body |
makeDummyReport.js | /*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http:... | }
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps[bucketSize];
return {
fromDate: startDate.format(DATE_FORMAT),
toDate: endDate.format(DATE_FO... | return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); | random_line_split |
makeDummyReport.js | /*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http:... | (start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps... | randomDate | identifier_name |
logger.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v11.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c ... | var context_1 = require("./context/context");
var context_2 = require("./context/context");
var LoggerFactory = (function () {
function LoggerFactory() {
}
LoggerFactory.prototype.setBeans = function (gridOptionsWrapper) {
this.logging = gridOptionsWrapper.isDebug();
};
LoggerFactory.prototy... | var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); | random_line_split |
logger.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v11.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c ... | () {
}
LoggerFactory.prototype.setBeans = function (gridOptionsWrapper) {
this.logging = gridOptionsWrapper.isDebug();
};
LoggerFactory.prototype.create = function (name) {
return new Logger(name, this.isLogging.bind(this));
};
LoggerFactory.prototype.isLogging = function () {
... | LoggerFactory | identifier_name |
logger.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v11.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c ... |
Logger.prototype.isLogging = function () {
return this.isLoggingFunc();
};
Logger.prototype.log = function (message) {
if (this.isLoggingFunc()) {
console.log('ag-Grid.' + this.name + ': ' + message);
}
};
return Logger;
}());
exports.Logger = Logger;
| {
this.name = name;
this.isLoggingFunc = isLoggingFunc;
} | identifier_body |
EQSANSFlatTestAPIv2.py | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,attribute-defined-ou... | def requiredFiles(self):
files = []
files.append(FILE_LOCATION+"EQSANS_5704_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5734_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5732_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5738_event.nxs")
files.append(FILE_LOCATION+"... | identifier_body | |
EQSANSFlatTestAPIv2.py | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,attribute-defined-ou... | mtd['EQSANS_5729_event_frame1_Iq'].dataY(0)[1] = 856.30028119108
def validate(self):
self.tolerance = 5.0
self.disableChecking.append('Instrument')
self.disableChecking.append('Sample')
self.disableChecking.append('SpectraMap')
self.disableChecking.append('Axes')
... | SetAbsoluteScale(277.781)
Reduce1D()
# This reference is old, ignore the first non-zero point and
# give the comparison a reasonable tolerance (less than 0.5%). | random_line_split |
EQSANSFlatTestAPIv2.py | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,attribute-defined-ou... | (self):
self.tolerance = 5.0
self.disableChecking.append('Instrument')
self.disableChecking.append('Sample')
self.disableChecking.append('SpectraMap')
self.disableChecking.append('Axes')
return "EQSANS_5729_event_frame1_Iq", 'EQSANSFlatTest.nxs'
| validate | identifier_name |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
def _show_resource(self):
return self.client().show_qos_policy(
self.resource_id)['policy']
class QoSRule(neutron.NeutronResource):
"""A resource for Neutron QoS base rule."""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPER... | self.prepare_update_properties(prop_diff)
self.client().update_qos_policy(
self.resource_id,
{'policy': prop_diff}) | conditional_block |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | (self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.client().update_bandwidth_limit_rule(
self.resource_id,
self.policy_id,
{'bandwidth_limit_rule': prop_diff})
def _show_resource(self):
return self.client().show_bandwidth_limit... | handle_update | identifier_name |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
def resource_mapping():
return {
'OS::Neutron::QoSPolicy': QoSPolicy,
'OS::Neutron::QoSBandwidthLimitRule': QoSBandwidthLimitRule
}
| """A resource for Neutron QoS bandwidth limit rule.
This rule can be associated with QoS policy, and then the policy
can be used by neutron port and network, to provide bandwidth limit
QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
PROPE... | identifier_body |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | properties.Schema.BOOLEAN,
_('Whether this QoS policy should be shared to other tenants.'),
default=False,
update_allowed=True
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this QoS policy.')
... | ),
SHARED: properties.Schema( | random_line_split |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return thi... |
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
{
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
}
function keyupcode(el, keyCode) {
... | {
oEvent.initKeyEvent("keypress", true, true, document.defaultView, false, false, false, false, k, 0);
} | conditional_block |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return thi... | (el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el.dispatchEvent ? el.... | keyupcode | identifier_name |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return thi... | oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
{
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
}
function keyupcode(el, keyCode) {
v... | random_line_split | |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return thi... |
function keyupcode(el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el... | {
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
} | identifier_body |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... |
else:
return PyRegion.setParameter(self, name, index, value)
###############################################################################
def reset(self):
pass
###############################################################################
def compute(self, inputs, outputs):
"""
Pr... | self.inferenceMode = bool(int(value)) | conditional_block |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... |
###############################################################################
def clear(self):
self._claClassifier.clear()
###############################################################################
def getParameter(self, name, index=-1):
"""
Get the value of the parameter.
@param nam... | pass | identifier_body |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | (self):
pass
###############################################################################
def initialize(self, dims, splitterMaps):
pass
###############################################################################
def clear(self):
self._claClassifier.clear()
###########################... | _initEphemerals | identifier_name |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | @param value -- the value to which the parameter is to be set.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
self.inferenceMode = bool(int(value))
else:
return PyRegion.setParameter(self, name, index, value)
##################... |
@param name -- the name of the parameter to update, as defined
by the Node Spec. | random_line_split |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = ... |
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"b... | {
x = x[5..].trim().to_string();
} | conditional_block |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String |
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_too... | {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().t... | identifier_body |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = ... | \"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect... | pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\", | random_line_split |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn | ()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5.... | rustc_version | identifier_name |
mod.rs | use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
... | ///
///
///
impl Generate<()> for HtmlState {
fn generate(
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.gen... | random_line_split | |
mod.rs |
use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
... | (
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create ... | generate | identifier_name |
mod.rs |
use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
... |
}
| {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
} | identifier_body |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(self):
self.ensure_one() | included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.produc... | invoice = self.move_id | random_line_split |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def | (self):
self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_context(round=False).compute_all(
... | _l10n_ar_prices_and_taxes | identifier_name |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(self):
self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered(... |
else:
price_unit = included_taxes.compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)['total_included']
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
price_subtotal = included_taxes.compute_all(
... | price_unit = self.tax_ids.with_context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)
price_unit = price_unit['total_excluded']
price_subtotal = self.price_subtotal | conditional_block |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(self):
| self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_context(round=False).compute_all(
self.... | identifier_body | |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVer... | this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to add local storage event listener. ${e}`
}
)
}
}
private _resetStorage() {
localStorage.clear();
localStorage.setItem(this._apiVersionKey,... | random_line_split | |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVer... |
// Ensures that saving tab state should only happen per-session
localStorage.removeItem(LocalStorageKeys.siteTabs);
}
getItem(key: string): StorageItem {
return JSON.parse(localStorage.getItem(key));
}
addtoSavedSubsKey(sub: string) {
let savedSubs = <StoredSubscripti... | {
this._resetStorage();
} | conditional_block |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVer... | () {
localStorage.clear();
localStorage.setItem(this._apiVersionKey, this._apiVersion);
}
} | _resetStorage | identifier_name |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVer... |
addtoSavedSubsKey(sub: string) {
let savedSubs = <StoredSubscriptions>this.getItem(LocalStorageKeys.savedSubsKey);
if (!savedSubs) {
savedSubs = <StoredSubscriptions>{
id: LocalStorageKeys.savedSubsKey,
subscriptions: []
};
}
... | {
return JSON.parse(localStorage.getItem(key));
} | identifier_body |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# ... | (log):
# Set puppet to automatically start
if os.path.exists('/etc/default/puppet'):
util.subp(['sed', '-i',
'-e', 's/^START=.*/START=yes/',
'/etc/default/puppet'], capture=False)
elif os.path.exists('/bin/systemctl'):
util.subp(['/bin/systemctl', 'enable'... | _autostart_puppet | identifier_name |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# ... |
elif install:
log.debug(("Attempting to install puppet %s,"),
version if version else 'latest')
cloud.distro.install_packages(('puppet', version))
# ... and then update the puppet configuration
if 'conf' in puppet_cfg:
# Add all sections from the conf object to p... | log.warn(("Puppet install set false but version supplied,"
" doing nothing.")) | conditional_block |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# ... | if 'puppet' not in cfg:
log.debug(("Skipping module named %s,"
" no 'puppet' configuration found"), name)
return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package if necessary...
install = util.get_cfg_option_bool(puppet_cfg, 'install', True)
versio... | identifier_body | |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# ... | # Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False) | util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
| random_line_split |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER... |
def matrix_2_vector(
matrix: np.ndarray,
convention: OrientationConvention = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""Convert 4x4 matrix to a vector."""
# call function
try:
return globals()[f"_matrix_2_{convention.name.lower()}"](matrix)
except KeyError: # pragma: no cov... | """Get the position values from a 4x4 transform matrix."""
return matrix[:-1, -1] | identifier_body |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER... | """Generate a basic 4x4 rotation matrix about the Y axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_z(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about... | return matrix
def rotation_matrix_y(angle: float) -> np.ndarray: | random_line_split |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER... |
else:
b = np.arctan2(sb, cb)
sa = matrix[1, 0] / cb
ca = matrix[0, 0] / cb
a = np.arctan2(sa, ca)
sc = matrix[2, 1] / cb
cc = matrix[2, 2] / cb
c = np.arctan2(sc, cc)
vector = np.hstack((matrix[:-1, -1], [a, b, c]))
return vector
def wrap_2_pi(an... | a = 0.0
b = np.sign(sb) * np.pi / 2
sc = matrix[0, 1]
cc = matrix[1, 1]
c = np.sign(sb) * np.arctan2(sc, cc) | conditional_block |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER... | (angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Z axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def translation_matrix(xyz: Sequence[float]) -> np.ndarray:
"""Gen... | rotation_matrix_z | identifier_name |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) =... | assert chebyshevt(1, x) == x
assert chebyshevt(2, x) == 2*x**2-1
assert chebyshevt(3, x) == 4*x**3-3*x
for n in range(1, 4):
for k in range(n):
z = chebyshevt_root(n, k)
assert chebyshevt(n, z) == 0
for n in range(1, 4):
for k in range(n):
z = cheb... | random_line_split | |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) =... |
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x + (alpha+2)*(alpha+1)/2).expand()
assert laguerre_l(3, alpha, ... | assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120 | identifier_body |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) =... |
def test_hermite():
assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x*... | for k in range(n):
z = chebyshevu_root(n, k)
assert chebyshevu(n, z) == 0 | conditional_block |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) =... | ():
assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x... | test_hermite | identifier_name |
test_nice.py | from os import environ
from uwsgiconf.presets.nice import Section, PythonSection
def test_nice_section(assert_lines):
assert_lines([
'env = LANG=en_US.UTF-8',
'workers = %k',
'die-on-term = true',
'vacuum = true',
'threads = 4',
], Section(threads=4))
assert_lin... | def test_nice_python(assert_lines):
assert_lines([
'plugin = python',
'pyhome = /home/idle/venv/\npythonpath = /home/idle/apps/',
'wsgi = somepackage.module',
'need-app = true',
], PythonSection(
params_python=dict(
# We'll run our app using virtualenv.
... | 'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
], section)
| random_line_split |
test_nice.py | from os import environ
from uwsgiconf.presets.nice import Section, PythonSection
def test_nice_section(assert_lines):
assert_lines([
'env = LANG=en_US.UTF-8',
'workers = %k',
'die-on-term = true',
'vacuum = true',
'threads = 4',
], Section(threads=4))
assert_lin... | (assert_lines):
path = Section.get_bundled_static_path('503.html')
assert path.endswith('uwsgiconf/contrib/django/uwsgify/static/uwsgify/503.html')
def test_configure_https_redirect(assert_lines):
section = Section()
section.configure_https_redirect()
assert_lines(
'route-if-not = eq:${H... | test_get_bundled_static_path | identifier_name |
test_nice.py | from os import environ
from uwsgiconf.presets.nice import Section, PythonSection
def test_nice_section(assert_lines):
assert_lines([
'env = LANG=en_US.UTF-8',
'workers = %k',
'die-on-term = true',
'vacuum = true',
'threads = 4',
], Section(threads=4))
assert_lin... |
def test_nice_python(assert_lines):
assert_lines([
'plugin = python',
'pyhome = /home/idle/venv/\npythonpath = /home/idle/apps/',
'wsgi = somepackage.module',
'need-app = true',
], PythonSection(
params_python=dict(
# We'll run our app using virtualenv.
... | monkeypatch.setattr('pathlib.Path.exists', lambda self: True)
section = Section()
section.configure_certbot_https('mydomain.org', '/var/www/', address=':4443')
assert_lines([
'static-map2 = /.well-known/=/var/www/',
'https-socket = :4443,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
... | identifier_body |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn | () {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, im... | main | identifier_name |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() | {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_s... | identifier_body | |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}... | let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
let _ =... | let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
| random_line_split |
requestState.ts | import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store'; |
export function requestStateReducer(
state: RequestState = INITIAL_STATE.requestState,
action:
typeof actions.startRequesting.shape |
typeof actions.endRequesting.shape |
typeof actions.requestFailure.shape |
typeof actions.clearErrors.shape
): RequestState {
switch (action.type) {
case actio... | import { INITIAL_STATE } from './initialState'; | random_line_split |
requestState.ts | import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store';
import { INITIAL_STATE } from './initialState';
export function requestStateReducer(
state: RequestState = INITIAL_STATE.requestState,
action:
typeof actions.startRequesting.shape |
typeof actions.endRequesting.s... | {
switch (action.type) {
case actions.startRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: true
}
};
}
case actions.endRequesting.type: {
return {
...state,
requesting: {
...s... | identifier_body | |
requestState.ts | import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store';
import { INITIAL_STATE } from './initialState';
export function | (
state: RequestState = INITIAL_STATE.requestState,
action:
typeof actions.startRequesting.shape |
typeof actions.endRequesting.shape |
typeof actions.requestFailure.shape |
typeof actions.clearErrors.shape
): RequestState {
switch (action.type) {
case actions.startRequesting.type: {
ret... | requestStateReducer | identifier_name |
stringFormat.ts | import {
camelCase, capitalize, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, padEnd, padStart,
snakeCase, startCase, truncate, unescape, upperCase, upperFirst
} from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';
/**
* String format pipe, uses lodash string transform method... |
}
| {
switch (method) {
case 'camelCase':
return camelCase(value);
case 'capitalize':
return capitalize(value);
case 'deburr':
return deburr(value);
case 'escape':
return escape(value);
case 'escapeRegExp':
return escapeRegExp(value);
case 'keb... | identifier_body |
stringFormat.ts | import {
camelCase, capitalize, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, padEnd, padStart,
snakeCase, startCase, truncate, unescape, upperCase, upperFirst
} from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';
/**
* String format pipe, uses lodash string transform method... | (value: any, method: string, ...args: Array<any>): string {
switch (method) {
case 'camelCase':
return camelCase(value);
case 'capitalize':
return capitalize(value);
case 'deburr':
return deburr(value);
case 'escape':
return escape(value);
case 'escapeRe... | transform | identifier_name |
stringFormat.ts | import {
camelCase, capitalize, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, padEnd, padStart,
snakeCase, startCase, truncate, unescape, upperCase, upperFirst
} from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';
/**
* String format pipe, uses lodash string transform method... | } | random_line_split | |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
} |
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.