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 |
|---|---|---|---|---|
android_bitmap.rs | use core::prelude::*;
use core::raw;
use core::{ptr, mem};
use core::borrow::IntoCow;
use libc::c_void;
use jni::{jobject, jclass, jmethodID, JNIEnv};
use jni_constants::{JNI_TRUE, JNI_FALSE};
use android::bitmap::{AndroidBitmap_getInfo, AndroidBitmap_lockPixels, AndroidBitmap_unlockPixels, AndroidBitmapInfo};
use andr... | }
}
pub unsafe fn set_premultiplied(&mut self, premultiplied: bool) -> bool {
if let Some(set_premultiplied) = SET_PREMULTIPLIED {
let pm = if premultiplied { JNI_TRUE } else { JNI_FALSE };
((**self.env).CallVoidMethod)(self.env, self.obj, set_premultiplied, pm);
... | match self.as_slice_unsafe() {
Ok(ok) => Ok(&*ok),
Err(err) => Err(err), | random_line_split |
android_bitmap.rs | use core::prelude::*;
use core::raw;
use core::{ptr, mem};
use core::borrow::IntoCow;
use libc::c_void;
use jni::{jobject, jclass, jmethodID, JNIEnv};
use jni_constants::{JNI_TRUE, JNI_FALSE};
use android::bitmap::{AndroidBitmap_getInfo, AndroidBitmap_lockPixels, AndroidBitmap_unlockPixels, AndroidBitmapInfo};
use andr... |
pub unsafe fn set_premultiplied(&mut self, premultiplied: bool) -> bool {
if let Some(set_premultiplied) = SET_PREMULTIPLIED {
let pm = if premultiplied { JNI_TRUE } else { JNI_FALSE };
((**self.env).CallVoidMethod)(self.env, self.obj, set_premultiplied, pm);
true
... | {
match self.as_slice_unsafe() {
Ok(ok) => Ok(&*ok),
Err(err) => Err(err),
}
} | identifier_body |
SubmitTarget.ts | import { ISubmit } from "./ISubmit";
import { SubmitKey } from "./SubmitKey";
import { ColorFilter } from "../../filters/ColorFilter"
import { Context } from "../../resource/Context"
import { RenderTexture2D } from "../../resource/RenderTexture2D"
import { Stat } from "../../utils/Stat"
import { WebGLContext } from "..... | _mesh: Mesh2D; //代替 _vb,_ib
/**@internal */
_startIdx: number;
/**@internal */
_numEle: number;
shaderValue: Value2D;
blendType: number = 0;
/**@internal */
_ref: number = 1;
/**@internal */
_key: SubmitKey = new SubmitKey();
srcRT: RenderTexture2D;
constructor() {... | /**@internal */ | random_line_split |
SubmitTarget.ts | import { ISubmit } from "./ISubmit";
import { SubmitKey } from "./SubmitKey";
import { ColorFilter } from "../../filters/ColorFilter"
import { Context } from "../../resource/Context"
import { RenderTexture2D } from "../../resource/RenderTexture2D"
import { Stat } from "../../utils/Stat"
import { WebGLContext } from "..... | esh2D, sv: Value2D, rt: RenderTexture2D): SubmitTarget {
var o: SubmitTarget = (SubmitTarget.POOL as any)._length ? SubmitTarget.POOL[--(SubmitTarget.POOL as any)._length] : new SubmitTarget();
o._mesh = mesh;
o.srcRT = rt;
o._startIdx = mesh.indexNum * CONST3D2D.BYTES_PIDX;
o._r... | esh: M | identifier_name |
SubmitTarget.ts | import { ISubmit } from "./ISubmit";
import { SubmitKey } from "./SubmitKey";
import { ColorFilter } from "../../filters/ColorFilter"
import { Context } from "../../resource/Context"
import { RenderTexture2D } from "../../resource/RenderTexture2D"
import { Stat } from "../../utils/Stat"
import { WebGLContext } from "..... | static POOL: SubmitTarget[] = [];
renderSubmit(): number {
var gl = WebGLContext.mainContext;
this._mesh.useMesh(gl);
var target = this.srcRT;
if (target) {//??为什么会出现为空的情况
this.shaderValue.texture = target._getSource();
this.shaderValue.upload();
... | }
| identifier_body |
SubmitTarget.ts | import { ISubmit } from "./ISubmit";
import { SubmitKey } from "./SubmitKey";
import { ColorFilter } from "../../filters/ColorFilter"
import { Context } from "../../resource/Context"
import { RenderTexture2D } from "../../resource/RenderTexture2D"
import { Stat } from "../../utils/Stat"
import { WebGLContext } from "..... | ): number {
return 0;
}
releaseRender(): void {
if ((--this._ref) < 1) {
var pool: any = SubmitTarget.POOL;
pool[pool._length++] = this;
}
}
static create(context: Context, mesh: Mesh2D, sv: Value2D, rt: RenderTexture2D): SubmitTarget {
var o: Su... | GLContext.mainContext;
gl.enable(gl.BLEND);
BlendMode.fns[this.blendType](gl);
BlendMode.activeBlendFunction = BlendMode.fns[this.blendType];
}
}
getRenderType( | conditional_block |
main.js | var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed a... |
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
'use strict';
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
title: 'Build & Deploy',
... | {
app.quit();
} | conditional_block |
main.js | var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed a... | mainWindow = new BrowserWindow({
width: 1024,
height: 768,
title: 'Build & Deploy',
'auto-hide-menu-bar': true
});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
mainWindow.... | 'use strict';
// Create the browser window. | random_line_split |
identitycertlib.py | #
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of... |
# updated the cert, or at least checked
self.report._status = 1
return self.report
def _get_consumer(self, identity):
# FIXME: not much for error handling here
consumer = self.uep.getConsumer(identity.uuid)
return consumer
| log.debug('identity certificate changed, writing new one')
# FIXME: should be in this module? managerlib is an odd place
managerlib.persist_consumer_cert(consumer) | conditional_block |
identitycertlib.py | #
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of... | (certlib.BaseActionInvoker):
"""
An object to update the identity certificate in the event the server
deems it is about to expire. This is done to prevent the identity
certificate from expiring thus disallowing connection to the server
for updates.
"""
def _do_update(self):
action =... | IdentityCertActionInvoker | identifier_name |
identitycertlib.py | #
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of... |
def _update_cert(self, identity):
# to avoid circular imports
# FIXME: move persist stuff here
from subscription_manager import managerlib
idcert = identity.getConsumerCert()
consumer = self._get_consumer(identity)
# only write the cert if the serial has changed... | identity = inj.require(inj.IDENTITY)
if not identity.is_valid():
# we could in theory try to update the id in the
# case of it being bogus/corrupted, ala #844069,
# but that seems unneeded
# FIXME: more details
self.report._status = 0
retu... | identifier_body |
identitycertlib.py | #
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of... | 1 indicates identity cert was updated."""
def __init__(self):
self.cp_provider = inj.require(inj.CP_PROVIDER)
self.uep = self.cp_provider.get_consumer_auth_cp()
# Use the default report
self.report = certlib.ActionReport()
def perform(self):
identity = inj.require(i... |
class IdentityUpdateAction(object):
"""UpdateAction for consumer identity certificates.
Returns a certlib.ActionReport. report.status of | random_line_split |
htmlbodyelement.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::codegen::HTMLBodyElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBodyElementDeriv... | pub fn VLink(&self) -> DOMString {
~""
}
pub fn SetVLink(&self, _v_link: DOMString) -> ErrorResult {
Ok(())
}
pub fn ALink(&self) -> DOMString {
~""
}
pub fn SetALink(&self, _a_link: DOMString) -> ErrorResult {
Ok(())
}
pub fn BgColor(&self) -> DOM... | Ok(())
}
| random_line_split |
htmlbodyelement.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::codegen::HTMLBodyElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBodyElementDeriv... | (&self) -> DOMString {
~""
}
pub fn SetALink(&self, _a_link: DOMString) -> ErrorResult {
Ok(())
}
pub fn BgColor(&self) -> DOMString {
~""
}
pub fn SetBgColor(&self, _bg_color: DOMString) -> ErrorResult {
Ok(())
}
pub fn Background(&self) -> DOMString ... | ALink | identifier_name |
base.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use std::cmp::{max, min};
use structs::Point;
/// Trait wrapping base range implementation
pub trait Base: Borrow<Point> {
/// Find the points at the same height within the provided manhattan distance
fn base_range(&self, range: i32) -> HashSet<Point>;
}
im... | (&self, range: i32) -> HashSet<Point> {
let mut set: HashSet<Point> = HashSet::new();
for dq in -range..range + 1 {
let lower: i32 = max(-range, -dq - range);
let upper: i32 = min(range, -dq + range);
for ds in lower..upper + 1 {
let dr: i32 = -dq - ds;
let found = self.borro... | base_range | identifier_name |
base.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use std::cmp::{max, min};
use structs::Point;
/// Trait wrapping base range implementation
pub trait Base: Borrow<Point> {
/// Find the points at the same height within the provided manhattan distance
fn base_range(&self, range: i32) -> HashSet<Point>;
}
im... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base_range() {
let point: Point = Point(1, 2, 5);
let set: HashSet<Point> = point.base_range(&point, 1);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(2, 2, 5)));
assert!(set.contains(&Point(1, 3, 5)));
assert!(s... | {
let mut set: HashSet<Point> = HashSet::new();
for dq in -range..range + 1 {
let lower: i32 = max(-range, -dq - range);
let upper: i32 = min(range, -dq + range);
for ds in lower..upper + 1 {
let dr: i32 = -dq - ds;
let found = self.borrow() + &Point(dq, dr, 0);
set.... | identifier_body |
base.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use std::cmp::{max, min};
use structs::Point;
/// Trait wrapping base range implementation
pub trait Base: Borrow<Point> {
/// Find the points at the same height within the provided manhattan distance
fn base_range(&self, range: i32) -> HashSet<Point>;
}
im... | let found = self.borrow() + &Point(dq, dr, 0);
set.insert(found);
}
}
set
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base_range() {
let point: Point = Point(1, 2, 5);
let set: HashSet<Point> = point.base_range(&point, 1);
assert!(set.contains(&Point(1, 2... | let lower: i32 = max(-range, -dq - range);
let upper: i32 = min(range, -dq + range);
for ds in lower..upper + 1 {
let dr: i32 = -dq - ds; | random_line_split |
initData.js | import Provider from './models/provider';
import _ from 'lodash';
export default function () {
Provider.find({}, {name: 1}).exec((err, exists) => {
if (exists && exists.length === 5) {
return;
}
let providers = [];
_.forEach(['openweathermap', 'apixu', 'darksky', 'weatherunlocked', 'wundergro... | console.log('init data...');
}
});
});
} | random_line_split | |
Monomer.js | < 0) interestingID = -interestingID;
if (specialAtomID == interestingID) {
var offset = this.offsets[i] & 0xFF;
return (offset == 255 ? null : this.chain.model.ms.at[this.firstAtomIndex + offset]);
}}
return null;
}, "~A,~N");
Clazz.overrideMethod (c$, "isLeadAtom",
function (atomIndex) {
return atomIndex == this.lea... | vReturn.addLast (Integer.$valueOf (g.leadAtomIndex));
}} | random_line_split | |
PizzaOrder.js | 'use strict';
var formsApp = angular.module('myApp.forms', ['OfflinkJs']);
formsApp.controller('PizzaCtrl', ['$scope', '$http', 'ConnectionDetectorService', function ($scope, $http, ConnectionDetectorService) {
$scope.order = {};
//$scope.order.delivery = {
// value: new Date(1970, 0, 1, 14, 57, 0)
... | $scope.orderSubmitWithoutCache = function () {
// Simple POST request example (passing data) :
$http.post('http://httpbin.org/post', $scope.order, {"flnk_cache": false}).
then(function (response) {
$scope.result = response;
}, function (response) {
... | }, function (response) {
$scope.result = response;
});
};
| random_line_split |
test_glutwindow.py | """Test simple functions (i.e. no pointers involved)"""
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time
start = time.time()
window = None
def drawText( value, x,y, windowHeight, windowWidth, step = 18 ):
"""Draw the given text at given 2D position in window
"""
glMa... |
def ontimer( *args ):
print 'timer', args, '@time', time.time()-start
glutTimerFunc( 1000, ontimer, 24 )
def idle():
delta = time.time()-start
if delta < 10:
global size
x,y = size
if delta < 5:
change = +1
else:
change = -1
x = x-chan... | global size
size = args
glViewport( *( (0,0)+args) )
display() | identifier_body |
test_glutwindow.py | """Test simple functions (i.e. no pointers involved)"""
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time
start = time.time()
window = None
def | ( value, x,y, windowHeight, windowWidth, step = 18 ):
"""Draw the given text at given 2D position in window
"""
glMatrixMode(GL_PROJECTION);
# For some reason the GL_PROJECTION_MATRIX is overflowing with a single push!
# glPushMatrix()
matrix = glGetDouble( GL_PROJECTION_MATRIX )
glLoa... | drawText | identifier_name |
test_glutwindow.py | """Test simple functions (i.e. no pointers involved)"""
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time
start = time.time()
window = None
def drawText( value, x,y, windowHeight, windowWidth, step = 18 ):
"""Draw the given text at given 2D position in window
"""
glMa... | glMatrixMode(GL_MODELVIEW);
def display():
glutSetWindow(window);
glClearColor (0.0, 0.0, (time.time()%1.0)/1.0, 0.0)
glClear (GL_COLOR_BUFFER_BIT)
drawText( 'hello', 20,20, size[0],size[1] )
#glutBitmapCharacter( GLUT_BITMAP_8_BY_13, ord('a'))
glutSolidTeapot( .2 )
glFlush ()
glutS... | random_line_split | |
test_glutwindow.py | """Test simple functions (i.e. no pointers involved)"""
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time
start = time.time()
window = None
def drawText( value, x,y, windowHeight, windowWidth, step = 18 ):
"""Draw the given text at given 2D position in window
"""
glMa... | glutTimerFunc( 1000, ontimer, 23 )
glutIdleFunc( idle )
glutMainLoop() | import sys
newArgv = glutInit(sys.argv)
print 'newArguments', newArgv
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB )
glutInitWindowSize(250, 250)
glutInitWindowPosition(100, 100)
window = glutCreateWindow("hello")
print 'window', repr(window)
glutDisplayFunc(display)
glutReshapeFunc(r... | conditional_block |
mocks.rs | use crate::{
cart::Cart,
rom::{CHR_BANK_SIZE, PRG_BANK_SIZE},
};
pub struct CartMock {
pub prg: [u8; PRG_BANK_SIZE],
pub chr: [u8; CHR_BANK_SIZE],
}
impl Default for CartMock {
fn default() -> Self {
CartMock {
prg: [0; PRG_BANK_SIZE],
chr: [0; CHR_BANK_SIZE],
... | (&mut self, addr: u16, value: u8) {
self.prg[addr as usize] = value
}
fn read_chr(&self, addr: u16) -> u8 {
self.chr[addr as usize]
}
fn write_chr(&mut self, addr: u16, value: u8) {
self.chr[addr as usize] = value
}
}
| write_prg | identifier_name |
mocks.rs | use crate::{
cart::Cart,
rom::{CHR_BANK_SIZE, PRG_BANK_SIZE},
};
pub struct CartMock {
pub prg: [u8; PRG_BANK_SIZE],
pub chr: [u8; CHR_BANK_SIZE],
}
impl Default for CartMock {
fn default() -> Self {
CartMock {
prg: [0; PRG_BANK_SIZE],
chr: [0; CHR_BANK_SIZE],
... | fn read_prg(&self, addr: u16) -> u8 {
self.prg[addr as usize]
}
fn write_prg(&mut self, addr: u16, value: u8) {
self.prg[addr as usize] = value
}
fn read_chr(&self, addr: u16) -> u8 {
self.chr[addr as usize]
}
fn write_chr(&mut self, addr: u16, value: u8) {
... | }
}
impl Cart for CartMock { | random_line_split |
build.rs | use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use time::{strftime, now};
use std::process::Command;
fn main() {
let version = env::var("CARGO_PKG_VERSION").unwrap();
let timestamp = strftime("%F %H:%M:%S %z", &now()).unwrap();
let commit = get_head_comm... | (contents: &str, filename: &str) {
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let file = out_dir.join(filename);
let debug_path = file.to_str().unwrap().to_string();
File::create(file)
.expect(&format!("Unable to create file {:?}", debug_path))
.write_all(contents.as_b... | write | identifier_name |
build.rs | use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use time::{strftime, now};
use std::process::Command;
fn main() {
let version = env::var("CARGO_PKG_VERSION").unwrap();
let timestamp = strftime("%F %H:%M:%S %z", &now()).unwrap();
let commit = get_head_comm... | } | File::create(file)
.expect(&format!("Unable to create file {:?}", debug_path))
.write_all(contents.as_bytes())
.expect(&format!("Unable to write string '{}' to file {:?}", contents, debug_path)); | random_line_split |
build.rs | use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use time::{strftime, now};
use std::process::Command;
fn main() {
let version = env::var("CARGO_PKG_VERSION").unwrap();
let timestamp = strftime("%F %H:%M:%S %z", &now()).unwrap();
let commit = get_head_comm... | {
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let file = out_dir.join(filename);
let debug_path = file.to_str().unwrap().to_string();
File::create(file)
.expect(&format!("Unable to create file {:?}", debug_path))
.write_all(contents.as_bytes())
.expect(&format!(... | identifier_body | |
auth.js | // The client ID is obtained from the {{ Google Cloud Console }}
// at {{ https://cloud.google.com/console }}.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '111436808615-d7mam74ms4a49846vpq7iqmn8ihu6mdu.apps.googleusercontent.com';... | (authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-lin... | handleAuthResult | identifier_name |
auth.js | // The client ID is obtained from the {{ Google Cloud Console }}
// at {{ https://cloud.google.com/console }}.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '111436808615-d7mam74ms4a49846vpq7iqmn8ihu6mdu.apps.googleusercontent.com';... | else {
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
... | {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} | conditional_block |
auth.js | // The client ID is obtained from the {{ Google Cloud Console }}
// at {{ https://cloud.google.com/console }}.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '111436808615-d7mam74ms4a49846vpq7iqmn8ihu6mdu.apps.googleusercontent.com';... |
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api
function loadAPIClientInterfaces() {
gapi.cli... | {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-link clickable. ... | identifier_body |
auth.js | // The client ID is obtained from the {{ Google Cloud Console }}
// at {{ https://cloud.google.com/console }}.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '111436808615-d7mam74ms4a49846vpq7iqmn8ihu6mdu.apps.googleusercontent.com';... | window.setTimeout(checkAuth, 1);
});
}
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fail... | // Upon loading, the Google APIs JS client automatically invokes this callback.
googleApiClientReady = function() {
gapi.auth.init(function() { | random_line_split |
app.js | var docDbClient = new azure.DocumentDbClient({
host: process.env.DOCUMENT_DB_HOST,
masterKey: process.env.DOCUMENT_DB_MASTER_KEY,
database: process.env.DOCUMENT_DB_DATABASE,
collection: process.env.DOCUMENT_DB_COLLECTION
});
var botStorage = new azure.AzureBotStorage({
gzipData: false
}, docDbClient... | {
// look up the person in the datbase or whatever
switch (personId) {
case "fdf13948-37ab-43f6-b336-27cddb00dc5c":
return "Jimmy McKewen";
case "c4524afb-9576-4885-9c54-b4e64eb4f98c":
return "Sandy Vincentia";
case "9f96c9fc-c700-41c4-b0c2-8a2a567c5fcd":
... | identifier_body | |
app.js | process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
// keys for storage
var contextStateKey = 'ConversationContextStack';
var stravaIdKey = 'StravaId';
var locationKey = 'Location';
var welcomedKey = 'UserWelcomed';
// Azure Documen... | else if (query == 'who are they') {
var userTimes = [{
"person": "fdf13948-37ab-43f6-b336-27cddb00dc5c",
"time": "08:14.6"
},
{
"person": "c4524afb-9576-4885-9c54-b4e64eb4f98c",
"time": "08:18.0"
},
... | {
newContextState = {
"queryTime": moment().utc().toISOString(),
"queryString": query,
"responseType": "scalar",
"entityType": "count",
"responseData": 4
};
fullResponse = {
"responseType": "plainText",
"respons... | conditional_block |
app.js | new azure.DocumentDbClient({
host: process.env.DOCUMENT_DB_HOST,
masterKey: process.env.DOCUMENT_DB_MASTER_KEY,
database: process.env.DOCUMENT_DB_DATABASE,
collection: process.env.DOCUMENT_DB_COLLECTION
});
var botStorage = new azure.AzureBotStorage({
gzipData: false
}, docDbClient);
// Setup bot ... | GetUserMotto | identifier_name | |
app.js | process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
// keys for storage
var contextStateKey = 'ConversationContextStack';
var stravaIdKey = 'StravaId';
var locationKey = 'Location';
var welcomedKey = 'UserWelcomed';
// Azure Documen... | });
var botStorage = new azure.AzureBotStorage({
gzipData: false
}, docDbClient);
// Setup bot with default dialog
var bot = new builder.UniversalBot(connector, function (session) {
var welcomed = session.privateConversationData[welcomedKey];
if (!welcomed) {
session.send('Welcome to StravaBot');
... | random_line_split | |
assets.js | : "12 otOT_CARRIER Carrier", "required" : "Y", "description" : "Trucks and M5 HTs - carrier of supplies and troops." },
{"name": "BB", "label" : "Boat", "damage" : "1000", "sdesc" : "13 otOT_BOMBABLE_BOAT Bombable boat", "required" : "Y", "description" : "Vic56 small coastal boat" },
{"name": "ST", "label" : "Stra... | {"name": "SM", "label" : "Struct", "damage" : "500", "sdesc" : "22 otOT_STRUCTURE_MODULE Structure module", "required" : "Y", "description" : "Any small structure necessary for base closure." },
{"name": "CM", "label" : "Cargo", "damage" : "1500", "sdesc" : "23 otOT_CARGO_MODULE Cargo module", "required" : "Y", "de... | {"name": "FM", "label" : "FacMod", "damage" : "4000", "sdesc" : "19 otOT_FACTORY_MODULE Factory module", "required" : "Y", "description" : "Various medium-sized associated factory buildings." },
{"name": "LM", "label" : "LivMod", "damage" : "2000", "sdesc" : "20 otOT_LIVING_MODULE Living module", "required" : "Y", ... | random_line_split |
assets.js | " : "Various large factory buildings at industry locations." },
{"name": "EB", "label" : "FactComplex", "damage" : "5000", "sdesc" : "43 otOT_FACTCOMPLEX FactComplex", "required" : "Y", "description" : "Very large factory building at industry locations." },
{"name": "EC", "label" : "FactAvionics", "damage" : "3000"... | {
return this.assets[i];
} | conditional_block | |
__init__.py | #!/usr/bin/env python
################################################################################
# GIPS: Geospatial Image Processing System
#
# AUTHOR: Matthew Hanson
# EMAIL: matt.a.hanson@gmail.com
#
# Copyright (C) 2014-2018 Applied Geosolutions
#
# This program is free software; you can redist... |
__version__ = detect_version()
| """Emit GIPS' software version. May be overridden for testing purposes.
To override version.py, put a desired version string in the environment
variable GIPS_OVERRIDE_VERSION."""
return os.environ.get('GIPS_OVERRIDE_VERSION', version.__version__) | identifier_body |
__init__.py | #!/usr/bin/env python
################################################################################
# GIPS: Geospatial Image Processing System
#
# AUTHOR: Matthew Hanson
# EMAIL: matt.a.hanson@gmail.com
#
# Copyright (C) 2014-2018 Applied Geosolutions
#
# This program is free software; you can redist... | ():
"""Emit GIPS' software version. May be overridden for testing purposes.
To override version.py, put a desired version string in the environment
variable GIPS_OVERRIDE_VERSION."""
return os.environ.get('GIPS_OVERRIDE_VERSION', version.__version__)
__version__ = detect_version()
| detect_version | identifier_name |
__init__.py | #!/usr/bin/env python
################################################################################
# GIPS: Geospatial Image Processing System | #
# Copyright (C) 2014-2018 Applied Geosolutions
#
# 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; either version 3 of the License, or
# (at your option) any later version.
#
# ... | #
# AUTHOR: Matthew Hanson
# EMAIL: matt.a.hanson@gmail.com | random_line_split |
runner.py | """
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def ingest_data(args):
"""
Write data to database w... | if len(results.synths) > 0:
synth_ids = results.synths.to_pandas().loc[:, ['synth_id']]
for plane in config.synth_check_masks:
masked = hugs.synths.find_masked_synths(results.synths,
results.exp_clean,
... | results = next_gen_search.run(config, False)
pm = results.hugs_exp.patch_meta
if (results.synths is not None) and results.success: | random_line_split |
runner.py | """
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def ingest_data(args):
"""
Write data to database w... | else:
results = next_gen_search.run(config, False)
pm = results.hugs_exp.patch_meta
if (results.synths is not None) and results.success:
if len(results.synths) > 0:
synth_ids = results.synths.to_pandas().loc[:, ['synth_id']]
for plane in config.synth_check_masks:
... | """
Workers initialize pipe configuration and run pipeline.
"""
rank = MPI.COMM_WORLD.Get_rank()
if p['seed'] is None:
tract, p1, p2 = p['tract'], int(p['patch'][0]), int(p['patch'][-1])
seed = [int(time()), tract, p1, p2, rank]
else:
seed = p['seed']
config = hugs.PipeC... | identifier_body |
runner.py | """
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def ingest_data(args):
"""
Write data to database w... |
else:
seed = p['seed']
config = hugs.PipeConfig(run_name=p['run_name'],
config_fn=p['config_fn'],
random_state=seed,
log_fn=p['log_fn'],
rerun_path=p['rerun_path'])
config.set_patc... | tract, p1, p2 = p['tract'], int(p['patch'][0]), int(p['patch'][-1])
seed = [int(time()), tract, p1, p2, rank] | conditional_block |
runner.py | """
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def | (args):
"""
Write data to database with the master process.
"""
timer = time()
success, sources, meta_data, synth_ids = args
run_name, tract, patch, patch_meta = meta_data
db_ingest = hugs.database.HugsIngest(session, run_name)
if success:
db_ingest.add_all(tract, patch, patch_me... | ingest_data | identifier_name |
sitemessage_send_scheduled.py | from traceback import format_exc
from django.core.management.base import BaseCommand
from ...toolbox import send_scheduled_messages
class Command(BaseCommand):
| self.stderr.write(self.style.ERROR(f'Error on send: {e}\n{format_exc()}'))
else:
self.stdout.write('Sending done.\n')
| help = 'Sends scheduled messages (both in pending and error statuses).'
def add_arguments(self, parser):
parser.add_argument(
'--priority', action='store', dest='priority', default=None,
help='Allows to filter scheduled messages by a priority number. Defaults to None.')
def han... | identifier_body |
sitemessage_send_scheduled.py | from traceback import format_exc
from django.core.management.base import BaseCommand
from ...toolbox import send_scheduled_messages
class Command(BaseCommand):
help = 'Sends scheduled messages (both in pending and error statuses).'
def add_arguments(self, parser):
parser.add_argument(
... | self.stdout.write('Sending done.\n') | conditional_block | |
sitemessage_send_scheduled.py | from traceback import format_exc
from django.core.management.base import BaseCommand
from ...toolbox import send_scheduled_messages
class Command(BaseCommand):
help = 'Sends scheduled messages (both in pending and error statuses).'
def add_arguments(self, parser):
parser.add_argument(
... | priority_str = ''
if priority is not None:
priority_str = f'with priority {priority} '
self.stdout.write(f'Sending scheduled messages {priority_str} ...\n')
try:
send_scheduled_messages(priority=priority)
except Exception as e:
self.stderr.... | help='Allows to filter scheduled messages by a priority number. Defaults to None.')
def handle(self, *args, **options):
priority = options.get('priority', None) | random_line_split |
sitemessage_send_scheduled.py | from traceback import format_exc
from django.core.management.base import BaseCommand
from ...toolbox import send_scheduled_messages
class Command(BaseCommand):
help = 'Sends scheduled messages (both in pending and error statuses).'
def add_arguments(self, parser):
parser.add_argument(
... | (self, *args, **options):
priority = options.get('priority', None)
priority_str = ''
if priority is not None:
priority_str = f'with priority {priority} '
self.stdout.write(f'Sending scheduled messages {priority_str} ...\n')
try:
send_scheduled_messages(... | handle | identifier_name |
record.py | from sys import byteorder
from array import array
from struct import pack
from multiprocessing import Process
import unreal_engine as ue
import pyaudio
import wave
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def is_silent(snd_data):
"Returns 'True' if below the 'silent' t... | snd_data.reverse()
snd_data = _trim(snd_data)
snd_data.reverse()
return snd_data
def add_silence(snd_data, seconds):
"Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
r = array('h', [0 for i in range(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0... | # Trim to the right
| random_line_split |
record.py | from sys import byteorder
from array import array
from struct import pack
from multiprocessing import Process
import unreal_engine as ue
import pyaudio
import wave
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def | (snd_data):
"Returns 'True' if below the 'silent' threshold"
return max(snd_data) < THRESHOLD
def normalize(snd_data):
"Average the volume out"
MAXIMUM = 16384
times = float(MAXIMUM)/max(abs(i) for i in snd_data)
r = array('h')
for i in snd_data:
r.append(int(i*times))
... | is_silent | identifier_name |
record.py | from sys import byteorder
from array import array
from struct import pack
from multiprocessing import Process
import unreal_engine as ue
import pyaudio
import wave
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def is_silent(snd_data):
"Returns 'True' if below the 'silent' t... |
return r
# Trim to the left
snd_data = _trim(snd_data)
# Trim to the right
snd_data.reverse()
snd_data = _trim(snd_data)
snd_data.reverse()
return snd_data
def add_silence(snd_data, seconds):
"Add silence to the start and end of 'snd_data' of length 'seconds' (fl... | r.append(i) | conditional_block |
record.py | from sys import byteorder
from array import array
from struct import pack
from multiprocessing import Process
import unreal_engine as ue
import pyaudio
import wave
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def is_silent(snd_data):
"Returns 'True' if below the 'silent' t... |
def record():
"""
Record a word or words from the microphone and
return the data as an array of signed shorts.
Normalizes the audio, trims silence from the
start and end, and pads with 0.5 seconds of
blank sound to make sure VLC et al can play
it without getting chopped off.... | "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
r = array('h', [0 for i in range(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0 for i in range(int(seconds*RATE))])
return r | identifier_body |
lib.rs | #![crate_name = "mockstream"]
#![crate_type = "lib"]
//! A reader/writer streams to mock real streams in tests.
use std::cell::RefCell;
use std::io::{Cursor, Error, ErrorKind, Read, Result, Write};
use std::mem::swap;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std:... |
}
}
impl Read for FailingMockStream {
fn read(&mut self, _: &mut [u8]) -> Result<usize> {
self.error()
}
}
impl Write for FailingMockStream {
fn write(&mut self, _: &[u8]) -> Result<usize> {
self.error()
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
| {
if self.repeat_count > 0 {
self.repeat_count -= 1;
}
Err(Error::new(self.kind, self.message))
} | conditional_block |
lib.rs | #![crate_name = "mockstream"]
#![crate_type = "lib"]
//! A reader/writer streams to mock real streams in tests.
use std::cell::RefCell;
use std::io::{Cursor, Error, ErrorKind, Read, Result, Write};
use std::mem::swap;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std:... | (&mut self, _: &[u8]) -> Result<usize> {
self.error()
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
| write | identifier_name |
lib.rs | #![crate_name = "mockstream"]
#![crate_type = "lib"]
//! A reader/writer streams to mock real streams in tests.
use std::cell::RefCell;
use std::io::{Cursor, Error, ErrorKind, Read, Result, Write};
use std::mem::swap;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std:... | fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.pimpl.borrow_mut().write(buf)
}
fn flush(&mut self) -> Result<()> {
self.pimpl.borrow_mut().flush()
}
}
/// Thread-safe stream.
#[derive(Clone, Default)]
pub struct SyncMockStream {
pimpl: Arc<Mutex<MockStream>>,
pub waiti... | impl Write for SharedMockStream { | random_line_split |
lib.rs | #![crate_name = "mockstream"]
#![crate_type = "lib"]
//! A reader/writer streams to mock real streams in tests.
use std::cell::RefCell;
use std::io::{Cursor, Error, ErrorKind, Read, Result, Write};
use std::mem::swap;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std:... |
}
impl Read for SharedMockStream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.pimpl.borrow_mut().read(buf)
}
}
impl Write for SharedMockStream {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.pimpl.borrow_mut().write(buf)
}
fn flush(&mut self) -> Result<(... | {
self.pimpl.borrow_mut().pop_bytes_written()
} | identifier_body |
app.updatebook.component.ts | import { Component , OnInit} from '@angular/core';
import { Book } from './app.book';
import { BookService } from './app.book.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector:'update-book',
templateUrl: 'views/app.updatebook.component.html',
})
export class UpdateBook ... | (private activatedRoute: ActivatedRoute, private bookService: BookService) { }
ngOnInit(): void {
this.activatedRoute.params.
subscribe((param:any) =>{
this.isbn = param['isbn'];
this.book = this.bookService.getBook(this.isbn);
this.name = this.book.name;
this.author = thi... | constructor | identifier_name |
app.updatebook.component.ts | import { Component , OnInit} from '@angular/core';
import { Book } from './app.book';
import { BookService } from './app.book.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector:'update-book',
templateUrl: 'views/app.updatebook.component.html',
})
export class UpdateBook ... | } | random_line_split | |
Board.ts | /// <reference path="../lib/phaser.d.ts" />
/// <reference path="Letter.ts" />
module states {
export class Board {
TILES_PER_ROW = 4;
game: Phaser.Game;
row: number;
column: number;
letters: Letter[];
font = 'bold 60pt Arial';
font2letters = 'bold 42pt Arial... | (game: Phaser.Game, letters: string[]) {
this.game = game;
this.height = Math.min(game.width, game.height);
this.width = this.height;
this.letters = [];
for (var i = 0; i < letters.length; i++) {
var x = (this.width / this.TILES_PER_ROW) * (i %... | constructor | identifier_name |
Board.ts | /// <reference path="../lib/phaser.d.ts" />
/// <reference path="Letter.ts" />
module states {
export class Board {
TILES_PER_ROW = 4;
game: Phaser.Game;
row: number;
column: number;
letters: Letter[];
font = 'bold 60pt Arial';
font2letters = 'bold 42pt Arial... |
}
isSpecialLetter(letter: string): boolean {
return (letter === 'NY' || letter === 'L·L');
}
createLetter(letter: string, x: number, y: number): Letter {
if (this.isSpecialLetter(letter)) {
return new Letter(this.game, x, y, letter, this.font2le... | {
var x = (this.width / this.TILES_PER_ROW) * (i % this.TILES_PER_ROW) + (this.width / this.TILES_PER_ROW) / 2;
var y = (this.height / this.TILES_PER_ROW) * Math.floor((i / this.TILES_PER_ROW));// - (this.width / this.TILES_PER_ROW) / 2;
this.letters.push(this.createLette... | conditional_block |
Board.ts | /// <reference path="../lib/phaser.d.ts" />
/// <reference path="Letter.ts" />
module states {
export class Board {
TILES_PER_ROW = 4;
game: Phaser.Game;
row: number;
column: number;
letters: Letter[];
font = 'bold 60pt Arial';
font2letters = 'bold 42pt Arial... |
isSpecialLetter(letter: string): boolean {
return (letter === 'NY' || letter === 'L·L');
}
createLetter(letter: string, x: number, y: number): Letter {
if (this.isSpecialLetter(letter)) {
return new Letter(this.game, x, y, letter, this.font2letters);
... | {
this.game = game;
this.height = Math.min(game.width, game.height);
this.width = this.height;
this.letters = [];
for (var i = 0; i < letters.length; i++) {
var x = (this.width / this.TILES_PER_ROW) * (i % this.TILES_PER_ROW) + (this.width / th... | identifier_body |
Board.ts | /// <reference path="../lib/phaser.d.ts" />
/// <reference path="Letter.ts" />
module states {
export class Board {
TILES_PER_ROW = 4;
game: Phaser.Game;
row: number;
column: number; | width: number;
height: number;
constructor(game: Phaser.Game, letters: string[]) {
this.game = game;
this.height = Math.min(game.width, game.height);
this.width = this.height;
this.letters = [];
for (var i = 0; i < letters.length; i++... | letters: Letter[];
font = 'bold 60pt Arial';
font2letters = 'bold 42pt Arial'; | random_line_split |
shader-convolution.js |
define(["three"],
/**
* Extend THREE namespace with ConvolutionShader
*/
function(THREE) {
/**
* @author alteredq / http://alteredqualia.com/
*
* Convolution shader
* ported from o3d sample to WebGL / GLSL
* http://o3d.googlecode.com/svn/trunk/samples/convolution.html
*/
THREE.Convoluti... |
var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
halfWidth = ( kernelSize - 1 ) * 0.5;
values = new Array( kernelSize );
sum = 0.0;
for ( i = 0; i < kernelSize; ++i ) {
val... | {
return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
} | identifier_body |
shader-convolution.js |
define(["three"],
/**
* Extend THREE namespace with ConvolutionShader
*/
function(THREE) {
/**
* @author alteredq / http://alteredqualia.com/
*
* Convolution shader
* ported from o3d sample to WebGL / GLSL
* http://o3d.googlecode.com/svn/trunk/samples/convolution.html
*/
THREE.Convoluti... | ( x, sigma ) {
return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
}
var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
halfWidth = ( kernelSize - 1 ) * 0.5;
values = new A... | gauss | identifier_name |
shader-convolution.js | define(["three"],
/**
* Extend THREE namespace with ConvolutionShader
*/
function(THREE) {
/**
* @author alteredq / http://alteredqualia.com/
*
* Convolution shader
* ported from o3d sample to WebGL / GLSL
* http://o3d.googlecode.com/svn/trunk/samples/convolution.html
*/
THREE.Convolutio... | "tDiffuse": { type: "t", value: null },
"uImageIncrement": { type: "v2", value: new THREE.Vector2( 0.001953125, 0.0 ) },
"cKernel": { type: "fv1", value: [] }
},
vertexShader: [
"uniform vec2 uImageIncrement;",
"varying vec2 vUv;",
"void main() {",
"vUv = uv - ( (... | uniforms: {
| random_line_split |
MD-MuellerBrown.py | from MuellerBrown import getPotentialAndForces
from PlotUtils import PlotUtils
import numpy as np
import matplotlib.pyplot as plt
import MuellerBrown as mbpot
m=1.0
def getKineticEnergy(velocity):
|
dt = 0.01
num_steps = 1000
#initial_position = np.array( [ 0.0 , 0.0 ] )
initial_position = mbpot.saddlePoints[0]
initial_velocity = np.array( [ 1.0 , -1.0 ] )
position = np.zeros([num_steps+1,2])
velocity = np.zeros([num_steps+1,2])
potential_energy = np.zeros(num_steps+1)
kinetic_energy = np.zeros(num_step... | return 0.5*m*(velocity[0]**2+velocity[1]**2) | identifier_body |
MD-MuellerBrown.py | from MuellerBrown import getPotentialAndForces
from PlotUtils import PlotUtils
import numpy as np
import matplotlib.pyplot as plt
import MuellerBrown as mbpot
m=1.0
def | (velocity):
return 0.5*m*(velocity[0]**2+velocity[1]**2)
dt = 0.01
num_steps = 1000
#initial_position = np.array( [ 0.0 , 0.0 ] )
initial_position = mbpot.saddlePoints[0]
initial_velocity = np.array( [ 1.0 , -1.0 ] )
position = np.zeros([num_steps+1,2])
velocity = np.zeros([num_steps+1,2])
potential_energ... | getKineticEnergy | identifier_name |
MD-MuellerBrown.py | from MuellerBrown import getPotentialAndForces
from PlotUtils import PlotUtils
import numpy as np
import matplotlib.pyplot as plt | m=1.0
def getKineticEnergy(velocity):
return 0.5*m*(velocity[0]**2+velocity[1]**2)
dt = 0.01
num_steps = 1000
#initial_position = np.array( [ 0.0 , 0.0 ] )
initial_position = mbpot.saddlePoints[0]
initial_velocity = np.array( [ 1.0 , -1.0 ] )
position = np.zeros([num_steps+1,2])
velocity = np.zeros([num_... | import MuellerBrown as mbpot
| random_line_split |
MD-MuellerBrown.py | from MuellerBrown import getPotentialAndForces
from PlotUtils import PlotUtils
import numpy as np
import matplotlib.pyplot as plt
import MuellerBrown as mbpot
m=1.0
def getKineticEnergy(velocity):
return 0.5*m*(velocity[0]**2+velocity[1]**2)
dt = 0.01
num_steps = 1000
#initial_position = np.array( [ 0.0 , ... |
total_energy = potential_energy + kinetic_energy
pu = PlotUtils(mbpot,[200,200])
pu.plotPotential(trajectory=position)
plt.figure(1)
plt.plot(times,position[:,0])
plt.figure(2)
plt.plot(times,position[:,1])
plt.figure(3)
plt.plot(times,potential_energy)
plt.figure(4)
plt.plot(times,kinetic_energy)
plt.figure(5)
pl... | position[i+1] = position[i] + velocity[i]*dt+0.5*(force/m)*dt**2
# get velocity at t+dt
(new_pot, new_force) = getPotentialAndForces(position[i+1])
velocity[i+1] = velocity[i] + (0.5/m)*(new_force+force)*dt
# add stuff
kinetic_energy[i+1] = getKineticEnergy(velocity[i+1])
potential_energy[i+1] =... | conditional_block |
settings.py | """
Django settings for asucourses project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... |
WSGI_APPLICATION = 'asucourses.wsgi.application'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates')
)
STATICFILES_DIRS = [
os.pat... | 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'asucourses.urls' | random_line_split |
WindowClass.rs | /**
Window Class Structures (Windows) / WNDCLASS structure (Windows)
**/
extern crate std;
use super::super::prelude::{
UINT , WNDPROC , CCINT , HINSTANCE , HICON , HCURSOR ,
HBRUSH , LPCTSTR , wapi , ToWindowTextConvertion ,
Application , Cursor , Icon , Text , WindowProcedure ,
Atom , Brush , ... | }
}
pub fn unregister(&self , app : Option<Application>) -> bool {
WindowService::UnregisterClass(self.lpszClassName , app)
}
} |
pub fn RegisterClass(&self) -> Atom {
unsafe {
wapi::WindowClass::RegisterClassW(self as *const WNDCLASS) | random_line_split |
WindowClass.rs | /**
Window Class Structures (Windows) / WNDCLASS structure (Windows)
**/
extern crate std;
use super::super::prelude::{
UINT , WNDPROC , CCINT , HINSTANCE , HICON , HCURSOR ,
HBRUSH , LPCTSTR , wapi , ToWindowTextConvertion ,
Application , Cursor , Icon , Text , WindowProcedure ,
Atom , Brush , ... | {
style : UINT , /* WindowClassStyle */
lpfnWndProc : WNDPROC , /* WindowProcedure */
cbClsExtra : CCINT , /* CCINT */
cbWndExtra : CCINT , /* CCINT */
hInstance : HINSTANCE , /* Application */
hIcon : HICON , /* Icon */
hCurs... | WindowClass | identifier_name |
help_info_extracter.py | in the section named for its scope).
typ: The type of the option.
default: The value of this option if no flags are specified (derived from config and env vars).
help: The help message registered for this option.
deprecated_message: If deprecated: A message explaining that this option is deprecated at
... | """All available help info."""
scope_to_help_info: Dict[str, OptionScopeHelpInfo]
name_to_goal_info: Dict[str, GoalHelpInfo]
name_to_target_type_info: Dict[str, TargetTypeHelpInfo]
ConsumedScopesMapper = Callable[[str], Tuple[str, ...]]
class HelpInfoExtracter:
"""Extracts information useful fo... | @dataclass(frozen=True)
class AllHelpInfo: | random_line_split |
help_info_extracter.py | _choices = sorted(
field.valid_choices
if isinstance(field.valid_choices, tuple)
else (choice.value for choice in field.valid_choices)
)
type_hint = " | ".join([*(repr(c) for c in valid_choices), "None"])
if field.required:
# W... | type_str = self.stringify_type(kwargs.get("member_type", str))
display_args.append(f"... -- [{type_str} [{type_str} [...]]]") | conditional_block | |
help_info_extracter.py | the section named for its scope).
typ: The type of the option.
default: The value of this option if no flags are specified (derived from config and env vars).
help: The help message registered for this option.
deprecated_message: If deprecated: A message explaining that this option is deprecated at
... |
if is_goal:
goal_subsystem_cls = cast(Type[GoalSubsystem], optionable_cls)
is_implemented = union_membership.has_members_for_all(
goal_subsystem_cls.required_union_implementations
)
name_to_goal_info[scope_info.scope] = Goa... | scope_to_help_info = {}
name_to_goal_info = {}
for scope_info in sorted(options.known_scope_to_info.values(), key=lambda x: x.scope):
options.for_scope(scope_info.scope) # Force parsing.
optionable_cls = scope_info.optionable_cls
if not scope_info.description:
... | identifier_body |
help_info_extracter.py | the section named for its scope).
typ: The type of the option.
default: The value of this option if no flags are specified (derived from config and env vars).
help: The help message registered for this option.
deprecated_message: If deprecated: A message explaining that this option is deprecated at
... | :
"""A container for help information for a target type."""
alias: str
summary: Optional[str]
description: Optional[str]
fields: Tuple[TargetFieldHelpInfo, ...]
@classmethod
def create(
cls, target_type: Type[Target], *, union_membership: UnionMembership
) -> TargetTypeHelpInfo... | TargetTypeHelpInfo | identifier_name |
volread.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
import numpy as np
import os
# Try importing imageio
imageio = None
try:
import imageio
except ImportError:
pass
... |
if __name__ == '__main__':
vol = vv.volread('stent')
t = vv.volshow(vol)
t.renderStyle = 'mip' # maximum intensity projection (is the default)
| raise RuntimeError("visvis.volread needs the imageio package to read arbitrary files.") | conditional_block |
volread.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
import numpy as np
import os
# Try importing imageio
imageio = None
try:
import imageio
except ImportError:
pass
... | elif imageio is not None:
return imageio.volread(filename)
else:
raise RuntimeError("visvis.volread needs the imageio package to read arbitrary files.")
if __name__ == '__main__':
vol = vv.volread('stent')
t = vv.volshow(vol)
t.renderStyle = 'mip' # maximum inten... | """ volread(filename)
Read volume from a file. If filename is 'stent', read a dedicated
test dataset. For reading any other kind of volume, the imageio
package is required.
"""
if filename == 'stent':
# Get full filename
path = vv.misc.getResourceDir()
filenam... | identifier_body |
volread.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
import numpy as np
import os
# Try importing imageio
imageio = None
try:
import imageio
except ImportError:
pass
... | """
if filename == 'stent':
# Get full filename
path = vv.misc.getResourceDir()
filename2 = os.path.join(path, 'stent_vol.ssdf')
if os.path.isfile(filename2):
filename = filename2
else:
raise IOError("File '%s' does not exist." % filename)
... |
Read volume from a file. If filename is 'stent', read a dedicated
test dataset. For reading any other kind of volume, the imageio
package is required.
| random_line_split |
volread.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
import numpy as np
import os
# Try importing imageio
imageio = None
try:
import imageio
except ImportError:
pass
... | (filename):
""" volread(filename)
Read volume from a file. If filename is 'stent', read a dedicated
test dataset. For reading any other kind of volume, the imageio
package is required.
"""
if filename == 'stent':
# Get full filename
path = vv.misc.getResourceDir()... | volread | identifier_name |
chain_params.rs | use super::{UInt256,ConsensusParams};
pub enum Chain {
MAIN,
TESTNET,
REGTEST, | }
pub struct ChainParams {
pub id : Chain,
pub message_start : [u8;4],
pub consensus: ConsensusParams,
}
lazy_static! {
#[allow(dead_code)]
static ref CHAIN_MAIN:ChainParams = ChainParams{
id : Chain::MAIN,
message_start : [ 0xf9, 0xbe, 0xb4, 0xd9 ],
consensus: ConsensusParams {
... | random_line_split | |
chain_params.rs | use super::{UInt256,ConsensusParams};
pub enum Chain {
MAIN,
TESTNET,
REGTEST,
}
pub struct | {
pub id : Chain,
pub message_start : [u8;4],
pub consensus: ConsensusParams,
}
lazy_static! {
#[allow(dead_code)]
static ref CHAIN_MAIN:ChainParams = ChainParams{
id : Chain::MAIN,
message_start : [ 0xf9, 0xbe, 0xb4, 0xd9 ],
consensus: ConsensusParams {
hash_genesis_block: U... | ChainParams | identifier_name |
setup.py | from setuptools import setup
setup(
name = "zml",
packages = ["zml"],
version = "0.8.1",
description = "zero markup language",
author = "Christof Hagedorn",
author_email = "team@zml.org",
url = "http://www.zml.org/",
download_url = "https://pypi.python.org/pypi/zml",
keywords = ["zml... | "Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
... | "Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Development Status :: 3 - Alpha",
"Environment :: Web Environment", | random_line_split |
harness.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
from rapidsms.router import Router
from rapidsms.backends.backend import Backend
from rapidsms.app import App
# a really dumb Logger stand-in
class MockLogger (list):
def __init__(self):
# enable logging during tests with an
# environment variable,... |
# a subclass of App with all the moving parts replaced
class MockApp (App):
def configure (self):
self.calls = []
def start (self):
self.calls.append(("start",))
def parse (self, message):
self.calls.append(("parse", message))
def handle (self, message):
self.calls... | self.outgoing.append(msg) | conditional_block |
harness.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
from rapidsms.router import Router
from rapidsms.backends.backend import Backend
from rapidsms.app import App
# a really dumb Logger stand-in
class MockLogger (list):
def __init__(self):
# enable logging during tests with an
# environment variable,... | (self):
self.calls.append(("stop",))
class EchoApp (MockApp):
def handle (self, message):
MockApp.handle(self, message)
message.respond(message.peer + ": " + message.text)
| stop | identifier_name |
harness.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
from rapidsms.router import Router
from rapidsms.backends.backend import Backend
from rapidsms.app import App
# a really dumb Logger stand-in
class MockLogger (list):
def __init__(self):
# enable logging during tests with an
# environment variable,... | class MockBackend (Backend):
def start (self):
self._running = True
self.outgoing = []
def run (self):
while self.running:
msg = self.next_message(0.25)
if msg is not None: self.outgoing.append(msg)
# a subclass of App with all the moving parts replaced
class ... | random_line_split | |
harness.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
from rapidsms.router import Router
from rapidsms.backends.backend import Backend
from rapidsms.app import App
# a really dumb Logger stand-in
class MockLogger (list):
def __init__(self):
# enable logging during tests with an
# environment variable,... |
def stop (self):
self.running = False
self.stop_all_backends()
class MockBackend (Backend):
def start (self):
self._running = True
self.outgoing = []
def run (self):
while self.running:
msg = self.next_message(0.25)
if msg is not None: self... | self.running = True
self.start_all_backends()
self.start_all_apps() | identifier_body |
BlockBuilder.ts | module Block {
export interface BlockBuilderInterface {
buildRandomBlocks(numberOfBlocks: number);
buildCustomBlocks(blocks: BlockDimensionModel[]);
}
export class BlockBuilder implements BlockBuilderInterface {
private _inputCanvasElement: HTMLCanvasElement;
private _outpu... | locks: BlockDimensionModel[]) {
var context = this._outputCanvasElement.getContext("2d");
context.clearRect(0, 0, this._outputCanvasElement.width, this._outputCanvasElement.height);
this.drawBlocks(context, blocks);
}
private writeRandomBlocksToStorageProvider() {
... | ildCustomBlocks(b | identifier_name |
BlockBuilder.ts | module Block {
export interface BlockBuilderInterface {
buildRandomBlocks(numberOfBlocks: number);
buildCustomBlocks(blocks: BlockDimensionModel[]);
}
export class BlockBuilder implements BlockBuilderInterface {
private _inputCanvasElement: HTMLCanvasElement;
private _outpu... | }
private writeRandomBlocksToStorageProvider() {
this._storageProvider.storeBlocks(this._randomBlocks);
}
private drawBlocks(canvasContext: CanvasRenderingContext2D, blocks: BlockDimensionModel[]) {
//Force reading of blocks back from local storage. This is bad ... | this.drawBlocks(context, blocks); | random_line_split |
capitalized-comments.js | /**
* @fileoverview enforce or disallow capitalization of the first letter of a comment
* @author Kevin Partington
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const... | capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase()
);
}
});
}
}
//----------------------------------------------------------------------
// Public
//---... | return fixer.replaceTextRange(
// Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*)
[comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], | random_line_split |
capitalized-comments.js | /**
* @fileoverview enforce or disallow capitalization of the first letter of a comment
* @author Kevin Partington
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const... |
/**
* Creates a regular expression for each ignorePattern defined in the rule
* options.
*
* This is done in order to avoid invoking the RegExp constructor repeatedly.
*
* @param {Object} normalizedOptions The normalized rule options.
* @returns {void}
*/
function createRegExpForIgnorePatterns(normalizedOptio... | {
return {
Line: getNormalizedOptions(rawOptions, "line"),
Block: getNormalizedOptions(rawOptions, "block")
};
} | identifier_body |
capitalized-comments.js | /**
* @fileoverview enforce or disallow capitalization of the first letter of a comment
* @author Kevin Partington
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const... | (context) {
const capitalize = context.options[0] || "always",
normalizedOptions = getAllNormalizedOptions(context.options[1]),
sourceCode = context.getSourceCode();
createRegExpForIgnorePatterns(normalizedOptions);
//---------------------------------------------------... | create | identifier_name |
capitalized-comments.js | /**
* @fileoverview enforce or disallow capitalization of the first letter of a comment
* @author Kevin Partington
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const... |
// 6. Is the initial word character a letter?
const commentWordCharsOnly = commentWithoutAsterisks
.replace(WHITESPACE, "");
if (commentWordCharsOnly.length === 0) {
return true;
}
const firstWordChar = commentWordCharsOnly[... | {
return true;
} | conditional_block |
extract-fileviewer-mappings.py | #!/usr/bin/env python3
# Update plural forms expressions from the data collected by Unicode Consortium
# (see http://www.unicode.org/cldr/charts/supplemental/language_plural_rules.html),
# but from a JSON version by Transifex folks
import os.path
import sys
import urllib.request
import re
import gettext
import json
i... |
with open(outfname, "rt") as f:
orig_content = f.read()
content = re.sub('%s(.*?)%s' % (MARKER_BEGIN, MARKER_END),
output,
orig_content,
0,
re.DOTALL)
with open(outfname, "wt") as f:
f.write(content)
print(output)
sys.stderr.write(f'Genera... | raise RuntimeError("run this script from project root directory") | conditional_block |
extract-fileviewer-mappings.py | #!/usr/bin/env python3
# Update plural forms expressions from the data collected by Unicode Consortium
# (see http://www.unicode.org/cldr/charts/supplemental/language_plural_rules.html),
# but from a JSON version by Transifex folks
import os.path
import sys
import urllib.request
import re
import gettext
import json
i... |
if os.path.isfile("src/fileviewer.extensions.h"):
outfname = "src/fileviewer.extensions.h"
else:
raise RuntimeError("run this script from project root directory")
with open(outfname, "rt") as f:
orig_content = f.read()
content = re.sub('%s(.*?)%s' % (MARKER_BEGIN, MARKER_END),
output,
... | output += f'{{ "{ext}", "{lang}" }},\n'
output += f'\n{MARKER_END}\n'
| random_line_split |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... | self.context.logger.log("Verifying if machine should exit unmount_oldroot state")
if os.path.exists('/oldroot/bin'):
self.context.logger.log("/oldroot was not unmounted")
return False
return super(UnmountOldrootState, self).should_exit() | identifier_body | |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... | (self, mountpoint, call_unmount_var=True):
if mountpoint != '/var':
self.unmount_var()
if self.command_executor.Execute("mountpoint " + mountpoint):
return
proc_comm = ProcessCommunicator()
self.command_executor.Execute(command_to_execute="fuser -vm " + mountpo... | unmount | identifier_name |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... |
self.context.logger.log("Attempt #{0} for restarting systemd-udevd".format(attempt))
self.command_executor.Execute('systemctl restart systemd-udevd')
sleep(10)
if self.command_executor.ExecuteInBash('[ -b {0} ]'.format(self.rootfs_block_device), False) == 0:
... | raise Exception("Block device {0} did not appear in 10 restart attempts".format(self.rootfs_block_device)) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.