file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer confi... | (&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_conf... | execute | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer confi... |
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
}... | {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
} | identifier_body |
filters.component.ts | import { FilterService, Filter, FilterTree, FilterType, FilterIndex } from 'lib/filter';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
@Component({
selector: 'iw-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css'],
providers: [FilterServic... | (operator: 'and' | 'or') {
this.operator = operator;
this.executeFiltering();
}
onFilterChange() {
this.executeFiltering();
}
isSimpleFilter(filter: Filter) {
return [FilterType.Array, FilterType.Object].indexOf(filter.type) < 0;
}
executeFiltering() {
const filterTree = {
opera... | changeOperator | identifier_name |
filters.component.ts | import { FilterService, Filter, FilterTree, FilterType, FilterIndex } from 'lib/filter';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
@Component({
selector: 'iw-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css'],
providers: [FilterServic... |
}
| {
return this.rows.reduce((result, row) => result.concat(row[key]), []);
} | identifier_body |
filters.component.ts | import { FilterService, Filter, FilterTree, FilterType, FilterIndex } from 'lib/filter';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
@Component({
selector: 'iw-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css'],
providers: [FilterServic... | filterAnyFields(value: any) {
const filterTree: FilterTree = {
operator: 'or',
filters: this.filters.map((f) => {
f.value = value;
return f;
})
};
const filtered = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filtered);
}
toggleAdvance... |
getLabel(filter: Filter) {
return filter.label ? filter.label : filter.key;
}
| random_line_split |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use... | (&self, cx: &Context, span: Span, id: ast::NodeId) {
if match self.authenticated_parent {
None => true,
Some(p) => !child_of(cx, id, p),
} {
cx.span_lint(UNAUTHORIZED_UNSAFE, span, "unauthorized unsafe block");
}
}
// Check a function's #[launch_code]... | authorize | identifier_name |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use... |
let launch_code = match launch_code {
Some(c) => c,
None => return,
};
// Authenticate the function arguments and body.
val.write(snip(cx, span).as_slice());
if val.verify(launch_code.1.as_slice(), &self.pubkey) {
self.authenticated_parent =... | }
} | random_line_split |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
in... | ),
parent = iframe.parentNode.parentNode;
switch ( index ) {
case 0:
iframe.style.height = "380px";
parent.style.height = "392px";
break;
case 1:
iframe.style.height = "220px";
parent.style.height = "232px";
break;
... | ( "iframe" | identifier_name |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
in... |
function initEvtHandler( conId ) {
var tabHeads = $G( conId );
for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) {
var tabObj = tabHeads.childNodes[i];
if ( tabObj.nodeType == 1 ) {
domUtils.on( tabObj, "click", (function ( index ) {
return function () {... | {
for ( var pro in emotion.SmilmgName ) {
var tempName = emotion.SmilmgName[pro],
tempBox = emotion.SmileyBox[pro],
tempStr = "";
if ( tempBox.length ) return;
for ( var i = 1; i <= tempName[1]; i++ ) {
tempStr = tempName[0];
if ( i < ... | identifier_body |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
in... | switch ( index ) {
case 0:
iframe.style.height = "380px";
parent.style.height = "392px";
break;
case 1:
iframe.style.height = "220px";
parent.style.height = "232px";
break;
case 2:
iframe.style.height = "260p... | random_line_split | |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
in... | td>" );
}
textHTML.push( "</tr>" );
}
textHTML.push( "</table>" );
textHTML = textHTML.join( "" );
tab.innerHTML = textHTML;
}
function over( td, srcPath, posFlag ) {
td.style.backgroundColor = "#ACCD3C";
$G( "faceReview" ).style.backgroundImage = "url(" + srcPath + ")";
if ... | positionLine ? 0 : 1;
offset = cssOffset * i * (-1) - 1;
infor = emotion.SmileyInfor[tabName][i];
textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="Inser... | conditional_block |
server.js | 'use strict';
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function | (baseDir, browser) {
// var routes = null;
// if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
// routes = {
// '/bower_components': 'bower_components'
// };
// }
/*
* You can add a proxy to your backend by uncommenting the line below.
* You ju... | browserSyncInit | identifier_name |
server.js | 'use strict';
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) |
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function() {
browserSyncInit(conf.dist);
});
gulp.task('serve:dist', ['inject'], function() {
browserSyncInit(conf.dist);
}); | {
// var routes = null;
// if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
// routes = {
// '/bower_components': 'bower_components'
// };
// }
/*
* You can add a proxy to your backend by uncommenting the line below.
* You just have to configur... | identifier_body |
server.js | 'use strict';
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
// var routes = null... | * Example: $http.get('/users') requests will be automatically proxified.
*
* For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.0.5/README.md
*/
// server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', proxyHost: 'jsonplaceholder.... | * You just have to configure a context which will we redirected and the target url. | random_line_split |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
... | ():
return "it works!"
@bottle.route('/<width>/<height>')
@bottle.route('/<width>/<height>/')
def image(width=320, height=240):
width=int(width)
height=int(height)
format = bottle.request.query.get('f', 'png').lower()
bg_color = bottle.request.query.get('bgcolor', 'aaaaaa').lower()
fg_c... | index | identifier_name |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
... | 'wxga+': [1440, 900],
'sxga': [1280, 1024],
'sxga+': [1400, 1050],
'wsxga+': [1680, 1050],
'uxga': [1600, 1200],
'wuxga': [1920, 1200],
'1080': [1920, 1080],
'720': [1280, 720],
}
@bottle.route('/')
def index():
return "it works!"
@bottle.route('/<width>/<height>')
@bottle.route('... | 'wsvga': [1024, 600],
'xga': [1024, 768],
'wxga': [1366, 768],
'fwxga': [1366, 768],
'xga+': [1152, 864], | random_line_split |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
... |
def application(environ, start_response):
app = bottle.default_app()
return app.wsgi(environ, start_response)
if __name__ == "__main__":
bottle.debug(True)
app = bottle.default_app()
bottle.run(app, host='0.0.0.0', port='8685', reloader=True)
| width=int(width)
height=int(height)
format = bottle.request.query.get('f', 'png').lower()
bg_color = bottle.request.query.get('bgcolor', 'aaaaaa').lower()
fg_color = bottle.request.query.get('fgcolor', 'ffffff').lower()
text = bottle.request.query.get('t', str(width) + 'x' + str(height)).lowe... | identifier_body |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
... | bottle.debug(True)
app = bottle.default_app()
bottle.run(app, host='0.0.0.0', port='8685', reloader=True) | conditional_block | |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import... | ValidTest = PicGet()
ValidTest.validImageGet() | conditional_block | |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import... | (self,driver,cookie,validcode):
# use the validcode to authentication
PostUrl = "http://bbs.csdn.net/human_validations"
elem = driver.find_element_by_id("captcha")
elem.send_keys(validcode)
elem.send_keys(Keys.TAB)
time.sleep(3)
driver.find_element_by_xpath('//button[@type="submit"]').send_keys(Keys.ENT... | validlogin | identifier_name |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import... | ValidCode = self.image_to_text(image)
image.save('captcha.png')
return ValidCode
def validlogin(self,driver,cookie,validcode):
# use the validcode to authentication
PostUrl = "http://bbs.csdn.net/human_validations"
elem = driver.find_element_by_id("captcha")
elem.send_keys(validcode)
elem.send_keys(... | random_line_split | |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import... |
if __name__ == '__main__':
ValidTest = PicGet()
ValidTest.validImageGet() | AuthUrl = "http://bbs.csdn.net/human_validations/new"
picname = 'captcha.png'
sel = webdriver.Chrome()
sel.get(AuthUrl)
cookie = sel.get_cookies()
auth_token = sel.find_element_by_xpath('//input[@name="authenticity_token"]')
captcha_key = sel.find_element_by_xpath('//input[@id="captcha_key"]')
# su... | identifier_body |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) {
return;
}
this.packageJson.merge({
scripts: {
format: 'prettier --... | (): void {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
files: packageFiles.map((packageFile) => `${packageFile}\n`).join(''),
flow: this.hasDevDependency('flow-bin'),
husky: this.hasFiles('.husky'),
jekyll: this.hasFiles('docs/_c... | writing | identifier_name |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) {
return;
}
this.packageJson.merge({
scripts: {
format: 'prettier --... |
}
| {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
files: packageFiles.map((packageFile) => `${packageFile}\n`).join(''),
flow: this.hasDevDependency('flow-bin'),
husky: this.hasFiles('.husky'),
jekyll: this.hasFiles('docs/_config.yml... | identifier_body |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) {
return;
}
this.packageJson.merge({
scripts: {
format: 'prettier --... | if (this.hasAnyDependency('typescript')) {
devDependencies.push('prettier-plugin-organize-imports');
}
await this.addDevDependencies(devDependencies);
}
public writing(): void {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
f... | random_line_split | |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) |
this.packageJson.merge({
scripts: {
format: 'prettier --write .',
'format:check': 'prettier --check .',
},
});
const devDependencies = ['prettier', 'prettier-plugin-pkg', 'prettier-plugin-sh'];
if (this.hasAnyDependency('typescript')) {
devDependencies.push('prettie... | {
return;
} | conditional_block |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def test_get_cost_functions(self):
fixture = ds_fakes.FakeDistributedScheduler()
fns = fixture.get_cost_functions()
self.assertEquals(len(fns), 1)
weight, fn = fns[0]
self.assertEquals(weight, 1.0)
hostinfo = zone_manager.HostInfo('host', free_ram_mb=1000)
se... | random_line_split | |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | (object):
def decryptor(self, key):
return lambda blob: blob
self.stubs.Set(distributed_scheduler, 'crypto', StubDecryptor())
weighted_host = fixture._make_weighted_host_from_blob(
json.dumps(test_data))
self.a... | StubDecryptor | identifier_name |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def _fake_ask_child_zone_to_create_instance(*args, **kwargs):
self.child_zone_called = True
return 2
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', _fake_schedule)
self.stubs.Set(sched, '_make_weighted_host_from_blob',
... | self.locally_called = True
return 1 | identifier_body |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def test_run_instance_no_hosts(self):
"""
Ensure empty hosts & child_zones result in NoValidHosts exception.
"""
def _fake_empty_call_zone_method(*args, **kwargs):
return []
sched = ds_fakes.FakeDistributedScheduler()
sched.zone_manager = FakeEmptyZoneM... | w = weighted_host.weight
if weighted_host.zone == 'zone1': # No change
self.assertTrue(w < 1000.0)
if weighted_host.zone == 'zone2': # Offset +1000
self.assertTrue(w >= 1000.0 and w < 2000)
if weighted_host.zone == 'zone3': # Scale x1000
... | conditional_block |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf}; | search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.s... |
pub(super) fn find_library(
name: Symbol,
verbatim: bool, | random_line_split |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> Pat... | ;
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unix... | {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
} | conditional_block |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn | (
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.targ... | find_library | identifier_name |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> Pat... |
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
w... | {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a"... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
"""
Moisture Plugin
Copyright (C) 2013 Olaf Lüke <olaf@tinkerforge.com>
__init__.py: package initialization
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 2
o... |
device_class = Moisture | from brickv.plugin_system.plugins.moisture.moisture import Moisture | random_line_split |
__init__.py | # PPFem: An educational finite element code
# Copyright (C) 2015 Matthias Rambausek
#
# 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 ... |
__all__ = ["Mesh", "Point", "Line", "Vertex", "Face", "Cell", "Mapping", "FunctionSpace", "Functional",
"LinearForm", "BilinearForm", "FormCollection", "DefaultSystemAssembler", "FEFunction", "FunctionEvaluator",
"PDE"]
__all__ += ppfem.user_elements.__all__ + ppfem.quadrature.__all__ + ppfem.us... | from ppfem.fem.assembler import DefaultSystemAssembler
from ppfem.fem.form import Functional, LinearForm, BilinearForm, FormCollection
from ppfem.fem.function import FEFunction, FunctionEvaluator
from ppfem.fem.function_space import FunctionSpace
from ppfem.fem.partial_differential_equation import PDE | random_line_split |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = ... | def _operator2(self, operator):
if len(self.stack) < 2:
self.stack = [0]
else:
val = operator(self.stack[-1], self.stack[-2])
self.stack = self.stack[:-2]
self.stack.append(val)
def _clr(self):
self.stack = []
def _push(self, a):
... | if self.stack:
self.stack.append(operator(self.stack.pop()))
| random_line_split |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = ... |
def _jlt(self, a):
if len(self.stack) > 1:
if self.stack.pop() < self.stack.pop():
self._jmp(a)
def _jgt(self, a):
if len(self.stack) > 1:
if self.stack.pop() > self.stack.pop():
self._jmp(a)
def verify_stack(self):
if len(s... | if len(self.stack) > 1:
if self.stack.pop() != self.stack.pop():
self._jmp(a) | identifier_body |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = ... |
def _jne(self, a):
if len(self.stack) > 1:
if self.stack.pop() != self.stack.pop():
self._jmp(a)
def _jlt(self, a):
if len(self.stack) > 1:
if self.stack.pop() < self.stack.pop():
self._jmp(a)
def _jgt(self, a):
if len(self.... | self._jmp(a) | conditional_block |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = ... | (self):
self.stack = []
def _push(self, a):
try:
a = float(a)
self.stack.append(a)
except:
pass
def _pop(self):
if self.stack:
self.stack.pop()
def _inc(self):
if self.stack:
self.stack[-1] += 1
def _... | _clr | identifier_name |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import ... | scrollId= scan_resp['_scroll_id']
response={}
total = scan_resp['hits']['total']
response_list =[]
scrollId_list =[]
for page_num in range(total/page_size + 1):
response_tmp ={}
response_tmp = es.scroll(scroll_id=scrollId, scroll= "5m")
... | else:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size)
| random_line_split |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import ... |
def search_from_es(host,index,query_str,startTime,endTime,scroll=False,_source=None,time_step=0):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
all_response={}
ti... | es = Elasticsearch(host,timeout=120)
response ={}
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.in... | identifier_body |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import ... |
else:
all_response = do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step)
return all_response
| response_tmp = do_search(host,index,query_str,_s1,_s2,scroll,_source,time_step)
#response_tmp = do_search(_s1,_s2)
if all_response.has_key('hits'):
_hits = all_response['hits']
_hits['hits']+=response_tmp['hits']['hits']
all_response['hits'] = _hit... | conditional_block |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import ... | (host,index,query_str,startTime,endTime,scroll=False):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
data_post_search = {"query":{"filtered":{"query":{"query_string":{"quer... | count_from_es | identifier_name |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils';
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() {
r... |
return (
<div>
<h1>Data Container</h1>
<pre className="scroll">
{formatJSON(this.state.data_container)}
</pre>
</div>
);
},
});
| {
return (<div className="alert alert-error">Data not available</div>);
} | conditional_block |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class'; |
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() {
return {
data_container: null,
};
},
componentDidMount() {
const id = this.props.params.id;
const payload = {
aggregate: [
{ $match: { _id: id } },
],
};
... | import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils'; | random_line_split |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils';
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() {
r... | () {
if (this.state.data_container == null) {
return (<h1>Loading Data Container<span className="loading" /></h1>);
}
if (_.isEmpty(this.state.data_container)) {
return (<div className="alert alert-error">Data not available</div>);
}
return (
<div>
<h1>Data Container</h1>... | render | identifier_name |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils';
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() | ,
componentDidMount() {
const id = this.props.params.id;
const payload = {
aggregate: [
{ $match: { _id: id } },
],
};
api.getDataContainers(payload)
.then(response => this.setState({ data_container: _.get(response, 'data_containers[0]', {}) }));
},
render() {
if ... | {
return {
data_container: null,
};
} | identifier_body |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.... | (self, in_data):
# There are five data augmentation steps
# 1. Color augmentation
# 2. Random expansion
# 3. Random cropping
# 4. Resizing with random interpolation
# 5. Random horizontal flipping
img, bbox, label = in_data
# 1. Color augmentation
... | __call__ | identifier_name |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.... |
train = TransformDataset(
ConcatenatedDataset(
VOCBboxDataset(year='2007', split='trainval'),
VOCBboxDataset(year='2012', split='trainval')
),
Transform(model.coder, model.insize, model.mean))
train_iter = chainer.iterators.MultiprocessIterator(train, args.batch... | chainer.cuda.get_device_from_id(args.gpu).use()
model.to_gpu() | conditional_block |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.... | pretrained_model='imagenet')
elif args.model == 'ssd512':
model = SSD512(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = MultiboxTrainChain(model)
if args.gpu >= 0:
chainer.cuda.get_device... | args = parser.parse_args()
if args.model == 'ssd300':
model = SSD300(
n_fg_class=len(voc_bbox_label_names), | random_line_split |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.... |
class Transform(object):
def __init__(self, coder, size, mean):
# to send cpu, make a copy
self.coder = copy.copy(coder)
self.coder.to_cpu()
self.size = size
self.mean = mean
def __call__(self, in_data):
# There are five data augmentation steps
# 1. ... | def __init__(self, model, alpha=1, k=3):
super(MultiboxTrainChain, self).__init__()
with self.init_scope():
self.model = model
self.alpha = alpha
self.k = k
def forward(self, imgs, gt_mb_locs, gt_mb_labels):
mb_locs, mb_confs = self.model(imgs)
loc_loss, ... | identifier_body |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... |
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if !pueue_dir.exists() {
if let Err(error) = cr... | {
setup_signal_panic_handling(&settings, &sender)?;
} | conditional_block |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... | }
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if !pueue_dir.exists() {
if let Err(error)... | // Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test {
setup_signal_panic_handling(&settings, &sender)?; | random_line_split |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... | (config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the... | run | identifier_name |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... | {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sen... | identifier_body | |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys... |
if year not in cls.QUAL_AVERAGE_YEARS:
qual_average = None
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return {
... | random_line_split | |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys... |
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return {
"rank": int(rank),
"team_key": team_key,
"rec... | qual_average = None | conditional_block |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys... | (
cls, event_details: EventDetails
) -> Optional[List[RankingSortOrderInfo]]:
return SORT_ORDER_INFO.get(event_details.game_year)
| get_sort_order_info | identifier_name |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys... | return SORT_ORDER_INFO.get(event_details.game_year) | identifier_body | |
assert.js | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_i... | (condition) {
var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'pre-condition failed';
if (!condition) {
throw new ErrorConditionFailed(msg);
}
} | require_condition | identifier_name |
assert.js | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_i... |
} | {
throw new ErrorConditionFailed(msg);
} | conditional_block |
assert.js | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_i... |
return ErrorConditionFailed;
}(ExtendableError);
export function require_condition(condition) {
var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'pre-condition failed';
if (!condition) {
throw new ErrorConditionFailed(msg);
}
} | {
_classCallCheck(this, ErrorConditionFailed);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _possibleConstructorReturn(this, _ExtendableError.call(this, args));
} | identifier_body |
assert.js | import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_inherits(ErrorConditionFailed, _ExtendableError);
function ErrorConditionFailed() {
_classCallCheck(this, ErrorConditionFailed);
for (var _len = ar... | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; | random_line_split | |
0002_contact_project_socialsite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message_from_me', models.Te... | identifier_body | |
0002_contact_project_socialsite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | Migration | identifier_name |
0002_contact_project_socialsite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('link', models.URLField()),
('image', models.ImageField(default=None, upload_to='myblog/image/project')),
... | migrations.CreateModel(
name='Project',
fields=[ | random_line_split |
role.upgrader.js | const { collectResource } = require('utils'),
role = {
/** @param {Creep} creep **/
run: function(creep) {
// If the sign is unclaimed or not claimed by me
if(!creep.room.controller.sign || creep.room.controller.sign.username != creep.owner.username) {
if(creep.sig... |
else {
collectResource(creep);
}
},
doUpgrade: function(creep) {
if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.doMove(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
}
}
};... | {
role.doUpgrade(creep);
} | conditional_block |
role.upgrader.js | const { collectResource } = require('utils'),
role = {
/** @param {Creep} creep **/
run: function(creep) { | }
}
if(creep.memory.upgrading && creep.carry.energy == 0) {
creep.memory.upgrading = false;
}
if(!creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
creep.memory.upgrading = true;
}
if(creep.memory.upgr... | // If the sign is unclaimed or not claimed by me
if(!creep.room.controller.sign || creep.room.controller.sign.username != creep.owner.username) {
if(creep.signController(creep.room.controller, "I'm claiming the objective") == ERR_NOT_IN_RANGE) {
creep.doMove(creep.room.cont... | random_line_split |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 's... |
getDashboardTags() {
return backendSrv.get('/api/dashboard/tags').then((res) => res.data);
}
getSortOptions() {
return backendSrv.get('/api/search/sorting').then((res) => res.data);
}
}
| {
if (results.length === 0) {
return sections;
}
// create folder index
for (const hit of results) {
if (hit.type === 'dash-folder') {
sections[hit.id] = {
id: hit.id,
uid: hit.uid,
title: hit.title,
expanded: false,
items: [],
... | identifier_body |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 's... | () {
return backendSrv.get('/api/dashboard/tags').then((res) => res.data);
}
getSortOptions() {
return backendSrv.get('/api/search/sorting').then((res) => res.data);
}
}
| getDashboardTags | identifier_name |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 's... |
let section = sections[hit.folderId || 0];
if (!section) {
if (hit.folderId) {
section = {
id: hit.folderId,
uid: hit.folderUid,
title: hit.folderTitle,
url: hit.folderUrl,
items: [],
icon: 'folder-open',
... | {
continue;
} | conditional_block |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 's... | type: DashboardSearchItemType.DashFolder,
};
}
});
}
search(options: any) {
const sections: any = {};
const promises = [];
const query = _.clone(options);
const filters = hasFilters(options) || query.folderIds?.length > 0;
query.folderIds = query.folderIds || [];
... | score: -2,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.starred`, true),
items: result, | random_line_split |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set o... | (self, flattened):
r"""
Takes a flattened vector and returns a new
:class:`BooleanImage` formed by
reshaping the vector to the correct dimensions. Note that this is
rebuilding a boolean image **itself** from boolean values. The mask
is in no way interpreted in performing ... | from_vector | identifier_name |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set o... | """
if round not in ['ceil', 'round', 'floor']:
raise ValueError('round must be either ceil, round or floor')
# Ensure that the '+' operator means concatenate tuples
shape = tuple(getattr(np, round)(shape))
if fill:
mask = np.ones(shape, dtype=np.bool)... | A blank mask of the requested size | random_line_split |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
| r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set of 'masked' pixels is those pixels corresponding to a True value in
the mask.
Parameters
-----------
mask_data : (M, N, ..., L) ndarray
... | identifier_body | |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set o... |
kwargs['order'] = 0
return Image.warp_to(self, template_mask, transform,
warp_landmarks=warp_landmarks,
interpolator=interpolator, **kwargs)
def _build_warped_image(self, template_mask, sampled_pixel_values,
**kw... | raise ValueError(
"The order of the interpolation on a boolean image has to be "
"0 (attempted to set {})".format(manually_set_order)) | conditional_block |
client_compatibility_produce_consume_test.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | (ProduceConsumeValidateTest):
"""
These tests validate that we can use a new client to produce and consume from older brokers.
"""
def __init__(self, test_context):
""":type test_context: ducktape.tests.test.TestContext"""
super(ClientCompatibilityProduceConsumeTest, self).__init__(test... | ClientCompatibilityProduceConsumeTest | identifier_name |
client_compatibility_produce_consume_test.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time")) | random_line_split | |
client_compatibility_produce_consume_test.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
def setUp(self):
self.zk.start()
def min_cluster_size(self):
# Override this since we're adding services outside of the constructor
return super(ClientCompatibilityProduceConsumeTest, self).min_cluster_size() + self.num_producers + self.num_consumers
@parametrize(broker_version=s... | """:type test_context: ducktape.tests.test.TestContext"""
super(ClientCompatibilityProduceConsumeTest, self).__init__(test_context=test_context)
self.topic = "test_topic"
self.zk = ZookeeperService(test_context, num_nodes=3)
self.kafka = KafkaService(test_context, num_nodes=3, zk=self.z... | identifier_body |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone w... | record_size: length of the header according to file (untrusted)
Returns:
A dict containing a single browser history record.
"""
record_header = "<4sLQQL"
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0... | random_line_split | |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone w... |
if __name__ == "__main__":
main(sys.argv)
| ie = IEParser(open(input_file))
for dat in ie.Parse():
dat["ctime"] = datetime.datetime.utcfromtimestamp(dat["ctime"]/1e6)
print "{ctime} {header} {url}".format(**dat) | conditional_block |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone w... | (object):
"""Parser object for index.dat files.
The file format for IE index.dat files is somewhat poorly documented.
The following implementation is based on information from:
http://www.forensicswiki.org/wiki/Internet_Explorer_History_File_Format
Returns results in chronological order based on mtime
""... | IEParser | identifier_name |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone w... |
def main(argv):
if len(argv) < 2:
print "Usage: {0} index.dat".format(os.path.basename(argv[0]))
else:
files_to_process = []
for input_glob in argv[1:]:
files_to_process += glob.glob(input_glob)
for input_file in files_to_process:
ie = IEParser(open(input_file))
for dat in ie.Pa... | """Parse a file for history records yielding dicts.
Yields:
Dicts containing browser history
"""
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
filesize = get4(0x1c)
offset = get4(0x20)
coffset = offset
while coffset < filesize:
etype = struct.unpack("4s", self.i... | identifier_body |
economy.js | /**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
... | (price) {
if (Gold.readMoney(user.userid) < price) return false;
if (Gold.readMoney(user.userid) >= price) return true;
}
function alertStaff(message, staffRoom) {
Gold.pmUpperStaff('/raw ' + message, '~Server', false);
if (staffRoom) {
Rooms.get('staff').add('|raw|<b>' + message + '</b>');
Room... | moneyCheck | identifier_name |
economy.js | /**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
... | if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
this.sendReply("You have purchased a custom symbol. You will have this until you log off for more than an hour.");
this.sendReply("Use /customsymbol [symbol] t... | switch (toId(parts[0])) {
case 'symbol':
price = prices['symbol'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy custom symbols from the shop. Use /customsymbol to change your symbol."); | random_line_split |
economy.js | /**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
... |
function moneyCheck(price) {
if (Gold.readMoney(user.userid) < price) return false;
if (Gold.readMoney(user.userid) >= price) return true;
}
function alertStaff(message, staffRoom) {
Gold.pmUpperStaff('/raw ' + message, '~Server', false);
if (staffRoom) {
Rooms.get('staff').add('|raw|<b>' + messa... | {
return '<a href="' + link + '" target="_blank">' + formatted + '</a>';
} | identifier_body |
board.js | (function () {
window.SnakeGame = window.SnakeGame || {};
var Board = SnakeGame.Board = function (options) {
options = options || {};
this.height = options.height || Board.HEIGHT;
this.width = options.width || Board.WIDTH;
this.player = options.player || new SnakeGame.Snake(this);
this.opponen... | var pos = row + "-" + col;
var $li = $("<li>").attr("id", pos);
board[row].append($li);
}
}
return board;
}
Board.prototype.inRange = function (pos) {
return (pos[0] >= 0 && pos[0] < this.height) &&
(pos[1] >= 0 && pos[1] < this.width);
}
Board.prototype.w... | board[row] = $("<ul>").addClass("snake-row").addClass("group");
for (col = 0; col < this.width; col++) { | random_line_split |
test-localizer.js | import globalize from 'globalize';
import configure from '../src/configure';
export default function testLocalizer() {
function getCulture(culture){
return culture ? globalize.findClosestCulture(culture) : globalize.culture()
}
function shortDay(dayOfTheWeek, culture) {
let names = getCulture(culture).... | ,
format(value, format, culture){
return globalize.format(value, format, culture)
}
}
function formatData(format, _culture){
var culture = getCulture(_culture)
, numFormat = culture.numberFormat
if (typeof format === 'string') {
if (format.indexOf('p') !== -1) numFormat = numFor... | {
return globalize.parseDate(value, format, culture)
} | identifier_body |
test-localizer.js | import globalize from 'globalize';
import configure from '../src/configure';
export default function testLocalizer() {
function getCulture(culture){
return culture ? globalize.findClosestCulture(culture) : globalize.culture()
}
function shortDay(dayOfTheWeek, culture) {
let names = getCulture(culture).... | (format, _culture){
var data = formatData(format, _culture)
if (typeof format === 'string' && format.length > 1)
return parseFloat(format.substr(1))
return data ? data.decimals : null
}
}
configure.setLocalizers({ date, number })
}
| precision | identifier_name |
test-localizer.js | import globalize from 'globalize';
import configure from '../src/configure';
export default function testLocalizer() {
function getCulture(culture){
return culture ? globalize.findClosestCulture(culture) : globalize.culture()
}
function shortDay(dayOfTheWeek, culture) {
let names = getCulture(culture).... |
format(value, format, culture){
return globalize.format(value, format, culture)
}
}
function formatData(format, _culture){
var culture = getCulture(_culture)
, numFormat = culture.numberFormat
if (typeof format === 'string') {
if (format.indexOf('p') !== -1) numFormat = numForma... |
parse(value, format, culture){
return globalize.parseDate(value, format, culture)
}, | random_line_split |
yamsdaq_models.py | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Colum... | (Base):
__tablename__ = 'valuepoints'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
value = Column(Float, nullable=False)
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company,... | ValuePoint | identifier_name |
yamsdaq_models.py | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Colum... |
class ValuePoint(Base):
__tablename__ = 'valuepoints'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
value = Column(Float, nullable=False)
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = rel... | return '<Company %r (%r)>' % (self.name, self.code) | identifier_body |
yamsdaq_models.py | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Colum... | id = Column(Integer, primary_key=True)
count = Column(Integer, nullable=False)
value_per_stock_at_purchase = Column(Float, nullable=False)
owner_number = Column(Integer, ForeignKey('accounts.number'), nullable=False)
owner = relationship(Account, back_populates="owned_stocks")
company_code = C... | random_line_split | |
jquery.media.template.shockplayer.js | /**
* Copyright (c) 2010 Alethia Inc,
* http://www.alethia-inc.com
* Developed by Travis Tidwell | travist at alethia-inc.com
*
* License: GPL version 3.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software")... | mediaplayer.node.player.play.show();
};
// See if we are using FireFox with an mp4 video.
this.isFireFoxWithH264 = function() {
if (this.player && this.player.media && this.player.media.mediaFile) {
var ext = this.player.media.mediaFile.getFileExtension();
... | };
this.onNodeLoad = function( data ) {
this.nodeInfo = data; | random_line_split |
jquery.media.template.shockplayer.js | /**
* Copyright (c) 2010 Alethia Inc,
* http://www.alethia-inc.com
* Developed by Travis Tidwell | travist at alethia-inc.com
*
* License: GPL version 3.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software")... |
}
});
// Show the volume bar when they hover over the mute button.
mediaplayer.controller.mute.display.bind("mousemove", function() {
if( jQuery.media.hasMedia ) {
jQuery.media.utils.showThenHide( _this.volumeBar, "volumeBar", "fast", "fast" );
... | {
jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", "fast", "slow", function() {
mediaplayer.node.player.play.css("bottom", "5px");
});
} | conditional_block |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
... |
elif prev_day < day:
item = ('up', day)
else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
a... | item = ('down', day) | conditional_block |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
|
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = la... | if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created'] | identifier_body |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
... | else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate thro... | elif prev_day < day:
item = ('up', day) | random_line_split |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def | (self):
if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created']
def summary(self):
"""Generates summary data of today's state"""
... | get_data | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.