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 |
|---|---|---|---|---|
shootout-ackermann.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_owned(), "12".to_owned())
} else if args.len() <= 1u {
vec!("".to_owned(), "8".to_owned())
} else {
args.move_iter().collect()
};
let n = from_str::<int>(*args.get(1)).unwrap();
pri... | identifier_body | |
authorize-config.ts | //============== OpenId Connect授权配置 ==========
//Copyright 2018 何镇汐
//Licensed under the MIT license
//================================================
/**
* OpenId Connect授权配置
*/
export class AuthorizeConfig {
/**
* OpenId Connect认证服务入口地址,该项为必填
*/
authority: string;
/**
* 客户端标识,该项为必填
... | } | ectUri;
}
| identifier_name |
authorize-config.ts | //============== OpenId Connect授权配置 ==========
//Copyright 2018 何镇汐
//Licensed under the MIT license
//================================================
/**
* OpenId Connect授权配置
*/
export class AuthorizeConfig {
/**
* OpenId Connect认证服务入口地址,该项为必填
*/
authority: string;
/**
* 客户端标识,该项为必填
... | return location.origin;
return this.postLogoutRedirectUri;
}
} | 录回调页面地址
*/
getRedirectUri() {
if (this.redirectUri === "/callback")
return `${location.origin}${this.redirectUri}`;
return this.redirectUri;
}
/**
* 获取注销回调页面地址
*/
getPostLogoutRedirectUri() {
if (!this.postLogoutRedirectUri)
| identifier_body |
authorize-config.ts | //============== OpenId Connect授权配置 ==========
//Copyright 2018 何镇汐
//Licensed under the MIT license
//================================================
/**
* OpenId Connect授权配置
*/
export class AuthorizeConfig {
/**
* OpenId Connect认证服务入口地址,该项为必填
*/
authority: string;
/**
* 客户端标识,该项为必填
... |
/**
* 验证
*/
validate() {
if (!this.authority)
throw new Error("OpenId Connect认证服务入口地址未设置,请设置AuthorizeConfig的authority属性");
if (!this.clientId)
throw new Error("OpenId Connect客户端标识未设置,请设置AuthorizeConfig的clientId属性");
}
/**
* 获取登录回调页面地址
*/
... | random_line_split | |
converter.ts |
/**
* Converts modlogs between text and SQLite; also modernizes old-format modlogs
* @author Annika
* @author jetou
*/
if (!global.Config) {
let hasSQLite = true;
try {
require.resolve('better-sqlite3');
} catch (e) {
hasSQLite = false;
}
global.Config = {
nofswriting: false,
usesqlitemodlog: hasSQLi... |
if (line[0] === '[') {
log.ip = parseBrackets(line, '[');
line = line.slice(log.ip.length + 3).trim();
}
}
let regex = /\bby .*:/;
let actionTakerIndex = regex.exec(line)?.index;
if (actionTakerIndex === undefined) {
actionTakerIndex = line.indexOf('by ');
regex = /\bby .*/;
}
if (actionTakerIndex... | {
const userid = toID(parseBrackets(line, '['));
log.userid = userid;
line = line.slice(userid.length + 3).trim();
if (line.startsWith('ac:')) {
line = line.slice(3).trim();
const ac = parseBrackets(line, '[');
log.autoconfirmedID = toID(ac);
line = line.slice(ac.length + 3).trim();
}
... | conditional_block |
converter.ts | /**
* Converts modlogs between text and SQLite; also modernizes old-format modlogs
* @author Annika
* @author jetou
*/
if (!global.Config) {
let hasSQLite = true;
try {
require.resolve('better-sqlite3');
} catch (e) {
hasSQLite = false;
}
global.Config = {
nofswriting: false,
usesqlitemodlog: hasSQLit... | await insertEntries();
if (entriesLogged) process.stdout.write('\n');
}
if (!Config.nofswriting) console.log(`Writing the global modlog...`);
await this.writeFile(`${this.textLogDir}/modlog_global.txt`, globalEntries.join(''));
}
async writeFile(path: string, text: string) {
if (this.isTesting) {
co... | random_line_split | |
converter.ts |
/**
* Converts modlogs between text and SQLite; also modernizes old-format modlogs
* @author Annika
* @author jetou
*/
if (!global.Config) {
let hasSQLite = true;
try {
require.resolve('better-sqlite3');
} catch (e) {
hasSQLite = false;
}
global.Config = {
nofswriting: false,
usesqlitemodlog: hasSQLi... |
async toTxt() {
const database = this.isTesting?.db || new Database(this.databaseFile, {fileMustExist: true});
const roomids = database.prepare('SELECT DISTINCT roomid FROM modlog').all();
const globalEntries = [];
for (const {roomid} of roomids) {
if (!Config.nofswriting) console.log(`Reading ${roomid}..... | {
this.databaseFile = databaseFile;
this.textLogDir = textLogDir;
if (isTesting || Config.nofswriting) {
this.isTesting = {files: new Map<string, string>(), db: isTesting || new Database(':memory:')};
}
} | identifier_body |
converter.ts |
/**
* Converts modlogs between text and SQLite; also modernizes old-format modlogs
* @author Annika
* @author jetou
*/
if (!global.Config) {
let hasSQLite = true;
try {
require.resolve('better-sqlite3');
} catch (e) {
hasSQLite = false;
}
global.Config = {
nofswriting: false,
usesqlitemodlog: hasSQLi... | () {
const files = await FS(this.inputDir).readdir();
// Read global modlog last to avoid inserting duplicate data to database
if (files.includes('modlog_global.txt')) {
files.splice(files.indexOf('modlog_global.txt'), 1);
files.push('modlog_global.txt');
}
const globalEntries = [];
for (const file ... | toTxt | identifier_name |
wide_deep.py | # Copyright 2017 The TensorFlow Authors. 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 by applica... |
# Extract lines from input files using the Dataset API.
dataset = tf.contrib.data.TextLineDataset(data_file)
dataset = dataset.map(parse_csv, num_threads=5)
# Apply transformations to the Dataset
dataset = dataset.batch(batch_size)
dataset = dataset.repeat(num_epochs)
# Input function that is called b... | print('Parsing', data_file)
columns = tf.decode_csv(value, record_defaults=_CSV_COLUMN_DEFAULTS)
features = dict(zip(_CSV_COLUMNS, columns))
labels = features.pop('income_bracket')
return features, tf.equal(labels, '>50K') | identifier_body |
wide_deep.py | # Copyright 2017 The TensorFlow Authors. 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 by applica... |
else:
iterator = dataset.make_one_shot_iterator()
features, labels = iterator.get_next()
return features, labels
return _input_fn
def main(unused_argv):
# Clean up the model directory if present
shutil.rmtree(FLAGS.model_dir, ignore_errors=True)
model = build_estimator(FLAGS.model_dir, FLA... | shuffled_dataset = dataset.shuffle(buffer_size=100000)
iterator = shuffled_dataset.make_one_shot_iterator() | conditional_block |
wide_deep.py | # Copyright 2017 The TensorFlow Authors. 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 by applica... | (unused_argv):
# Clean up the model directory if present
shutil.rmtree(FLAGS.model_dir, ignore_errors=True)
model = build_estimator(FLAGS.model_dir, FLAGS.model_type)
# Set up input function generators for the train and test data files.
train_input_fn = input_fn(
data_file=FLAGS.train_data,
num_... | main | identifier_name |
wide_deep.py | # Copyright 2017 The TensorFlow Authors. 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 by applica... | model.train(input_fn=train_input_fn)
results = model.evaluate(input_fn=eval_input_fn)
# Display evaluation metrics
print('Results at epoch', (n + 1) * FLAGS.epochs_per_eval)
print('-' * 30)
for key in sorted(results):
print('%s: %s' % (key, results[key]))
if __name__ == '__main__':
tf... | batch_size=FLAGS.batch_size)
# Train and evaluate the model every `FLAGS.epochs_per_eval` epochs.
for n in range(FLAGS.train_epochs // FLAGS.epochs_per_eval): | random_line_split |
xyz.py | # -*- coding: utf-8 -*- | # HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON 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 Foundati... | random_line_split | |
xyz.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | (filename):
'''Load a molecular geometry from a .xyz file.
**Argument:**
filename
The file to load the geometry from
**Returns:** dictionary with ``title`, ``coordinates`` and ``numbers``.
'''
f = file(filename)
size = int(f.next())
title = f.next().strip()
co... | load_xyz | identifier_name |
xyz.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... |
def dump_xyz(filename, data):
'''Write an ``.xyz`` file.
**Arguments:**
filename
The name of the file to be written. This usually the extension
".xyz".
data
An IOData instance. Must contain ``coordinates`` and ``numbers``.
May contain ``titl... | '''Load a molecular geometry from a .xyz file.
**Argument:**
filename
The file to load the geometry from
**Returns:** dictionary with ``title`, ``coordinates`` and ``numbers``.
'''
f = file(filename)
size = int(f.next())
title = f.next().strip()
coordinates = np.e... | identifier_body |
xyz.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | n = periodic[data.numbers[i]].symbol
x, y, z = data.coordinates[i]/angstrom
print >> f, '%2s %15.10f %15.10f %15.10f' % (n, x, y, z) | conditional_block | |
print_queue_resolvers.rs | use async_graphql::{
ID,
Context,
FieldResult,
};
// use eyre::{
// eyre,
// // Result,
// Context as _,
// };
use printspool_json_store::{ Record, JsonRow };
use crate::{
PrintQueue,
part::Part,
// package::Package,
};
#[derive(async_graphql::InputObject, Default)]
struct PrintQue... |
async fn parts<'ctx>(
&self,
ctx: &'ctx Context<'_>,
// id: Option<ID>,
input: Option<PrintQueuePartsInput>,
) -> FieldResult<Vec<Part>> {
let db: &crate::Db = ctx.data()?;
let input = input.unwrap_or(PrintQueuePartsInput {
include_queued: true,
... | {
&self.name
} | identifier_body |
print_queue_resolvers.rs | use async_graphql::{
ID,
Context,
FieldResult,
};
// use eyre::{
// eyre,
// // Result,
// Context as _,
// };
use printspool_json_store::{ Record, JsonRow };
use crate::{
PrintQueue,
part::Part,
// package::Package,
};
#[derive(async_graphql::InputObject, Default)]
struct PrintQue... | <'ctx>(
&self,
ctx: &'ctx Context<'_>,
// id: Option<ID>,
input: Option<PrintQueuePartsInput>,
) -> FieldResult<Vec<Part>> {
let db: &crate::Db = ctx.data()?;
let input = input.unwrap_or(PrintQueuePartsInput {
include_queued: true,
include_fin... | parts | identifier_name |
print_queue_resolvers.rs | use async_graphql::{
ID,
Context,
FieldResult,
};
// use eyre::{
// eyre,
// // Result,
// Context as _,
// };
use printspool_json_store::{ Record, JsonRow };
use crate::{
PrintQueue,
part::Part,
// package::Package,
};
#[derive(async_graphql::InputObject, Default)]
struct PrintQue... | impl PrintQueue {
async fn id(&self) -> ID { (&self.id).into() }
async fn name<'ctx>(&self) -> &String {
&self.name
}
async fn parts<'ctx>(
&self,
ctx: &'ctx Context<'_>,
// id: Option<ID>,
input: Option<PrintQueuePartsInput>,
) -> FieldResult<Vec<Part>> {
... |
#[async_graphql::Object] | random_line_split |
cargo.rs | extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
// Write the Docopt usage string.
const USAGE: &'static str = "
Rust's package manager
Usage:
cargo <command> [<args>...]
cargo [options]
Options:
-h, --help Display this message
-V, --version Print version info and exit... | .unwrap_or_else(|e| e.exit());
println!("{:?}", args);
} | random_line_split | |
cargo.rs | extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
// Write the Docopt usage string.
const USAGE: &'static str = "
Rust's package manager
Usage:
cargo <command> [<args>...]
cargo [options]
Options:
-h, --help Display this message
-V, --version Print version info and exit... | () {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.options_first(true).decode())
.unwrap_or_else(|e| e.exit());
println!("{:?}", args);
}
| main | identifier_name |
all_c.js | ['maxsteps',['maxSteps',['../class_dataset.html#a5350c5b634efd3979339149aca3264f2',1,'Dataset']]],
['model',['Model',['../class_model.html',1,'Model'],['../class_model.html#ae3b375de5f6df4faf74a95d64748e048',1,'Model::Model()']]],
['msg',['msg',['../class_timer.html#a439eced3ba76f02f685358373cd7d124',1,'Timer']]]... | var searchData=
[
['mainfolder',['mainFolder',['../class_dataset.html#accd7ce9be4329d6e3b758f71269a8703',1,'Dataset']]], | random_line_split | |
sha.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
pub fn handle_interrupt(&self, _nvic: u32) {
let ref regs = unsafe { &*self.regs }.sha;
regs.itop.set(0);
}
}
pub static mut KEYMGR0_SHA: ShaEngine = unsafe { ShaEngine::new(KEYMGR0_REGS) };
const HMAC_KEY_SIZE_BYTES: usize = 32;
const HMAC_KEY_SIZE_WORDS: usize = HMAC_KEY_SIZE_BYTES / 4;
i... | {
ShaEngine {
regs: regs,
current_mode: Cell::new(None),
}
} | identifier_body |
sha.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (regs: *mut Registers) -> ShaEngine {
ShaEngine {
regs: regs,
current_mode: Cell::new(None),
}
}
pub fn handle_interrupt(&self, _nvic: u32) {
let ref regs = unsafe { &*self.regs }.sha;
regs.itop.set(0);
}
}
pub static mut KEYMGR0_SHA: ShaEngine = uns... | new | identifier_name |
sha.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | DigestMode::Sha1 => flags |= ShaCfgEnMask::Sha1 as u32,
DigestMode::Sha256 => (),
DigestMode::Sha256Hmac => flags |= ShaCfgEnMask::Hmac as u32,
}
regs.cfg_en.set(flags);
regs.trig.set(ShaTrigMask::Go as u32);
Ok(())
}
fn initialize_hmac(&sel... |
let mut flags = ShaCfgEnMask::Livestream as u32 |
ShaCfgEnMask::IntEnDone as u32;
match mode { | random_line_split |
renderer.tsx | import * as electron from 'electron';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
type SizeType = '640 x 480' | '800 x 600' | '1280 x 800' | '1440 x 900' | '1680 x 1050';
export type FormatType = 'webm' | 'gif';
export interface CaptureSize {
width: number;
height: number;
}
interface ... |
render(): JSX.Element {
return (
<ul
className="list-group"
>{this.state.captureSources.map((source: Electron.DesktopCapturerSource) => {
return (
<li
key={source.id}
id={source.id}
className='list-group-item'
onClick={this.se... | {
this.fetchScreen();
this.ipc.on('fetchScreen', () => {
this.fetchScreen();
});
} | identifier_body |
renderer.tsx | import * as electron from 'electron';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
type SizeType = '640 x 480' | '800 x 600' | '1280 x 800' | '1440 x 900' | '1680 x 1050';
export type FormatType = 'webm' | 'gif';
export interface CaptureSize {
width: number;
height: number;
}
interface ... |
this.capture.className = 'icon icon-stop capture';
this.frames = [];
this.startTime = Date.now();
this.setState({
isRecord: true,
timer: '00:00:00'
});
this.requestId = requestAnimationFrame(this.draw.bind(this));
}
private draw(): void {
this.canvasctx.drawImage(this.p... | {
this.capture.className = 'icon icon-record capture';
cancelAnimationFrame(this.requestId);
let downloaderURL = this.downloader.getAttribute('href');
if (downloaderURL) {
window.URL.revokeObjectURL(downloaderURL);
}
if (this.format === 'webm') {
this.toWebm();
... | conditional_block |
renderer.tsx | import * as electron from 'electron';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
type SizeType = '640 x 480' | '800 x 600' | '1280 x 800' | '1440 x 900' | '1680 x 1050';
export type FormatType = 'webm' | 'gif';
export interface CaptureSize {
width: number;
height: number;
}
interface ... | (blob: Blob, format: FormatType): void {
let clicker = document.createEvent('MouseEvent') as MouseEvent;
clicker.initEvent('click', false, true);
this.downloader.setAttribute('href', window.URL.createObjectURL(blob));
this.downloader.setAttribute('download', `${this.startTime}.${format}`);
this.down... | finalize | identifier_name |
renderer.tsx | import * as electron from 'electron';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
type SizeType = '640 x 480' | '800 x 600' | '1280 x 800' | '1440 x 900' | '1680 x 1050';
export type FormatType = 'webm' | 'gif';
export interface CaptureSize {
width: number;
height: number;
}
interface ... | className="btn btn-default pull-right"
onClick={this.fetchScreen.bind(this)}
>
<span
className="icon icon-arrows-ccw"/>
</button>
</div>
);
}
private toggleAlwaysOnTop(): void {
let alwaysOnTop = !this.state.alwaysOnTop;
this.window.setAlw... | <button | random_line_split |
script.rs | use std::fmt;
use std::str::FromStr;
use super::lang_mapping;
use crate::error::Error;
use crate::Lang;
#[cfg(feature = "enum-map")]
use enum_map::Enum;
/// Represents a writing system (Latin, Cyrillic, Arabic, etc).
#[cfg_attr(feature = "enum-map", derive(Enum))]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enu... |
}
| {
// Vec of all langs obtained with script.langs()
let script_langs: Vec<Lang> = Script::all()
.iter()
.map(|script| script.langs())
.flatten()
.copied()
.collect();
// Ensure all langs belong at least to one script
for lang in... | identifier_body |
script.rs | use std::fmt;
use std::str::FromStr;
use super::lang_mapping;
use crate::error::Error;
use crate::Lang;
#[cfg(feature = "enum-map")]
use enum_map::Enum;
/// Represents a writing system (Latin, Cyrillic, Arabic, etc).
#[cfg_attr(feature = "enum-map", derive(Enum))]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enu... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl FromStr for Script {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().trim() {
"latin" => Ok(Script::Latin),
"cyrillic" => Ok(Script::Cyr... | fmt | identifier_name |
script.rs | use std::fmt;
use std::str::FromStr;
use super::lang_mapping;
use crate::error::Error;
use crate::Lang;
#[cfg(feature = "enum-map")]
use enum_map::Enum;
/// Represents a writing system (Latin, Cyrillic, Arabic, etc).
#[cfg_attr(feature = "enum-map", derive(Enum))]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enu... | "mandarin" => Ok(Script::Mandarin),
"hangul" => Ok(Script::Hangul),
"greek" => Ok(Script::Greek),
"kannada" => Ok(Script::Kannada),
"tamil" => Ok(Script::Tamil),
"thai" => Ok(Script::Thai),
"gujarati" => Ok(Script::Gujarati),
... | "katakana" => Ok(Script::Katakana),
"ethiopic" => Ok(Script::Ethiopic),
"hebrew" => Ok(Script::Hebrew),
"bengali" => Ok(Script::Bengali),
"georgian" => Ok(Script::Georgian), | random_line_split |
sync.py | import io
try:
import requests
except ImportError:
print("Requests module not installed, sync functions unavailable!")
class ResponseError(BaseException):
pass
class Route:
def __init__(self, base_url, path, cdn_url=None, method="GET", headers=None):
self.base_url = base_url
self.path... |
def sync_download(self):
res = requests.get(self.cdn_url+self.cdn_path)
if 200 <= res.status_code < 300:
return io.BytesIO(res.content)
else:
raise ResponseError(
"Expected a status code 200-299, got {}"
.format(res.status_cod... | self.path = path
self.cdn_path = path[2:]
self.img_id = id
self.img_type = type
self.nsfw = nsfw
self.cdn_url = cdn_url | identifier_body |
sync.py | import io
try:
import requests
except ImportError:
print("Requests module not installed, sync functions unavailable!")
class ResponseError(BaseException):
pass
class Route:
def __init__(self, base_url, path, cdn_url=None, method="GET", headers=None):
self.base_url = base_url
self.path... | (self):
res = requests.get(self.cdn_url+self.cdn_path)
if 200 <= res.status_code < 300:
return io.BytesIO(res.content)
else:
raise ResponseError(
"Expected a status code 200-299, got {}"
.format(res.status_code))
def __call__(s... | sync_download | identifier_name |
sync.py | import io
try:
import requests
except ImportError:
print("Requests module not installed, sync functions unavailable!")
class ResponseError(BaseException):
pass
class Route:
def __init__(self, base_url, path, cdn_url=None, method="GET", headers=None):
self.base_url = base_url
self.path... |
def __call__(self):
return self.sync_download()
| raise ResponseError(
"Expected a status code 200-299, got {}"
.format(res.status_code)) | conditional_block |
sync.py | import io
try:
import requests
except ImportError:
print("Requests module not installed, sync functions unavailable!")
class ResponseError(BaseException):
pass
class Route:
def __init__(self, base_url, path, cdn_url=None, method="GET", headers=None):
self.base_url = base_url
self.path... | def __call__(self):
return self.sync_download() | random_line_split | |
cst.py | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 20 16:01:21 2016
@author: KB
"""
#Listes des images du jeu
import pygame
dossier = "./Img_FS/"
extension1 = ".png"
extension2 = ".jpg"
image_accueil = dossier + "accueil" + extension1
image_fond = dossier + "back1" + extension2
image_mur = dossier + "mur" + extension... |
cote_fenetre = nombre_sprite_cote * taille_sprite
#Personnalisation de la fenêtre
titre_fenetre = "Fear Shadows" | random_line_split | |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn contact_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N... | ;
Some(Contact::new(
*center1 + *normal * r1,
*center2 + *normal * (-r2),
normal,
sum_radius - distance_squared.sqrt(),
))
} else {
None
}
}
| {
Vector::x_axis()
} | conditional_block |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn contact_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N... | {
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + prediction;
if distance_squared < sum_radius_with_error * sum_radius_with_error {
let no... | identifier_body | |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn | <N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N>> {
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
... | contact_ball_ball | identifier_name |
contact_ball_ball.rs | use crate::math::{Point, Vector};
use crate::query::Contact;
use crate::shape::Ball;
use na::{self, RealField, Unit};
/// Contact between balls.
#[inline]
pub fn contact_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
prediction: N,
) -> Option<Contact<N... | let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + prediction;
if distance_squared < sum_radius_with_error * sum_radius_with_error {
let normal = if !distance_square... | let r1 = b1.radius; | random_line_split |
longlive.js | var mongo = require('../');
var db = mongo.db('192.168.0.103/test');
// var db = mongo.db('127.0.0.1/test');
var myconsole = require('myconsole');
var foo = db.collection('foo');
setInterval(function() {
foo.insert({foo:'foo'}, function(err, result){
if(err) return myconsole.error(err);
foo.count(function(err, ... | process.on('SIGINT', function(){
myconsole.log('SIGINT')
foo.drop(function(err){
if(err) myconsole.error(err);
process.exit();
})
}) | random_line_split | |
tests.rs | extern crate rustsocks;
use rustsocks::{Socks4, Socks4a, Socks5};
use std::io::net::ip::IpAddr;
static SOCKS_HOST : &'static str = "127.0.0.1";
static SOCKS_PORT : u16 = 9150;
static GET_REQUEST : &'static str =
"GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n";
#[test]
fn socks4a() {
let mu... | {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let addr = from_str::<IpAddr>("74.125.230.65").unwrap();
let mut stream = socks.connect(addr, 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
} | identifier_body | |
tests.rs | extern crate rustsocks;
use rustsocks::{Socks4, Socks4a, Socks5};
use std::io::net::ip::IpAddr;
static SOCKS_HOST : &'static str = "127.0.0.1";
static SOCKS_PORT : u16 = 9150;
static GET_REQUEST : &'static str =
"GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n";
#[test]
fn socks4a() {
let mu... | () {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let mut stream = socks.connect("www.google.com", 80);
let _ = stream.write_str(GET_REQUEST);
println!("{}", stream.read_to_string().unwrap());
}
#[test]
fn socks5_ipv4() {
let mut socks = Socks5::new(SOCKS_HOST, SOCKS_PORT);
let addr = ... | socks5_domain | identifier_name |
tests.rs | extern crate rustsocks;
use rustsocks::{Socks4, Socks4a, Socks5};
use std::io::net::ip::IpAddr;
static SOCKS_HOST : &'static str = "127.0.0.1";
static SOCKS_PORT : u16 = 9150;
static GET_REQUEST : &'static str =
"GET /404 HTTP/1.1\nHost: www.google.com\nConnection: close\n\n";
#[test]
fn socks4a() {
let mu... | println!("{}", stream.read_to_string().unwrap());
} |
let _ = stream.write_str(GET_REQUEST); | random_line_split |
main.rs | use {
futures::{
future::{BoxFuture, FutureExt},
task::{waker_ref, ArcWake},
},
std::{
future::Future,
sync::mpsc::{sync_channel, Receiver, SyncSender},
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
},
};
struct Task {
future: Mut... | {
let (sender, receiver) = std::sync::mpsc::channel::<i32>();
let s1 = sender.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(1000));
println!("sent!");
s1.send(1).unwrap();
});
let receiver = FutureReceiver(Arc::from(Mutex::from(re... | identifier_body | |
main.rs | use {
futures::{
future::{BoxFuture, FutureExt},
task::{waker_ref, ArcWake},
},
std::{
future::Future,
sync::mpsc::{sync_channel, Receiver, SyncSender},
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
},
};
struct Task {
future: Mut... | (
self: std::pin::Pin<&mut Self>,
ctx: &mut std::task::Context<'_>,
) -> std::task::Poll<T> {
println!("FutureReceiver.poll.1");
let ch = self.0.lock().unwrap();
let mut iter = ch.try_iter();
match iter.next() {
Some(v) => std::task::Poll::Ready(v),
... | poll | identifier_name |
main.rs | use {
futures::{
future::{BoxFuture, FutureExt},
task::{waker_ref, ArcWake},
},
std::{
future::Future,
sync::mpsc::{sync_channel, Receiver, SyncSender},
sync::{Arc, Mutex},
task::{Context, Poll},
time::Duration,
},
};
struct Task {
future: Mut... | };
let exec = new_executor_and_spawner();
exec.spawn(f);
exec.run();
} | receiver.await;
println!("done!"); | random_line_split |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | "votre équipage individuellement. Il existe également " \
"la commande %équipage% qui permet de manipuler l'équipage " \
"d'un coup d'un seul."
def ajouter_parametres(self):
"""Ajout des paramètres"""
self.ajouter_parametre(PrmAffecter())
self.ajouter_par... | self.nom_categorie = "navire"
self.aide_courte = "manipulation des matelots"
self.aide_longue = \
"Cette commande permet de manipuler les matelots de " \ | random_line_split |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | out des paramètres"""
self.ajouter_parametre(PrmAffecter())
self.ajouter_parametre(PrmCreer())
self.ajouter_parametre(PrmEditer())
self.ajouter_parametre(PrmInfo())
self.ajouter_parametre(PrmListe())
self.ajouter_parametre(PrmPoste())
self.ajouter_parametre(PrmPro... | identifier_body | |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | Commande):
"""Commande 'matelot'.
"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "matelot", "seaman")
self.nom_categorie = "navire"
self.aide_courte = "manipulation des matelots"
self.aide_longue = \
"Cette commande pe... | mdMatelot( | identifier_name |
ellipse.js | /*
Class: Graphic.Ellipse
Shape implementation of an ellipse.
Author:
Sébastien Gruhier, <http://www.xilinus.com>
License:
MIT-style license.
See Also: | Graphic.Ellipse = Class.create();
Object.extend(Graphic.Ellipse.prototype, Graphic.Shape.prototype);
// Keep parent initialize
Graphic.Ellipse.prototype._shapeInitialize = Graphic.Shape.prototype.initialize;
Object.extend(Graphic.Ellipse.prototype, {
initialize: function(renderer) {
this._shapeInitialize(rendere... | <Shape>
*/ | random_line_split |
treeUtils.js | //@line 39 "/builds/slave/rel-m-rel-xr-osx64-bld/build/toolkit/content/treeUtils.js"
var gTreeUtils = {
deleteAll: function (aTree, aView, aItems, aDeletedItems)
{
for (var i = 0; i < aItems.length; ++i)
aDeletedItems.push(aItems[i]);
aItems.splice(0, aItems.length);
var oldCount = aView.rowCount... | }; | random_line_split | |
treeUtils.js | //@line 39 "/builds/slave/rel-m-rel-xr-osx64-bld/build/toolkit/content/treeUtils.js"
var gTreeUtils = {
deleteAll: function (aTree, aView, aItems, aDeletedItems)
{
for (var i = 0; i < aItems.length; ++i)
aDeletedItems.push(aItems[i]);
aItems.splice(0, aItems.length);
var oldCount = aView.rowCount... |
}
var nextSelection = 0;
for (i = 0; i < aItems.length; ++i) {
if (!aItems[i]) {
var j = i;
while (j < aItems.length && !aItems[j])
++j;
aItems.splice(i, j - i);
nextSelection = j < aView.rowCount ? j - 1 : j - 2;
aView._rowCount -= j - i;
aT... | {
aDeletedItems.push(aItems[j]);
aItems[j] = null;
} | conditional_block |
cg.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 https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStr... | <F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type
where
F: FnMut(&Ident) -> Type,
{
match *ty {
Type::Slice(ref inner) => Type::from(TypeSlice {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
Type::Array(ref inner) => {
... | map_type_params | identifier_name |
cg.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 https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStr... |
}
Type::from(TypePath {
qself: None,
path: map_type_params_in_path(path, params, f),
})
},
Type::Path(TypePath {
ref qself,
ref path,
}) => Type::from(TypePath {
qself: qself.as_ref().map(|qs... | {
return f(ident);
} | conditional_block |
cg.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 https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStr... | ty,
);
let ident = match path_to_ident(path) {
Some(i) => i,
None => panic!("Unhanded complex where type path: {:?}", path),
};
if generics.type_params().any(|param| param.ident == *ident) {
extra_bounds.push(ty.clone());
}
}
... | assert!(
ty.lifetimes.is_none(),
"Unhanded complex lifetime bound: {:?}", | random_line_split |
cg.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 https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStr... |
pub fn parse_variant_attrs<A>(variant: &Variant) -> A
where
A: FromVariant,
{
match A::from_variant(variant) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse variant attributes: {}", e),
}
}
pub fn ref_pattern<'a>(
variant: &'a VariantInfo,
prefix: &str,
) -> (TokenStream, ... | {
let v = Variant {
ident: variant.ident.clone(),
attrs: variant.attrs.to_vec(),
fields: variant.fields.clone(),
discriminant: variant.discriminant.clone(),
};
parse_variant_attrs(&v)
} | identifier_body |
webgl-detector.js | 'use strict';
/* global THREE,Modernizr */
angular.module('artpopApp')
.directive('webglDetector', function (X3) {
function Detector(){
X3.apply(this,arguments);
}
Detector.prototype = Object.create(X3.prototype);
var app = new Detector();
window.apwgl = app;
app.init();
function configCamera(){
app.cam... | function addLight(){
var lightBack = new THREE.DirectionalLight( 0xffffff, 5, 1000 );
lightBack.position.set( 0, 0, 400 );
app.scene.add( lightBack );
app.updateStack.push(function(){
lightBack.rotation.z += 0.004;
lightBack.rotation.x += 0.004;
lightBack.rotation.y += 0.004;
lightBack.color.offse... | random_line_split | |
webgl-detector.js | 'use strict';
/* global THREE,Modernizr */
angular.module('artpopApp')
.directive('webglDetector', function (X3) {
function Detector(){
X3.apply(this,arguments);
}
Detector.prototype = Object.create(X3.prototype);
var app = new Detector();
window.apwgl = app;
app.init();
function configCamera(){
app.cam... |
addLight();
return {
template: '<div class="gl-canvas-container"></div>',
restrict: 'E',
transclude: true,
//link function is not di.
link: function($scope, $element, $transclude){
var container = $element[0].querySelector('.gl-canvas-container');
if (Modernizr.webgl){
app.reconfig($scope, $ele... | {
var lightBack = new THREE.DirectionalLight( 0xffffff, 5, 1000 );
lightBack.position.set( 0, 0, 400 );
app.scene.add( lightBack );
app.updateStack.push(function(){
lightBack.rotation.z += 0.004;
lightBack.rotation.x += 0.004;
lightBack.rotation.y += 0.004;
lightBack.color.offsetHSL(0.001,0.0,0);
... | identifier_body |
webgl-detector.js | 'use strict';
/* global THREE,Modernizr */
angular.module('artpopApp')
.directive('webglDetector', function (X3) {
function Detector(){
X3.apply(this,arguments);
}
Detector.prototype = Object.create(X3.prototype);
var app = new Detector();
window.apwgl = app;
app.init();
function configCamera(){
app.cam... | else{
container.appendChild($transclude());
}
}
};
});
/**/
| {
app.reconfig($scope, $element, container);
} | conditional_block |
webgl-detector.js | 'use strict';
/* global THREE,Modernizr */
angular.module('artpopApp')
.directive('webglDetector', function (X3) {
function Detector(){
X3.apply(this,arguments);
}
Detector.prototype = Object.create(X3.prototype);
var app = new Detector();
window.apwgl = app;
app.init();
function configCamera(){
app.cam... | (){
//onetime use only.
var material = new THREE.MeshLambertMaterial({
color: 0xff0000,
wireframe: true,
wireframeLinewidth: 2,
side: THREE.BackSide,
transparent: true,
opacity: 0.9,
});
var inner = new THREE.Mesh(
new THREE.IcosahedronGeometry(
10,
2
),
material
);
app.... | addObject | identifier_name |
db.py | import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import mapper, sessionmaker
import subprocess
class PygrationState(object):
'''Python object representing the state table'''
def __init__(self, migration=None, step_id=None, step_name=None):
self.migration = migration
... | (url=None, drivername=None, schema=None, username=None,
password=None, host=None, port=None, database=None, query=None):
"""Open the DB through a SQLAlchemy engine.
Returns an open session.
"""
if url is None and drivername is None:
raise Exception("Either a url or a driver name ... | open | identifier_name |
db.py | import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import mapper, sessionmaker
import subprocess
class PygrationState(object):
'''Python object representing the state table'''
def __init__(self, migration=None, step_id=None, step_name=None):
self.migration = migration
... |
class FileLoader(object):
'''Object for running SQL from a file on the file system'''
def __init__(self, binary, args = [], formatting_dict = {}):
self._binary = binary
self._args = [arg.format(filename="{filename}", **formatting_dict) for arg in args]
def __call__(self, filename):
... | cls.pygration_state = sqlalchemy.Table('pygration_state', cls.metadata
, Column('migration', String(length=160), primary_key=True)
, Column('step_id', String(length=160), primary_key=True)
, Column('step_name', String(length=160))
, Column('sequence', Inte... | identifier_body |
db.py | import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import mapper, sessionmaker
import subprocess
class PygrationState(object):
'''Python object representing the state table'''
def __init__(self, migration=None, step_id=None, step_name=None):
self.migration = migration
... | metadata = sqlalchemy.MetaData()
engine = None
pygration_state = None
@classmethod
def define(cls, schema=None):
cls.pygration_state = sqlalchemy.Table('pygration_state', cls.metadata
, Column('migration', String(length=160), primary_key=True)
, Column('step... | def __repr__(self):
return "<PygrationState(%s, %s)>" % (self.migration, self.step_id)
class Table(object): | random_line_split |
db.py | import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import mapper, sessionmaker
import subprocess
class PygrationState(object):
'''Python object representing the state table'''
def __init__(self, migration=None, step_id=None, step_name=None):
self.migration = migration
... |
Table.engine = sqlalchemy.create_engine(url)
Table.metadata.bind = Table.engine
Session = sessionmaker()
Session.configure(bind=Table.engine)
session = Session()
Table.define(schema)
mapper(PygrationState, Table.pygration_state)
return session
| url = sqlalchemy.engine.url.URL(drivername = drivername,
username = username,
password = password,
host = host,
port = port,
... | conditional_block |
sendmanyBuilder.ts | import { BaseCoin as CoinConfig, NetworkType, StacksNetwork as BitgoStacksNetwork } from '@bitgo/statics';
import BigNum from 'bn.js';
import {
AddressHashMode,
addressToString,
AddressVersion,
bufferCVFromString,
ClarityValue,
FungibleConditionCode,
listCV,
makeStandardSTXPostCondition,
PostCondition... |
if (!!memo && !isValidMemo(memo)) {
throw new BuildTransactionError('Invalid memo, got: ' + memo);
}
this._sendParams.push({ address, amount, memo });
return this;
}
/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
this._contractAddress = (this._coinCon... | {
throw new BuildTransactionError('Invalid or missing amount, got: ' + amount);
} | conditional_block |
sendmanyBuilder.ts | import { BaseCoin as CoinConfig, NetworkType, StacksNetwork as BitgoStacksNetwork } from '@bitgo/statics';
import BigNum from 'bn.js';
import {
AddressHashMode,
addressToString,
AddressVersion,
bufferCVFromString,
ClarityValue,
FungibleConditionCode,
listCV,
makeStandardSTXPostCondition,
PostCondition... |
public static isValidContractCall(coinConfig: Readonly<CoinConfig>, payload: ContractCallPayload): boolean {
return (
(coinConfig.network as BitgoStacksNetwork).sendmanymemoContractAddress ===
addressToString(payload.contractAddress) &&
CONTRACT_NAME_SENDMANY === payload.contractName.content... | {
super(_coinConfig);
} | identifier_body |
sendmanyBuilder.ts | import { BaseCoin as CoinConfig, NetworkType, StacksNetwork as BitgoStacksNetwork } from '@bitgo/statics';
import BigNum from 'bn.js';
import {
AddressHashMode,
addressToString,
AddressVersion,
bufferCVFromString,
ClarityValue,
FungibleConditionCode,
listCV,
makeStandardSTXPostCondition,
PostCondition... | (coinConfig.network as BitgoStacksNetwork).sendmanymemoContractAddress ===
addressToString(payload.contractAddress) &&
CONTRACT_NAME_SENDMANY === payload.contractName.content &&
FUNCTION_NAME_SENDMANY === payload.functionName.content
);
}
private sendParamsToFunctionArgs = (sendParams... |
public static isValidContractCall(coinConfig: Readonly<CoinConfig>, payload: ContractCallPayload): boolean {
return ( | random_line_split |
sendmanyBuilder.ts | import { BaseCoin as CoinConfig, NetworkType, StacksNetwork as BitgoStacksNetwork } from '@bitgo/statics';
import BigNum from 'bn.js';
import {
AddressHashMode,
addressToString,
AddressVersion,
bufferCVFromString,
ClarityValue,
FungibleConditionCode,
listCV,
makeStandardSTXPostCondition,
PostCondition... | extends AbstractContractBuilder {
private _sendParams: SendParams[] = [];
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
}
public static isValidContractCall(coinConfig: Readonly<CoinConfig>, payload: ContractCallPayload): boolean {
return (
(coinConfig.network as BitgoStac... | SendmanyBuilder | identifier_name |
index.js | /*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/
var UNKNOWN = 'UNKNOWN';
var fs = require('fs');
var path = require('path');
var read = require('read-installed');
var chalk = require('chalk');
var treeify = require('treeify');
var license =... | var module = sorted[key];
text.push('[' + key + '](' + module.repository + ') - ' + module.licenses);
});
text = text.join('\n');
}
return text;
};
/*istanbul ignore next*/
exports.parseJson = function(jsonPath) {
if (typeof jsonPath !== 'string') {
return n... | random_line_split | |
index.js | /*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/
var UNKNOWN = 'UNKNOWN';
var fs = require('fs');
var path = require('path');
var read = require('read-installed');
var chalk = require('chalk');
var treeify = require('treeify');
var license =... | else if (typeof licenseData === 'string') {
moduleInfo.licenses = licenseData;
}
} else if (license(json.readme)) {
moduleInfo.licenses = license(json.readme);
}
/*istanbul ignore else*/
if (json.path && fs.existsSync(json.path)) {
files = fs.readdirSync(json.path).... | {
moduleInfo.licenses = licenseData.type;
} | conditional_block |
subp_main.py | # Copyright 2009 Noam Yorav-Raphael
#
# This file is part of DreamPie.
#
# DreamPie 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.
# ... | ():
port = int(sys.argv[1])
py_ver = sys.version_info[0]
lib_name = abspath(join(dirname(__file__), 'subp-py%d' % py_ver))
sys.path.insert(0, lib_name)
from dreampielib.subprocess import main as subprocess_main
del sys.path[0]
if sys.version_info[:2] == (3, 0):
sys.stderr.... | main | identifier_name |
subp_main.py | # Copyright 2009 Noam Yorav-Raphael
#
# This file is part of DreamPie.
#
# DreamPie 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.
# ... |
subprocess_main(port)
if __name__ == '__main__':
main()
| sys.stderr.write("Warning: DreamPie doesn't support Python 3.0. \n"
"Please upgrade to Python 3.1.\n") | conditional_block |
subp_main.py | # Copyright 2009 Noam Yorav-Raphael
#
# This file is part of DreamPie.
#
# DreamPie 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.
# ... | import sys
from os.path import abspath, join, dirname
def main():
port = int(sys.argv[1])
py_ver = sys.version_info[0]
lib_name = abspath(join(dirname(__file__), 'subp-py%d' % py_ver))
sys.path.insert(0, lib_name)
from dreampielib.subprocess import main as subprocess_main
del sys.path[0]... | # (which are expected to be in the directory of __file__),
# and runs dreampielib.subprocess.main(port). | random_line_split |
subp_main.py | # Copyright 2009 Noam Yorav-Raphael
#
# This file is part of DreamPie.
#
# DreamPie 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.
# ... |
if __name__ == '__main__':
main()
| port = int(sys.argv[1])
py_ver = sys.version_info[0]
lib_name = abspath(join(dirname(__file__), 'subp-py%d' % py_ver))
sys.path.insert(0, lib_name)
from dreampielib.subprocess import main as subprocess_main
del sys.path[0]
if sys.version_info[:2] == (3, 0):
sys.stderr.write("W... | identifier_body |
test_dot-jump25Oct2016_10-53.py | from __future__ import print_function
__author__ = """Alex "O." Holcombe, Charles Ludowici, """ ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor
import time, sys, platform, os
from math import atan, atan2, pi, cos, sin, sqrt, ceil, radians, degrees
import numpy as np
import psychopy, ... |
elif not sameEachTime:
stim = stimulusObject[dot]
stim.pos = (xpos,ypos)
stimuli.append(stim)
return stimuli
def checkTiming(ts):
interframeIntervals = np.diff(ts) * 1000
#print(interframeIntervals)
frameTimeTolerance=.3 #proportion longer than refreshRate that will... | stim = copy.copy(stimulusObject) | conditional_block |
test_dot-jump25Oct2016_10-53.py | from __future__ import print_function
__author__ = """Alex "O." Holcombe, Charles Ludowici, """ ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor
import time, sys, platform, os
from math import atan, atan2, pi, cos, sin, sqrt, ceil, radians, degrees
import numpy as np
import psychopy, ... |
def oneTrial(stimuli):
dotOrder = np.arange(len(stimuli))
np.random.shuffle(dotOrder)
print(dotOrder)
shuffledStimuli = [stimuli[i] for i in dotOrder]
ts = []
myWin.flip(); myWin.flip() #Make sure raster at top of screen (unless not in blocking mode), and give CPU a chance to finish other task... | cueFrame = cuePos * SOAFrames
cueMax = cueFrame + cueFrames
showIdx = int(np.floor(n/SOAFrames))
#objectIdxs = [i for i in range(len(trialObjects))]
#objectIdxs.append(len(trialObjects)-1) #AWFUL hack
#print(objectIdxs[showIdx])
#floored quotient
obj = trialObjects[showIdx]
drawObject ... | identifier_body |
test_dot-jump25Oct2016_10-53.py | from __future__ import print_function
__author__ = """Alex "O." Holcombe, Charles Ludowici, """ ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor
import time, sys, platform, os
from math import atan, atan2, pi, cos, sin, sqrt, ceil, radians, degrees
import numpy as np
import psychopy, ... | #end of header
trialClock = core.Clock()
stimClock = core.Clock()
if eyeTracking:
if getEyeTrackingFileFromEyetrackingMachineAtEndOfExperiment:
eyeMoveFile=('EyeTrack_'+subject+'_'+timeAndDateStr+'.EDF')
tracker=Tracker_EyeLink(myWin,trialClock,subject,1, 'HV5',(255,255,255),(0,0,0),False,(widthPix,he... | myWin.flip() | random_line_split |
test_dot-jump25Oct2016_10-53.py | from __future__ import print_function
__author__ = """Alex "O." Holcombe, Charles Ludowici, """ ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor
import time, sys, platform, os
from math import atan, atan2, pi, cos, sin, sqrt, ceil, radians, degrees
import numpy as np
import psychopy, ... | (stimuli):
dotOrder = np.arange(len(stimuli))
np.random.shuffle(dotOrder)
print(dotOrder)
shuffledStimuli = [stimuli[i] for i in dotOrder]
ts = []
myWin.flip(); myWin.flip() #Make sure raster at top of screen (unless not in blocking mode), and give CPU a chance to finish other tasks
t0 = tri... | oneTrial | identifier_name |
StatusResize.tsx | import * as React from "react"
import styled from "styled-components"
import { withProps } from "./common"
interface IChildDimensions {
direction: string
width: number
id: string
priority: number
hide: boolean
}
type PassWidth = (data: IChildDimensions) => void
interface Props {
children?: R... |
components.statusItems[item.id] = {
...this.state.children[item.id],
hide,
}
return components
},
{ widths: 0, statusItems: {} },
)
this.setState({ children: statusItems })
}
}
export de... | {
hide = true
} | conditional_block |
StatusResize.tsx | import * as React from "react"
import styled from "styled-components"
import { withProps } from "./common"
interface IChildDimensions {
direction: string
width: number
id: string
priority: number
hide: boolean
}
type PassWidth = (data: IChildDimensions) => void
interface Props {
children?: R... |
public render() {
const { containerWidth } = this.state
const { children, direction } = this.props
const count = React.Children.count(children)
return (
<StatusbarSection
direction={direction}
count={count < 1}
innerRef={(... | {
this.observer.disconnect()
} | identifier_body |
StatusResize.tsx | import * as React from "react"
import styled from "styled-components"
import { withProps } from "./common"
interface IChildDimensions {
direction: string
width: number
id: string
priority: number
hide: boolean
}
type PassWidth = (data: IChildDimensions) => void
interface Props {
children?: R... | class StatusBarResizer extends React.Component<Props, State> {
private observer: any
private elem: Element
constructor(props: Props) {
super(props)
this.state = {
containerWidth: null,
children: {},
}
}
public componentDidMount() {
this.setSta... | max-width: 48%;
justify-content: ${props => props.direction};
`
| random_line_split |
StatusResize.tsx | import * as React from "react"
import styled from "styled-components"
import { withProps } from "./common"
interface IChildDimensions {
direction: string
width: number
id: string
priority: number
hide: boolean
}
type PassWidth = (data: IChildDimensions) => void
interface Props {
children?: R... | (props: Props) {
super(props)
this.state = {
containerWidth: null,
children: {},
}
}
public componentDidMount() {
this.setState({
containerWidth: this.elem.getBoundingClientRect().width,
})
// tslint:disable-next-line
t... | constructor | identifier_name |
bollingTrader.py | from utils.rwlogging import log
from utils.rwlogging import strategyLogger as logs
from trader import Trader
from indicator import ma, macd, bolling, rsi, kdj
from strategy.pool import StrategyPool
highest = 0
def runStrategy(prices):
logs.info('STRATEGY,BUY TIMES, SELL TIMES, FINAL EQUITY')
#prices = SqliteDB().... | # -*- coding: utf-8 -*-
import datetime, time, csv, os
from utils.db import SqliteDB | random_line_split | |
bollingTrader.py | # -*- coding: utf-8 -*-
import datetime, time, csv, os
from utils.db import SqliteDB
from utils.rwlogging import log
from utils.rwlogging import strategyLogger as logs
from trader import Trader
from indicator import ma, macd, bolling, rsi, kdj
from strategy.pool import StrategyPool
highest = 0
def runStrategy(prices)... |
pool.estimate(t)
| if ps[i-1] > bollings['lower'][i-1] and ps[i] < bollings['lower'][i] and t.bsflag < 1:
notes = 'LAST p: ' + str(ps[i - 1]) + ';boll lower: ' + str(bollings['lower'][i-1]) + 'CURRENT p: ' + str(ps[i]) + ';boll lower: ' + str(bollings['lower'][i])
t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes)... | conditional_block |
bollingTrader.py | # -*- coding: utf-8 -*-
import datetime, time, csv, os
from utils.db import SqliteDB
from utils.rwlogging import log
from utils.rwlogging import strategyLogger as logs
from trader import Trader
from indicator import ma, macd, bolling, rsi, kdj
from strategy.pool import StrategyPool
highest = 0
def runStrategy(prices)... |
def doBollingTrade(pool, prices, ps, period, deviate):
global highest
sname = 'BOLLING_' + str(period) + '_' + str(deviate)
bollings = bolling.calc_bolling(prices, period, deviate)
t = Trader(sname)
for i in range(period, len(prices)):
if ps[i-1] > bollings['lower'][i-1] and ps[i] < bollings['lower'][i] a... | logs.info('STRATEGY,BUY TIMES, SELL TIMES, FINAL EQUITY')
#prices = SqliteDB().getAllPrices(table)
ps = [p['close'] for p in prices]
pool = StrategyPool(100)
#doBollingTrade(pool, prices, ps, 12, 2.4)
#pool.showStrategies()
#return
for i in range(2, 40):
j = 0
log.debug(i)
while j <= 5:
doBollingT... | identifier_body |
bollingTrader.py | # -*- coding: utf-8 -*-
import datetime, time, csv, os
from utils.db import SqliteDB
from utils.rwlogging import log
from utils.rwlogging import strategyLogger as logs
from trader import Trader
from indicator import ma, macd, bolling, rsi, kdj
from strategy.pool import StrategyPool
highest = 0
def | (prices):
logs.info('STRATEGY,BUY TIMES, SELL TIMES, FINAL EQUITY')
#prices = SqliteDB().getAllPrices(table)
ps = [p['close'] for p in prices]
pool = StrategyPool(100)
#doBollingTrade(pool, prices, ps, 12, 2.4)
#pool.showStrategies()
#return
for i in range(2, 40):
j = 0
log.debug(i)
while j <= 5:
... | runStrategy | identifier_name |
yash_bls.py | from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import clean_and_search
from ktransit import FitTransit
from multiprocessing import Pool
from scipy import ndimage
import glob, timeit, sys
import time as pythonTime
# OPTI... |
return flux - medians
def getPhase(time, flux, period, epoch, centerPhase = 0):
"""Get the phase of a lightcurve.
How it works using an example where epoch = 2, period = 3:
1. Subtract the epoch from all times [1, 2, 3, 4, 5, 6, 7] to get
[-1, 0, 1, 2, 3, 4, 5] then divide by the period [3] to get all t... | medians.append(np.median(flux[i-halfNumPoints : i+halfNumPoints+1])) | conditional_block |
yash_bls.py | from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import clean_and_search
from ktransit import FitTransit
from multiprocessing import Pool
from scipy import ndimage
import glob, timeit, sys
import time as pythonTime
# OPTI... | (time, flux, period, epoch, duration):
halfDur = 0.5 * duration / 24.
bad = np.where(time < epoch - period + halfDur)[0]
for p in np.arange(epoch, time[-1] + period, period):
bad = np.append(bad, np.where((p - halfDur < time) & (time < p + halfDur))[0])
good = np.setxor1d(range(len(time)), bad)
return time... | removeTransits | identifier_name |
yash_bls.py | from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import clean_and_search
from ktransit import FitTransit
from multiprocessing import Pool
from scipy import ndimage
import glob, timeit, sys
import time as pythonTime
# OPTI... | arr = array.astype(np.float32)
arr = arr - threshold + 1e-12
arrPlus = np.roll(arr, 1)
#Location of changes from -ve to +ve (or vice versa)
#Last point is bogus , so we calculate it by hand
sgnChange = arr*arrPlus
#Roll around can't compute sign change for zeroth elt.
sgnChange[0] = +1
if arr[0] > 0:
... | np.max(out[:,1] - out[:,0])
The algorithm fails if a value is exactly equal to the threshold.
To guard against this, we add a very small amount to threshold
to ensure floating point arithmetic prevents two numbers being
exactly equal."""
| random_line_split |
yash_bls.py | from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import clean_and_search
from ktransit import FitTransit
from multiprocessing import Pool
from scipy import ndimage
import glob, timeit, sys
import time as pythonTime
# OPTI... |
def computeTransitDuration(period, rho, k):
b = 0.1 # Impact parameter (default value in ktransit)
G = 6.67384e-11 # Gravitational constant
P = period * 86400 # Period in seconds
stellarDensity = rho * 1000
rStarOverA = ((4 * np.pi**2) / (G * stellarDensity * P**2))**(1./3.)
cosI = b * rSta... | halfDur = 0.5 * duration / 24.
bad = np.where(time < epoch - period + halfDur)[0]
for p in np.arange(epoch, time[-1] + period, period):
bad = np.append(bad, np.where((p - halfDur < time) & (time < p + halfDur))[0])
good = np.setxor1d(range(len(time)), bad)
return time[good], flux[good] | identifier_body |
index.js | import Zip from 'adm-zip';
/**
* @param {Type}
* @return {Type}
*/
export default function (filePath) {
let courseZip = new Zip(filePath);
let courseFileScanner = {
getZipObject: () => {
return courseZip;
},
getCourseFiles: () => {
return courseZip.getEntries().filter(courseFileScanner... | let fileName = file.entryName;
let startIndex = fileName.lastIndexOf('xid-') + 4;
let endIndex = fileName.indexOf('_', startIndex);
file.courseFileId = fileName.substring(startIndex, endIndex);
return file;
},
getDatFiles: () => {
return courseZip.getEntries().filter(course... | },
_getCourseFileId: (file) => { | random_line_split |
MegareleaseOrg.py | # -*- coding: utf-8 -*-
############################################################################
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as #
# published by the Free Software Foundation, either version 3 of ... |
getInfo = create_getInfo(MegareleaseOrg)
| __name__ = "MegareleaseOrg"
__type__ = "hoster"
__pattern__ = r'https?://(?:www\.)?megarelease.org/\w{12}'
__version__ = "0.01"
__description__ = """Megarelease.org hoster plugin"""
__author_name__ = ("derek3x", "stickell")
__author_mail__ = ("derek3x@vmail.me", "l.stickell@yahoo.it")
HOSTE... | identifier_body |
MegareleaseOrg.py | # -*- coding: utf-8 -*-
############################################################################
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as #
# published by the Free Software Foundation, either version 3 of ... | (XFileSharingPro):
__name__ = "MegareleaseOrg"
__type__ = "hoster"
__pattern__ = r'https?://(?:www\.)?megarelease.org/\w{12}'
__version__ = "0.01"
__description__ = """Megarelease.org hoster plugin"""
__author_name__ = ("derek3x", "stickell")
__author_mail__ = ("derek3x@vmail.me", "l.stickel... | MegareleaseOrg | identifier_name |
MegareleaseOrg.py | # -*- coding: utf-8 -*-
############################################################################
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as #
# published by the Free Software Foundation, either version 3 of ... | ############################################################################
from module.plugins.hoster.XFileSharingPro import XFileSharingPro, create_getInfo
class MegareleaseOrg(XFileSharingPro):
__name__ = "MegareleaseOrg"
__type__ = "hoster"
__pattern__ = r'https?://(?:www\.)?megarelease.org/\w{12}'
... | # along with this program. If not, see <http://www.gnu.org/licenses/>. # | random_line_split |
comments.component.ts | import {Component, Input} from '@angular/core';
import {MatSnackBar} from '@angular/material';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/finally';
import {GraphApiError} from '../graph-api-error';
import {GraphApiErrorComponent} from '../graph-api-error.component';
import {Comment} from '.... |
/*
* All Comments shown by this Component.
*/
_comments: Comment[];
/*
* Whether more comments can currently be loaded.
*/
_loaded = false;
/*
* Whether to override the loading indicator.
*
* If the containing Component knows for a fact, that the data to be sho... | {} | identifier_body |
comments.component.ts | import {Component, Input} from '@angular/core';
import {MatSnackBar} from '@angular/material';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/finally';
import {GraphApiError} from '../graph-api-error';
import {GraphApiErrorComponent} from '../graph-api-error.component';
import {Comment} from '.... | this._loaded = this.loaded;
comments
.finally(() => this._loaded = true)
.subscribe(
comment => this._comments.push(comment),
err => GraphApiErrorComponent.show(this.matSnackBar, err));
}
}
} | set comments(comments: Observable<Comment>|undefined) {
if (comments) {
this._comments = []; | random_line_split |
comments.component.ts | import {Component, Input} from '@angular/core';
import {MatSnackBar} from '@angular/material';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/finally';
import {GraphApiError} from '../graph-api-error';
import {GraphApiErrorComponent} from '../graph-api-error.component';
import {Comment} from '.... |
}
}
| {
this._comments = [];
this._loaded = this.loaded;
comments
.finally(() => this._loaded = true)
.subscribe(
comment => this._comments.push(comment),
err => GraphApiErrorComponent.show(this.matSnackBar, err));
... | conditional_block |
comments.component.ts | import {Component, Input} from '@angular/core';
import {MatSnackBar} from '@angular/material';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/finally';
import {GraphApiError} from '../graph-api-error';
import {GraphApiErrorComponent} from '../graph-api-error.component';
import {Comment} from '.... | (protected matSnackBar: MatSnackBar) {}
/*
* All Comments shown by this Component.
*/
_comments: Comment[];
/*
* Whether more comments can currently be loaded.
*/
_loaded = false;
/*
* Whether to override the loading indicator.
*
* If the containing Component kn... | constructor | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.