file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
A_evolve_outer_star_to_giant.py | import os
import os.path
from amuse.units import units
from amuse.datamodel import Particle
from amuse.ext.star_to_sph import pickle_stellar_model
from amuse.community.mesa.interface import MESA as stellar_evolution_code
from xiTau_parameters import triple_parameters
def evolve_giant(giant, stop_radius):
stell... | giant_in_code.evolve_one_step()
print giant_in_code.radius, giant_in_code.age
pickle_file_name = "./model_{0:=04}_".format(i) + "%0.1f"%(giant_in_code.radius.value_in(units.AU))
pickle_stellar_model(giant_in_code, pickle_file_name)
i += 1
if __name__ == "__main__":
mode... | print "Giant starts to ascend the giant branch, now saving model every step..."
print giant_in_code.as_set()
i = 0
while (giant_in_code.radius < stop_radius): | random_line_split |
A_evolve_outer_star_to_giant.py | import os
import os.path
from amuse.units import units
from amuse.datamodel import Particle
from amuse.ext.star_to_sph import pickle_stellar_model
from amuse.community.mesa.interface import MESA as stellar_evolution_code
from xiTau_parameters import triple_parameters
def | (giant, stop_radius):
stellar_evolution = stellar_evolution_code()
giant_in_code = stellar_evolution.particles.add_particle(giant)
while (giant_in_code.radius < 0.7 | units.AU):
giant_in_code.evolve_one_step()
print "Giant starts to ascend the giant branch, now saving model every step..."
... | evolve_giant | identifier_name |
A_evolve_outer_star_to_giant.py | import os
import os.path
from amuse.units import units
from amuse.datamodel import Particle
from amuse.ext.star_to_sph import pickle_stellar_model
from amuse.community.mesa.interface import MESA as stellar_evolution_code
from xiTau_parameters import triple_parameters
def evolve_giant(giant, stop_radius):
|
if __name__ == "__main__":
model_directory = os.path.join("../../../../../BIGDATA/code/amuse-10.0", "giant_models")
if not os.path.exists(model_directory):
os.mkdir(model_directory)
os.chdir(model_directory)
giant = Particle(mass = triple_parameters["mass_out"])
print "\nEvo... | stellar_evolution = stellar_evolution_code()
giant_in_code = stellar_evolution.particles.add_particle(giant)
while (giant_in_code.radius < 0.7 | units.AU):
giant_in_code.evolve_one_step()
print "Giant starts to ascend the giant branch, now saving model every step..."
print giant_in_code.as... | identifier_body |
shadow.rs | // Copyright 2012 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: Vec<int> ) {
let a: int = 5;
let mut b: Vec<int> = Vec::new();
match t::none::<int> {
t::some::<int>(_) => {
for _i in c.iter() {
println!("{}", a);
let a = 17i;
b.push(a);
}
}
_ => { }
}
}
enum t<T> {... | foo | identifier_name |
shadow.rs | // Copyright 2012 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn foo(c: Vec<int> ... | random_line_split | |
ColorSlider.ts | import { Behaviour, Slider, Toggling } from '@ephox/alloy';
import { Css } from '@ephox/sugar';
import Receivers from '../channels/Receivers';
import Styles from '../style/Styles';
import UiDomFactory from '../util/UiDomFactory';
import ToolbarWidgets from './ToolbarWidgets';
const BLACK = -1;
const makeSlider = fun... | (slider, thumb) {
Toggling.on(thumb);
},
onDragEnd (slider, thumb) {
Toggling.off(thumb);
},
onInit,
stepSize: 10,
min: 0,
max: 360,
getInitialValue: spec.getInitialValue,
sliderBehaviours: Behaviour.derive([
Receivers.orientation(Slider.refresh)
])
});
};
... | onDragStart | identifier_name |
ColorSlider.ts | import { Behaviour, Slider, Toggling } from '@ephox/alloy';
import { Css } from '@ephox/sugar';
| const BLACK = -1;
const makeSlider = function (spec) {
const getColor = function (hue) {
// Handle edges.
if (hue < 0) {
return 'black';
} else if (hue > 360) {
return 'white';
} else {
return 'hsl(' + hue + ', 100%, 50%)';
}
};
// Does not fire change intentionally.
cons... | import Receivers from '../channels/Receivers';
import Styles from '../style/Styles';
import UiDomFactory from '../util/UiDomFactory';
import ToolbarWidgets from './ToolbarWidgets';
| random_line_split |
ColorSlider.ts | import { Behaviour, Slider, Toggling } from '@ephox/alloy';
import { Css } from '@ephox/sugar';
import Receivers from '../channels/Receivers';
import Styles from '../style/Styles';
import UiDomFactory from '../util/UiDomFactory';
import ToolbarWidgets from './ToolbarWidgets';
const BLACK = -1;
const makeSlider = fun... | ,
getInitialValue (/* slider */) {
// Return black
return BLACK;
}
};
return ToolbarWidgets.button(realm, 'color', function () {
return makeItems(spec);
});
};
export default {
makeItems,
sketch
}; | {
editor.undoManager.transact(function () {
editor.formatter.apply('forecolor', { value: color });
editor.nodeChanged();
});
} | identifier_body |
jquery.carouselit.js | /*
--> carouselit jQuery Plugin <--
author : Horacio Herrera
website : hherrerag.com
twitter : @hhg2288
email: : me@hherrerag.com
description : plugin to made a simple carousel of list objects
SYNTAX:
$("yourSelector").carouselit({
step ---> how many blocks it move ,
visible ---> how many bloc... |
function moveRight(){
if(current - settings.step < 0 || current - settings.step > maximum - settings.visible) {
$(this).addClass('disable');
return;
} else {
current = current - settings.step;
pager--;
$(container).animate({left: -(settings.liSize * current)}, settings.speed, n... | {
if(current + settings.step < 0 || current + settings.step > maximum - settings.visible) {return; }
else {
current = current + settings.step;
pager++;
$(container).animate({left: -(settings.liSize * current)}, settings.speed, null);
$(settings.prevBtn).removeClass('disable');
if (setti... | identifier_body |
jquery.carouselit.js | /*
--> carouselit jQuery Plugin <--
author : Horacio Herrera
website : hherrerag.com
twitter : @hhg2288
email: : me@hherrerag.com
description : plugin to made a simple carousel of list objects
SYNTAX:
$("yourSelector").carouselit({
step ---> how many blocks it move ,
visible ---> how many bloc... | // Calculate if the swipe was left or right
function touchEnd(event) {
//console.log('Ending swipe gesture...')
var changeX = originalCoord.x - finalCoord.x;
if(changeX > settings.threshold.x) {
moveLeft();
... | finalCoord.y = event.targetTouches[0].pageY
}
// Done Swiping
// Swipe should only be on X axis, ignore if swipe on Y axis | random_line_split |
jquery.carouselit.js | /*
--> carouselit jQuery Plugin <--
author : Horacio Herrera
website : hherrerag.com
twitter : @hhg2288
email: : me@hherrerag.com
description : plugin to made a simple carousel of list objects
SYNTAX:
$("yourSelector").carouselit({
step ---> how many blocks it move ,
visible ---> how many bloc... |
}
function moveLeft(){
if(current + settings.step < 0 || current + settings.step > maximum - settings.visible) {return; }
else {
current = current + settings.step;
pager++;
$(container).animate({left: -(settings.liSize * current)}, settings.speed, null);
$(settings.prevBtn).remove... | { $(settings._maximun).append(pagination); } | conditional_block |
jquery.carouselit.js | /*
--> carouselit jQuery Plugin <--
author : Horacio Herrera
website : hherrerag.com
twitter : @hhg2288
email: : me@hherrerag.com
description : plugin to made a simple carousel of list objects
SYNTAX:
$("yourSelector").carouselit({
step ---> how many blocks it move ,
visible ---> how many bloc... | (event) {
//console.log('Canceling swipe gesture...')
}
// Add gestures to all swipable areas
this.addEventListener("touchstart", touchStart, false);
this.addEventListener("touchmove", touchMove, false);
this.addEventListener("touchend", touchEnd, false);
... | touchCancel | identifier_name |
BitbucketImportRepositoryForm.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | <BitbucketRepositories
disableRepositories={disableRepositories}
onSelectRepository={props.onSelectRepository}
projectRepositories={projectRepositories}
projects={projects}
selectedRepository={selectedRepository}
/>
)}
</div>
);
} | />
) : ( | random_line_split |
test_getter.py | """Browser instance getter tests."""
import pytest
@pytest.fixture(scope='session')
def | ():
"""Override to default to test getter twice."""
return True
def test_browser_instance_getter(request, browser_instance_getter):
"""Test browser_instance_getter fixture.
Test that it return a function and if run this function then each time we will get
different instance of plugin.Browser clas... | splinter_session_scoped_browser | identifier_name |
test_getter.py | """Browser instance getter tests."""
import pytest
@pytest.fixture(scope='session')
def splinter_session_scoped_browser():
"""Override to default to test getter twice."""
return True
def test_browser_instance_getter(request, browser_instance_getter):
| """Test browser_instance_getter fixture.
Test that it return a function and if run this function then each time we will get
different instance of plugin.Browser class.
"""
assert callable(browser_instance_getter)
browser1 = browser_instance_getter(request, test_browser_instance_getter)
browser... | identifier_body | |
test_getter.py | """Browser instance getter tests."""
import pytest
@pytest.fixture(scope='session')
def splinter_session_scoped_browser():
"""Override to default to test getter twice."""
return True
def test_browser_instance_getter(request, browser_instance_getter):
"""Test browser_instance_getter fixture. | different instance of plugin.Browser class.
"""
assert callable(browser_instance_getter)
browser1 = browser_instance_getter(request, test_browser_instance_getter)
browser2 = browser_instance_getter(request, lambda: 1)
assert hasattr(browser1, 'visit_condition')
assert hasattr(browser2, 'vi... |
Test that it return a function and if run this function then each time we will get | random_line_split |
helper.ts |
import {Injectable} from '@angular/core';
import {Events} from "ionic-angular";
import {NativeService} from "./nativeService";
import {JPush} from "../../typings/modules/jpush/index";
/**
* Helper类存放和业务有关的公共方法
* @description
*/
@Injectable()
export class Helper {
constructor(public events: Events,
... | identifier_name | ||
helper.ts | import {Injectable} from '@angular/core';
import {Events} from "ionic-angular";
import {NativeService} from "./nativeService";
import {JPush} from "../../typings/modules/jpush/index";
/**
* Helper类存放和业务有关的公共方法
* @description
*/
@Injectable()
export class Helper {
constructor(public events: Events,
... | if (this.nativeService.isIos()) {
this.jPush.setDebugModeFromIos();
} else {
this.jPush.setDebugMode(true);
}
this.jPushAddEventListener();
}
private jPushAddEventListener() {
this.jPush.getUserNotificationSettings().then(result=>{
if (result == 0) {
console.log('系统设置... | }
this.jPush.init(); | random_line_split |
helper.ts |
import {Injectable} from '@angular/core';
import {Events} from "ionic-angular";
import {NativeService} from "./nativeService";
import {JPush} from "../../typings/modules/jpush/index";
/**
* Helper类存放和业务有关的公共方法
* @description
*/
@Injectable()
export class Helper {
constructor(public events: Events,
... | !this.nativeService.isMobile()) {
return;
}
this.jPush.init();
if (this.nativeService.isIos()) {
this.jPush.setDebugModeFromIos();
} else {
this.jPush.setDebugMode(true);
}
this.jPushAddEventListener();
}
private jPushAddEventListener() {
this.jPush.getUserNotificatio... | if ( | identifier_body |
helper.ts |
import {Injectable} from '@angular/core';
import {Events} from "ionic-angular";
import {NativeService} from "./nativeService";
import {JPush} from "../../typings/modules/jpush/index";
/**
* Helper类存放和业务有关的公共方法
* @description
*/
@Injectable()
export class Helper {
constructor(public events: Events,
... | etDebugMode(true);
}
this.jPushAddEventListener();
}
private jPushAddEventListener() {
this.jPush.getUserNotificationSettings().then(result=>{
if (result == 0) {
console.log('系统设置中已关闭应用推送');
} else if (result > 0) {
console.log('系统设置中打开了应用推送');
}
});
//点击通知进入... | gModeFromIos();
} else {
this.jPush.s | conditional_block |
orginfo.service.ts | import {OrganizationModel} from './orginfo.model';
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import{API_URL} from "../../../shared/configs/env.config";
import{Config} from "../../../shared/configs/general.config";
import {FileOper... |
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
//this.progressObserver.next(this.progress);
};
xhr.open('POST', API_URL + this.apiRoute, true);
xhr.setRequestHeader("Author... | {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
console.log(xhr.response);
}
... | conditional_block |
orginfo.service.ts | import {OrganizationModel} from './orginfo.model';
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import{API_URL} from "../../../shared/configs/env.config";
import{Config} from "../../../shared/configs/general.config";
import {FileOper... | (fileName:string, orgExt:string, path:string):Observable < any > {
return this.fileService.deleteFile(fileName, orgExt, path, "image");
}
handleError(error) {
console.log(error.json());
return Observable.throw(error.json() || 'server error');
}
} | deleteImage | identifier_name |
orginfo.service.ts | import {OrganizationModel} from './orginfo.model';
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import{API_URL} from "../../../shared/configs/env.config";
import{Config} from "../../../shared/configs/general.config";
import {FileOper... | };
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
//this.progressObserver.next(this.progress);
};
xhr.open('POST', API_URL + this.apiRoute, true);
xhr.setRequestHeader("Authori... | {
let body = JSON.stringify(objSave);
return Observable.create(observer => {
let formData:FormData = new FormData(),
xhr:XMLHttpRequest = new XMLHttpRequest();
if (file) {
formData.append('imageName', file);
}
formData.appe... | identifier_body |
orginfo.service.ts | import {OrganizationModel} from './orginfo.model';
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import{API_URL} from "../../../shared/configs/env.config";
import{Config} from "../../../shared/configs/general.config";
import {FileOper... |
} | console.log(error.json());
return Observable.throw(error.json() || 'server error');
} | random_line_split |
jquery.event.move.js | fn,
active = false,
running = false;
function trigger(time) {
if (active){
callback();
requestFrame(trigger);
running = true;
active = false;
}
else {
running = false;
}
}
this.kick = function(fn) {
active = true;
if (!running) { trigger(); }
};
this.end... | removeTouch(template.identifier);
}
function removeTouch(identifier) {
remove(document, '.' + identifier, touchmove);
remove(document, '.' + identifier, touchend);
}
// Logic for deciding when to trigger a movestart.
function checkThreshold(e, template, touch, fn) {
var distX = touch.pageX - template.sta... | turn; }
| conditional_block |
jquery.event.move.js | ,
active = false,
running = false;
function trigger(time) {
if (active){
callback();
requestFrame(trigger);
running = true;
active = false;
}
else {
running = false;
}
}
this.kick = function(fn) {
active = true;
if (!running) { trigger(); }
};
this.end = ... | nt) {
remove(document, '.' + event.identifier, activeTouchmove);
remove(document, '.' + event.identifier, activeTouchend);
}
// Logic for triggering move and moveend events
function updateEvent(event, touch, timeStamp, timer) {
var time = timeStamp - event.timeStamp;
event.type = 'move';
event.distX = ... | veActiveTouch(eve | identifier_name |
jquery.event.move.js | fn,
active = false,
running = false;
function trigger(time) {
if (active){
callback();
requestFrame(trigger);
running = true;
active = false;
}
else {
running = false;
}
}
this.kick = function(fn) {
active = true;
if (!running) { trigger(); }
};
this.end... | unction touchend(e) {
var template = e.data,
touch = identifiedTouch(e.changedTouches, template.identifier);
if (!touch) { return; }
removeTouch(template.identifier);
}
function removeTouch(identifier) {
remove(document, '.' + identifier, touchmove);
remove(document, '.' + identifier, touchend);
}... | var data = e.data,
touch = changedTouch(e, data);
if (!touch) { return; }
checkThreshold(e, data, touch, removeTouch);
}
f | identifier_body |
jquery.event.move.js | l;
if (touchList.identifiedTouch) {
return touchList.identifiedTouch(id);
}
// touchList.identifiedTouch() does not exist in
// webkit yet鈥� we must do the search ourselves...
i = -1;
l = touchList.length;
while (++i < l) {
if (touchList[i].identifier === id) {
return touchList[i];
... | random_line_split | ||
settings.py | """
Django settings for unusebamboo project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see | ERROR: type should be large_string, got "https://docs.djangoproject.com/en/1.8/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '29e3ohmh+=s^udbct$yg^2p+9n+fpdpp%+9-^or(g+o%@2oosm'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'accounts',\n 'polls',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n)\n\nROOT_URLCONF = 'unusebamboo.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'unusebamboo.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.8/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'idjango',\n 'USER': 'root',\n 'PASSWORD': 'root',\n 'HOST': '127.0.0.1',\n 'PORT': '3306',\n 'OPTIONS': {'charset': 'utf8mb4'},\n }\n}\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.8/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.8/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = 'static'\n\n# EMAIL\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = 'smtp.163.com'\nEMAIL_HOST_USER = 'ilifediary2@163.com'\nEMAIL_HOST_PASSWORD = 'a297413'\nEMAIL_USE_TLS = True\nDEFAULT_FROM_EMAIL = 'ilifediary2@163.com'" | https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see | random_line_split |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings:... |
}
}
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
// TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
ConsoleMessage {
message: String::from(message),
logLevel: logLevel,
filename: "test".to_owned(),
... | {
let message = message.unwrap_or_else(|| DOMString::from("no message"));
println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
} | conditional_block |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings:... | {
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
pub fn new(global: GlobalRef) -> Root<Console> {
r... | Console | identifier_name |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings:... | println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
}
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
// TODO: Sending fake values for filename, lineNumber and columnNumber in LogM... | fn Assert(&self, condition: bool, message: Option<DOMString>) {
if !condition {
let message = message.unwrap_or_else(|| DOMString::from("no message")); | random_line_split |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings:... |
pub fn new(global: GlobalRef) -> Root<Console> {
reflect_dom_object(box Console::new_inherited(global),
global,
ConsoleBinding::Wrap)
}
}
impl ConsoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
fn ... | {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
} | identifier_body |
JQueryAdapter.ts | (selector: any, options?: ScrollOptions): void {
const scroll: Scroll = new Scroll();
scroll.to(selector, options);
}
/**
* 自信の要素を基準に、指定の子要素を背景のように扱う
*
* TODO: BaserElement化する
*
* CSSの`background-size`の`contain`と`cover`の振る舞いに対応
*
* 基準も縦横のセンター・上下・左右に指定可能
*
* @version 0.11.0
* @since 0.0.9
*... | bcScrollTo | identifier_name | |
JQueryAdapter.ts | _ITEM);
BaserElement.addClassTo($item, CLASS_NAME, CLASS_NAME_ITEM, CLASS_NAME_NTH + i);
}
}
$list.remove();
});
return self;
}
/**
* マウスオーバー時に一瞬透明になるエフェクトをかける
*
* @version 0.0.14
* @since 0.0.14
*
*/
public bcWink (options: any): JQuery {
const self: JQuery = $(this);
const con... | identifier_body | ||
JQueryAdapter.ts |
public bcBoxLink (): JQuery {
return $(this).on('click', function (e: JQueryEventObject): void {
const $elem: JQuery = $(this);
const $link: JQuery = $elem.find('a, area').eq(0);
const href: string = $link.prop('href');
if ($link.length && href) {
const isBlank: boolean = $link.prop('target') === '_... | tslint:enable */
});
}
} else {
/* tslint:disable */
new AlignedBoxes(self, column, callback);
/* tslint:enable */
}
}
return self;
}
// @version 0.12.1
// @since 0.1.0 | conditional_block | |
JQueryAdapter.ts | const $detailTarget: JQuery = self.find(detailTarget);
if ($detailTarget.length) {
self.each(function () {
const $split: JQuery = $(this).find(detailTarget);
/* tslint:disable */
new AlignedBoxes($split, column, callback);
/* tslint:enable */
});
}
} else {
/* tslint... | random_line_split | ||
synthetic_files_compiler_host.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
*/
/// <amd-module name="@angular/compiler-cli/src/ngtsc/synthetic_files_compiler_host" />
import { PluginCompilerHost }... | getNewLine(): string;
getDirectories?: (path: string) => string[];
readFile(fileName: string): string | undefined;
trace(s: string): void;
} | useCaseSensitiveFileNames(): boolean; | random_line_split |
synthetic_files_compiler_host.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
*/
/// <amd-module name="@angular/compiler-cli/src/ngtsc/synthetic_files_compiler_host" />
import { PluginCompilerHost }... | implements PluginCompilerHost {
private rootFiles;
private delegate;
/**
* SourceFiles which are added to the program but which never existed on disk.
*/
syntheticFiles: Map<string, ts.SourceFile>;
constructor(rootFiles: string[], delegate: ts.CompilerHost, generatedFiles: (rootFiles: str... | SyntheticFilesCompilerHost | identifier_name |
jspack.js | sb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, i;
v = (v<el.min)?el.min:(v>el.max)?el.max:v;
for (i = lsb; i != stop; a[p+i]=v&0xff, i+=nsb, v>>=8);
};
// ASCII character strings
m._DeString = function (a, p, l)
{
for (var rv = new Array(l), i = 0; i < l; rv[i] = String.fromCharCode(a[p+i]), i... | 'Q': {en:m._EnInt, de:m._DeInt, len:8, bSigned:false, min:0, max:Math.pow(2, 64)-1}};
// Unpack a series of n elements of size s from array a at offset p with fxn
m._UnpackSeries = function (n, s, a, p)
{
for (var fxn = el.de, rv = [], i = 0; i < n; rv.push(fxn(a, p+i*s)), i++);
return rv;
};
// Pack a s... | 'q': {en:m._EnInt, de:m._DeInt, len:8, bSigned:true, min:-Math.pow(2, 63), max:Math.pow(2, 63)-1}, | random_line_split |
jspack.js | return rv;
};
m._EnInt = function (a, p, v)
{
var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, i;
v = (v<el.min)?el.min:(v>el.max)?el.max:v;
for (i = lsb; i != stop; a[p+i]=v&0xff, i+=nsb, v>>=8);
};
// ASCII character strings
m._DeString = function (a, p, l)
{
for (var rv = new Arra... | rv -= Math.pow(2, el.len*8); }
| conditional_block | |
jspack.js | )
{
// Module-level (private) variables
var el, bBE = false, m = this;
// Raw byte arrays
m._DeArray = function (a, p, l)
{
return [a.slice(p,p+l)];
};
m._EnArray = function (a, p, l, v)
{
for (var i = 0; i < l; a[p+i] = v[i]?v[i]:0, i++);
};
// ASCII characters
m._DeChar = function (a, p)
{
retur... | SPack( | identifier_name | |
jspack.js | m._EnChar = function (a, p, v)
{
a[p] = v.charCodeAt(0);
};
// Little-endian (un)signed N-byte integers
m._DeInt = function (a, p)
{
var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, rv, i, f;
for (rv = 0, i = lsb, f = 1; i != stop; rv+=(a[p+i]*f), i+=nsb, f*=256);
if (el.bSigned && (rv ... |
// Module-level (private) variables
var el, bBE = false, m = this;
// Raw byte arrays
m._DeArray = function (a, p, l)
{
return [a.slice(p,p+l)];
};
m._EnArray = function (a, p, l, v)
{
for (var i = 0; i < l; a[p+i] = v[i]?v[i]:0, i++);
};
// ASCII characters
m._DeChar = function (a, p)
{
return S... | identifier_body | |
thread.rs | // Copyright 2015 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 ... | (&self) -> RawPthread {
self.as_inner().id() as RawPthread
}
fn into_pthread_t(self) -> RawPthread {
self.into_inner().into_id() as RawPthread
}
}
| as_pthread_t | identifier_name |
thread.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unix-specific e... | // http://rust-lang.org/COPYRIGHT.
// | random_line_split |
thread.rs | // Copyright 2015 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 ... |
}
| {
self.into_inner().into_id() as RawPthread
} | identifier_body |
test_misc.py | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Cathy Nangini <cnangini@gmail.com>
# Mainak Jas <mainak@neuro.hut.fi>
#... |
run_tests_if_main()
| """Test plotting dipole amplitudes."""
dipoles = read_dipole(dip_fname)
dipoles.plot_amplitudes(show=False) | identifier_body |
test_misc.py | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Cathy Nangini <cnangini@gmail.com>
# Mainak Jas <mainak@neuro.hut.fi>
#... | ():
"""Test plotting dipole amplitudes."""
dipoles = read_dipole(dip_fname)
dipoles.plot_amplitudes(show=False)
run_tests_if_main()
| test_plot_dipole_amplitudes | identifier_name |
test_misc.py | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Cathy Nangini <cnangini@gmail.com>
# Mainak Jas <mainak@neuro.hut.fi>
#... | sample_src = read_source_spaces(op.join(subjects_dir, 'sample',
'bem', 'sample-oct-6-src.fif'))
# dense version
vertices = [s['vertno'] for s in sample_src]
n_times = 5
n_verts = sum(len(v) for v in vertices)
stc_data = np.ones((n_verts, n_times))
... |
@testing.requires_testing_data
def test_plot_source_spectrogram():
"""Test plotting of source spectrogram.""" | random_line_split |
tensorflow.py | .path.exists(labels):
_LOGGER.error("Unable to locate tensorflow models or label map.")
return
# append custom model path to sys.path
sys.path.append(model_dir)
try:
# Verify that the TensorFlow Object Detection API is pre-installed
# pylint: disable=unused-import,unused-va... | paths.append(path_template.render(
camera_entity=self._camera_entity)) | conditional_block | |
tensorflow.py | '
CONF_MODEL_DIR = 'model_dir'
CONF_CATEGORIES = 'categories'
CONF_CATEGORY = 'category'
CONF_AREA = 'area'
CONF_TOP = 'top'
CONF_LEFT = 'left'
CONF_BOTTOM = 'bottom'
CONF_RIGHT = 'right'
AREA_SCHEMA = vol.Schema({
vol.Optional(CONF_TOP, default=0): cv.small_float,
vol.Optional(CONF_LEFT, default=0): cv.small_... |
@property
def state(self):
"""Return the state of the entity."""
return self._total_matches
@property
def device_state_attributes(self):
"""Return device specific state attributes."""
return {
ATTR_MATCHES: self._matches,
ATTR_SUMMARY: {category... | """Return the name of the image processor."""
return self._name | identifier_body |
tensorflow.py | '
CONF_MODEL_DIR = 'model_dir'
CONF_CATEGORIES = 'categories'
CONF_CATEGORY = 'category'
CONF_AREA = 'area'
CONF_TOP = 'top'
CONF_LEFT = 'left'
CONF_BOTTOM = 'bottom'
CONF_RIGHT = 'right'
AREA_SCHEMA = vol.Schema({
vol.Optional(CONF_TOP, default=0): cv.small_float,
vol.Optional(CONF_LEFT, default=0): cv.small_... | (ImageProcessingEntity):
"""Representation of an TensorFlow image processor."""
def __init__(self, hass, camera_entity, name, session, detection_graph,
category_index, config):
"""Initialize the TensorFlow entity."""
model_config = config.get(CONF_MODEL)
self.hass = has... | TensorFlowImageProcessor | identifier_name |
tensorflow.py | '
CONF_MODEL_DIR = 'model_dir'
CONF_CATEGORIES = 'categories'
CONF_CATEGORY = 'category'
CONF_AREA = 'area'
CONF_TOP = 'top'
CONF_LEFT = 'left'
CONF_BOTTOM = 'bottom'
CONF_RIGHT = 'right'
AREA_SCHEMA = vol.Schema({
vol.Optional(CONF_TOP, default=0): cv.small_float,
vol.Optional(CONF_LEFT, default=0): cv.small_... | vol.Optional(CONF_CATEGORIES, default=[]):
vol.All(cv.ensure_list, [vol.Any(
cv.string,
CATEGORY_SCHEMA
)])
})
})
def draw_box(draw, box, img_width,
img_height, text='', color=(255, 255, 0)):
"""Draw bounding box on image."""
ymi... | vol.Required(CONF_GRAPH): cv.isfile,
vol.Optional(CONF_LABELS): cv.isfile,
vol.Optional(CONF_MODEL_DIR): cv.isdir,
vol.Optional(CONF_AREA): AREA_SCHEMA, | random_line_split |
lib.rs | //! A generic filesystem with disk and in-memory implementations.
//!
//! # Reason for existence
//!
//! The [`std::fs`] module provides functions to manipulate the filesytem, and these functions are
//! good. However, if you have code that uses `std::fs`, it is difficult to ensure that your code
//! handles errors pro... | mod errors;
mod path_parts;
mod ptr; |
pub mod disk;
pub mod mem;
pub mod unix_ext;
| random_line_split |
sleep.rs | #[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
... | (count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
| sleep_for_ms | identifier_name |
sleep.rs | #[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) | break;
}
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]
pub fn sleep_for_ms(count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
| {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
must_reach.increment_ms(count);
must_reach
});
loop {
let mut reached... | identifier_body |
sleep.rs | #[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
... | let mut reached = false;
x86_64::instructions::interrupts::without_interrupts(|| {
let current = TIMER.get();
reached = *current >= must_reach;
});
if reached {
break;
}
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]... |
loop { | random_line_split |
sleep.rs | #[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
... |
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]
pub fn sleep_for_ms(count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
| {
break;
} | conditional_block |
vendor.js | window.jQuery = window.$ = require("jquery");
require('foundation-sites/dist/js/foundation');
$(document).ready(function() {
$(document).foundation();
/*
$(document).foundation({
orbit: {
animation: 'slide',
timer_speed: 1000,
pause_on_hover: true,
animation_speed: 500,
navigation_... |
require(['highlight.js/lib/highlight'], function(hljs) {
hljs.registerLanguage('bash', require('highlight.js/lib/languages/bash'));
hljs.registerLanguage('cpp', require('highlight.js/lib/languages/cpp'));
hljs.registerLanguage('cmake', require('highlight.js/lib/languages/cmake'));
hljs.registerLanguage('java',... |
require('highlight.js/styles/railscasts.css'); | random_line_split |
vfixupimmsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vfixupimmsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some... | {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM21)), operand2: Some(Direct(XMM27)), operand3: Some(IndirectDisplaced(RAX, 1072326570, Some(OperandSize::Qword), None)), operand4: Some(Literal8(108)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false,... | identifier_body | |
vfixupimmsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
| run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, EBX, Two, 1540894690, Some(OperandSize::Qword), None)), operand4: Some(Literal8(71)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::... | fn vfixupimmsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM7)), operand4: Some(Literal8(115)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K2), broadcast: N... | random_line_split |
vfixupimmsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vfixupimmsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some... | () {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, EBX, Two, 1540894690, Some(OperandSize::Qword), None)), operand4: Some(Literal8(71)), lock: false, rounding_mode: None, merge_mode: Some(MergeM... | vfixupimmsd_2 | identifier_name |
releases.py | '''
MLAB calls MATLAB funcitons and looks like a normal python library.
authors:
Yauhen Yakimovich <eugeny.yakimovitch@gmail.com>
Module wrapping borrowed from `sh` project by Andrew Moffat.
'''
import os
import sys
from types import ModuleType
from mlabwrap import (MlabWrap, choose_release, find_available_releas... |
# accept special keywords argument to define defaults for all operations
# that will be processed with given by return SelfWrapper
def __call__(self, **kwargs):
return SelfWrapper(self.self_module, kwargs)
# we're being imported from somewhere
if __name__ != '__main__':
self = sys.modules[_... | if name == "instances": raise AttributeError
if name in dir(self.module):
return getattr(self.module, name)
return self.instances[name] | identifier_body |
releases.py | '''
MLAB calls MATLAB funcitons and looks like a normal python library.
authors:
Yauhen Yakimovich <eugeny.yakimovitch@gmail.com>
Module wrapping borrowed from `sh` project by Andrew Moffat.
'''
import os
import sys
from types import ModuleType
from mlabwrap import (MlabWrap, choose_release, find_available_releas... | (self, name, value):
#if hasattr(self, "instances"): self.instances[name] = value
ModuleType.__setattr__(self, name, value)
def __getattr__(self, name):
if name == "instances": raise AttributeError
if name in dir(self.module):
return getattr(self.module, name)
r... | __setattr__ | identifier_name |
releases.py | '''
MLAB calls MATLAB funcitons and looks like a normal python library.
authors:
Yauhen Yakimovich <eugeny.yakimovitch@gmail.com>
Module wrapping borrowed from `sh` project by Andrew Moffat.
'''
import os
import sys
from types import ModuleType
from mlabwrap import (MlabWrap, choose_release, find_available_releas... |
versions = available_releases.keys()
latest_release_version = sorted(versions)[-1]
return latest_release_version
class MatlabVersions(dict):
def __init__(self, globs):
self.globs = globs
self.__selected_instance = None
self._available_releases = dict(find_available_releases()... | available_releases = dict(find_available_releases()) | conditional_block |
releases.py | '''
MLAB calls MATLAB funcitons and looks like a normal python library.
authors:
Yauhen Yakimovich <eugeny.yakimovitch@gmail.com>
Module wrapping borrowed from `sh` project by Andrew Moffat.
'''
import os
import sys
from types import ModuleType
from mlabwrap import (MlabWrap, choose_release, find_available_releas... | return latest_release_version
class MatlabVersions(dict):
def __init__(self, globs):
self.globs = globs
self.__selected_instance = None
self._available_releases = dict(find_available_releases())
def __setitem__(self, k, v):
self.globs[k] = v
def __getitem__(self, k):... | available_releases = dict(find_available_releases())
versions = available_releases.keys()
latest_release_version = sorted(versions)[-1] | random_line_split |
ip.ts | import _ from "lodash";
import axios from "axios";
import { isIPv4, isIPv6 } from "net";
import { IpEcho } from "@cloudflare-ddns/config";
import { getParser } from "@cloudflare-ddns/ip-echo-parser";
import { verifySchema } from "@cloudflare-ddns/schema";
import { Context } from "./context";
interface CheckIp {
(ip... |
const checkIPv4 = (ip: string): void => {
if (!isIPv4(ip)) {
throw new Error(`Not IPv4: ${ip}`);
}
};
const checkIPv6 = (ip: string): void => {
if (!isIPv6(ip)) {
throw new Error(`Not IPv6: ${ip}`);
}
};
const fetchIpEcho = async (ipEcho: IpEcho): Promise<string> => {
const { url, type, ...opts } =... | random_line_split | |
ip.ts | import _ from "lodash";
import axios from "axios";
import { isIPv4, isIPv6 } from "net";
import { IpEcho } from "@cloudflare-ddns/config";
import { getParser } from "@cloudflare-ddns/ip-echo-parser";
import { verifySchema } from "@cloudflare-ddns/schema";
import { Context } from "./context";
interface CheckIp {
(ip... |
};
const fetchIpEcho = async (ipEcho: IpEcho): Promise<string> => {
const { url, type, ...opts } = ipEcho;
const res = await axios.get<string>(url, { transformResponse: d => d });
const { parser, schema } = await getParser(type);
const validOpts = schema ? await verifySchema(schema, opts) : opts;
return par... | {
throw new Error(`Not IPv6: ${ip}`);
} | conditional_block |
ch16-checkerboard.py | from tkinter import *
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Game")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, bd=0, highlightthickness=0)... |
else:
draw_background = 1
self.sprites = []
self.running = True
def add(self, sprite):
self.sprites.append(sprite)
def mainloop(self):
while 1:
for sprite in self.sprites:
sprite.m... | self.canvas.create_image(x * w, y * h, image=self.bg, anchor='nw')
draw_background = 0 | conditional_block |
ch16-checkerboard.py | from tkinter import * | self.tk = Tk()
self.tk.title("Game")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, bd=0, highlightthickness=0)
self.canvas.pack()
self.tk.update()
self.canvas_he... | import random
import time
class Game:
def __init__(self): | random_line_split |
ch16-checkerboard.py | from tkinter import *
import random
import time
class Game:
def | (self):
self.tk = Tk()
self.tk.title("Game")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, bd=0, highlightthickness=0)
self.canvas.pack()
self.tk.update()
self.c... | __init__ | identifier_name |
ch16-checkerboard.py | from tkinter import *
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Game")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, bd=0, highlightthickness=0)... |
def mainloop(self):
while 1:
for sprite in self.sprites:
sprite.move()
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
g = Game()
g.mainloop() | self.sprites.append(sprite) | identifier_body |
principe_de_superposition_lineaire.py | # -*- coding: utf-8 -*-
import os
"""
Illustration d'un exercice de TD visant à montrer l'évolution temporelle de la
densité de probabilité pour la superposition équiprobable d'un état n=1 et
d'un état n quelconque (à fixer) pour le puits quantique infini.
Par souci de simplicité, on se débrouille pour que E_1/hbar... | t = i * dt + t0
line.set_ydata(abs(psi(x, t))**2)
plt.title('$t={}$'.format(t))
anim = animation.FuncAnimation(fig, animate, frames=1000, interval=20)
plt.show()
os.system("pause")
| i):
| identifier_body |
principe_de_superposition_lineaire.py | # -*- coding: utf-8 -*-
import os
"""
Illustration d'un exercice de TD visant à montrer l'évolution temporelle de la
densité de probabilité pour la superposition équiprobable d'un état n=1 et
d'un état n quelconque (à fixer) pour le puits quantique infini.
Par souci de simplicité, on se débrouille pour que E_1/hbar... |
plt.show()
os.system("pause") | random_line_split | |
principe_de_superposition_lineaire.py | # -*- coding: utf-8 -*-
import os
"""
Illustration d'un exercice de TD visant à montrer l'évolution temporelle de la
densité de probabilité pour la superposition équiprobable d'un état n=1 et
d'un état n quelconque (à fixer) pour le puits quantique infini.
Par souci de simplicité, on se débrouille pour que E_1/hbar... | animate(i):
t = i * dt + t0
line.set_ydata(abs(psi(x, t))**2)
plt.title('$t={}$'.format(t))
anim = animation.FuncAnimation(fig, animate, frames=1000, interval=20)
plt.show()
os.system("pause")
| def | identifier_name |
ionItem.js | Template.ionItem.helpers({
itemClasses: function () {
var classes = ['item'];
if (this.class) {
var customClasses = this.class.split(' ');
_(customClasses).each(function (customClass) {
classes.push(customClass);
});
}
if (this.avatar) {
classes.push('item-avatar');
... |
return classes.join(' ');
},
isAnchor: function () {
return _.some([this.href,this.path,this.url,this.route],function(path){return path != undefined});
},
target: function () {
return this.target;
},
url: function () {
if (this.href) {
return this.href;
}
if ( this.path |... | {
classes.push('item-text-wrap');
} | conditional_block |
ionItem.js | Template.ionItem.helpers({
itemClasses: function () {
var classes = ['item'];
if (this.class) {
var customClasses = this.class.split(' ');
_(customClasses).each(function (customClass) {
classes.push(customClass);
});
}
if (this.avatar) {
classes.push('item-avatar');
... |
target: function () {
return this.target;
},
url: function () {
if (this.href) {
return this.href;
}
if ( this.path || this.url || this.route ) {
var path = _.find([this.path,this.url,this.route],function(path){return path !=undefined});
if ( this.query || this.hash || this.... | },
isAnchor: function () {
return _.some([this.href,this.path,this.url,this.route],function(path){return path != undefined});
}, | random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2021 Luca Falavigna
#
# Author: Luca Falavigna <dktrkranz@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#... | ['Luca Falavigna'], 1)] | latex_elements = {
'classoptions': ',oneside',
'babel': '\\usepackage[english]{babel}'}
man_pages = [
('index', 'deb-o-matic', 'Deb-o-Matic Documentation', | random_line_split |
snapshot.js | /*
* Snapshot multiple pages using arrays.
*
* Use an array to snapshot specific urls.
* Use per-page selectors.
* Use per-page output paths.
* Remove all script tags from output.
* Use javascript arrays.
*/
var path = require("path");
var util = require("util");
var assert = require("assert");
var htmlSnapsho... | return prev;
}, {}),
// remove all script tags from the output
snapshotScript: {
script: "removeScripts"
}
}, function(err, completed) {
console.log("completed snapshots:");
console.log(util.inspect(completed));
// throw if there was an error
assert.ifError(err);
}); | // per url selectors, { url: selector [, url: selector] }
selector: sites.reduce(function(prev, curr) {
prev[curr.url] = curr.selector; | random_line_split |
organizations.fixtures.js | import Immutable from 'seamless-immutable';
export const initialState = Immutable({
loading: false,
});
export const loadingState = Immutable({
loading: true,
});
export const requestSuccessResponse = Immutable({
label: 'Default_Organization',
owner_details: {
parentOwner: null,
id: 'ff8080815ea5ea44... | result: new Error('Request failed with status code 422'),
type: 'SAVE_ORGANIZATION_FAILURE',
},
]; | random_line_split | |
workspace_folders.rs | use serde::{Deserialize, Serialize};
use url::Url;
use crate::OneOf;
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersServerCapabilities {
/// The server has support for workspace folders
#[serde(skip_serializing_if = "Option... |
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFolder {
/// The associated URI for this workspace folder.
pub uri: Url,
/// The name of the workspace folder. Defaults to the uri's basename.
pub name: String,
}
#[derive(Debug, Eq, P... | /// side. The ID can be used to unregister for these events
/// using the `client/unregisterCapability` request.
#[serde(skip_serializing_if = "Option::is_none")]
pub change_notifications: Option<OneOf<bool, String>>,
} | random_line_split |
workspace_folders.rs | use serde::{Deserialize, Serialize};
use url::Url;
use crate::OneOf;
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersServerCapabilities {
/// The server has support for workspace folders
#[serde(skip_serializing_if = "Option... | {
/// The actual workspace folder change event.
pub event: WorkspaceFoldersChangeEvent,
}
/// The workspace folder change event.
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersChangeEvent {
/// The array of added worksp... | DidChangeWorkspaceFoldersParams | identifier_name |
basicTest.py | import os
import sys
import logging
import datetime
from future.utils import iteritems
from pandaharvester.harvesterconfig import harvester_config
try:
os.remove(harvester_config.db.database_filename)
except Exception:
pass
from pandaharvester.harvestercore.db_proxy_pool import DBProxyPool as DBProxy
from panda... | a.get_jobs('siteName', 'nodeName', 'prodSourceLabel', 'computingElement', 1, {}) |
a = CommunicatorPool() | random_line_split |
basicTest.py | import os
import sys
import logging
import datetime
from future.utils import iteritems
from pandaharvester.harvesterconfig import harvester_config
try:
os.remove(harvester_config.db.database_filename)
except Exception:
pass
from pandaharvester.harvestercore.db_proxy_pool import DBProxyPool as DBProxy
from panda... |
queueConfigMapper = QueueConfigMapper()
proxy = DBProxy()
proxy.make_tables(queueConfigMapper)
job = JobSpec()
job.PandaID = 1
job.modificationTime = datetime.datetime.now()
proxy.insert_jobs([job])
newJob = proxy.get_job(1)
a = CommunicatorPool()
a.get_jobs('siteName', 'nodeName', 'prodSourceLabel', 'computin... | if loggerName.startswith('panda.log'):
if len(loggerObj.handlers) == 0:
continue
if loggerName.split('.')[-1] in ['db_proxy']:
continue
stdoutHandler = logging.StreamHandler(sys.stdout)
stdoutHandler.setFormatter(loggerObj.handlers[0].formatter)
loggerObj.... | conditional_block |
error.rs | // Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not... |
}
| {
Error::SerdeYaml(error)
} | identifier_body |
error.rs | // Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not... | fn from(error: serde_json::error::Error) -> Error {
Error::SerdeJson(error)
}
}
impl From<serde_yaml::error::Error> for Error {
fn from(error: serde_yaml::error::Error) -> Error {
Error::SerdeYaml(error)
}
} | }
}
impl From<serde_json::error::Error> for Error { | random_line_split |
error.rs | // Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not... | (error: serde_json::error::Error) -> Error {
Error::SerdeJson(error)
}
}
impl From<serde_yaml::error::Error> for Error {
fn from(error: serde_yaml::error::Error) -> Error {
Error::SerdeYaml(error)
}
}
| from | identifier_name |
package_repository_modal_body_spec.tsx | /*
* Copyright 2022 ThoughtWorks, 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 the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | () {
helper.mount(() => <PackageRepositoryModalBody pluginInfos={pluginInfos} packageRepo={packageRepo}
disableId={disabled} disablePluginField={disablePluginField}
pluginIdProxy={pluginIdProxy}/>);
}
it('shou... | mount | identifier_name |
package_repository_modal_body_spec.tsx | /*
* Copyright 2022 ThoughtWorks, 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 the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
it('should render input fields for name and package repo', () => {
mount();
expect(helper.byTestId('form-field-input-name')).toBeInDOM();
expect(helper.byTestId('form-field-input-name')).not.toBeDisabled();
expect(helper.byTestId("form-field-input-name")).toHaveValue(packageRepo.name());
expec... | {
helper.mount(() => <PackageRepositoryModalBody pluginInfos={pluginInfos} packageRepo={packageRepo}
disableId={disabled} disablePluginField={disablePluginField}
pluginIdProxy={pluginIdProxy}/>);
} | identifier_body |
package_repository_modal_body_spec.tsx | /*
* Copyright 2022 ThoughtWorks, 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 the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | }); | expect(helper.byTestId('form-field-input-plugin')).toBeInDOM();
expect(helper.byTestId('form-field-input-plugin')).toBeDisabled();
}); | random_line_split |
1541082619105-AddForeignKeyConstraints.ts | import {MigrationInterface, QueryRunner} from "typeorm";
export class AddForeignKeyConstraints1541082619105 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> |
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query("ALTER TABLE `datasets` ADD CONSTRAINT `FK_d717ea97450b05d06316d69501a` FOREIGN KEY (`createdByUserId`) REFERENCES `users` (`id`)")
await queryRunner.query("ALTER TABLE `dataset_files` DROP FOREIGN KEY `dataset_fil... | {
// Remove duplicate foreign key
await queryRunner.query("ALTER TABLE `datasets` DROP FOREIGN KEY `FK_d717ea97450b05d06316d69501a`")
// Add missing foreign key constraints
await queryRunner.query("ALTER TABLE `dataset_files` ADD CONSTRAINT `dataset_files_datasetId` FOREIGN KEY (`dataset... | identifier_body |
1541082619105-AddForeignKeyConstraints.ts | import {MigrationInterface, QueryRunner} from "typeorm";
export class AddForeignKeyConstraints1541082619105 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
// Remove duplicate foreign key
await queryRunner.query("ALTER TABLE `datasets` DROP FOREIGN KEY `FK... | } | await queryRunner.query("ALTER TABLE `sources` DROP FOREIGN KEY `sources_datasetId`")
}
| random_line_split |
1541082619105-AddForeignKeyConstraints.ts | import {MigrationInterface, QueryRunner} from "typeorm";
export class AddForeignKeyConstraints1541082619105 implements MigrationInterface {
public async | (queryRunner: QueryRunner): Promise<any> {
// Remove duplicate foreign key
await queryRunner.query("ALTER TABLE `datasets` DROP FOREIGN KEY `FK_d717ea97450b05d06316d69501a`")
// Add missing foreign key constraints
await queryRunner.query("ALTER TABLE `dataset_files` ADD CONSTRAINT `datas... | up | identifier_name |
google.py | import random
from cloudbot.util import http, formatting
def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=moderate'
return http.get_json(url % kind, q=query)
# @hook.command("googleimage", "gis", "image... | content = http.html.fromstring(content).text_content()
content = formatting.truncate_str(content, 150).replace('\n', '')
return '{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content) | else: | random_line_split |
google.py | import random
from cloudbot.util import http, formatting
def api_get(kind, query):
|
# @hook.command("googleimage", "gis", "image")
def googleimage(text):
"""<query> - returns the first google image result for <query>"""
parsed = api_get('images', text)
if not 200 <= parsed['responseStatus'] < 300:
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'... | """Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=moderate'
return http.get_json(url % kind, q=query) | identifier_body |
google.py | import random
from cloudbot.util import http, formatting
def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=moderate'
return http.get_json(url % kind, q=query)
# @hook.command("googleimage", "gis", "image... |
return '{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content)
| content = http.html.fromstring(content).text_content()
content = formatting.truncate_str(content, 150).replace('\n', '') | conditional_block |
google.py | import random
from cloudbot.util import http, formatting
def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=moderate'
return http.get_json(url % kind, q=query)
# @hook.command("googleimage", "gis", "image... | (text):
"""<query> - returns the first google search result for <query>"""
parsed = api_get('web', text)
if not 200 <= parsed['responseStatus'] < 300:
raise IOError('error searching for pages: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return... | google | identifier_name |
utils.tsx | import { useDispatch } from 'react-redux';
import { useAsync } from 'react-use';
import { formValueSelector, reduxForm } from 'redux-form';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import {
loadFlavors,
loadSecurityGroups,
loadFloatingIps,
loadSubnets,... |
export function getFreeSubnets(
subnets: Option[],
networks: BackupNetworkType[],
currentNetwork: BackupNetworkType,
): Option[] {
const usedSubnets = {};
networks.forEach((network) => {
if (network.subnet) {
usedSubnets[network.subnet] = true;
}
});
return subnets.filter(
(subnet) =>
... | {
return (
subnets.length - 1 > networks.filter((network) => network.subnet).length
);
} | identifier_body |
utils.tsx | import { useDispatch } from 'react-redux';
import { useAsync } from 'react-use';
import { formValueSelector, reduxForm } from 'redux-form';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import {
loadFlavors,
loadSecurityGroups,
loadFloatingIps,
loadSubnets,... |
});
return subnets.filter(
(subnet) =>
!usedSubnets[subnet.value] || subnet.value === currentNetwork.subnet,
);
}
export function getFreeFloatingIps(
floatingIps: Option[],
networks: BackupNetworkType[],
currentNetwork: BackupNetworkType,
): Option[] {
const usedFloatingIps = {};
networks.fo... | {
usedSubnets[network.subnet] = true;
} | conditional_block |
utils.tsx | import { useDispatch } from 'react-redux';
import { useAsync } from 'react-use';
import { formValueSelector, reduxForm } from 'redux-form';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import {
loadFlavors,
loadSecurityGroups,
loadFloatingIps,
loadSubnets,... | (
subnets: Option[],
networks: BackupNetworkType[],
) {
return (
subnets.length - 1 > networks.filter((network) => network.subnet).length
);
}
export function getFreeSubnets(
subnets: Option[],
networks: BackupNetworkType[],
currentNetwork: BackupNetworkType,
): Option[] {
const usedSubnets = {};
... | hasFreeSubnets | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.