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
gulpfile.js
var gulp = require('gulp'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var stylus = require('gulp-stylus'); var rename = require("gulp-rename"); var uglify = require("gulp-uglify"); var cssmin = require("gulp-cssmin"); var ngAnnotate = require('gulp-ng-a...
(devOnly) { var streams = []; ['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) { streams.push(compileCss(name, devOnly)); }); return merge.apply(null, streams); } gulp.task('default', function() { return merge.apply(compileJs(), compileAllCss()); }); gulp.task('_watc...
compileAllCss
identifier_name
gulpfile.js
var gulp = require('gulp'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var stylus = require('gulp-stylus'); var rename = require("gulp-rename"); var uglify = require("gulp-uglify"); var cssmin = require("gulp-cssmin"); var ngAnnotate = require('gulp-ng-a...
if (!devOnly) { stream = stream.pipe(cssmin()) .pipe(rename('angular-' + name + '.min.css')) .pipe(gulp.dest('dist')); } return stream; } function compileAllCss(devOnly) { var streams = []; ['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) { streams.push(compile...
random_line_split
gulpfile.js
var gulp = require('gulp'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var stylus = require('gulp-stylus'); var rename = require("gulp-rename"); var uglify = require("gulp-uglify"); var cssmin = require("gulp-cssmin"); var ngAnnotate = require('gulp-ng-a...
function compileAllCss(devOnly) { var streams = []; ['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) { streams.push(compileCss(name, devOnly)); }); return merge.apply(null, streams); } gulp.task('default', function() { return merge.apply(compileJs(), compileAllCss()...
{ var stream = gulp.src('styles/' + name + '.styl') .pipe(stylus({use: nib()})) .pipe(rename('angular-' + name + '.css')) .pipe(gulp.dest('dist')) ; if (!devOnly) { stream = stream.pipe(cssmin()) .pipe(rename('angular-' + name + '.min.css')) .pipe(gulp.dest('dist')); } return stream; }
identifier_body
gulpfile.js
var gulp = require('gulp'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var stylus = require('gulp-stylus'); var rename = require("gulp-rename"); var uglify = require("gulp-uglify"); var cssmin = require("gulp-cssmin"); var ngAnnotate = require('gulp-ng-a...
return stream; } function compileAllCss(devOnly) { var streams = []; ['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) { streams.push(compileCss(name, devOnly)); }); return merge.apply(null, streams); } gulp.task('default', function() { return merge.apply(compileJs...
{ stream = stream.pipe(cssmin()) .pipe(rename('angular-' + name + '.min.css')) .pipe(gulp.dest('dist')); }
conditional_block
category.component.ts
/** * Copyright 2021 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...
() {} ngOnInit(): void {} }
constructor
identifier_name
category.component.ts
/** * Copyright 2021 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...
* limitations under the License. */ import { Component, Input, OnInit } from '@angular/core'; import { CategoryDetails } from '../store.service'; @Component({ selector: 'app-category', templateUrl: './category.component.html', styleUrls: ['./category.component.scss'], }) export class CategoryComponent impleme...
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and
random_line_split
category.component.ts
/** * Copyright 2021 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...
}
{}
identifier_body
test_GLM2_syn_2659x1049.py
import unittest, time, sys sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i params = { 'response': 1049, 'family': 'binomial', 'beta_epsilon': 0.0001, 'alpha': 1.0, 'lambda': 1e-05, 'n_folds': 1, 'max_iter': 20, } class Basic(unittest.TestCase):...
(cls): h2o.tear_down_cloud() def test_GLM2_syn_2659x1049(self): csvFilename = "syn_2659x1049.csv" csvPathname = 'logreg' + '/' + csvFilename parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname, hex_key=csvFilename + ".hex", schema='put') kwargs = params ...
tearDownClass
identifier_name
test_GLM2_syn_2659x1049.py
import unittest, time, sys sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i params = { 'response': 1049, 'family': 'binomial', 'beta_epsilon': 0.0001, 'alpha': 1.0, 'lambda': 1e-05, 'n_folds': 1, 'max_iter': 20, } class Basic(unittest.TestCase):...
h2o.unit_main()
conditional_block
test_GLM2_syn_2659x1049.py
import unittest, time, sys sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i params = { 'response': 1049, 'family': 'binomial', 'beta_epsilon': 0.0001, 'alpha': 1.0, 'lambda': 1e-05, 'n_folds': 1, 'max_iter': 20, } class Basic(unittest.TestCase):...
if __name__ == '__main__': h2o.unit_main()
csvFilename = "syn_2659x1049x2enum.csv" csvPathname = 'logreg' + '/' + csvFilename parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname, hex_key=csvFilename + ".hex", schema='put') kwargs = params glm = h2o_cmd.runGLM(parseResult=parseResult, timeoutSecs=240, **kwargs) ...
identifier_body
test_GLM2_syn_2659x1049.py
import unittest, time, sys sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i params = { 'response': 1049, 'family': 'binomial', 'beta_epsilon': 0.0001, 'alpha': 1.0, 'lambda': 1e-05, 'n_folds': 1, 'max_iter': 20, } class Basic(unittest.TestCase):
@classmethod def setUpClass(cls): h2o.init(1) @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_GLM2_syn_2659x1049(self): csvFilename = "syn_2659x1049.csv" csvPathname = 'logreg' + '/' + csvFilename parseResult = h2i.import_parse(bucket='s...
def tearDown(self): h2o.check_sandbox_for_errors()
random_line_split
settings.py
""" Django settings for busquecursos project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, .....
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Stati...
# Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases
random_line_split
shootout-spectralnorm.rs
use core::from_str::FromStr; use core::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32 { (i+j) * (i+j+1) / 2 + i + 1 } fn dot(v: &[f64], u: &[f64]) -> f64 { let mut sum = 0.0; for v.eachi |i, &v_i| { sum += v_i * u[i]; } sum } fn mult_Av(v: &mut [f64], out: &mut [f64]) { ...
} println(fmt!("%.9f", f64::sqrt(dot(u,v) / dot(v,v)) as float)); }
for 8.times { mult_AtAv(u, v, tmp); mult_AtAv(v, u, tmp);
random_line_split
shootout-spectralnorm.rs
use core::from_str::FromStr; use core::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32 { (i+j) * (i+j+1) / 2 + i + 1 } fn dot(v: &[f64], u: &[f64]) -> f64 { let mut sum = 0.0; for v.eachi |i, &v_i| { sum += v_i * u[i]; } sum } fn mult_Av(v: &mut [f64], out: &mut [f64]) { ...
(v: &mut [f64], out: &mut [f64], tmp: &mut [f64]) { mult_Av(v, tmp); mult_Atv(tmp, out); } #[fixed_stack_segment] fn main() { let n: uint = FromStr::from_str(os::args()[1]).get(); let mut u = vec::from_elem(n, 1f64), v = u.clone(), tmp = u.clone(); for 8.times { mult_AtAv(u, v, tmp); ...
mult_AtAv
identifier_name
shootout-spectralnorm.rs
use core::from_str::FromStr; use core::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32
fn dot(v: &[f64], u: &[f64]) -> f64 { let mut sum = 0.0; for v.eachi |i, &v_i| { sum += v_i * u[i]; } sum } fn mult_Av(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(i ...
{ (i+j) * (i+j+1) / 2 + i + 1 }
identifier_body
withLatestFrom.d.ts
import { Observable, ObservableInput } from '../Observable'; /** * Combines the source Observable with other Observables to create an Observable * whose values are calculated from the latest values of each, only when the * source emits. * * <span class="informal">Whenever the source Observable emits a value, it
* `withLatestFrom` combines each value from the source Observable (the * instance) with the latest values from the other input Observables only when * the source emits a value, optionally using a `project` function to determine * the value to be emitted on the output Observable. All input Observables must * emit a...
* computes a formula using that value plus the latest values from other input * Observables, then emits the output of that formula.</span> * * <img src="./img/withLatestFrom.png" width="100%"> *
random_line_split
run_finetuning.py
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
from finetune import preprocessing from finetune import task_builder from model import modeling from model import optimization from util import training_utils from util import utils class FinetuningModel(object): """Finetuning model with support for multi-task training.""" def __init__(self, config: configure_fi...
import configure_finetuning
random_line_split
run_finetuning.py
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
else: utils.log("Skipping task", task.name, "- writing predictions is not supported for this task") if trial != config.num_trials and (not config.keep_all_models): utils.rmrf(config.model_dir) trial += 1 def main(): parser = argparse.ArgumentParser(descrip...
scorer = model_runner.evaluate_task(task, "test", False) scorer.write_predictions() preds = utils.load_json(config.qa_preds_file("squad")) null_odds = utils.load_json(config.qa_na_file("squad")) for q, _ in preds.items(): if null_odds[q] > config.qa_na_thres...
conditional_block
run_finetuning.py
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data-dir", required=True, help="Location of data files (model weights, etc).") parser.add_argument("--model-name", required=True, help="The name of the model being fine-tuned.") ...
"""Run finetuning.""" # Setup for training results = [] trial = 1 heading_info = "model={:}, trial {:}/{:}".format( config.model_name, trial, config.num_trials) heading = lambda msg: utils.heading(msg + ": " + heading_info) heading("Config") utils.log_config(config) generic_model_dir = config.mod...
identifier_body
run_finetuning.py
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
(self): return {task.name: self.evaluate_task(task) for task in self._tasks} def evaluate_task(self, task, split="dev", return_results=True): """Evaluate the current model.""" utils.log("Evaluating", task.name) eval_input_fn, _ = self._preprocessor.prepare_predict([task], split) results = self._e...
evaluate
identifier_name
tehgladiators.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Teh Gladiators" language = "en" url = "http://www.tehgladiators.com/" start_date = "2008-03-18" rights = "Uros Jojic & Borislav Grabovic" class...
history_capable_days = 90 schedule = "We" time_zone = "Europe/Belgrade" def crawl(self, pub_date): feed = self.parse_feed("http://www.tehgladiators.com/rss.xml") for entry in feed.for_date(pub_date): page = self.parse_page(entry.link) url = page.src('img[alt^="Teh Gl...
identifier_body
tehgladiators.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Teh Gladiators" language = "en" url = "http://www.tehgladiators.com/" start_date = "2008-03-18" rights = "Uros Jojic & Borislav Grabovic" class...
title = entry.title return CrawlerImage(url, title)
page = self.parse_page(entry.link) url = page.src('img[alt^="Teh Gladiators Webcomic"]')
random_line_split
tehgladiators.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Teh Gladiators" language = "en" url = "http://www.tehgladiators.com/" start_date = "2008-03-18" rights = "Uros Jojic & Borislav Grabovic" class...
page = self.parse_page(entry.link) url = page.src('img[alt^="Teh Gladiators Webcomic"]') title = entry.title return CrawlerImage(url, title)
conditional_block
tehgladiators.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class
(ComicDataBase): name = "Teh Gladiators" language = "en" url = "http://www.tehgladiators.com/" start_date = "2008-03-18" rights = "Uros Jojic & Borislav Grabovic" class Crawler(CrawlerBase): history_capable_days = 90 schedule = "We" time_zone = "Europe/Belgrade" def crawl(self, pu...
ComicData
identifier_name
request_proxy.rs
use std::io::Read; use std::net::SocketAddr; use conduit;
#[allow(missing_debug_implementations)] pub struct RequestProxy<'a> { pub other: &'a mut (Request + 'a), pub path: Option<&'a str>, pub method: Option<conduit::Method>, } impl<'a> Request for RequestProxy<'a> { fn http_version(&self) -> semver::Version { self.other.http_version() } fn c...
use conduit::Request; use semver; // Can't derive Debug because of Request.
random_line_split
request_proxy.rs
use std::io::Read; use std::net::SocketAddr; use conduit; use conduit::Request; use semver; // Can't derive Debug because of Request. #[allow(missing_debug_implementations)] pub struct RequestProxy<'a> { pub other: &'a mut (Request + 'a), pub path: Option<&'a str>, pub method: Option<conduit::Method>, } ...
fn host(&self) -> conduit::Host { self.other.host() } fn virtual_root(&self) -> Option<&str> { self.other.virtual_root() } fn path(&self) -> &str { self.path.map(|s| &*s).unwrap_or_else(|| self.other.path()) } fn query_string(&self) -> Option<&str> { self.oth...
{ self.other.scheme() }
identifier_body
request_proxy.rs
use std::io::Read; use std::net::SocketAddr; use conduit; use conduit::Request; use semver; // Can't derive Debug because of Request. #[allow(missing_debug_implementations)] pub struct RequestProxy<'a> { pub other: &'a mut (Request + 'a), pub path: Option<&'a str>, pub method: Option<conduit::Method>, } ...
(&self) -> Option<u64> { self.other.content_length() } fn headers(&self) -> &conduit::Headers { self.other.headers() } fn body(&mut self) -> &mut Read { self.other.body() } fn extensions(&self) -> &conduit::Extensions { self.other.extensions() } fn mut_ext...
content_length
identifier_name
ControlButton.js
import React from 'react' import {TouchableOpacity, Image} from 'react-native' import {ResponsiveStyleSheet} from 'react-native-responsive-stylesheet' import {resource} from '../utils/image'
return ( <TouchableOpacity onPress={onPress} style={[s.button, {backgroundColor}]} activeOpacity={0.8}> <Image source={resource(`icons/${type}.png`)} style={s.image} /> </TouchableOpacity> ) } const makeStyles = ResponsiveStyleSheet.create(({controlButtonSize}) => { const padding ...
export const ControlButton = ({onPress, type, backgroundColor}) => { const s = makeStyles()
random_line_split
zepto.js
/*! * CanJS - 1.1.4 (2013-02-05) * http://canjs.us/ * Copyright (c) 2013 Bitovi * Licensed MIT */ define(['can/util/can', 'zepto', 'can/util/object/isplain', 'can/util/event', 'can/util/fragment', 'can/util/deferred', 'can/util/array/each'], function (can) { var $ = Zepto; // data.js // --------- // _jQuery-like d...
(node, name, value) { var id = node[exp] || (node[exp] = ++uuid), store = data[id] || (data[id] = {}); if (name !== undefined) store[name] = value; return store; }; $.fn.data = function (name, value) { return value === undefined ? this.length == 0 ? undefined : getData(this[0], name) : this.each(function ...
setData
identifier_name
zepto.js
/*! * CanJS - 1.1.4 (2013-02-05) * http://canjs.us/ * Copyright (c) 2013 Bitovi * Licensed MIT */ define(['can/util/can', 'zepto', 'can/util/object/isplain', 'can/util/event', 'can/util/fragment', 'can/util/deferred', 'can/util/array/each'], function (can) { var $ = Zepto; // data.js // --------- // _jQuery-like d...
} // Make ajax. var XHR = $.ajaxSettings.xhr; $.ajaxSettings.xhr = function () { var xhr = XHR() var open = xhr.open; xhr.open = function (type, url, async) { open.call(this, type, url, ASYNC === undefined ? true : ASYNC) } return xhr; } var ASYNC; var AJAX = $.ajax; var updateDeferred = function ...
can.proxy = function (f, ctx) { return function () { return f.apply(ctx, arguments) }
random_line_split
zepto.js
/*! * CanJS - 1.1.4 (2013-02-05) * http://canjs.us/ * Copyright (c) 2013 Bitovi * Licensed MIT */ define(['can/util/can', 'zepto', 'can/util/object/isplain', 'can/util/event', 'can/util/fragment', 'can/util/deferred', 'can/util/array/each'], function (can) { var $ = Zepto; // data.js // --------- // _jQuery-like d...
} } can.ajax = function (options) { var success = options.success, error = options.error; var d = can.Deferred(); options.success = function (data) { updateDeferred(xhr, d); d.resolve.call(d, data); success && success.apply(this, arguments); } options.error = function () { updateDeferre...
{ d[prop] = prop[xhr] }
conditional_block
zepto.js
/*! * CanJS - 1.1.4 (2013-02-05) * http://canjs.us/ * Copyright (c) 2013 Bitovi * Licensed MIT */ define(['can/util/can', 'zepto', 'can/util/object/isplain', 'can/util/event', 'can/util/fragment', 'can/util/deferred', 'can/util/array/each'], function (can) { var $ = Zepto; // data.js // --------- // _jQuery-like d...
; $.fn.data = function (name, value) { return value === undefined ? this.length == 0 ? undefined : getData(this[0], name) : this.each(function (idx) { setData(this, name, $.isFunction(value) ? value.call(this, idx, getData(this, name)) : value); }); }; $.cleanData = function (elems) { for (var i = 0, elem;...
{ var id = node[exp] || (node[exp] = ++uuid), store = data[id] || (data[id] = {}); if (name !== undefined) store[name] = value; return store; }
identifier_body
auth.js
import * as Cookies from 'js-cookie'; import axios from 'axios'; import { route } from 'preact-router'; function storeUserCredentials({ user, accessToken, expires }) { Cookies.set('crendentials', { user, accessToken }, { expires: new Date(expires) }); } export function
() { return Cookies.getJSON('crendentials'); } export function isAuthenticated() { const crendentials = getUserCredentials(); return !(crendentials === null || crendentials === undefined); } export function onLogin(response) { storeUserCredentials(response); route('/', true); } export function logout() { ...
getUserCredentials
identifier_name
auth.js
import * as Cookies from 'js-cookie'; import axios from 'axios'; import { route } from 'preact-router'; function storeUserCredentials({ user, accessToken, expires }) { Cookies.set('crendentials', { user, accessToken }, { expires: new Date(expires) }); } export function getUserCredentials() { return Cookies.getJSO...
}); }
alert('User could not login'); console.error(error);
random_line_split
auth.js
import * as Cookies from 'js-cookie'; import axios from 'axios'; import { route } from 'preact-router'; function storeUserCredentials({ user, accessToken, expires }) { Cookies.set('crendentials', { user, accessToken }, { expires: new Date(expires) }); } export function getUserCredentials() { return Cookies.getJSO...
export function onLogin(response) { storeUserCredentials(response); route('/', true); } export function logout() { Cookies.remove('crendentials'); route('/login', true); } export function authenticate(params = {}) { axios .post(`/auth/${params.network}`, { access_token: params.access_token }) .the...
{ const crendentials = getUserCredentials(); return !(crendentials === null || crendentials === undefined); }
identifier_body
example_grid_time.py
#!/usr/bin/env python from datetime import timedelta import numpy as np from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift o = OceanDrift(loglevel=0) # Set loglevel to 0 for debug information reader_norkys...
# Running model (until end of driver data) o.run(steps=66*4, time_step=900) # Print and plot results print(o) o.animation()
o.seed_elements(lons, lats, radius=0, number=100, time=start_time + i*time_step)
random_line_split
example_grid_time.py
#!/usr/bin/env python from datetime import timedelta import numpy as np from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift o = OceanDrift(loglevel=0) # Set loglevel to 0 for debug information reader_norkys...
# Running model (until end of driver data) o.run(steps=66*4, time_step=900) # Print and plot results print(o) o.animation()
o.seed_elements(lons, lats, radius=0, number=100, time=start_time + i*time_step)
conditional_block
views.py
""" Views for PubSite app. """ from django.conf import settings from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.shortcuts import render import requests import logging logger = logging.getLogger(__name__...
View for 403 (Permission Denied) error. """ return render( request, "common/403.html", _get_context("Permission Denied"), ) def handler404(request, exception): """ """ return render(request, "common/404.html", _get_context("Page Not Found")) class ResetPassword(Passwo...
random_line_split
views.py
""" Views for PubSite app. """ from django.conf import settings from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.shortcuts import render import requests import logging logger = logging.getLogger(__name__...
except requests.exceptions.Timeout: logger.warning("Connection to GiveButter API Timed out") except requests.ConnectionError: logger.warning("Connection to GiveButter API could not be resolved") except requests.exceptions.RequestException: logger.error( "An unknown issue...
logger.error(f"ERROR in request: {r.status_code}")
conditional_block
views.py
""" Views for PubSite app. """ from django.conf import settings from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.shortcuts import render import requests import logging logger = logging.getLogger(__name__...
(request): """ View for the static chapter service page. """ return render( request, "public/activities.html", _get_context("Service & Activities"), ) def rush(request): """ View for the static chapter service page. """ return render( request, ...
activities
identifier_name
views.py
""" Views for PubSite app. """ from django.conf import settings from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.shortcuts import render import requests import logging logger = logging.getLogger(__name__...
class ResetPasswordConfirm(PasswordResetConfirmView): template_name = "password_reset/password_reset_confirm.html" class ResetPasswordComplete(PasswordResetCompleteView): template_name = "password_reset/password_reset_complete.html"
template_name = "password_reset/password_reset_done.html"
identifier_body
main.rs
// Task : Guess number game // Date : 10 Sept 2016 // Author : Vigneshwer extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main()
{ println!("Guess the Number game!"); let secret_number = rand::thread_rng().gen_range(1,101); // println!("You secret number is {}", secret_number); loop { println!("Enter the number in your mind"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Fa...
identifier_body
main.rs
// Task : Guess number game // Date : 10 Sept 2016 // Author : Vigneshwer extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn
() { println!("Guess the Number game!"); let secret_number = rand::thread_rng().gen_range(1,101); // println!("You secret number is {}", secret_number); loop { println!("Enter the number in your mind"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect(...
main
identifier_name
main.rs
// Task : Guess number game
use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the Number game!"); let secret_number = rand::thread_rng().gen_range(1,101); // println!("You secret number is {}", secret_number); loop { println!("Enter the number in your mind"); let mut guess = Strin...
// Date : 10 Sept 2016 // Author : Vigneshwer extern crate rand;
random_line_split
propeditor.py
#!/usr/bin/python # -*- coding: utf-8 -*- "Visual Property Editor (using wx PropertyGrid) of gui2py's components" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2013- Mariano Reingart" __license__ = "LGPL 3.0" # some parts where inspired or borrowed from wxFormBuilders & wxPython...
def OnDeleteProperty(self, event): p = self.pg.GetSelectedProperty() if p: self.pg.DeleteProperty(p) else: wx.MessageBox("First select a property to delete") def OnReserved(self, event): pass def OnPropGridRightClick(self, event): p = event...
p = event.GetProperty() if p: self.log.write(u'%s selected\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing selected\n')
identifier_body
propeditor.py
#!/usr/bin/python # -*- coding: utf-8 -*- "Visual Property Editor (using wx PropertyGrid) of gui2py's components" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2013- Mariano Reingart" __license__ = "LGPL 3.0" # some parts where inspired or borrowed from wxFormBuilders & wxPython...
(self, event): p = self.pg.GetSelectedProperty() if p: self.pg.DeleteProperty(p) else: wx.MessageBox("First select a property to delete") def OnReserved(self, event): pass def OnPropGridRightClick(self, event): p = event.GetProperty() if ...
OnDeleteProperty
identifier_name
propeditor.py
#!/usr/bin/python # -*- coding: utf-8 -*- "Visual Property Editor (using wx PropertyGrid) of gui2py's components" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2013- Mariano Reingart" __license__ = "LGPL 3.0" # some parts where inspired or borrowed from wxFormBuilders & wxPython...
w.load_object(o) f.Show() app.MainLoop()
random_line_split
propeditor.py
#!/usr/bin/python # -*- coding: utf-8 -*- "Visual Property Editor (using wx PropertyGrid) of gui2py's components" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2013- Mariano Reingart" __license__ = "LGPL 3.0" # some parts where inspired or borrowed from wxFormBuilders & wxPython...
if p: name = p.GetName() spec = p.GetPyClientData() if spec and 'enum' in spec.type: value = p.GetValueAsString() else: value = p.GetValue() #self.log.write(u'%s changed to "%s"\n' % (p,p.GetValueAsString())) ...
print "change!", p
conditional_block
updateWeight.js
/** * @file js for changing weights of terms with Up and Down arrows */ (function ($) { //object to store weights (tid => weight) var termWeightsData = new Object(); Drupal.behaviors.TaxonomyManagerWeights = { attach: function(context, settings) { var weightSettings = settings.updateWeight || []; if (!$(...
* return array of selected terms */ Drupal.getSelectedTerms = function() { var terms = new Array(); $('.treeview').find("input:checked").each(function() { var term = $(this).parents("li").eq(0); terms.push(term); }); return terms; } /** * reorders terms * - swap list elements in DOM * - post ...
} /**
random_line_split
updateWeight.js
/** * @file js for changing weights of terms with Up and Down arrows */ (function ($) { //object to store weights (tid => weight) var termWeightsData = new Object(); Drupal.behaviors.TaxonomyManagerWeights = { attach: function(context, settings) { var weightSettings = settings.updateWeight || []; if (!$...
return weight; } })(jQuery);
{ weight = $(li).find("input:hidden[class=weight-form]").attr("value"); }
conditional_block
text_run.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform,...
} } pub type TextRunDataHandle = intern::Handle<TextRun>; #[derive(Debug, MallocSizeOf)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct TextRun { pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyph...
{ request.push(ColorF::from(self.font.color).premultiplied()); // this is the only case where we need to provide plain color to GPU let bg_color = ColorF::from(self.font.bg_color); request.push([bg_color.r, bg_color.g, bg_color.b, 1.0]); let mut gpu_block = [...
conditional_block
text_run.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform,...
request.push(ColorF::from(self.font.color).premultiplied()); // this is the only case where we need to provide plain color to GPU let bg_color = ColorF::from(self.font.bg_color); request.push([bg_color.r, bg_color.g, bg_color.b, 1.0]); let mut gpu_block = [0....
frame_state: &mut FrameBuildingState, ) { // corresponds to `fetch_glyph` in the shaders if let Some(mut request) = frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle) {
random_line_split
text_run.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform,...
pub fn request_resources( &mut self, prim_offset: LayoutVector2D, specified_font: &FontInstance, glyphs: &[GlyphInstance], transform: &LayoutToWorldTransform, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, allow_subpixel: bool, ...
{ let prim_spatial_node = spatial_tree.get_spatial_node(prim_spatial_node_index); if prim_spatial_node.is_ancestor_or_self_zooming { if low_quality_pinch_zoom { // In low-quality mode, we set the scale to be 1.0. However, the device-pixel // scale selected for...
identifier_body
text_run.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform,...
(&self) -> &Self::Target { &self.common } } impl ops::DerefMut for TextRunTemplate { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.common } } impl From<TextRunKey> for TextRunTemplate { fn from(item: TextRunKey) -> Self { let common = PrimTemplateCommonData::with_key...
deref
identifier_name
GridTooltips.js
/** * @author Mike Hill * @version 1.0.0 (2014/09/30) * * This plugin attaches tooltips to grid cells. */ Ext.define('Ext.ux.GridTooltips.grid.plugin.GridTooltips', { extend: 'Ext.plugin.Abstract', alias: 'plugin.gridtooltips', /* * Internal */ tooltipEl: null, /* * Configura...
if (showTooltip === true) { // Set tooltip contents to the target's text tooltip.update(target.innerText); } return showTooltip; }, /** * Deconstructs objects created by this plugin. */ destroy: function () { var me; me = this; ...
{ // Show tooltip only if the target's contents are overflowing /* * TODO: (Tested in Chrome 37) When clientWidth is equal to the * minimum scrollWidth, CSS text-overflow: ellipsis will still * display an ellipsis. * * For example,...
conditional_block
GridTooltips.js
/** * @author Mike Hill * @version 1.0.0 (2014/09/30) * * This plugin attaches tooltips to grid cells. */ Ext.define('Ext.ux.GridTooltips.grid.plugin.GridTooltips', { extend: 'Ext.plugin.Abstract', alias: 'plugin.gridtooltips', /* * Internal */ tooltipEl: null, /* * Configura...
}); }, /** * Creates the configured tooltip which will be used for the grid. */ createTooltip: function (grid) { var me; var tooltip; me = this; tooltip = Ext.create('Ext.tip.ToolTip', { target: grid.view.getEl(), delegate: me.del...
* Initializes the tooltips plugin. */ init: function (grid) { grid.mon(grid, 'afterrender', this.createTooltip, this, { single: true
random_line_split
test_triangularbarkbands.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
""" def testNotEnoughSpectrumBins(self): self.assertConfigureFails(TriangularBarkBands(), {'numberBands': 256, 'inputSize': 1025}) """ suite = allTests(TestTriangularBarkBands) if __name__ == '__main_...
spec = [.1,.4,.5,.2,.1,.01,.04]*100 np.savetxt("out.csv", TriangularBarkBands(inputSize=1024, sampleRate=10, highFrequencyBound=4)(spec), delimiter=',') self.assertAlmostEqualVector( TriangularBarkBands(inputSize=1024, sampleRate=10, highFrequencyBound=4)(spec), [0.0460...
identifier_body
test_triangularbarkbands.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
TextTestRunner(verbosity=2).run(suite)
conditional_block
test_triangularbarkbands.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
(self): # This test makes sure that even though the inputSize given at # configure time does not match the input spectrum, the algorithm does # not crash and correctly resizes internal structures to avoid errors. spec = [.1,.4,.5,.2,.1,.01,.04]*100 np.savetxt("out.csv", Triangul...
testWrongInputSize
identifier_name
test_triangularbarkbands.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
self.assertAlmostEqualVector( np.mean(np.log(pool['TriangularBarkBands']),0), expected,1e-2) def testZero(self): # Inputting zeros should return zero. Try with different sizes size = 1024 while (size >= 256 ): self.assertEqualVector(TriangularBarkBands()(zeros(size...
np.savetxt("out.csv", np.mean(np.log(pool['TriangularBarkBands']),0), delimiter=',')
random_line_split
keyboard.rs
use serde::Deserialize; use smithay::wayland::seat::Keysym; pub use smithay::{ backend::input::KeyState, wayland::seat::{keysyms as KeySyms, ModifiersState as KeyModifiers}, }; use xkbcommon::xkb; #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub enum KeyModifier { Ctrl, Alt, Shift, Logo,...
(Vec<KeyModifier>); impl From<KeyModifiersDef> for KeyModifiers { fn from(src: KeyModifiersDef) -> Self { src.0.into_iter().fold( KeyModifiers { ctrl: false, alt: false, shift: false, caps_lock: false, logo: false, ...
KeyModifiersDef
identifier_name
keyboard.rs
use serde::Deserialize; use smithay::wayland::seat::Keysym; pub use smithay::{ backend::input::KeyState, wayland::seat::{keysyms as KeySyms, ModifiersState as KeyModifiers}, }; use xkbcommon::xkb; #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub enum KeyModifier { Ctrl, Alt, Shift, Logo,...
match xkb::keysym_from_name(&name, xkb::KEYSYM_NO_FLAGS) { KeySyms::KEY_NoSymbol => match xkb::keysym_from_name(&name, xkb::KEYSYM_CASE_INSENSITIVE) { KeySyms::KEY_NoSymbol => Err(<D::Error as Error>::invalid_value( Unexpected::Str(&name), &"One of the keysym name...
use serde::de::{Error, Unexpected}; let name = String::deserialize(deserializer)?; //let name = format!("KEY_{}", code);
random_line_split
customImageSearchAPIClient.d.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ i...
* @param {string} [baseUri] - The base URI of the service. * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline * * @param {object} [options.requestOptions] - Options for the underlying request object * {@link ht...
* @param {credentials} credentials - Subscription credentials which uniquely identify client subscription. *
random_line_split
customImageSearchAPIClient.d.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ i...
extends ServiceClient { /** * @class * Initializes a new instance of the CustomImageSearchAPIClient class. * @constructor * * @param {credentials} credentials - Subscription credentials which uniquely identify client subscription. * * @param {string} [baseUri] - The base URI of the service. *...
CustomImageSearchAPIClient
identifier_name
check_tftp.py
# Copyright 2014 Huawei Technologies Co. Ltd # # 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...
return True def check_tftp_service(self): """Checks if TFTP is running on port 69.""" print "Checking TFTP services......", serv_err_msg = health_check_utils.check_service_running(self.NAME, 'xinetd') if not s...
self._set_status( 0, "[%s]Error: No tftp-boot libraries found, " "please check if tftp server is properly " "installed/managed" % self.NAME)
conditional_block
check_tftp.py
# Copyright 2014 Huawei Technologies Co. Ltd # # 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...
same machine where this health check runs at """ try: remote = xmlrpclib.Server( self.config.COBBLER_INSTALLER_URL, allow_none=True) remote.login( *self.config.COBBLER_INSTALLER_TOKEN) except Exception: ...
:note: we assume TFTP service is running at the
random_line_split
check_tftp.py
# Copyright 2014 Huawei Technologies Co. Ltd # # 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...
"""tftp health check class.""" NAME = "TFTP Check" def run(self): """do health check.""" installer = self.config.OS_INSTALLER method_name = "self.check_" + installer + "_tftp()" return eval(method_name) def check_cobbler_tftp(self): """Checks if Cobbler manages TFTP...
identifier_body
check_tftp.py
# Copyright 2014 Huawei Technologies Co. Ltd # # 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...
(self): """Checks if TFTP is running on port 69.""" print "Checking TFTP services......", serv_err_msg = health_check_utils.check_service_running(self.NAME, 'xinetd') if not serv_err_msg == "": self._set_status(0...
check_tftp_service
identifier_name
players-list.component.ts
import { Component, OnInit } from '@angular/core'; import { Player } from './player'; import { PlayerService } from './player.service'; import { PlayerSailsService } from './player.sails.service'; import { PlayerJSONService } from './player.json.service';
}) export class PlayersListComponent implements OnInit { players: Player[]; selectedPlayer: Player; isAddingPlayer: boolean; constructor( private playerService: PlayerService, private playerSailsService: PlayerSailsService, private playerJSONService: PlayerJSONService ) { } getPlayers(): voi...
@Component({ selector: 'players-list', templateUrl: 'app/templates/players-list.html', styleUrls: ['app/stylesheets/css/players-list.css']
random_line_split
players-list.component.ts
import { Component, OnInit } from '@angular/core'; import { Player } from './player'; import { PlayerService } from './player.service'; import { PlayerSailsService } from './player.sails.service'; import { PlayerJSONService } from './player.json.service'; @Component({ selector: 'players-list', templateUrl: 'app/te...
this.playerService.create(firstName, lastName) .then(player => { this.players.push(player); this.selectedPlayer = null; this.add(); }); } add() { this.isAddingPlayer = !this.isAddingPlayer; } delete(player: Player): void { this.playerService ....
{ this.add(); return; }
conditional_block
players-list.component.ts
import { Component, OnInit } from '@angular/core'; import { Player } from './player'; import { PlayerService } from './player.service'; import { PlayerSailsService } from './player.sails.service'; import { PlayerJSONService } from './player.json.service'; @Component({ selector: 'players-list', templateUrl: 'app/te...
(): void { this.playerService.getPlayers().then((players) => { this.players = players; }); } create(firstName: string, lastName: string): void { firstName = firstName.trim(); lastName = lastName.trim(); if (!firstName || !lastName) { this.add(); return; } this.p...
getPlayers
identifier_name
players-list.component.ts
import { Component, OnInit } from '@angular/core'; import { Player } from './player'; import { PlayerService } from './player.service'; import { PlayerSailsService } from './player.sails.service'; import { PlayerJSONService } from './player.json.service'; @Component({ selector: 'players-list', templateUrl: 'app/te...
ngOnInit(): void { this.getPlayers(); this.isAddingPlayer = false; } onSelect(player: Player): void { this.selectedPlayer = player; } }
{ this.playerService .delete(player.id) .then(() => { this.getPlayers(); }); }
identifier_body
test_ucs_inventory_v2.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Cisco Systems, 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....
assert(0) def _test_get_all_ucms(self, cmd): """Runs tests for commands that expect a list of all UCMS""" LOG.debug("test_%s - START", cmd) results = getattr(self._ucs_inventory, cmd)([]) self.assertEqual(results[const.DEVICE_IP], self.inventory.keys()) LOG.debug("t...
assert(1) return
conditional_block
test_ucs_inventory_v2.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Cisco Systems, 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....
(self, cmd): """Runs tests for commands that expect a list of all UCMS""" LOG.debug("test_%s - START", cmd) results = getattr(self._ucs_inventory, cmd)([]) self.assertEqual(results[const.DEVICE_IP], self.inventory.keys()) LOG.debug("test_%s - END", cmd) def _test_with_port_c...
_test_get_all_ucms
identifier_name
test_ucs_inventory_v2.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Cisco Systems, 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....
def test_get_all_ports(self): """Test that the UCS Inventory returns the correct devices to use""" self._test_get_all_ucms('get_all_ports')
"""Test that the UCS Inventory returns the correct devices to use""" self._test_get_all_ucms('update_network')
random_line_split
test_ucs_inventory_v2.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Cisco Systems, 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....
""" Tests for the UCS Inventory. Each high-level operation should return some information about which devices to perform the action on. """ def setUp(self): """Setup our tests""" cdb.initialize() creds.Store.initialize() # Create the ucs inventory object self....
identifier_body
index.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import './index.scss' import React, { Component } from 'react' // import { Grid, Col, Row } from 'react-bootstrap'; export default class IndexPage extends Component { ...
() { return ( <div className="top-page"> <div> <img className="top-image" src="/cover2.jpg" width="100%" alt="cover image" /> </div> <div className="top-page--footer"> The source code of this website is avail...
render
identifier_name
index.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import './index.scss' import React, { Component } from 'react' // import { Grid, Col, Row } from 'react-bootstrap'; export default class IndexPage extends Component { ...
}
</div> ) }
random_line_split
combaseapi.rs
// Copyright © 2016 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modi...
ppMalloc: *mut LPMALLOC ) -> HRESULT} STRUCT!{struct ServerInformation { dwServerPid: DWORD, dwServerTid: DWORD, ui64ServerAddress: UINT64, }} pub type PServerInformation = *mut ServerInformation; DECLARE_HANDLE!(CO_MTA_USAGE_COOKIE, CO_MTA_USAGE_COOKIE__);
dwMemContext: DWORD,
random_line_split
interface.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Observable, SubscribableOrPromise } from 'rxjs'; import { JsonArray, JsonObject, JsonValue } from '../interf...
addFormat(format: SchemaFormat): void; addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void; usePromptProvider(provider: PromptProvider): void; /** * Add a transformation step before the validation of any Json. * @param {JsonVisitor} visitor The visitor to transf...
export interface SchemaRegistry { compile(schema: Object): Observable<SchemaValidator>; flatten(schema: JsonObject | string): Observable<JsonObject>;
random_line_split
utils.js
'use strict'; var path = require('path'); var fileRe = require('filename-regex'); var win32 = process && process.platform === 'win32'; var utils = require('lazy-cache')(require); /** * Temporarily re-assign require to trick browserify * into recognizing lazy-cached deps. */ var fn = require; require = utils; /**...
if (opts && opts.unescape === true) { return fp ? fp.toString().replace(/\\(\w)/g, '$1') : ''; } return fp; }; /** * Escape/unescape utils */ utils.escapePath = function escapePath(fp) { return fp.replace(/[\\.]/g, '\\$&'); }; utils.unescapeGlob = function unescapeGlob(fp) { return fp.replace(/[\\"'...
{ return utils.normalize(fp, false); }
conditional_block
utils.js
'use strict'; var path = require('path'); var fileRe = require('filename-regex'); var win32 = process && process.platform === 'win32'; var utils = require('lazy-cache')(require); /** * Temporarily re-assign require to trick browserify * into recognizing lazy-cached deps. */ var fn = require;
/** * Lazily required module dependencies */ require('arr-diff', 'diff'); require('array-unique', 'unique'); require('braces'); require('expand-brackets', 'brackets'); require('extglob'); require('is-extglob'); require('is-glob', 'isGlob'); require('kind-of', 'typeOf'); require('normalize-path', 'normalize'); requi...
require = utils;
random_line_split
SWIM.py
import unittest import random from pygraph.classes.graph import graph class SWIM(object): def __init__(self, graph): self.graph = graph def edge_alive(self, nodeA, nodeB, alive): ''' edge_alive(A, B, True|False) ''' edge = (nodeA, nodeB) if alive: s...
def test_good_ping(self): swim = self.swim self.assertTrue(swim.ping(0, 1, 0)) self.assertTrue(swim.ping(1, 3, 0)) def test_dead_edge_ping(self): swim = self.swim swim.edge_alive(0, 1, False) self.assertFalse(swim.ping(0, 1, 0)) self.assertTrue(swim.pin...
g = graph() g.add_nodes(xrange(10)) g.complete() self.graph = g self.swim = SWIM(g)
identifier_body
SWIM.py
import unittest import random from pygraph.classes.graph import graph class
(object): def __init__(self, graph): self.graph = graph def edge_alive(self, nodeA, nodeB, alive): ''' edge_alive(A, B, True|False) ''' edge = (nodeA, nodeB) if alive: self.graph.add_edge(edge) else: self.graph.del_edge(edge) ...
SWIM
identifier_name
SWIM.py
import unittest import random from pygraph.classes.graph import graph class SWIM(object): def __init__(self, graph): self.graph = graph def edge_alive(self, nodeA, nodeB, alive): ''' edge_alive(A, B, True|False) ''' edge = (nodeA, nodeB) if alive: s...
# All pings have failed return False def _random_neighbors(self, node, b): neighbors = self.graph.neighbors(node) if len(neighbors) <= b: return neighbors else: return random.sample(neighbors, b) class SWIMTest(unittest.TestCase): def setUp(sel...
return True
conditional_block
SWIM.py
import unittest import random from pygraph.classes.graph import graph class SWIM(object): def __init__(self, graph): self.graph = graph def edge_alive(self, nodeA, nodeB, alive): ''' edge_alive(A, B, True|False) ''' edge = (nodeA, nodeB) if alive: s...
def _random_neighbors(self, node, b): neighbors = self.graph.neighbors(node) if len(neighbors) <= b: return neighbors else: return random.sample(neighbors, b) class SWIMTest(unittest.TestCase): def setUp(self): g = graph() g.add_nodes(xrange(10)...
for neighbor in self._random_neighbors(nodeStart, k): if self.ping(neighbor, nodeEnd, 0): return True # All pings have failed return False
random_line_split
runTest.py
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
try: os.chdir(outputDir) success = diskpy.pychanga.changa_run(runcmd, log_file='changa.out',\ return_success=True) finally: os.chdir(cwd) if success: print "Success! Test results saved to:" print outputDir return s...
json.dump(arguments, open(runparname, 'w'), indent=4, sort_keys=True) # Run ChaNGa cwd = os.getcwd()
random_line_split
runTest.py
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
(directory, nproc=None, copydir=None): """ builds ChaNGa in directory. nproc can be set optionally for multicore building. Defaults to n_cpu-1 Can also copy the built binaries (ChaNGa and charmrun) to a directory copydir """ if nproc is None: nproc = max([cpu_count()...
buildChanga
identifier_name
runTest.py
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
def shellRun(cmd, verbose=True, logfile=None, returnStdOut=False, env=None): """ Try to run the basic shell command (can only run command + opts, no piping) """ output = subprocess.PIPE p = subprocess.Popen(cmd.split(), stderr=subprocess.STDOUT, stdout=output, env=env)...
""" A small wrapper for distutils.dir_util.copy_tree. See that for documentation There is a bug in copy_tree where if you copy a tree, delete it, then try to copy it again it will fail. """ dir_util._path_created = {} return dir_util.copy_tree(src, dst, **kwargs)
identifier_body
runTest.py
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
configureChanga(changaDir, configOpts, charm_dir, verbose) buildChanga(changaDir, nproc, outputDir) finally: os.chdir(cwd) return outputDir def _copy_w_permissions(src, dest): from subprocess import Popen p = Popen(['cp','-p','--preserve',src,dest]) p.wai...
shutil.copyfile(src, dest)
conditional_block
test_stock_change_qty_reason.py
# pylint: disable=import-error,protected-access,too-few-public-methods # Copyright 2016-2017 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import SavepointCase class TestStockQuantityChangeReason(SavepointCase)...
inventory.preset_reason_id = self._create_reason("Test 1", "Description Test 1") inventory.action_start() self.assertEqual(len(inventory.line_ids), 1) inventory.reason = "Reason 2" inventory.onchange_reason() self.assertEqual(inventory.line_ids.reason, inventory.reason) ...
)
random_line_split
test_stock_change_qty_reason.py
# pylint: disable=import-error,protected-access,too-few-public-methods # Copyright 2016-2017 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import SavepointCase class
(SavepointCase): @classmethod def setUpClass(cls): super(TestStockQuantityChangeReason, cls).setUpClass() # MODELS cls.stock_move = cls.env["stock.move"] cls.product_product_model = cls.env["product.product"] cls.product_category_model = cls.env["product.category"] ...
TestStockQuantityChangeReason
identifier_name
test_stock_change_qty_reason.py
# pylint: disable=import-error,protected-access,too-few-public-methods # Copyright 2016-2017 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import SavepointCase class TestStockQuantityChangeReason(SavepointCase)...
"""Check that adding a reason or a preset reason explode to lines""" product2 = self._create_product("product_product_2") self._product_change_qty(product2, 50) inventory = self.env["stock.inventory"].create( { "name": "remove product2", "product_ids":...
identifier_body
youtube_apiSpec.js
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas is distribut...
const mock = sinon.mock(link).expects('text').withArgs(vidTitle) ytApi.titleYouTubeText(link) mock.verify() }) test('titleYouTubeText increments the failure count on failure', () => { sinon.stub(ytApi, 'fetchYouTubeTitle').callsArgWith(1, null, {responseText: 'error'}) const mock = sinon.mock(link).expects('...
test('titleYouTubeText changes the text of a link to match the title', () => { sinon.stub(ytApi, 'fetchYouTubeTitle').callsArgWith(1, vidTitle)
random_line_split
youtube_apiSpec.js
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas is distribut...
}) test('titleYouTubeText changes the text of a link to match the title', () => { sinon.stub(ytApi, 'fetchYouTubeTitle').callsArgWith(1, vidTitle) const mock = sinon.mock(link).expects('text').withArgs(vidTitle) ytApi.titleYouTubeText(link) mock.verify() }) test('titleYouTubeText increments the failure count...
{ $.youTubeID = undefined }
identifier_body
youtube_apiSpec.js
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas is distribut...
() { $.youTubeID = () => {return videoId} ytApi = new YouTubeApi() }, teardown () { $.youTubeID = undefined } }) test('titleYouTubeText changes the text of a link to match the title', () => { sinon.stub(ytApi, 'fetchYouTubeTitle').callsArgWith(1, vidTitle) const mock = sinon.mock(link).expects('...
setup
identifier_name
dataid.py
""" Module defining DataID as enumeration, e.g. concentration, velocity. class Enum allows accessing members by .name and .value FunctionID is deprecated and will be removed """ from enum import IntEnum, auto # Schema for metadata DataSchema = { "type": "object", "properties": { "Type": {"type": "strin...
""" This class represents the supported values of IDs of property, field, etc. Values of members should be stored by .name, .value should not be used. """ # # # # # # # # # # # # # # # # # # # # # # Field FID_Displacement = auto() FID_Strain = auto() FID_Stress = auto() FID_Temper...
identifier_body
dataid.py
""" Module defining DataID as enumeration, e.g. concentration, velocity. class Enum allows accessing members by .name and .value FunctionID is deprecated and will be removed """ from enum import IntEnum, auto # Schema for metadata DataSchema = { "type": "object", "properties": { "Type": {"type": "strin...
(IntEnum): """ This class represents the supported values of IDs of property, field, etc. Values of members should be stored by .name, .value should not be used. """ # # # # # # # # # # # # # # # # # # # # # # Field FID_Displacement = auto() FID_Strain = auto() FID_Stress = auto()...
DataID
identifier_name
dataid.py
""" Module defining DataID as enumeration, e.g. concentration, velocity. class Enum allows accessing members by .name and .value FunctionID is deprecated and will be removed """ from enum import IntEnum, auto # Schema for metadata DataSchema = { "type": "object", "properties": { "Type": {"type": "strin...
# Misc ID_None = auto() ID_GrainState = auto() ID_InputFile = auto() # # # # # # # # # # # # # # # # # # # # # # Property PID_Concentration = auto() PID_CumulativeConcentration = auto() PID_Velocity = auto() PID_transient_simulation_time = auto() PID_effective_conductivi...
FuncID_ProbabilityDistribution = auto() # # # # # # # # # # # # # # # # # # # # #
random_line_split
test_guest_vlan_range.py
""" P1 tests for Dedicating Guest Vlan Ranges """ # Import Local Modules from marvin.cloudstackAPI import * from marvin.cloudstackTestCase import * from marvin.lib.base import * from marvin.lib.common import * from marvin.lib.utils import * from nose.plugins.attrib import attr class TestDedicateGuestVlanRange(cloudst...
@classmethod def tearDownClass(cls): try: # Cleanup resources used removeGuestVlanRangeResponse = \ cls.physical_network.update(cls.apiclient, id=cls.physical_network.id, vla...
testClient = super(TestDedicateGuestVlanRange, cls).getClsTestClient() cls.apiclient = testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() # Get Zone, Domain cls.domain = get_domain(cls.apiclient) cls.zone = get_zone(cls.apiclient, testClient.getZoneFor...
identifier_body