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
angular-locale_en-vg.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function
(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide....
getDecimals
identifier_name
angular-locale_en-vg.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_pre...
var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday...
{ v = Math.min(getDecimals(n), 3); }
conditional_block
angular-locale_en-vg.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n)
function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], ...
{ n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; }
identifier_body
angular-locale_en-vg.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_pre...
"AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "Septemb...
random_line_split
git_unittest.py
# Copyright (c) 2013 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. """Unit tests for chromite.lib.git and helpers for testing that module.""" from __future__ import print_function import functools import mock import...
(cros_test_lib.TestCase): """Tests for git.ProjectCheckout""" def setUp(self): self.fake_unversioned_patchable = git.ProjectCheckout( dict(name='chromite', path='src/chromite', revision='remotes/for/master')) self.fake_unversioned_unpatchable = git.ProjectCheckout( ...
ProjectCheckoutTest
identifier_name
git_unittest.py
# Copyright (c) 2013 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. """Unit tests for chromite.lib.git and helpers for testing that module.""" from __future__ import print_function import functools import mock import...
"""Non fast-forward push error propagates to the caller.""" with cros_build_lib_unittest.RunCommandMock() as rc_mock: rc_mock.AddCmdResult(partial_mock.In('push'), returncode=128, error=self.NON_FF_PUSH_ERROR) self.assertRaises(cros_build_lib.RunCommandError, self._RunGitP...
def testNonFFPush(self):
random_line_split
git_unittest.py
# Copyright (c) 2013 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. """Unit tests for chromite.lib.git and helpers for testing that module.""" from __future__ import print_function import functools import mock import...
class NormalizeRefTest(cros_test_lib.TestCase): """Test the Normalize*Ref functions.""" def _TestNormalize(self, functor, tests): """Helper function for testing Normalize*Ref functions. Args: functor: Normalize*Ref functor that only needs the input ref argument. tests: Dict of test ...
"""Partial mock for git.ManifestCheckout.""" TARGET = 'chromite.lib.git.ManifestCheckout' ATTRS = ('_GetManifestsBranch',) def _GetManifestsBranch(self, _root): return 'default'
identifier_body
git_unittest.py
# Copyright (c) 2013 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. """Unit tests for chromite.lib.git and helpers for testing that module.""" from __future__ import print_function import functools import mock import...
class GitBranchDetectionTest(patch_unittest.GitRepoPatchTestCase): """Tests that git library functions related to branch detection work.""" def testDoesCommitExistInRepoWithAmbiguousBranchName(self): git1 = self._MakeRepo('git1', self.source) git.CreateBranch(git1, 'peach', track=True) self.CommitFi...
with cros_build_lib_unittest.RunCommandMock() as rc_mock: results = [ rc_mock.CmdResult(128, '', error), rc_mock.CmdResult(0, 'success', ''), ] # pylint: disable=cell-var-from-loop side_effect = lambda *_args, **_kwargs: results.pop(0) rc_mock.AddCmdResult...
conditional_block
build.py
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # blog.py - maps requests to methods and handles them accordingly. # Copyright (C) 2017 Jose Ricardo Ziviani # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwa...
def update_folder(): ''' Updates local repository ''' print 'Updating folders' run_command('git pull') # -- # ENTRY POINT # -- if __name__ == '__main__': update_folder() create_feeds()
''' Creates the feed.xml file based on the published posts available ''' print 'Creating feeds' tmpls = templates() if not tmpls.generate_metadata(): print 'ERROR: cannot create feed.xml' sys.exit(1)
identifier_body
build.py
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # blog.py - maps requests to methods and handles them accordingly. # Copyright (C) 2017 Jose Ricardo Ziviani # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwa...
''' proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if err: print err #sys.exit(1) return out def create_feeds(): ''' Creates the feed.xml file based on the published posts available...
# -- def run_command(cmd): ''' Runs arbitrary command on shell
random_line_split
build.py
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # blog.py - maps requests to methods and handles them accordingly. # Copyright (C) 2017 Jose Ricardo Ziviani # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwa...
return out def create_feeds(): ''' Creates the feed.xml file based on the published posts available ''' print 'Creating feeds' tmpls = templates() if not tmpls.generate_metadata(): print 'ERROR: cannot create feed.xml' sys.exit(1) def update_folder(): ''' Updates ...
print err #sys.exit(1)
conditional_block
build.py
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # blog.py - maps requests to methods and handles them accordingly. # Copyright (C) 2017 Jose Ricardo Ziviani # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwa...
(): ''' Creates the feed.xml file based on the published posts available ''' print 'Creating feeds' tmpls = templates() if not tmpls.generate_metadata(): print 'ERROR: cannot create feed.xml' sys.exit(1) def update_folder(): ''' Updates local repository ''' print...
create_feeds
identifier_name
dispatcher.rs
use color_printer::ColorPrinter; use command::{Command, WorkResult, WorkType}; use std::{collections::BTreeMap, sync::mpsc::Receiver}; use threadpool::ThreadPool; const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work"; pub struct Dispatcher<'a> { queue: BTreeMap<usize, Option<Box<dyn WorkR...
} } } // Sanity check if !self.queue.is_empty() { panic!( "There are {} unprocessed items in the queue. \ Did you forget to send WorkEmpty::WorkEmpty messages?", self.queue.len() ); } ...
// If there are adjacent items in the queue, process them. self.process_queue();
random_line_split
dispatcher.rs
use color_printer::ColorPrinter; use command::{Command, WorkResult, WorkType}; use std::{collections::BTreeMap, sync::mpsc::Receiver}; use threadpool::ThreadPool; const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work"; pub struct Dispatcher<'a> { queue: BTreeMap<usize, Option<Box<dyn WorkR...
(&mut self, rx: &Receiver<WorkType>) { while let Ok(result) = rx.recv() { match result { WorkType::Repo { index, repo, tx } => { let worker = self.command.box_clone(); self.pool.execute(move || { let result = match worke...
run
identifier_name
dispatcher.rs
use color_printer::ColorPrinter; use command::{Command, WorkResult, WorkType}; use std::{collections::BTreeMap, sync::mpsc::Receiver}; use threadpool::ThreadPool; const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work"; pub struct Dispatcher<'a> { queue: BTreeMap<usize, Option<Box<dyn WorkR...
WorkType::WorkEmpty { index } => { if index == self.next_index { self.process_queue(); } else { self.queue.insert(index, None); } } WorkType::Work { index, result ...
{ let worker = self.command.box_clone(); self.pool.execute(move || { let result = match worker.process(repo) { Some(r) => WorkType::result(index, r), None => WorkType::empty(index), ...
conditional_block
dispatcher.rs
use color_printer::ColorPrinter; use command::{Command, WorkResult, WorkType}; use std::{collections::BTreeMap, sync::mpsc::Receiver}; use threadpool::ThreadPool; const THREAD_SIGNAL: &str = "Could not signal main thread with WorkType::Work"; pub struct Dispatcher<'a> { queue: BTreeMap<usize, Option<Box<dyn WorkR...
}
{ self.next_index += 1; while let Some(result) = self.queue.remove(&self.next_index) { if let Some(work_result) = result { work_result.print(&mut self.printer); } self.next_index += 1; } }
identifier_body
file-drop.ts
import { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import FilePlugin, { DEFAULT_STORE_NAME, FileService } from '../../utils/file/file'; import { ModulVue } from '../../utils/vue/vue'; import { FILE_DROP_NAME } from '../directive-names'; interface MFileDropElement extends HTMLElement { cl...
( el: MFileDropElement, binding: VNodeDirective, vnode: VNode, oldVnode: VNode ): void { el.cleanupMFileDropDirective(); const $file: FileService = (vnode.context as ModulVue).$file; if (!(binding as any).modifiers['keep-store']) { $file.destroy( ...
unbind
identifier_name
file-drop.ts
import { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import FilePlugin, { DEFAULT_STORE_NAME, FileService } from '../../utils/file/file'; import { ModulVue } from '../../utils/vue/vue'; import { FILE_DROP_NAME } from '../directive-names'; interface MFileDropElement extends HTMLElement { cl...
} }; const FileDropPlugin: PluginObject<any> = { install(v, options): void { v.use(FilePlugin); v.directive(FILE_DROP_NAME, MFileDropDirective); } }; export default FileDropPlugin;
{ $file.destroy( binding.value ? binding.value : DEFAULT_STORE_NAME ); }
conditional_block
file-drop.ts
import { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import FilePlugin, { DEFAULT_STORE_NAME, FileService } from '../../utils/file/file'; import { ModulVue } from '../../utils/vue/vue'; import { FILE_DROP_NAME } from '../directive-names'; interface MFileDropElement extends HTMLElement { cl...
, unbind( el: MFileDropElement, binding: VNodeDirective, vnode: VNode, oldVnode: VNode ): void { el.cleanupMFileDropDirective(); const $file: FileService = (vnode.context as ModulVue).$file; if (!(binding as any).modifiers['keep-store']) { $fil...
{ const $file: FileService = (vnode.context as ModulVue).$file; const onDragEnterOver: (e: DragEvent) => void = (e: DragEvent) => { el.classList.add('m--is-drag-over'); e.stopPropagation(); e.preventDefault(); }; const onDragLeave: (e: DragEvent) => ...
identifier_body
file-drop.ts
import { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import FilePlugin, { DEFAULT_STORE_NAME, FileService } from '../../utils/file/file'; import { ModulVue } from '../../utils/vue/vue'; import { FILE_DROP_NAME } from '../directive-names'; interface MFileDropElement extends HTMLElement { cl...
const FileDropPlugin: PluginObject<any> = { install(v, options): void { v.use(FilePlugin); v.directive(FILE_DROP_NAME, MFileDropDirective); } }; export default FileDropPlugin;
} } };
random_line_split
services.js
const https = require('https') const cookie = require('cookie'); var exports = module.exports = {} exports.getResponseHeaders = function(httpOptions, formData) { if (formData) { httpOptions.headers = formData.getHeaders() } return new Promise((resolve, reject) => { const request = https.request(httpOp...
// temporary data holder const body = []; // on every content chunk, push it to the data array response.on('data', () => {}); // we are done, resolve promise with those joined chunks response.on('end', () => resolve(response.headers)); }); // handle connection errors of the ...
{ reject(new Error('Failed to load page, status code: ' + response.statusCode)); }
conditional_block
services.js
const https = require('https') const cookie = require('cookie'); var exports = module.exports = {} exports.getResponseHeaders = function(httpOptions, formData) { if (formData) { httpOptions.headers = formData.getHeaders() } return new Promise((resolve, reject) => { const request = https.request(httpOp...
return cookies }
random_line_split
models.py
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError import datetime # Create your models here. class Article(models.Model): title = models.CharField(max_length=255) brief = models.CharField(null=True,blank=True,max_length=255) category...
egory(models.Model): name = models.CharField(max_length=64,unique=True) brief = models.CharField(null=True,blank=True,max_length=255) set_as_top_menu = models.BooleanField(default=False) position_index = models.SmallIntegerField() admins = models.ManyToManyField("UserProfile",blank=True) def __s...
self): return "C:%s" %(self.comment) class Cat
conditional_block
models.py
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError import datetime # Create your models here. class Article(models.Model): title = models.CharField(max_length=255) brief = models.CharField(null=True,blank=True,max_length=255) category...
name =models.CharField(max_length=32) signature= models.CharField(max_length=255,blank=True,null=True) head_img = models.ImageField(height_field=150,width_field=150,blank=True,null=True) def __str__(self): return self.name
OneField(User)
identifier_body
models.py
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError import datetime # Create your models here. class
(models.Model): title = models.CharField(max_length=255) brief = models.CharField(null=True,blank=True,max_length=255) category = models.ForeignKey("Category") content = models.TextField(u"文章内容") author = models.ForeignKey("UserProfile") pub_date = models.DateTimeField(blank=True,null=True) ...
Article
identifier_name
models.py
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError import datetime # Create your models here. class Article(models.Model): title = models.CharField(max_length=255) brief = models.CharField(null=True,blank=True,max_length=255) category ...
status_choices = (('draft',u"草稿"), ('published',u"已发布"), ('hidden',u"隐藏"), ) status = models.CharField(choices=status_choices,default='published',max_length=32) def __str__(self): return self.title def clean(self): # Don'...
priority = models.IntegerField(u"优先级",default=1000) head_img = models.ImageField(u"文章标题图片",upload_to="uploads")
random_line_split
OverlayComponent.tsx
import React from "react"; import formatDate from "date-fns/esm/format"; import isFinite from "lodash/isFinite"; import DatumManager from "./DatumManager"; function renderWeather(weather: any)
export default class OverlayComponent extends React.Component { private clockUpdateTimer?: number; public UNSAFE_componentWillMount() { this.clockUpdateTimer = window.setInterval(() => { this.forceUpdate(); }, 5000); } public componentWillUnmount() { clearInterval(...
{ if (!weather) { return null; } let temperature; let icon; try { temperature = weather.main.temp - 273.15; } catch (problem) { temperature = null; } try { icon = weather.weather[0].icon; icon = <img src={`http://openweathermap.org/img/w/${icon}.pn...
identifier_body
OverlayComponent.tsx
import React from "react"; import formatDate from "date-fns/esm/format"; import isFinite from "lodash/isFinite"; import DatumManager from "./DatumManager";
function renderWeather(weather: any) { if (!weather) { return null; } let temperature; let icon; try { temperature = weather.main.temp - 273.15; } catch (problem) { temperature = null; } try { icon = weather.weather[0].icon; icon = <img src={`http...
random_line_split
OverlayComponent.tsx
import React from "react"; import formatDate from "date-fns/esm/format"; import isFinite from "lodash/isFinite"; import DatumManager from "./DatumManager"; function
(weather: any) { if (!weather) { return null; } let temperature; let icon; try { temperature = weather.main.temp - 273.15; } catch (problem) { temperature = null; } try { icon = weather.weather[0].icon; icon = <img src={`http://openweathermap.org/i...
renderWeather
identifier_name
OverlayComponent.tsx
import React from "react"; import formatDate from "date-fns/esm/format"; import isFinite from "lodash/isFinite"; import DatumManager from "./DatumManager"; function renderWeather(weather: any) { if (!weather)
let temperature; let icon; try { temperature = weather.main.temp - 273.15; } catch (problem) { temperature = null; } try { icon = weather.weather[0].icon; icon = <img src={`http://openweathermap.org/img/w/${icon}.png`} alt="weather icon" />; } catch (problem)...
{ return null; }
conditional_block
install-esxi-spec.js
// Copyright 2016, EMC, Inc. /* jshint node: true */ 'use strict'; describe(require('path').basename(__filename), function() { var schemaFileName = 'install-esxi.json'; var canonical = { "osType": "esx", "profile": "install-esx.ipxe", "installScript": "esx-ks", "installScriptU...
"gateway": "192.168.1.1", "netmask": "255.255.255.0", "vlanIds": [ 104, 105 ] }, "ipv6": { "ipAddr": "fec0::6ab4:0:5efe:157.60.14.21", ...
"ipAddr": "192.168.1.29",
random_line_split
modal-native.esm.js
/*! * Native JavaScript for Bootstrap Modal v3.0.15-alpha2 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ var addEventListener = 'addEventListener'; var removeEventListener = 'removeEventLis...
e) { if (modal.isAnimating) { return; } var clickTarget = e.target; var hasData = clickTarget.getAttribute('data-dismiss') === 'modal'; var parentWithData = clickTarget.closest('[data-dismiss="modal"]'); if (modal.classList.contains('show') && (parentWithData || hasData || (clickTarget === ...
ismissHandler(
identifier_name
modal-native.esm.js
/*! * Native JavaScript for Bootstrap Modal v3.0.15-alpha2 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ var addEventListener = 'addEventListener'; var removeEventListener = 'removeEventLis...
/* Native JavaScript for Bootstrap 4 | Modal -------------------------------------------- */ // MODAL DEFINITION // ================ function Modal(elem, opsInput) { // element can be the modal/triggering button var element; // set options var options = opsInput || {}; // bind, modal var self = this; v...
element.focus(); }
identifier_body
modal-native.esm.js
/*! * Native JavaScript for Bootstrap Modal v3.0.15-alpha2 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ var addEventListener = 'addEventListener'; var removeEventListener = 'removeEventLis...
// prevent adding event handlers over and over // modal is independent of a triggering element if (element && !element.Modal) { element.addEventListener('click', clickHandler, false); } if (ops.content) { self.setContent(ops.content.trim()); } // set associations if (element) { modal.moda...
random_line_split
modal-native.esm.js
/*! * Native JavaScript for Bootstrap Modal v3.0.15-alpha2 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ var addEventListener = 'addEventListener'; var removeEventListener = 'removeEventLis...
modal.classList.add('show'); modal.setAttribute('aria-hidden', false); if (modal.classList.contains('fade')) { emulateTransitionEnd(modal, triggerShow); } else { triggerShow(); } } function triggerShow() { setFocus(modal); modal.isAnimating = false; toggleEvents(1); shownCustomEv...
document.body.classList.add('modal-open'); }
conditional_block
badge.rs
use krate::Crate; use schema::badges; use diesel::pg::Pg; use diesel::prelude::*; use serde_json; use std::collections::HashMap; #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")] pub enum Badge { TravisCi { repository...
pub struct EncodableBadge { pub badge_type: String, pub attributes: HashMap<String, Option<String>>, } impl Queryable<badges::SqlType, Pg> for Badge { type Row = (i32, String, serde_json::Value); fn build((_, badge_type, attributes): Self::Row) -> Self { let json = json!({"badge_type": badge_t...
LookingForMaintainer, Deprecated, } #[derive(PartialEq, Debug, Serialize, Deserialize)]
random_line_split
badge.rs
use krate::Crate; use schema::badges; use diesel::pg::Pg; use diesel::prelude::*; use serde_json; use std::collections::HashMap; #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")] pub enum Badge { TravisCi { repository...
<'a>( conn: &PgConnection, krate: &Crate, badges: Option<&'a HashMap<String, HashMap<String, String>>>, ) -> QueryResult<Vec<&'a str>> { use diesel::{insert, delete}; #[derive(Insertable, Debug)] #[table_name = "badges"] struct NewBadge<'a> { crat...
update_crate
identifier_name
badge.rs
use krate::Crate; use schema::badges; use diesel::pg::Pg; use diesel::prelude::*; use serde_json; use std::collections::HashMap; #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case", tag = "badge_type", content = "attributes")] pub enum Badge { TravisCi { repository...
else { invalid_badges.push(&**k); } } } conn.transaction(|| { delete(badges::table.filter(badges::crate_id.eq(krate.id))) .execute(conn)?; insert(&new_badges).into(badges::table).execute(conn)?; Ok(inva...
{ new_badges.push(NewBadge { crate_id: krate.id, badge_type: &**k, attributes: attributes_json, }); }
conditional_block
bit_iterator.js
var test = require('tape'); var bitIterator = require('../lib/bit_iterator'); test('should return the correct bit pattern across byte boundaries', function(t) { t.plan(5); var bi = bitIterator(function() { return new Buffer([0x0f,0x10,0x01,0x80]); }); t.equal(bi(16), 0x0f10); t.equal(bi(7...
t.equal(bi(7), 0x0); t.equal(bi(2), 0x03); t.equal(bi(7), 0x0); t.equal(bi.bytesRead, 3); }); test('each iterator has an independent bytesRead property', function(t) { t.plan(6); var i = 0, ii = 0; var buffs = [[0x01],[0x80]]; var bi1 = bitIterator(function() { return buffs[i++...
});
random_line_split
transform-data.js
const fs = require('fs'); const jsesc = require('jsesc'); const template = require('lodash.template'); function format(object) { return jsesc(object, { json: true, compact: false, }) + '\n'; } function parse(source) { const indexByCodePoint = {}; const indexByPointer = {}; let decoded = ''; const encoded = ...
const pointer = Number(data[0]); const codePoint = Number(data[1]); const symbol = String.fromCodePoint(codePoint); decoded += symbol; encoded.push(pointer + 0x80); indexByCodePoint[codePoint] = pointer; indexByPointer[pointer] = symbol; } return { decoded: decoded, encoded: encoded, indexByCodeP...
{ continue; }
conditional_block
transform-data.js
const fs = require('fs'); const jsesc = require('jsesc'); const template = require('lodash.template'); function format(object) { return jsesc(object, { json: true, compact: false, }) + '\n'; } function parse(source) { const indexByCodePoint = {}; const indexByPointer = {}; let decoded = ''; const encoded = ...
// src/koi8-r.src.mjs → koi8-r.mjs const LIB_TEMPLATE = fs.readFileSync('./src/koi8-r.src.mjs', 'utf8'); const createLib = template(LIB_TEMPLATE, TEMPLATE_OPTIONS); const libCode = createLib(require('./export-data.js')); fs.writeFileSync('./koi8-r.mjs', libCode); // src/koi8-r.d.ts → koi8-r.d.ts const TYPES_TEMPLATE ...
fs.writeFileSync('./tests/tests.mjs', testCode);
random_line_split
transform-data.js
const fs = require('fs'); const jsesc = require('jsesc'); const template = require('lodash.template'); function format(object) { return jsesc(object, { json: true, compact: false, }) + '\n'; } function
(source) { const indexByCodePoint = {}; const indexByPointer = {}; let decoded = ''; const encoded = []; var lines = source.split('\n'); for (const line of lines) { const data = line.trim().split('\t'); if (data.length != 3) { continue; } const pointer = Number(data[0]); const codePoint = Number(data...
parse
identifier_name
transform-data.js
const fs = require('fs'); const jsesc = require('jsesc'); const template = require('lodash.template'); function format(object) { return jsesc(object, { json: true, compact: false, }) + '\n'; } function parse(source)
const source = fs.readFileSync('./data/index.txt', 'utf-8'); const result = parse(source); fs.writeFileSync( './data/index-by-code-point.json', format(result.indexByCodePoint) ); fs.writeFileSync( './data/index-by-pointer.json', format(result.indexByPointer) ); fs.writeFileSync( './data/decoded.json', format(re...
{ const indexByCodePoint = {}; const indexByPointer = {}; let decoded = ''; const encoded = []; var lines = source.split('\n'); for (const line of lines) { const data = line.trim().split('\t'); if (data.length != 3) { continue; } const pointer = Number(data[0]); const codePoint = Number(data[1]); c...
identifier_body
relations.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify ...
this.eraseByURI(uri); } } Zotero.DB.commitTransaction(); } } this.xmlToRelation = function (xml) { var relation = new Zotero.Relation; var libraryID = xml.@libraryID.toString(); if (libraryID) { relation.libraryID = parseInt(libraryID); } else { libraryID = Zotero.libraryID; if...
if (uri.indexOf(prefix) == -1) { continue; } if (!Zotero.URI.getURIItem(uri)) {
random_line_split
relations.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify ...
Zotero.DB.beginTransaction(); var sql = "UPDATE relations SET libraryID=? WHERE libraryID=?"; Zotero.DB.query(sql, [fromLibraryID, toLibraryID]); sql = "UPDATE relations SET " + "subject=REPLACE(subject, 'zotero.org/users/" + fromUserID + "', " + "'zotero.org/users/" + toUserID + "'), " + ...
throw ("Invalid target libraryID " + toLibraryID + " in Zotero.Relations.updateUserID"); }
conditional_block
relations.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify ...
}
var [prefix, value] = uri.split(':'); if (prefix && value) { if (!_namespaces[prefix]) { throw ("Invalid prefix '" + prefix + "' in Zotero.Relations._getPrefixAndValue()"); } return [prefix, value]; } for (var prefix in namespaces) { if (uri.indexOf(namespaces[prefix]) == 0) { var value ...
identifier_body
relations.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify ...
uri) { var [prefix, value] = uri.split(':'); if (prefix && value) { if (!_namespaces[prefix]) { throw ("Invalid prefix '" + prefix + "' in Zotero.Relations._getPrefixAndValue()"); } return [prefix, value]; } for (var prefix in namespaces) { if (uri.indexOf(namespaces[prefix]) == 0) { var ...
getPrefixAndValue(
identifier_name
torrentleech.py
# Author: Idan Gutman # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your o...
return results def seedRatio(self): return self.ratio class TorrentLeechCache(tvcache.TVCache): def __init__(self, provider): tvcache.TVCache.__init__(self, provider) # only poll TorrentLeech every 20 minutes max self.minTime = 20 def _getRSSData(self): ...
self.show = helpers.findCertainShow(sickbeard.showList, int(sqlshow["showid"])) if self.show: curEp = self.show.getEpisode(int(sqlshow["season"]), int(sqlshow["episode"])) searchString = self._get_episode_search_strings(curEp, add_string='PROPER|REPACK') for...
conditional_block
torrentleech.py
# Author: Idan Gutman # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your o...
self.ratio = None self.minseed = None self.minleech = None self.cache = TorrentLeechCache(self) self.urls = {'base_url': 'https://torrentleech.org/', 'login': 'https://torrentleech.org/user/account/login/', 'detail': 'https://torrentleech.org/tor...
random_line_split
torrentleech.py
# Author: Idan Gutman # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your o...
(self): search_params = {'RSS': ['']} return {'entries': self.provider._doSearch(search_params)} provider = TorrentLeechProvider()
_getRSSData
identifier_name
torrentleech.py
# Author: Idan Gutman # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your o...
def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0, epObj=None): results = [] items = {'Season': [], 'Episode': [], 'RSS': []} if not self._doLogin(): return results for mode in search_params.keys(): logger.log(u"Search Mode: %s" % ...
login_params = {'username': self.username, 'password': self.password, 'remember_me': 'on', 'login': 'submit', } response = self.getURL(self.urls['login'], post_data=login_params, timeout=30) if not response...
identifier_body
mock_location_strategy.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 {LocationStrategy} from '@angular/common'; import {EventEmitter, Injectable} from '@angular/core'; /** * ...
(public newUrl: string) {} }
constructor
identifier_name
mock_location_strategy.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 {LocationStrategy} from '@angular/common'; import {EventEmitter, Injectable} from '@angular/core'; /** * ...
} forward(): void { throw 'not implemented'; } } class _MockPopStateEvent { pop: boolean = true; type: string = 'popstate'; constructor(public newUrl: string) {} }
{ this.urlChanges.pop(); var nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); }
conditional_block
mock_location_strategy.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 {LocationStrategy} from '@angular/common'; import {EventEmitter, Injectable} from '@angular/core'; /** * ...
path(includeHash: boolean = false): string { return this.internalPath; } prepareExternalUrl(internal: string): string { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; } pu...
this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); }
random_line_split
cssrulelist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::...
(&self, index: u32) -> Option<Root<CSSRule>> { self.Item(index) } }
IndexedGetter
identifier_name
cssrulelist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::...
// In case of a keyframe rule, index must be valid. pub fn remove_rule(&self, index: u32) -> ErrorResult { let index = index as usize; match self.rules { RulesSource::Rules(ref css_rules) => { css_rules.write().remove_rule(index)?; let mut dom_rules...
{ let css_rules = if let RulesSource::Rules(ref rules) = self.rules { rules } else { panic!("Called insert_rule on non-CssRule-backed CSSRuleList"); }; let global = self.global(); let window = global.as_window(); let index = idx as usize; ...
identifier_body
cssrulelist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::...
let global = self.global(); let window = global.as_window(); let index = idx as usize; let parent_stylesheet = self.parent_stylesheet.style_stylesheet(); let new_rule = css_rules.write().insert_rule(rule, parent_stylesheet, index, nested)?; let parent_stylesheet = &*sel...
random_line_split
EditConfigNode.tsx
import React, { FC, useState } from 'react'; import { Handle, Position } from 'react-flow-renderer'; import { Container, JobName, JobStatusText, StatusIcon, InheritedTag } from './elements'; import { configStatusText, JobNodeProps, statusIcons, WORKFLOW_JOB_NODE_CHANNELS } from './shared'; import GridRow from 'componen...
('workflow.job_node_reused')}</InheritedTag> </Tooltip> )} </GridRow> )} {data.isSource && <Handle type="source" position={Position.Bottom} />} </Container> ); function onDisabledChange(val: boolean) { setUseRawDisabled(false); PubSub.publish(WORKFLOW_JOB_NODE...
t
identifier_name
EditConfigNode.tsx
import React, { FC, useState } from 'react'; import { Handle, Position } from 'react-flow-renderer'; import { Container, JobName, JobStatusText, StatusIcon, InheritedTag } from './elements'; import { configStatusText, JobNodeProps, statusIcons, WORKFLOW_JOB_NODE_CHANNELS } from './shared'; import GridRow from 'componen...
; export default ConfigJobNode;
{data.isSource && <Handle type="source" position={Position.Bottom} />} </Container> ); function onDisabledChange(val: boolean) { setUseRawDisabled(false); PubSub.publish(WORKFLOW_JOB_NODE_CHANNELS.disable_job, { id, data, disabled: !val }); } }
identifier_body
EditConfigNode.tsx
import React, { FC, useState } from 'react'; import { Handle, Position } from 'react-flow-renderer'; import { Container, JobName, JobStatusText, StatusIcon, InheritedTag } from './elements'; import { configStatusText, JobNodeProps, statusIcons, WORKFLOW_JOB_NODE_CHANNELS } from './shared'; import GridRow from 'componen...
PubSub.publish(WORKFLOW_JOB_NODE_CHANNELS.disable_job, { id, data, disabled: !val }); } }; export default ConfigJobNode;
function onDisabledChange(val: boolean) { setUseRawDisabled(false);
random_line_split
upload_root_keys.py
from JumpScale import j descr = """ Fetches the public keys from the vscalers_sysadmin repo and puts them in authorized_keys use '-e system ' to only use the system key (e.g. in production env on a mgmt node) """ organization = "vscalers" author = "tim@incubaid.com" license = "bsd" version = "1.0" category = "ssh....
keys = [] cuapi=node.cuapi tags=j.core.tags.getObject(node.args.extra) basepath=j.dirs.replaceTxtDirVars(j.application.config.get("admin.basepath")) d = j.system.fs.joinPaths(basepath, 'identities') if not j.system.fs.exists(path=d): raise RuntimeError("cannot find basepath:%s"%d) if ...
identifier_body
upload_root_keys.py
from JumpScale import j descr = """ Fetches the public keys from the vscalers_sysadmin repo and puts them in authorized_keys use '-e system ' to only use the system key (e.g. in production env on a mgmt node) """ organization = "vscalers" author = "tim@incubaid.com" license = "bsd" version = "1.0" category = "ssh.k...
if str(tags)<>"": #only use system key username=str(tags) u = j.system.fs.joinPaths(basepath, 'identities',username) filename = j.system.fs.joinPaths(u, 'id.hrd') hrd=j.core.hrd.getHRD(filename) pkey=hrd.get("id.key.dsa.pub") keys.append(pkey) print "F...
raise RuntimeError("cannot find basepath:%s"%d)
random_line_split
upload_root_keys.py
from JumpScale import j descr = """ Fetches the public keys from the vscalers_sysadmin repo and puts them in authorized_keys use '-e system ' to only use the system key (e.g. in production env on a mgmt node) """ organization = "vscalers" author = "tim@incubaid.com" license = "bsd" version = "1.0" category = "ssh....
else: # Fetch keys from repo for filename in j.system.fs.listFilesInDir(d, recursive=True, filter='*id.hrd'): hrd=j.core.hrd.getHRD(filename) pkey=hrd.get("id.key.dsa.pub") keys.append(pkey) print "Found", len(keys), "public ssh keys" #Remove current...
username=str(tags) u = j.system.fs.joinPaths(basepath, 'identities',username) filename = j.system.fs.joinPaths(u, 'id.hrd') hrd=j.core.hrd.getHRD(filename) pkey=hrd.get("id.key.dsa.pub") keys.append(pkey) print "Found", len(keys), "public system ssh keys" if str(t...
conditional_block
upload_root_keys.py
from JumpScale import j descr = """ Fetches the public keys from the vscalers_sysadmin repo and puts them in authorized_keys use '-e system ' to only use the system key (e.g. in production env on a mgmt node) """ organization = "vscalers" author = "tim@incubaid.com" license = "bsd" version = "1.0" category = "ssh....
(node): keys = [] cuapi=node.cuapi tags=j.core.tags.getObject(node.args.extra) basepath=j.dirs.replaceTxtDirVars(j.application.config.get("admin.basepath")) d = j.system.fs.joinPaths(basepath, 'identities') if not j.system.fs.exists(path=d): raise RuntimeError("cannot find basepath:%s"...
action
identifier_name
tcp.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(c::WSAEVENT); unsafe impl Send for Event {} unsafe impl Sync for Event {} impl Event { pub fn new() -> IoResult<Event> { let event = unsafe { c::WSACreateEvent() }; if event == c::WSA_INVALID_EVENT { Err(super::last_error()) } else { Ok(Event(event)) } ...
Event
identifier_name
tcp.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ TcpAcceptor { inner: self.inner.clone(), deadline: 0, } }
identifier_body
tcp.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let ret = unsafe { c::WSAEventSelect(socket, events[1], 0) }; if ret != 0 { return Err(last_net_error()) } set_nonblocking(socket, false); return Ok(stream) } } ...
// so we need to deregister our event and switch the socket back // to blocking mode socket => { let stream = TcpStream::new(socket);
random_line_split
button.d.ts
import { ElementRef, Renderer } from 'angular2/core'; import { Config } from '../../config/config'; /** * @name Button * @module ionic * * @description * Buttons are simple components in Ionic. They can consist of text and icons * and be enhanced by a wide range of attributes. * * @property [outline] - ...
{ private _elementRef; private _renderer; private _role; private _size; private _style; private _shape; private _display; private _colors; private _icon; private _disabled; private _init; /** * @private */ isItem: boolean; /** * @input {string} The...
Button
identifier_name
button.d.ts
import { ElementRef, Renderer } from 'angular2/core'; import { Config } from '../../config/config'; /** * @name Button * @module ionic * * @description * Buttons are simple components in Ionic. They can consist of text and icons * and be enhanced by a wide range of attributes. * * @property [outline] - ...
isItem: boolean; /** * @input {string} The category of the button. */ category: string; /** * @input {string} Large button. */ large: boolean; /** * @input {string} Small button. */ small: boolean; /** * @input {string} Default button. */ defau...
private _init; /** * @private */
random_line_split
baby-steps.ts
console.log("hello from typescript (j'ai été compilé !!!)"); let a: number = 120 * 2; let b: string = "hello world"; let c: boolean = true && false || true; let d: number[] = [1, 2, 3, 55]; let e: string[] = ["a", "b", "c"]; let f: [number, boolean] = [1, true]; let g: any = {}; let userAddress: [number, string] = [10...
nction printNomUser(u: User): void { console.log(u.name); } printNomUser(user1); // addNumbers(42, "10"); addNumbers(42, 10); let complex: { data: number[], output: (all: boolean) => number[] } = { data: [1, 2, 42], output: (all: boolean): number[] => { return this.data; } };
return a + b; } fu
identifier_body
baby-steps.ts
console.log("hello from typescript (j'ai été compilé !!!)"); let a: number = 120 * 2; let b: string = "hello world"; let c: boolean = true && false || true; let d: number[] = [1, 2, 3, 55]; let e: string[] = ["a", "b", "c"]; let f: [number, boolean] = [1, true]; let g: any = {}; let userAddress: [number, string] = [10...
User): void { console.log(u.name); } printNomUser(user1); // addNumbers(42, "10"); addNumbers(42, 10); let complex: { data: number[], output: (all: boolean) => number[] } = { data: [1, 2, 42], output: (all: boolean): number[] => { return this.data; } };
tNomUser(u:
identifier_name
baby-steps.ts
console.log("hello from typescript (j'ai été compilé !!!)"); let a: number = 120 * 2; let b: string = "hello world"; let c: boolean = true && false || true; let d: number[] = [1, 2, 3, 55]; let e: string[] = ["a", "b", "c"]; let f: [number, boolean] = [1, true]; let g: any = {}; let userAddress: [number, string] = [10...
console.log(c); console.log(d); console.log(e); console.log(f); console.log(g); type User = { name: string, age: number, hobbies: string[] }; let user1: User = { name: "gui", age: 37, hobbies: ["skate", "zik", "movies"] }; let user2: User = { name: "42", age: 37, hobbies: ["skate", "zik", "movies"] }; //...
console.log(a); console.log(b);
random_line_split
card.rs
use game_state::GameState; use minion_card::UID; use client_option::{OptionGenerator, ClientOption, OptionType}; use tags_list::TARGET; use controller::Controller; use hlua; #[derive(Copy, Clone)] #[allow(dead_code)] pub enum ECardType { Minion, Spell, Weapon, } #[derive(Clone)] pub struct Card { cost...
pub fn get_content(&self) -> String { self.content.clone() } // fn set_cost(&mut self, cost: u16){ // self.cost = cost; // } // // fn set_uid(&mut self, uid: String){ // self.uid = uid; // } // // fn set_name(&mut self, name: String){ // self.name = name; /...
{ self.id.clone() }
identifier_body
card.rs
use game_state::GameState; use minion_card::UID; use client_option::{OptionGenerator, ClientOption, OptionType}; use tags_list::TARGET; use controller::Controller; use hlua; #[derive(Copy, Clone)] #[allow(dead_code)] pub enum ECardType { Minion, Spell, Weapon, } #[derive(Clone)] pub struct Card { cost...
(&self) -> u32 { self.uid.clone() } pub fn _get_name(&self) -> String { self.name.clone() } pub fn get_card_type(&self) -> ECardType { self.card_type } pub fn _get_id(&self) -> String { self.id.clone() } pub fn get_content(&self) -> String { se...
get_uid
identifier_name
card.rs
use game_state::GameState; use minion_card::UID; use client_option::{OptionGenerator, ClientOption, OptionType}; use tags_list::TARGET; use controller::Controller; use hlua; #[derive(Copy, Clone)] #[allow(dead_code)] pub enum ECardType { Minion,
Weapon, } #[derive(Clone)] pub struct Card { cost: u8, card_type: ECardType, id: String, uid: UID, name: String, // for play minion cards this is the uid of the minion // for spells this is the rhai file that executes the spell content: String, } impl Card { pub fn new(cost: u8...
Spell,
random_line_split
XYZ.py
''' Created on May 26, 2016 @author: Jonathan Muckell, Ph.D. @license: GNU General Public License v3.0 Users are encouraged to use, modify and extend this work under the GNU GPLv3 license. Please cite the following paper to provide credit to this work: Jonathan Muckell, Yuchi Young, and Mitch Leventhal....
, p2): distance = math.sqrt( (p1.x - p2.x)**2 + (p1.y - p2.y)**2 + (p1.z - p2.z)**2 ) return distance # https://www.mathsisfun.com/algebra/trig-cosine-law.html @staticmethod def getAngleOfTriangle(a,b,c): #math.acos(0) # returns in radians numerator = c**2 - a**2...
DistanceBetweenPoints(p1
identifier_name
XYZ.py
''' Created on May 26, 2016 @author: Jonathan Muckell, Ph.D. @license: GNU General Public License v3.0 Users are encouraged to use, modify and extend this work under the GNU GPLv3 license. Please cite the following paper to provide credit to this work: Jonathan Muckell, Yuchi Young, and Mitch Leventhal....
XYZ.testNormal()
random_line_split
XYZ.py
''' Created on May 26, 2016 @author: Jonathan Muckell, Ph.D. @license: GNU General Public License v3.0 Users are encouraged to use, modify and extend this work under the GNU GPLv3 license. Please cite the following paper to provide credit to this work: Jonathan Muckell, Yuchi Young, and Mitch Leventhal....
XYZ.testNormal()
XYZ([1, -2, 0]) Q = XYZ([3, 1, 4]) R = XYZ([0, -1, 2]) normal = XYZ.getPlaneNormal(P, Q, R) # print("normal = ", normal.x, " | ", normal.y, " | ", normal.z) a = XYZ([2, 1, -1]) b = XYZ([-3, 4, 1]) XYZ.crossProduct(a, b)
identifier_body
test-main.js
/*jslint browser: true, nomen: true */ (function (requirejs) { 'use strict'; var allTestFiles = [], pathToModule = function (path) { return path.replace(/^\/base\//, '../../').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function (file) { if (/^\...
'angular-strap-tpl': "/base/static/lib/angular-strap/angular-strap.tpl", marked: "/base/static/lib/marked/marked", fastclick: "/base/static/lib/fastclick/fastclick", moment: "/base/static/lib/moment/moment", underscore: "/base/static/lib/underscore/underscore"...
'angular-strap': "/base/static/lib/angular-strap/angular-strap",
random_line_split
test-main.js
/*jslint browser: true, nomen: true */ (function (requirejs) { 'use strict'; var allTestFiles = [], pathToModule = function (path) { return path.replace(/^\/base\//, '../../').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function (file) { if (/^\...
}); requirejs.config({ // Karma serves files under /base, which is the basePath from your config file baseUrl: '/base/static/js', waitSeconds: 0, paths: { 'app.templates': "/base/test/app.templates", jquery: "/base/static/lib/jquery/jquery", ...
{ // Normalize paths to RequireJS module names. allTestFiles.push(pathToModule(file)); }
conditional_block
notify.js
/** * @desc notify() * - http://notifyjs.com/ for examples / docs * * @param {Function} fn - the function to curry * @param {Number} [len] - specifies the number of arguments needed to call the function * * @return {Function} - the curried function */ const url = '//rawgit.com/clearhead/clearhead/master/bower_...
// wait for jQuery if (!window.jQuery) { return setTimeout(notify.bind(this, ...args), 1000); } script = script || jQuery.getScript(url); // promise script.done(function () { jQuery.notify.call(jQuery, args.join(': ')); }); } export default notify;
{ return; }
conditional_block
notify.js
/** * @desc notify() * - http://notifyjs.com/ for examples / docs * * @param {Function} fn - the function to curry * @param {Number} [len] - specifies the number of arguments needed to call the function * * @return {Function} - the curried function */ const url = '//rawgit.com/clearhead/clearhead/master/bower_...
export default notify;
{ // only notify in debug mode if (!/clearhead-debug=true/.test(document.cookie)) { return; } // wait for jQuery if (!window.jQuery) { return setTimeout(notify.bind(this, ...args), 1000); } script = script || jQuery.getScript(url); // promise script.done(function () { jQuery.notify.call(...
identifier_body
notify.js
/** * @desc notify() * - http://notifyjs.com/ for examples / docs * * @param {Function} fn - the function to curry * @param {Number} [len] - specifies the number of arguments needed to call the function * * @return {Function} - the curried function */ const url = '//rawgit.com/clearhead/clearhead/master/bower_...
}); } export default notify;
random_line_split
notify.js
/** * @desc notify() * - http://notifyjs.com/ for examples / docs * * @param {Function} fn - the function to curry * @param {Number} [len] - specifies the number of arguments needed to call the function * * @return {Function} - the curried function */ const url = '//rawgit.com/clearhead/clearhead/master/bower_...
(...args) { // only notify in debug mode if (!/clearhead-debug=true/.test(document.cookie)) { return; } // wait for jQuery if (!window.jQuery) { return setTimeout(notify.bind(this, ...args), 1000); } script = script || jQuery.getScript(url); // promise script.done(function () { jQuery.no...
notify
identifier_name
form_control_directive.d.ts
import { EventEmitter } from 'angular2/src/facade/async';
* * # Example * * In this example, we bind the control to an input element. When the value of the input element * changes, the value of * the control will reflect that change. Likewise, if the value of the control changes, the input * element reflects that * change. * * Here we use {@link formDirecti...
import { ControlDirective } from './control_directive'; import { Control } from '../model'; /** * Binds a control to a DOM element.
random_line_split
form_control_directive.d.ts
import { EventEmitter } from 'angular2/src/facade/async'; import { ControlDirective } from './control_directive'; import { Control } from '../model'; /** * Binds a control to a DOM element. * * # Example * * In this example, we bind the control to an input element. When the value of the input element * c...
extends ControlDirective { form: Control; ngModel: EventEmitter; _added: boolean; model: any; constructor(); onChange(c: any): void; control: Control; path: List<string>; viewToModelUpdate(newValue: any): void; } export declare var __esModule: boolean;
FormControlDirective
identifier_name
import_all_provider_classes.py
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
(source_path: str, provider_ids: List[str] = None, print_imports: bool = False) -> List[str]: """ Imports all classes in providers packages. This method loads and imports all the classes found in providers, so that we can find all the subclasse...
import_all_provider_classes
identifier_name
import_all_provider_classes.py
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
if __name__ == '__main__': install_source_path = None for python_path_candidate in sys.path: providers_path_candidate = os.path.join(python_path_candidate, "airflow", "providers") if os.path.isdir(providers_path_candidate): install_source_path = python_path_candidate print() ...
""" Imports all classes in providers packages. This method loads and imports all the classes found in providers, so that we can find all the subclasses of operators/sensors etc. :param provider_ids - provider ids that should be loaded. :param print_imports - if imported class should also be printed...
identifier_body
import_all_provider_classes.py
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
""" if provider_ids: prefixed_provider_paths = [source_path + "/airflow/providers/" + provider_id.replace(".", "/") for provider_id in provider_ids] else: prefixed_provider_paths = [source_path + "/airflow/providers/"] imported_classes = [] traceba...
:param provider_ids - provider ids that should be loaded. :param print_imports - if imported class should also be printed in output :param source_path: path to look for sources - might be None to look for all packages in all source paths :return: list of all imported classes
random_line_split
import_all_provider_classes.py
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
imported_classes.append(class_name) except Exception: exception_str = traceback.format_exc() tracebacks.append(exception_str) if tracebacks: print(""" ERROR: There were some import errors """, file=sys.stderr) for t...
print(f"Imported {class_name}")
conditional_block
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of ...
idMap = collections.OrderedDict() addProvider(Google) addProvider(GitHub) addProvider(LinkedIn)
idMap[provider.getProviderName()] = provider
identifier_body
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of ...
(provider): idMap[provider.getProviderName()] = provider idMap = collections.OrderedDict() addProvider(Google) addProvider(GitHub) addProvider(LinkedIn)
addProvider
identifier_name
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc.
# 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See th...
# # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License.
random_line_split
virt_who_conf.py
""" VirtWhoConf - File ``/etc/virt-who.conf`` and ``/etc/virt-who.d/*.conf`` ======================================================================== The ``VirtWhoConf`` class parses the virt-who configuration files in `ini-like` format. .. note::
The configuration files under ``/etc/virt-who.d/`` might contain sensitive information, like ``password``. It must be filtered. """ from insights.core import IniConfigFile from insights.core.filters import add_filter from insights.core.plugins import parser from insights.specs import Specs filter_list...
random_line_split
virt_who_conf.py
""" VirtWhoConf - File ``/etc/virt-who.conf`` and ``/etc/virt-who.d/*.conf`` ======================================================================== The ``VirtWhoConf`` class parses the virt-who configuration files in `ini-like` format. .. note:: The configuration files under ``/etc/virt-who.d/`` might ...
(IniConfigFile): """ Parse the ``virt-who`` configuration files ``/etc/virt-who.conf`` and ``/etc/virt-who.d/*.conf``. Sample configuration file:: #Terse version of the general config template: [global] interval=3600 #reporter_id= debug=False oneshot=Fa...
VirtWhoConf
identifier_name
virt_who_conf.py
""" VirtWhoConf - File ``/etc/virt-who.conf`` and ``/etc/virt-who.d/*.conf`` ======================================================================== The ``VirtWhoConf`` class parses the virt-who configuration files in `ini-like` format. .. note:: The configuration files under ``/etc/virt-who.d/`` might ...
""" Parse the ``virt-who`` configuration files ``/etc/virt-who.conf`` and ``/etc/virt-who.d/*.conf``. Sample configuration file:: #Terse version of the general config template: [global] interval=3600 #reporter_id= debug=False oneshot=False #log_per_...
identifier_body
jsTyping.ts
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// <reference path='../compiler/types.ts' /> /// <reference path='../compiler/core.ts' /> /// <reference path='../compiler/commandLineParser.t...
host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map<string>, typeAcquisition: TypeAcquisition, unresolvedImports: ReadonlyArray<string>): { cachedTypingPaths: string[], newTyp...
scoverTypings(
identifier_name
jsTyping.ts
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// <reference path='../compiler/types.ts' /> /// <reference path='../compiler/core.ts' /> /// <reference path='../compiler/commandLineParser.t...
if (jsonConfig.optionalDependencies) { mergeTypings(getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { mergeTypings(getOwnKeys(jsonConfig.peerDependencies)); } } ...
mergeTypings(getOwnKeys(jsonConfig.devDependencies)); }
conditional_block
jsTyping.ts
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// <reference path='../compiler/types.ts' /> /// <reference path='../compiler/core.ts' /> /// <reference path='../compiler/commandLineParser.t...
/** * Infer typing names from node_module folder * @param nodeModulesPath is the path to the "node_modules" folder */ function getTypingNamesFromNodeModuleFolder(nodeModulesPath: string) { // Todo: add support for ModuleResolutionHost too if (!h...
const jsFileNames = filter(fileNames, hasJavaScriptFileExtension); const inferredTypingNames = map(jsFileNames, f => removeFileExtension(getBaseFileName(f.toLowerCase()))); const cleanedTypingNames = map(inferredTypingNames, f => f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, "...
identifier_body
jsTyping.ts
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// <reference path='../compiler/types.ts' /> /// <reference path='../compiler/core.ts' /> /// <reference path='../compiler/commandLineParser.t...
return { cachedTypingPaths, newTypingNames, filesToWatch }; /** * Merge a given list of typingNames to the inferredTypings map */ function mergeTypings(typingNames: string[]) { if (!typingNames) { return; } for (co...
newTypingNames.push(typing); } });
random_line_split