file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
utils_libguestfs.py | """
libguestfs tools test utility functions.
"""
import logging
from autotest.client import os_dep, utils
from autotest.client.shared import error
import propcan
class LibguestfsCmdError(Exception):
"""
Error of libguestfs-tool command.
"""
def __init__(self, details=''):
self.details = det... |
# Raise exception if ignore_status == False
try:
ret = utils.run(cmd, ignore_status=ignore_status,
verbose=debug, timeout=timeout)
except error.CmdError, detail:
raise LibguestfsCmdError(detail)
if debug:
logging.debug("status: %s", ret.exit_status)
... | logging.debug("Running command %s in debug mode.", cmd) | conditional_block |
keyboard-select-picker.js | import Ember from 'ember';
import SelectPicker from './select-picker';
import ItemCursorMixin from 'ember-cli-select-picker/mixins/item-cursor';
const KEY_ENTER = 13;
const KEY_ESC = 27;
const KEY_UP = 38;
const KEY_DOWN = 40;
export default SelectPicker.extend(ItemCursorMixin, {
layoutName: 'components/selec... |
return true;
}
});
| {
e.preventDefault();
Ember.run(() => { this.send(actionName); });
this.focusActiveItem();
return false;
} | conditional_block |
keyboard-select-picker.js | import Ember from 'ember';
import SelectPicker from './select-picker';
import ItemCursorMixin from 'ember-cli-select-picker/mixins/item-cursor';
const KEY_ENTER = 13;
const KEY_ESC = 27;
const KEY_UP = 38;
const KEY_DOWN = 40;
export default SelectPicker.extend(ItemCursorMixin, {
layoutName: 'components/selec... | (e) {
var actionName = (() => {
switch (e.which) {
case KEY_DOWN: return 'activeNext';
case KEY_UP: return 'activePrev';
case KEY_ESC: return 'closeDropdown';
case KEY_ENTER:
return this.get('showDropdown') ?
'selectActiveItem' :
'openDropdo... | handleKeyPress | identifier_name |
keyboard-select-picker.js | import Ember from 'ember';
import SelectPicker from './select-picker';
import ItemCursorMixin from 'ember-cli-select-picker/mixins/item-cursor';
const KEY_ENTER = 13;
const KEY_ESC = 27;
const KEY_UP = 38;
const KEY_DOWN = 40;
export default SelectPicker.extend(ItemCursorMixin, {
layoutName: 'components/selec... | ,
handleKeyPress(e) {
var actionName = (() => {
switch (e.which) {
case KEY_DOWN: return 'activeNext';
case KEY_UP: return 'activePrev';
case KEY_ESC: return 'closeDropdown';
case KEY_ENTER:
return this.get('showDropdown') ?
'selectActiveItem' :
... | {
this.$(`[data-itemid=${this.get('activeItem.itemId')}]`).focus();
} | identifier_body |
keyboard-select-picker.js | import Ember from 'ember';
import SelectPicker from './select-picker';
import ItemCursorMixin from 'ember-cli-select-picker/mixins/item-cursor';
const KEY_ENTER = 13;
const KEY_ESC = 27;
const KEY_UP = 38;
const KEY_DOWN = 40;
export default SelectPicker.extend(ItemCursorMixin, {
layoutName: 'components/selec... | switch (e.which) {
case KEY_DOWN: return 'activeNext';
case KEY_UP: return 'activePrev';
case KEY_ESC: return 'closeDropdown';
case KEY_ENTER:
return this.get('showDropdown') ?
'selectActiveItem' :
'openDropdown';
default: return null;
... |
handleKeyPress(e) {
var actionName = (() => { | random_line_split |
resolv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2013, IOhannes m zmölnig, IEM
# This file is part of WILMix
#
# 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 of th... | ostname, preferIPv6=None):
# IPv6=true: prefer IPv6 addresses (if there are none, the function might still return IPv4)
# IPv6=false: prefer IPv4 addresses (if there are none, the function might still return IPv6)
# IPv6=None: first available address returned
info=QHostInfo()
adr=info.fromName(hostname).address... | tAddress(h | identifier_name |
resolv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2013, IOhannes m zmölnig, IEM
# This file is part of WILMix | # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANT... | #
# This program is free software; you can redistribute it and/or modify | random_line_split |
resolv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2013, IOhannes m zmölnig, IEM
# This file is part of WILMix
#
# 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 of th... | import sys
progname=sys.argv[0]
ipv6=None
args=[]
if len(sys.argv)>1:
s=sys.argv[1]
if s.startswith('-'):
args=sys.argv[2:]
if "-ipv4" == s:
ipv6=False
elif "-ipv6" == s:
ipv6=True
else:
p... | dr=getAddress(name, ipv6)
print("%s -> %s" % (name, addr))
| identifier_body |
resolv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2013, IOhannes m zmölnig, IEM
# This file is part of WILMix
#
# 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 of th... | else:
args=sys.argv[1:]
if not args:
args=['localhost', 'umlautq', 'example.com']
for h in args:
testfun(h,ipv6)
| int("Usage: resolv.py [-ipv4|-ipv6] <host1> [<host2> ...]")
sys.exit(1)
| conditional_block |
mv.rs | use board::chess::board::*;
use pgn_traits::pgn::PgnBoard;
use board_game_traits::board::Board;
|
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct ChessReverseMove {
pub from : Square,
pub to : Square,
pub capture : PieceType,
pub prom : bool,
pub old_castling_en_passant : u8,
pub old_half_move_clock : u8,
pub old_past_move_hashes: Option<Vec<u64>>,
}
impl ChessReverseMove {
/// R... | use std::fmt; | random_line_split |
mv.rs | use board::chess::board::*;
use pgn_traits::pgn::PgnBoard;
use board_game_traits::board::Board;
use std::fmt;
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct ChessReverseMove {
pub from : Square,
pub to : Square,
pub capture : PieceType,
pub prom : bool,
pub old_castling_en_passant : u8,
pub... | (&self, fmt : &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt.write_str(&format!("{}", ChessBoard::start_board().move_to_lan(self))).unwrap();
Ok(())
}
}
impl fmt::Debug for ChessMove {
fn fmt(&self, fmt : &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Display::fmt(self, fmt... | fmt | identifier_name |
models.py | from django.db import models
class Group(models.Model):
BASE_URL = "https://www.facebook.com/groups/%s"
def | (self):
return self.name
id = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length = 100)
school = models.CharField(max_length = 100)
class User(models.Model):
def __unicode__(self):
return self.name
id = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length = ... | __unicode__ | identifier_name |
models.py | from django.db import models
class Group(models.Model):
BASE_URL = "https://www.facebook.com/groups/%s"
def __unicode__(self):
return self.name
id = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length = 100)
school = models.CharField(max_length = 100)
class User(models.Model):
def ... |
id = models.BigIntegerField(primary_key=True)
created_time = models.DateTimeField(null=False)
updated_time = models.DateTimeField(null=False)
type = models.CharField(max_length = 6)
message = models.TextField(null=False, blank=True, default="")
picture = models.TextField(null=False, blank=True, default="")
pa... | return self.message or u'No Text' | identifier_body |
models.py | from django.db import models
class Group(models.Model):
BASE_URL = "https://www.facebook.com/groups/%s"
def __unicode__(self):
return self.name
id = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length = 100)
school = models.CharField(max_length = 100)
class User(models.Model):
def ... | created_time = models.DateTimeField(null=False)
updated_time = models.DateTimeField(null=False)
type = models.CharField(max_length = 6)
message = models.TextField(null=False, blank=True, default="")
picture = models.TextField(null=False, blank=True, default="")
parsed = models.BooleanField(default=False)
user =... |
id = models.BigIntegerField(primary_key=True) | random_line_split |
default_bool.js | var test = require( 'tape' );
var parse = require( '../' );
test( 'boolean default true', function( t ) {
var argv = parse( [], {
boolean: 'sometrue',
default: { sometrue: true }
} );
t.equal( argv.sometrue, true );
t.end();
} ); |
test( 'boolean default false', function( t ) {
var argv = parse( [], {
boolean: 'somefalse',
default: { somefalse: false }
} );
t.equal( argv.somefalse, false );
t.end();
} );
test( 'boolean default to null', function( t ) {
var argv = parse( [], {
boolean: 'maybe',
default: { maybe: null }
} );
t.equa... | random_line_split | |
SpaceToDepthOptions.py | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | self._tab = flatbuffers.table.Table(buf, pos)
# SpaceToDepthOptions
def BlockSize(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
return 0
def Spac... | # SpaceToDepthOptions
def Init(self, buf, pos): | random_line_split |
SpaceToDepthOptions.py | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
return 0
def SpaceToDepthOptionsStart(builder): builder.StartObject(1)
def SpaceToDepthOptionsAddBlockSize(builder, blockSize): builder.PrependInt32Slot(0, blockSize, 0)
def SpaceToDepthOptionsEnd(builder): return builder.EndObject()
class SpaceToDepthOptionsT(object):
# SpaceToDepthOptionsT
def __... | return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) | conditional_block |
SpaceToDepthOptions.py | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (builder): builder.StartObject(1)
def SpaceToDepthOptionsAddBlockSize(builder, blockSize): builder.PrependInt32Slot(0, blockSize, 0)
def SpaceToDepthOptionsEnd(builder): return builder.EndObject()
class SpaceToDepthOptionsT(object):
# SpaceToDepthOptionsT
def __init__(self):
self.blockSize = 0 # typ... | SpaceToDepthOptionsStart | identifier_name |
SpaceToDepthOptions.py | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# SpaceToDepthOptionsT
def _UnPack(self, spaceToDepthOptions):
if spaceToDepthOptions is None:
return
self.blockSize = spaceToDepthOptions.BlockSize()
# SpaceToDepthOptionsT
def Pack(self, builder):
SpaceToDepthOptionsStart(builder)
SpaceToDepthOptionsAddBl... | x = SpaceToDepthOptionsT()
x._UnPack(spaceToDepthOptions)
return x | identifier_body |
tests.rs | use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::http::{ContentType, Status};
use super::rocket;
fn test_login(username: &str, password: &str, age: isize, status: Status,
body: Option<&'static str>) {
let rocket = rocket();
let mut req = MockRequest::new(Post, "/login")... |
#[test]
fn test_bad_form() {
check_bad_form("&", Status::BadRequest);
check_bad_form("=", Status::BadRequest);
check_bad_form("&&&===&", Status::BadRequest);
check_bad_form("username=Sergio", Status::UnprocessableEntity);
check_bad_form("username=Sergio&", Status::UnprocessableEntity);
check_... | {
let rocket = rocket();
let mut req = MockRequest::new(Post, "/login")
.header(ContentType::Form)
.body(form_str);
let response = req.dispatch_with(&rocket);
assert_eq!(response.status(), status);
} | identifier_body |
tests.rs | use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::http::{ContentType, Status};
use super::rocket;
fn test_login(username: &str, password: &str, age: isize, status: Status,
body: Option<&'static str>) {
let rocket = rocket();
let mut req = MockRequest::new(Post, "/login")... | () {
test_login("Sergio", "password", 30, Status::SeeOther, None);
}
const OK: Status = self::Status::Ok;
#[test]
fn test_bad_login() {
test_login("Sergio", "password", 20, OK, Some("Sorry, 20 is too young!"));
test_login("Sergio", "password", 200, OK, Some("Are you sure you're 200?"));
test_login("Se... | test_good_login | identifier_name |
tests.rs | use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::http::{ContentType, Status};
use super::rocket;
fn test_login(username: &str, password: &str, age: isize, status: Status,
body: Option<&'static str>) {
let rocket = rocket();
let mut req = MockRequest::new(Post, "/login")... |
}
#[test]
fn test_good_login() {
test_login("Sergio", "password", 30, Status::SeeOther, None);
}
const OK: Status = self::Status::Ok;
#[test]
fn test_bad_login() {
test_login("Sergio", "password", 20, OK, Some("Sorry, 20 is too young!"));
test_login("Sergio", "password", 200, OK, Some("Are you sure you'... | {
assert!(body_str.map_or(true, |s| s.contains(string)));
} | conditional_block |
tests.rs | use rocket::testing::MockRequest;
use rocket::http::Method::*;
use rocket::http::{ContentType, Status};
use super::rocket;
fn test_login(username: &str, password: &str, age: isize, status: Status,
body: Option<&'static str>) {
let rocket = rocket();
let mut req = MockRequest::new(Post, "/login")... | #[test]
fn test_bad_login() {
test_login("Sergio", "password", 20, OK, Some("Sorry, 20 is too young!"));
test_login("Sergio", "password", 200, OK, Some("Are you sure you're 200?"));
test_login("Sergio", "jk", -100, OK, Some("'-100' is not a valid integer."));
test_login("Sergio", "ok", 30, OK, Some("Wro... | }
const OK: Status = self::Status::Ok;
| random_line_split |
post-vehicle.ts | import { Component, NgZone } from '@angular/core';
import { UserService } from '../../providers/user-service';
import { NavController, NavParams, ViewController, AlertController, LoadingController } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import firebase from 'firebase';
@Compo... | title: tittle,
subTitle: message,
buttons: ['OK']
});
alert.present();
}
clearView() {
this.brandField = undefined;
this.modelField = undefined;
this.yearField = undefined;
this.odomTypeField = undefined;
this.odomField = undefined;
this.typeField = undefined;
... | showAlert(tittle: string, message:string) {
let alert = this.alertCtrl.create({ | random_line_split |
post-vehicle.ts | import { Component, NgZone } from '@angular/core';
import { UserService } from '../../providers/user-service';
import { NavController, NavParams, ViewController, AlertController, LoadingController } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import firebase from 'firebase';
@Compo... | mageId) {
this.firestore.ref().child(imageId).getDownloadURL().then((url) => {
this.zone.run(() => {
this.image = url;
})
})
}
getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
}
| splay(i | identifier_name |
post-vehicle.ts | import { Component, NgZone } from '@angular/core';
import { UserService } from '../../providers/user-service';
import { NavController, NavParams, ViewController, AlertController, LoadingController } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import firebase from 'firebase';
@Compo... | console.log("...");
}
}
publish() {
// First validate any important field.
this.removeWhitespaces();
// Important fields:
// Brand, Model, Year, Price, Desc and Phone.
if (this.brandField == undefined || this.modelField == undefined ||
this.yearField == undefined || this.priceFie... | {
try {
this.brandField = this.brandField.replace(" ", "");
this.modelField = this.modelField.replace(" ", "");
this.yearField = this.yearField.replace(" ", "");
this.odomTypeField = this.odomTypeField.replace(" ", "");
this.odomField = this.odomField.replace(" ", "");
this.typeF... | identifier_body |
post-vehicle.ts | import { Component, NgZone } from '@angular/core';
import { UserService } from '../../providers/user-service';
import { NavController, NavParams, ViewController, AlertController, LoadingController } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import firebase from 'firebase';
@Compo... | if (this.originField == undefined) {
this.originField = "";
};
// Some minor validations for estandarization.
if (this.currencyField == "USD") {
this.priceField *= 7.33;
this.priceField = Math.round(this.priceField * 100) / 100;
};
if (this.currencyField == "... | this.intTypeField = "";
};
| conditional_block |
combat.js | const npcWins = document.querySelector('#NPCWins');
const playerWins = document.querySelector('#PlayerWins');
// Add a badge to the winning side
function addWinningBadge(winSide){
const badge = createElementWithClass('span', 'oi')
badge.setAttribute('data-glyph', 'star');
winSide.appendChild(badge)
}
// The comb... |
// Cleanup equipment card
function cleanUpEquip() {
removeAllChild(player.equip);
removeAllChild(npc.equip);
}
// Return the score of a playing side
function getStatus(playingSide) {
const score = Object.assign({}, CONSTANT.ELEMENT_SCORE)
let maxScore = -1;
let maxElement = null;
Array.from(playingSide.equip... | {
const pointEl = playingSide.point[element];
let currentPoint = parseInt(pointEl.innerHTML);
const originalColor = pointEl.style.color;
pointEl.style.color = 'red';
const targetPoint = currentPoint - point;
while (currentPoint > targetPoint) {
pointEl.innerHTML = --currentPoint;
await wait(100);
}
po... | identifier_body |
combat.js | const npcWins = document.querySelector('#NPCWins');
const playerWins = document.querySelector('#PlayerWins');
// Add a badge to the winning side
function addWinningBadge(winSide){
const badge = createElementWithClass('span', 'oi')
badge.setAttribute('data-glyph', 'star');
winSide.appendChild(badge)
}
// The comb... |
else if (playerFinalScore > npcFinalScore) {
checkAndIncrement(STOREKEY.PLAYER_ROUND);
nextTurn = CONSTANT.TURN.PLAYER;
addWinningBadge(playerWins);
await dialog(`
${scoreReportString}
You won the round!
`)
}
else {
checkAndIncrement(STOREKEY.NPC_ROUND);
nextTurn = CONSTANT.TURN.NPC;
addWin... | {
nextTurn = CONSTANT.TURN.PLAYER;
await dialog(`
${scoreReportString}
It was a draw!
`)
} | conditional_block |
combat.js | const npcWins = document.querySelector('#NPCWins');
const playerWins = document.querySelector('#PlayerWins');
// Add a badge to the winning side
function addWinningBadge(winSide){
const badge = createElementWithClass('span', 'oi')
badge.setAttribute('data-glyph', 'star');
winSide.appendChild(badge)
}
// The comb... | checkAndIncrement(STOREKEY.NPC_ROUND);
nextTurn = CONSTANT.TURN.NPC;
addWinningBadge(npcWins);
await dialog(`
${scoreReportString}
I got this round!
`)
}
cleanUpEquip();
npcHideEquipment();
npcHideStats();
newRound(nextTurn);
}
// go through all score card and return the total point
function g... | ${scoreReportString}
You won the round!
`)
}
else { | random_line_split |
combat.js | const npcWins = document.querySelector('#NPCWins');
const playerWins = document.querySelector('#PlayerWins');
// Add a badge to the winning side
function addWinningBadge(winSide){
const badge = createElementWithClass('span', 'oi')
badge.setAttribute('data-glyph', 'star');
winSide.appendChild(badge)
}
// The comb... | () {
removeAllChild(player.equip);
removeAllChild(npc.equip);
}
// Return the score of a playing side
function getStatus(playingSide) {
const score = Object.assign({}, CONSTANT.ELEMENT_SCORE)
let maxScore = -1;
let maxElement = null;
Array.from(playingSide.equip.children).map(child => {
const {element, point... | cleanUpEquip | identifier_name |
build.rs | #![warn(rust_2018_idioms)]
use std::env;
include!("no_atomic.rs");
// The rustc-cfg listed below are considered public API, but it is *unstable*
// and outside of the normal semver guarantees:
//
// - `crossbeam_no_atomic_cas`
// Assume the target does *not* support atomic CAS operations.
// This is usuall... |
println!("cargo:rerun-if-changed=no_atomic.rs");
}
| {
let target = match env::var("TARGET") {
Ok(target) => target,
Err(e) => {
println!(
"cargo:warning={}: unable to get TARGET environment variable: {}",
env!("CARGO_PKG_NAME"),
e
);
return;
}
};
// N... | identifier_body |
build.rs | #![warn(rust_2018_idioms)]
use std::env;
include!("no_atomic.rs");
// The rustc-cfg listed below are considered public API, but it is *unstable*
// and outside of the normal semver guarantees:
//
// - `crossbeam_no_atomic_cas`
// Assume the target does *not* support atomic CAS operations.
// This is usuall... | () {
let target = match env::var("TARGET") {
Ok(target) => target,
Err(e) => {
println!(
"cargo:warning={}: unable to get TARGET environment variable: {}",
env!("CARGO_PKG_NAME"),
e
);
return;
}
};
/... | main | identifier_name |
build.rs | #![warn(rust_2018_idioms)]
use std::env;
include!("no_atomic.rs");
// The rustc-cfg listed below are considered public API, but it is *unstable*
// and outside of the normal semver guarantees:
//
// - `crossbeam_no_atomic_cas`
// Assume the target does *not* support atomic CAS operations.
// This is usuall... | Err(e) => {
println!(
"cargo:warning={}: unable to get TARGET environment variable: {}",
env!("CARGO_PKG_NAME"),
e
);
return;
}
};
// Note that this is `no_*`, not `has_*`. This allows treating
// `cfg(targe... | fn main() {
let target = match env::var("TARGET") {
Ok(target) => target, | random_line_split |
normalize.js | (function polyfill() {
"use strict";
// On some versions of IE 11, normalize is hosed. Detect and fix.
var frag = document.createDocumentFragment();
frag.appendChild(document.createElement("p"));
frag.appendChild(document.createTextNode(""));
frag.normalize();
if (frag.childNodes.length === 1) {
r... | if (data === "") {
this.removeChild(child);
}
else {
var prev = child.previousSibling;
if (prev && prev.nodeType === TEXT_NODE) {
child.data = prev.data + data;
this.removeChild(prev);
}
}
}
else if (child.firstC... | random_line_split | |
normalize.js | (function polyfill() {
"use strict";
// On some versions of IE 11, normalize is hosed. Detect and fix.
var frag = document.createDocumentFragment();
frag.appendChild(document.createElement("p"));
frag.appendChild(document.createTextNode(""));
frag.normalize();
if (frag.childNodes.length === 1) {
r... |
};
}());
| {
var next = child.nextSibling;
if (child.nodeType === TEXT_NODE) {
var data = child.data;
if (data === "") {
this.removeChild(child);
}
else {
var prev = child.previousSibling;
if (prev && prev.nodeType === TEXT_NODE) {
child.data = ... | conditional_block |
test_crafting.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# test_crafting.py
import os
import sys
import unittest
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." )
pth = root_folder #+ os.sep + 'worldbuild'
sys.path.append(pth)
from worldbuild.crafting import craft as mod_craft
class Test... | def test_02_dataset_recipe(self):
recipes = mod_craft.DataSet(mod_craft.Recipe, mod_craft.get_fullname('recipes.csv'))
self.assertTrue(len(recipes.object_list) > 18)
tot_time_to_build = 0
for recipe in recipes.object_list:
#print(recipe)
tot_time_to_build += i... | #print(res)
self.assertEqual(str(res),'new recipe')
| random_line_split |
test_crafting.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# test_crafting.py
import os
import sys
import unittest
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." )
pth = root_folder #+ os.sep + 'worldbuild'
sys.path.append(pth)
from worldbuild.crafting import craft as mod_craft
class Test... | (self):
recipes = mod_craft.DataSet(mod_craft.Recipe, mod_craft.get_fullname('recipes.csv'))
self.assertTrue(len(recipes.object_list) > 18)
tot_time_to_build = 0
for recipe in recipes.object_list:
#print(recipe)
tot_time_to_build += int(recipe.base_time_to_build)
... | test_02_dataset_recipe | identifier_name |
test_crafting.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# test_crafting.py
import os
import sys
import unittest
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." )
pth = root_folder #+ os.sep + 'worldbuild'
sys.path.append(pth)
from worldbuild.crafting import craft as mod_craft
class Test... |
def test_01_recipe(self):
res = mod_craft.Recipe('1', 'new recipe','20','mix')
#print(res)
self.assertEqual(str(res),'new recipe')
def test_02_dataset_recipe(self):
recipes = mod_craft.DataSet(mod_craft.Recipe, mod_craft.get_fullname('recipes.csv'))
self.assertTrue(le... | unittest.TestCase.tearDown(self) | identifier_body |
test_crafting.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# test_crafting.py
import os
import sys
import unittest
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." )
pth = root_folder #+ os.sep + 'worldbuild'
sys.path.append(pth)
from worldbuild.crafting import craft as mod_craft
class Test... |
#print('total time to build all recipes = ' + str(tot_time_to_build))
self.assertEqual(str(recipes.object_list[0]), 'Torch')
self.assertEqual(str(recipes.object_list[1]), 'Wooden Plank')
self.assertTrue(tot_time_to_build > 10)
if __name__ == '__main__':
unittest.main() | tot_time_to_build += int(recipe.base_time_to_build) | conditional_block |
FizzBuzzspec.js | });
it("knows that 3 is divisible by 3", function() {
expect(fizzBuzz.isDivisibleByThree(3)).toBe(true);
});
it("knows that 1 is not divisible by 3", function() {
expect(fizzBuzz.isDivisibleByThree(1)).toBe(false);
});
it("knows that 5 is divisible by 5", function() {
expect(fizzBuzz.isDivisibleByFive(5)... | describe("FizzBuzz", function() {
var fizzBuzz;
beforeEach(function() {
fizzBuzz = new FizzBuzz(); | random_line_split | |
lr.template.rs | #![allow(dead_code)]
#![allow(unused_mut)]
#![allow(unreachable_code)]
extern crate onig;
#[macro_use]
extern crate lazy_static;
use onig::{Regex, Syntax, RegexOptions};
use std::collections::HashMap;
/**
* Stack value.
*/
enum SV {
Undefined,
{{{SV_ENUM}}}
}
/**
* Lex rules.
*/
static LEX_RULES: {{{LE... |
let entry = &TABLE[state][&column];
match entry {
// Shift a token, go to state.
&TE::Shift(next_state) => {
// Push token.
self.values_stack.push(SV::_0(token));
// Push next state number: "s5" -> 5... | {
self.unexpected_token(&token);
break;
} | conditional_block |
lr.template.rs | #![allow(dead_code)]
#![allow(unused_mut)]
#![allow(unreachable_code)]
extern crate onig;
#[macro_use]
extern crate lazy_static;
use onig::{Regex, Syntax, RegexOptions};
use std::collections::HashMap;
/**
* Stack value.
*/
enum SV {
Undefined,
{{{SV_ENUM}}}
}
/**
* Lex rules.
*/
static LEX_RULES: {{{LE... | {
Accept,
// Shift, and transit to the state.
Shift(usize),
// Reduce by a production number.
Reduce(usize),
// Simple state transition.
Transit(usize),
}
lazy_static! {
/**
* Lexical rules grouped by lexer state (by start condition).
*/
static ref LEX_RULES_BY_START_C... | TE | identifier_name |
lr.template.rs | #![allow(dead_code)]
#![allow(unused_mut)]
#![allow(unreachable_code)]
extern crate onig;
#[macro_use]
extern crate lazy_static;
use onig::{Regex, Syntax, RegexOptions};
use std::collections::HashMap;
/**
* Stack value.
*/
enum SV {
Undefined,
{{{SV_ENUM}}}
}
/**
* Lex rules.
*/
static LEX_RULES: {{{LE... |
{{{PRODUCTION_HANDLERS}}}
}
| {
{{{ON_PARSE_ERROR_CALL}}}
} | identifier_body |
lr.template.rs | #![allow(dead_code)]
#![allow(unused_mut)]
#![allow(unreachable_code)]
extern crate onig;
#[macro_use]
extern crate lazy_static;
use onig::{Regex, Syntax, RegexOptions};
use std::collections::HashMap;
/**
* Stack value.
*/
enum SV {
Undefined,
{{{SV_ENUM}}}
}
/**
* Lex rules.
*/
static LEX_RULES: {{{LE... | while rhs_length > 0 {
self.states_stack.pop();
rhs_length = rhs_length - 1;
}
// Call the handler, push result onto the stack.
let result_value = self.handlers[production_number](self);
... |
let mut rhs_length = production[1]; | random_line_split |
registrar.rs | // Copyright 2012-2013 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-MI... | impl Visitor<()> for MacroRegistrarContext {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"macro_registrar") {
self.registrars.pu... | registrars: Vec<(ast::NodeId, Span)> ,
}
| random_line_split |
registrar.rs | // Copyright 2012-2013 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-MI... | (diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::DefId> {
let mut ctx = MacroRegistrarContext { registrars: Vec::new() };
visit::walk_crate(&mut ctx, krate, ());
match ctx.registrars.len() {
0 => None,
1 => {
let (node_id, _) ... | find_macro_registrar | identifier_name |
registrar.rs | // Copyright 2012-2013 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-MI... |
}
visit::walk_item(self, item, ());
}
}
pub fn find_macro_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::DefId> {
let mut ctx = MacroRegistrarContext { registrars: Vec::new() };
visit::walk_crate(&mut ctx, krate, ());
ma... | {} | conditional_block |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use l... | .starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_closed(&uri)
}
pub fn on_did_change_text_document(
lsp_state: &impl GlobalState,
params: <DidChangeTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidChang... | let uri = params.text_document.uri;
if !uri
.path() | random_line_split |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use l... |
#[allow(clippy::unnecessary_wraps)]
pub fn on_cancel(
_lsp_state: &impl GlobalState,
_params: <Cancel as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
| {
Ok(())
} | identifier_body |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use l... |
lsp_state.document_opened(&uri, &text)
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_did_close_text_document(
lsp_state: &impl GlobalState,
params: <DidCloseTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let uri = params.text_document.uri;
if !uri
.path()
.st... | {
return Ok(());
} | conditional_block |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use l... | (
lsp_state: &impl GlobalState,
params: <DidOpenTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidOpenTextDocumentParams { text_document } = params;
let TextDocumentItem { text, uri, .. } = text_document;
if !uri
.path()
.starts_with(lsp_state.root_dir().to_st... | on_did_open_text_document | identifier_name |
test_smoke.py | #!/usr/bin/python
import io
import os
import unittest
import logging
import uuid
from mediafire import MediaFireApi, MediaFireUploader, UploadSession
from mediafire.uploader import UPLOAD_SIMPLE_LIMIT_BYTES
APP_ID = '42511'
MEDIAFIRE_EMAIL = os.environ.get('MEDIAFIRE_EMAIL')
MEDIAFIRE_PASSWORD = os.environ.get('MEDI... | (object):
"""Smoke tests for API"""
class BaseTest(unittest.TestCase):
def setUp(self):
# Reset logging to info to avoid leaking credentials
logger = logging.getLogger('mediafire.api')
logger.setLevel(logging.INFO)
self.api = MediaFireApi()
s... | MediaFireSmokeBaseTestCase | identifier_name |
test_smoke.py | #!/usr/bin/python
import io
import os
import unittest
import logging
import uuid
from mediafire import MediaFireApi, MediaFireUploader, UploadSession
from mediafire.uploader import UPLOAD_SIMPLE_LIMIT_BYTES
APP_ID = '42511'
MEDIAFIRE_EMAIL = os.environ.get('MEDIAFIRE_EMAIL')
MEDIAFIRE_PASSWORD = os.environ.get('MEDI... | result = uploader.upload(fd, 'smallfile.txt',
folder_key=self.folder_key)
self.assertIsNotNone(result.quickkey)
self.assertEqual(result.action, 'upload/simple')
def test_upload_large(self):
"""Test large file upload"""
# make sure we... |
with UploadSession(self.api): | random_line_split |
test_smoke.py | #!/usr/bin/python
import io
import os
import unittest
import logging
import uuid
from mediafire import MediaFireApi, MediaFireUploader, UploadSession
from mediafire.uploader import UPLOAD_SIMPLE_LIMIT_BYTES
APP_ID = '42511'
MEDIAFIRE_EMAIL = os.environ.get('MEDIAFIRE_EMAIL')
MEDIAFIRE_PASSWORD = os.environ.get('MEDI... |
def test_upload_small(self):
"""Test simple upload"""
# make sure we most likely will get upload/simple
data = b'This is a tiny file content: ' + os.urandom(32)
fd = io.BytesIO(data)
uploader = MediaFireUploader(self.api)
with UploadSession(self.api):
... | self.api.folder_purge(self.folder_key) | identifier_body |
test_smoke.py | #!/usr/bin/python
import io
import os
import unittest
import logging
import uuid
from mediafire import MediaFireApi, MediaFireUploader, UploadSession
from mediafire.uploader import UPLOAD_SIMPLE_LIMIT_BYTES
APP_ID = '42511'
MEDIAFIRE_EMAIL = os.environ.get('MEDIAFIRE_EMAIL')
MEDIAFIRE_PASSWORD = os.environ.get('MEDI... | unittest.main() | conditional_block | |
utilfuncs.py | """
This file holds utility functions that have no dependencies on other console code.
Avoids import loops
"""
import webcolors
def wc(clr, factor=0.0, layercolor=(255, 255, 255)):
lc = webcolors.name_to_rgb(layercolor.lower()) if isinstance(layercolor, str) else layercolor
if isinstance(clr, str):
try:
v = we... |
def get_field(self, field_name, args, kwargs):
# Handle a key not found
try:
val = super().get_field(field_name, args, kwargs)
except (KeyError, AttributeError):
val = None, field_name
return val
def format_field(self, value, spec):
# handle an invalid format
if value is None: return self.missing... | self.missing, self.bad_fmt = missing, bad_fmt | identifier_body |
utilfuncs.py | """
This file holds utility functions that have no dependencies on other console code.
Avoids import loops
"""
import webcolors
def wc(clr, factor=0.0, layercolor=(255, 255, 255)):
lc = webcolors.name_to_rgb(layercolor.lower()) if isinstance(layercolor, str) else layercolor
if isinstance(clr, str):
try:
v = we... | (string.Formatter):
def __init__(self, missing='--', bad_fmt='--'):
self.missing, self.bad_fmt = missing, bad_fmt
def get_field(self, field_name, args, kwargs):
# Handle a key not found
try:
val = super().get_field(field_name, args, kwargs)
except (KeyError, AttributeError):
val = None, field_name
re... | PartialFormatter | identifier_name |
utilfuncs.py | """
This file holds utility functions that have no dependencies on other console code.
Avoids import loops
"""
import webcolors
def wc(clr, factor=0.0, layercolor=(255, 255, 255)):
lc = webcolors.name_to_rgb(layercolor.lower()) if isinstance(layercolor, str) else layercolor
if isinstance(clr, str):
try:
v = we... |
else:
return TreeDict(d[args[0]], args[1:])
#return TreeDict(getattr(d,args[0]),args[1:])
import string
class PartialFormatter(string.Formatter):
def __init__(self, missing='--', bad_fmt='--'):
self.missing, self.bad_fmt = missing, bad_fmt
def get_field(self, field_name, args, kwargs):
# Handle a key not ... | temp = d[args[0]]
#temp = getattr(d,args[0])
if isinstance(temp, str) and temp.isdigit():
temp = int(temp)
else:
try:
temp = float(temp)
except (ValueError, TypeError):
pass
return temp | conditional_block |
utilfuncs.py | """
This file holds utility functions that have no dependencies on other console code.
Avoids import loops
"""
import webcolors
def wc(clr, factor=0.0, layercolor=(255, 255, 255)):
lc = webcolors.name_to_rgb(layercolor.lower()) if isinstance(layercolor, str) else layercolor
if isinstance(clr, str):
try:
v = we... | except Exception as E:
print('wc: {}'.format(E))
print(v, lc, clr, layercolor)
def interval_str(sec_elapsed, shrt=False):
d = int(sec_elapsed / (60 * 60 * 24))
h = int((sec_elapsed % (60 * 60 * 24)) / 3600)
m = int((sec_elapsed % (60 * 60)) / 60)
s = int(sec_elapsed % 60)
if d != 0:
if shrt:
return "{}... | else:
v = clr
try:
return v[0] + (lc[0] - v[0]) * factor, v[1] + (lc[1] - v[1]) * factor, v[2] + (lc[2] - v[2]) * factor | random_line_split |
react-responsive-select.tsx | import * as React from 'react';
import singleline from 'singleline';
import * as actionTypes from './constants/actionTypes';
import { handleBlur, handleClick, handleKeyEvent, handleTouchMove, handleTouchStart } from './lib/eventHandlers';
import { getCustomLabelText } from './lib/getCustomLabelText';
import { multiSele... |
});
/* Allow user to listen to actions being fired */
if (onListen) {
const isOpen = [
actionTypes.SET_OPTIONS_PANEL_OPEN,
actionTypes.SET_NEXT_SELECTED_INDEX,
actionTypes.SET_NEXT_SELECTED_INDEX_ALPHA_NUMERIC,
actionTypes.SET_IS_DRAGGING,
].some((actionType: st... | {
callback(nextState);
} | conditional_block |
react-responsive-select.tsx | import * as React from 'react';
import singleline from 'singleline';
import * as actionTypes from './constants/actionTypes';
import { handleBlur, handleClick, handleKeyEvent, handleTouchMove, handleTouchStart } from './lib/eventHandlers';
import { getCustomLabelText } from './lib/getCustomLabelText';
import { multiSele... | }
}
public focusButton(): void {
const el: HTMLDivElement | null = this.selectBox && this.selectBox.querySelector('.rrs__button');
// tslint:disable-next-line no-unused-expression
el && el.focus();
}
public onHandleKeyEvent = (e: any): void => {
handleKeyEvent({
event: e,
RRSC... | {
const { onListen, name } = this.props;
const nextState = this.reducer(this.state, action);
this.setState(nextState, () => {
if (callback) {
callback(nextState);
}
});
/* Allow user to listen to actions being fired */
if (onListen) {
const isOpen = [
actionTy... | identifier_body |
react-responsive-select.tsx | import * as React from 'react';
import singleline from 'singleline';
import * as actionTypes from './constants/actionTypes';
import { handleBlur, handleClick, handleKeyEvent, handleTouchMove, handleTouchStart } from './lib/eventHandlers';
import { getCustomLabelText } from './lib/getCustomLabelText';
import { multiSele... | (): void {
const { options, noSelectionLabel, selectedValue, selectedValues, name, multiselect, disabled } = this.props;
this.updateState({
type: actionTypes.INITIALISE,
value: {
options,
noSelectionLabel,
selectedValue,
selectedValues,
name,
multisel... | componentDidMount | identifier_name |
react-responsive-select.tsx | import * as React from 'react';
import singleline from 'singleline';
import * as actionTypes from './constants/actionTypes';
import { handleBlur, handleClick, handleKeyEvent, handleTouchMove, handleTouchStart } from './lib/eventHandlers';
import { getCustomLabelText } from './lib/getCustomLabelText';
import { multiSele... | state: this.state,
});
};
public onHandleTouchMove = (_e: any): void => {
handleTouchMove({
RRSClassRef: this,
state: this.state,
});
};
public onHandleClick = (e: any): void => {
handleClick({
event: e,
RRSClassRef: this,
state: this.state,
props: thi... | random_line_split | |
Logo.test.js | import React from 'react'
import TestRenderer from 'react-test-renderer'
import Image from './Logo.js'
const sizes = {
small: { width: 18, height: 18 },
medium: { width: 24, height: 24 },
large: { width: 36, height: 36 },
extralarge: { width: 48, height: 48 }
}
describe('Logo.svg generated styled component', ... | }) | }) | random_line_split |
auth-http.service.ts | import { Injectable } from '@angular/core'
import {
Http,
RequestOptions,
RequestOptionsArgs,
Headers,
Request,
Response,
RequestMethod,
} from '@angular/http'
import { OAuth2Token } from './oauth2token'
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromPromise'
export interf... |
export function provideAuth(config = {}): any {
return {
provide: AuthHttp,
deps: [Http],
useFactory: (http: Http) => {
return new AuthHttp(new AuthConfig(config), http)
},
}
}
| {
let date = getTokenExpirationDate(token)
// not sure is that trully needed
if (date.getSeconds() === new Date().getSeconds()) {
return false
}
// Token expired?
return !(date.valueOf() > (new Date().valueOf()))
} | identifier_body |
auth-http.service.ts | import { Injectable } from '@angular/core'
import {
Http,
RequestOptions,
RequestOptionsArgs,
Headers,
Request,
Response,
RequestMethod,
} from '@angular/http'
import { OAuth2Token } from './oauth2token'
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromPromise'
export interf... | if (additionalOptions) {
options = options.merge(additionalOptions)
}
return this.request(new Request(this.mergeOptions(options)))
}
private mergeOptions(providedOpts: RequestOptionsArgs, defaultOpts?: RequestOptions) {
let newOptions = defaultOpts || new RequestOptions()
if (this.config.... | ): Observable<Response> {
let options = new RequestOptions(requestArgs) | random_line_split |
auth-http.service.ts | import { Injectable } from '@angular/core'
import {
Http,
RequestOptions,
RequestOptionsArgs,
Headers,
Request,
Response,
RequestMethod,
} from '@angular/http'
import { OAuth2Token } from './oauth2token'
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromPromise'
export interf... | (options: AuthConfig, private http: Http) {
this.config = options.getConfig()
}
public setGlobalHeaders(headers: Array<Object>, request: Request | RequestOptionsArgs) {
if (!request.headers) {
request.headers = new Headers()
}
headers.forEach((header: Object) => {
let key: string = Obje... | constructor | identifier_name |
auth-http.service.ts | import { Injectable } from '@angular/core'
import {
Http,
RequestOptions,
RequestOptionsArgs,
Headers,
Request,
Response,
RequestMethod,
} from '@angular/http'
import { OAuth2Token } from './oauth2token'
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromPromise'
export interf... |
this.noTokenScheme = config.noTokenScheme || false
this.tokenGetter = config.tokenGetter || defaultTokenGetter
this.tokenName = config.tokenName || 'token'
}
public getConfig(): IAuthConfig {
return {
globalHeaders: this.globalHeaders,
headerName: this.headerName,
headerPrefix: ... | {
this.headerPrefix = 'Bearer '
} | conditional_block |
test_filter.py | # -*- coding: utf-8 -*-
from unittest import TestCase
# from nose.tools import eq_
import numpy as np
from pysas import waveread, World
from pysas.mcep import estimate_alpha, spec2mcep_from_matrix, mcep2coef
from pysas.synthesis.mlsa import MLSAFilter
from pysas.synthesis import Synthesis
from pysas.excite import Exci... | (TestCase):
def setUp(self):
signal, samplingrate, _ = waveread("test/cmu_arctic/arctic_a0001.wav")
self.world = World(samplingrate)
self.alpha = estimate_alpha(samplingrate)
self.samplingrate = samplingrate
self.signal = signal
self.f0, self.spec_mat, _ = self.world.... | SynthesisTest | identifier_name |
test_filter.py | # -*- coding: utf-8 -*-
from unittest import TestCase
# from nose.tools import eq_
import numpy as np
from pysas import waveread, World
from pysas.mcep import estimate_alpha, spec2mcep_from_matrix, mcep2coef
from pysas.synthesis.mlsa import MLSAFilter
from pysas.synthesis import Synthesis
from pysas.excite import Exci... | def setUp(self):
signal, samplingrate, _ = waveread("test/cmu_arctic/arctic_a0001.wav")
self.world = World(samplingrate)
self.alpha = estimate_alpha(samplingrate)
self.samplingrate = samplingrate
self.signal = signal
self.f0, self.spec_mat, _ = self.world.analyze(signal)
... | identifier_body | |
test_filter.py | # -*- coding: utf-8 -*-
from unittest import TestCase
# from nose.tools import eq_
import numpy as np
from pysas import waveread, World
from pysas.mcep import estimate_alpha, spec2mcep_from_matrix, mcep2coef
from pysas.synthesis.mlsa import MLSAFilter
from pysas.synthesis import Synthesis
from pysas.excite import Exci... |
coef_mat = np.array(coef_mat)
mlsa = MLSAFilter(self.order, self.alpha, 5)
syn = Synthesis(80, mlsa)
syn.synthesis(excite, coef_mat)
| coef_mat.append(mcep2coef(mcep_mat[i], 0.41)) | conditional_block |
test_filter.py | # -*- coding: utf-8 -*-
from unittest import TestCase
# from nose.tools import eq_
import numpy as np
from pysas import waveread, World
from pysas.mcep import estimate_alpha, spec2mcep_from_matrix, mcep2coef
from pysas.synthesis.mlsa import MLSAFilter
from pysas.synthesis import Synthesis
from pysas.excite import Exci... | coef_mat.append(mcep2coef(mcep_mat[i], 0.41))
coef_mat = np.array(coef_mat)
mlsa = MLSAFilter(self.order, self.alpha, 5)
syn = Synthesis(80, mlsa)
syn.synthesis(excite, coef_mat) | random_line_split | |
utils.js | /*
* EJS Embedded JavaScript templates
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* 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/L... |
/**
* Stringified version of constants used by {@link module:utils.escapeXML}.
*
* It is used in the process of generating {@link ClientFunction}s.
*
* @readonly
* @type {String}
*/
var escapeFuncStr =
'var _ENCODE_HTML_RULES = {\n'
+ ' "&": "&"\n'
+ ' , "<": "<"\n'
+ ' , ">": ">"\n'
+ ... | {
return _ENCODE_HTML_RULES[c] || c;
} | identifier_body |
utils.js | /*
* EJS Embedded JavaScript templates
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* 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/L... |
/**
* Naive copy of a list of key names, from one object to another.
* Only copies property if it is actually defined
* Does not recurse into non-scalar properties
*
* @param {Object} to Destination object
* @param {Object} from Source object
* @param {Array} list List of properties to copy
* @return {Obj... | }
return to;
}; | random_line_split |
utils.js | /*
* EJS Embedded JavaScript templates
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* 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/L... |
}
return to;
};
/**
* Simple in-process cache implementation. Does not implement limits of any
* sort.
*
* @implements Cache
* @static
* @private
*/
exports.cache = {
_data: {},
set: function (key, val) {
this._data[key] = val;
},
get: function (key) {
return this._data[key];
},
reset: ... | {
to[p] = from[p];
} | conditional_block |
utils.js | /*
* EJS Embedded JavaScript templates
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* 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/L... | (c) {
return _ENCODE_HTML_RULES[c] || c;
}
/**
* Stringified version of constants used by {@link module:utils.escapeXML}.
*
* It is used in the process of generating {@link ClientFunction}s.
*
* @readonly
* @type {String}
*/
var escapeFuncStr =
'var _ENCODE_HTML_RULES = {\n'
+ ' "&": "&"\n'
+ ' ... | encode_char | identifier_name |
models.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
def unfreeze(self, names):
callZooFunc(self.bigdl_type, "unFreeze", self.value, names)
@staticmethod
def from_jvalue(jvalue, bigdl_type="float"):
"""
Create a Python Model base on the given java value
:param jvalue: Java object create by Py4j
:return: A Python Mode... | callZooFunc(self.bigdl_type, "freezeUpTo", self.value, names) | identifier_body |
models.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
input_shapes = model.input_shape
else:
input_shapes = self.get_output_shape()
model = model.create(remove_batch(input_shapes))
self.value.add(model.value)
return self
@staticmethod
def from_jvalue(jvalue, bigdl_type="float"):
"""
... | raise Exception("You should specify inputShape for the first layer") | conditional_block |
models.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | (self, outputs):
value = callZooFunc(self.bigdl_type, "newGraph", self.value, outputs)
return self.from_jvalue(value)
def freeze_up_to(self, names):
callZooFunc(self.bigdl_type, "freezeUpTo", self.value, names)
def unfreeze(self, names):
callZooFunc(self.bigdl_type, "unFreeze",... | new_graph | identifier_name |
models.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | self.get_output_shape()
return True
except:
return False
def add(self, model):
from zoo.pipeline.api.autograd import Lambda
if (isinstance(model, Lambda)):
if not self.is_built():
if not model.input_shape:
r... | # TODO: expose is_built from scala side
def is_built(self):
try: | random_line_split |
forms.py | from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserLogin(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegister(UserCreationForm):
email = ... | (ModelForm):
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name']
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.fields["username"].disabled = True
self.fields["email"].disabled = True
| UserProfile | identifier_name |
forms.py | from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserLogin(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegister(UserCreationForm):
email = ... | self.fields["email"].disabled = True | random_line_split | |
forms.py | from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserLogin(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegister(UserCreationForm):
|
class UserProfile(ModelForm):
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name']
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.fields["username"].disabled = True
self.fields["email"].disabl... | email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = ['username']
def save(self, commit=True):
user = super(UserRegister, self).save(commit=False)
user.email = se... | identifier_body |
forms.py | from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserLogin(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserRegister(UserCreationForm):
email = ... |
return user
class UserProfile(ModelForm):
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name']
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.fields["username"].disabled = True
self.fi... | user.save() | conditional_block |
modals_page_spec.ts | import { ModalsPo } from '../support/modals.po';
describe('Modals demo page testing suite', () => {
const modals = new ModalsPo();
beforeEach(() => modals.navigateTo());
describe('Template modal', () => {
const templateDemo = modals.exampleDemosArr.serviceTemplate;
const btnText = 'Create template mod... |
xit('when user press on ESC btn then the modal is closed', () => {
modals.clickByText(templateDemo, btnText);
modals.pressEsc();
modals.isModalEnabled(modals.modalContainer, false);
modals.isBackdropExist(false);
});
it('when user starts to click on body then release click on backd... | modals.clickOnBackdrop();
modals.isModalVisible(modals.modalContainer, true);
modals.isModalEnabled(modals.modalContainer, false);
}); | random_line_split |
vpcmpistri.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistri_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(D... | {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadc... | identifier_body | |
vpcmpistri.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistri_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(D... | () {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, bro... | vpcmpistri_4 | identifier_name |
vpcmpistri.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*; | run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 214, 114], OperandSize::Dword)
}
fn ... | use ::Reg::*;
use ::RegScale::*;
fn vpcmpistri_1() { | random_line_split |
scipy.py | ##
# Copyright 2009-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | """Custom sanity check for scipy."""
# can't use self.pylibdir here, need to determine path on the fly using currently active 'python' command;
# this is important for numpy installations for multiple Python version (via multi_deps)
custom_paths = {
'files': [],
... | """Support for installing the scipy Python package as part of a Python installation."""
def __init__(self, *args, **kwargs):
"""Set scipy-specific test command."""
super(EB_scipy, self).__init__(*args, **kwargs)
self.testinstall = True
self.testcmd = "cd .. && %(python)s -c 'import... | identifier_body |
scipy.py | ##
# Copyright 2009-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
if LooseVersion(self.version) >= LooseVersion('0.13'):
# in recent scipy versions, additional compilation is done in the install step,
# which requires unsetting $LDFLAGS
if self.toolchain.comp_family() in [toolchain.GCC, toolchain.CLANGGCC]: # @UndefinedVariable
... | self.testcmd = "cd .. && %(python)s -c 'import numpy; import scipy; scipy.test(verbose=2)'"
def configure_step(self):
"""Custom configure step for scipy: set extra installation options when needed."""
super(EB_scipy, self).configure_step() | random_line_split |
scipy.py | ##
# Copyright 2009-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | (self, *args, **kwargs):
"""Set scipy-specific test command."""
super(EB_scipy, self).__init__(*args, **kwargs)
self.testinstall = True
self.testcmd = "cd .. && %(python)s -c 'import numpy; import scipy; scipy.test(verbose=2)'"
def configure_step(self):
"""Custom configure ... | __init__ | identifier_name |
scipy.py | ##
# Copyright 2009-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
def sanity_check_step(self, *args, **kwargs):
"""Custom sanity check for scipy."""
# can't use self.pylibdir here, need to determine path on the fly using currently active 'python' command;
# this is important for numpy installations for multiple Python version (via multi_deps)
cu... | self.cfg.update('preinstallopts', "unset LDFLAGS && ") | conditional_block |
structofp13__meter__band__dscp__remark.js | var structofp13__meter__band__dscp__remark =
[
[ "burst_size", "structofp13__meter__band__dscp__remark.html#a65ae2e874c730303bbc5d780640f7fc9", null ],
[ "len", "structofp13__meter__band__dscp__remark.html#ad56aaad8bcc7a48f6f2328ff81b0d67f", null ], | [ "type", "structofp13__meter__band__dscp__remark.html#a6837249197a1667e26a848d4870ebaff", null ]
]; | [ "pad", "structofp13__meter__band__dscp__remark.html#a5e621372646568aa14544869bbbdcf46", null ],
[ "prec_level", "structofp13__meter__band__dscp__remark.html#a753ecc92ac6a4685c02baa954acee8aa", null ],
[ "rate", "structofp13__meter__band__dscp__remark.html#a1087876e1f2f5eacbb785424dad28347", null ], | random_line_split |
plugin.js | /**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'sourcedialog', {
// lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is... | }
});
| editor.ui.addButton( 'Sourcedialog', {
label: editor.lang.sourcedialog.toolbar,
command: 'sourcedialog',
toolbar: 'mode,10'
});
}
| conditional_block |
plugin.js | /**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'sourcedialog', {
// lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is... | }); | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// For simd (currently x86_64/aarch64)
#![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "wi... | // Platforms that use Freetype/Fontconfig library dependencies
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate fontconfig;
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate freetype;
extern crate gfx_traits;
// Eventually we would l... |
extern crate euclid;
extern crate fnv;
| random_line_split |
run_tests.py | #!/usr/bin/env python
import os
import re
import subprocess
import sys
import tempfile
CC = "gcc"
CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main".split... | ():
pass_ = 0
fail_compile_parse = 1
fail_compile_sem = 2
fail_compile_ice = 3
fail_c = 4
fail_run = 5
fail_output = 6
fail_other = 7
disable = 8
test_modes = [TestMode.pass_, TestMode.fail_compile_parse,
TestMode.fail_compile_sem, TestMode.fail_compile_ice,
... | TestMode | identifier_name |
run_tests.py | #!/usr/bin/env python
import os
import re
import subprocess
import sys
import tempfile
CC = "gcc"
CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main".split... |
def pick(v, m):
if v not in m:
raise Exception("Unknown value '%s'" % v)
return m[v]
def run_test(filename):
testname = os.path.basename(filename)
print("Test '%s'..." % testname)
workdir = tempfile.mkdtemp(prefix="boringtest")
tempfiles = []
src = open(filename)
headers = Tabl... | test_mode_values = {}
for m, (s, _) in test_mode_names.iteritems():
test_mode_values[s] = m | random_line_split |
run_tests.py | #!/usr/bin/env python
import os
import re
import subprocess
import sys
import tempfile
CC = "gcc"
CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main".split... |
def run_test(filename):
testname = os.path.basename(filename)
print("Test '%s'..." % testname)
workdir = tempfile.mkdtemp(prefix="boringtest")
tempfiles = []
src = open(filename)
headers = Table()
headers.mode = TestMode.pass_
headers.is_expr = False
headers.stdout = None
while... | if v not in m:
raise Exception("Unknown value '%s'" % v)
return m[v] | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.