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 |
|---|---|---|---|---|
0_setiplist.py | import os
serverA = open('serverlistA.list', 'r')
serverB = open('serverlistB.list', 'r')
numA = int(serverA.readline())
numB = int(serverB.readline())
iplistA = open('iplistA', 'w')
iplistB = open('iplistB', 'w')
sshconfig = open('/Users/iqua/.ssh/config', 'w')
csshconfig = open('/etc/clusters', 'w')
csshconfig.wr... |
for j in range(1, numB+1):
os.system("echo '" + str(i+j) + "' > iplist && cat iplistA >> iplist")
cmd = "scp ./iplist " + serverB[j] + ":~/repnet/exp_code/iplist"
os.system(cmd)
print "Done copying iplist to", serverB[j]
os.system("rm iplist*")
| os.system("echo '" + str(i) + "' > iplist && cat iplistB >> iplist")
os.system("scp ./iplist " + serverA[i] + ":~/repnet/exp_code/iplist")
print "Done copying iplist to", serverA[i] | conditional_block |
report.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { GlobalService } from '../service/global.service';
@Injectable()
export class ReportService {
constructor (private http: HttpClient, private global: GlobalService) {... | (): Observable<any> {
return this.http.get(this.global.url + `/report`).map((res: any) => {
if ( res.status === 'success' ) {
return res.result;
} else {
alert('[ERROR]: ' + res.result);
}
})
}
public getReportById (id: number... | getReportList | identifier_name |
report.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { GlobalService } from '../service/global.service';
@Injectable()
export class ReportService {
constructor (private http: HttpClient, private global: GlobalService) |
public postReport (data: FormData): Observable<any> {
return this.http.post(this.global.url + `/report`, data).map((res: any) => {
if ( res.status === 'success' ) {
return res.result;
} else {
alert('[ERROR]: ' + res.result);
}
})... | {
} | identifier_body |
report.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { GlobalService } from '../service/global.service';
@Injectable()
export class ReportService {
constructor (private http: HttpClient, private global: GlobalService) {... | }
} | random_line_split | |
report.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { GlobalService } from '../service/global.service';
@Injectable()
export class ReportService {
constructor (private http: HttpClient, private global: GlobalService) {... | else {
alert('[ERROR]: ' + res.result);
}
});
}
public getReportList (): Observable<any> {
return this.http.get(this.global.url + `/report`).map((res: any) => {
if ( res.status === 'success' ) {
return res.result;
} else {
... | {
return res.result;
} | conditional_block |
gotoolchain.py | #
# SPDX-License-Identifier: MIT
#
import glob
import os
import shutil
import tempfile
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_vars
class oeGoToolchainSelfTest(OESelftestTestCase):
"""
Test cases for OE's Go toolchain
"""
@staticmetho... | ():
bb_vars = get_bb_vars(['SDK_DEPLOY', 'TOOLCHAIN_OUTPUTNAME'],
"meta-go-toolchain")
sdk_deploy = bb_vars['SDK_DEPLOY']
toolchain_name = bb_vars['TOOLCHAIN_OUTPUTNAME']
return os.path.join(sdk_deploy, toolchain_name + ".sh")
@classmethod
def setUp... | get_sdk_toolchain | identifier_name |
gotoolchain.py | #
# SPDX-License-Identifier: MIT
#
import glob
import os
import shutil
import tempfile
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_vars
class oeGoToolchainSelfTest(OESelftestTestCase):
"""
Test cases for OE's Go toolchain
"""
@staticmetho... |
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmpdir_SDKQA, ignore_errors=True)
super(oeGoToolchainSelfTest, cls).tearDownClass()
def run_sdk_go_command(self, gocmd):
cmd = "cd %s; " % self.tmpdir_SDKQA
cmd = cmd + ". %s; " % self.env_SDK
cmd = cmd + "expo... | super(oeGoToolchainSelfTest, cls).setUpClass()
cls.tmpdir_SDKQA = tempfile.mkdtemp(prefix='SDKQA')
cls.go_path = os.path.join(cls.tmpdir_SDKQA, "go")
# Build the SDK and locate it in DEPLOYDIR
bitbake("meta-go-toolchain")
cls.sdk_path = oeGoToolchainSelfTest.get_sdk_toolchain()
... | identifier_body |
gotoolchain.py | #
# SPDX-License-Identifier: MIT
#
import glob
import os
import shutil
import tempfile
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_vars
class oeGoToolchainSelfTest(OESelftestTestCase):
"""
Test cases for OE's Go toolchain
"""
@staticmetho... | bb_vars = get_bb_vars(['SDK_DEPLOY', 'TOOLCHAIN_OUTPUTNAME'],
"meta-go-toolchain")
sdk_deploy = bb_vars['SDK_DEPLOY']
toolchain_name = bb_vars['TOOLCHAIN_OUTPUTNAME']
return os.path.join(sdk_deploy, toolchain_name + ".sh")
@classmethod
def setUpClas... | return glob.glob(pattern)[0]
@staticmethod
def get_sdk_toolchain(): | random_line_split |
mouse-timer.js | function MouseTimer(){
timers = {};
listenersWait = {};
function init(){
setMouseMoveHandler();
}
function setMouseMoveHandler(){
$(document).mousemove(function(event) {
for (var time in timers){
var timer = timers[time];
clearTimeout(ti... |
};
init();
}
var MouseTimer = new MouseTimer();
| {
if (!listenersWait[time]) return;
var pos = listenersWait[time].indexOf(handler);
if (pos >= 0){
listenersWait[time].splice(pos, 1);
}
} | conditional_block |
mouse-timer.js | function MouseTimer(){
timers = {};
listenersWait = {};
function init(){
setMouseMoveHandler();
}
function setMouseMoveHandler(){
$(document).mousemove(function(event) {
for (var time in timers){
var timer = timers[time];
clearTimeout(ti... | for (var i in listenersWait[time]){
var handler = listenersWait[time][i];
handler();
}
}, time);
}
}
function mousewait(time, handler){
if (!listenersWait[time]){
listenersWait[time] = [];
}
... | if (!timers[time]) {
timers[time] = setTimeout(function(){ | random_line_split |
mouse-timer.js | function MouseTimer(){
timers = {};
listenersWait = {};
function init(){
setMouseMoveHandler();
}
function setMouseMoveHandler(){
$(document).mousemove(function(event) {
for (var time in timers){
var timer = timers[time];
clearTimeout(ti... | (time, handler){
if (!listenersWait[time]){
listenersWait[time] = [];
}
listenersWait[time].push(handler);
addTimer(time);
}
this.on = function(event, time, handler){
if (event.toLowerCase() == "mousewait"){
mousewait(time, handler);
}
... | mousewait | identifier_name |
mouse-timer.js | function MouseTimer(){
timers = {};
listenersWait = {};
function init(){
setMouseMoveHandler();
}
function setMouseMoveHandler() |
function addTimer(time){
if (!timers[time]) {
timers[time] = setTimeout(function(){
for (var i in listenersWait[time]){
var handler = listenersWait[time][i];
handler();
}
}, time);
}
}
function... | {
$(document).mousemove(function(event) {
for (var time in timers){
var timer = timers[time];
clearTimeout(timer);
delete timers[time];
addTimer(time);
}
});
} | identifier_body |
basewidget.py | from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indi... |
@staticmethod
def _biselar(imagen, color_luz, color_sombra):
w, h = imagen.get_size()
draw.line(imagen, color_sombra, (0, h - 2), (w - 1, h - 2), 2)
draw.line(imagen, color_sombra, (w - 2, h - 2), (w - 2, 0), 2)
draw.lines(imagen, color_luz, 0, [(w - 2, 0), (0, 0), (0, h -... | ss
| identifier_body |
basewidget.py | from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indi... | self.opciones = opciones
super().__init__()
def on_focus_in(self):
self.hasFocus = True
def on_focus_out(self):
self.hasFocus = False
def on_mouse_down(self, mousedata):
pass
def on_mouse_up(self, mousedata):
pass
def on_mouse_over(... | lf.parent = parent
self.layer = self.parent.layer + 1
| conditional_block |
basewidget.py | from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indi... | @staticmethod
def _biselar(imagen, color_luz, color_sombra):
w, h = imagen.get_size()
draw.line(imagen, color_sombra, (0, h - 2), (w - 1, h - 2), 2)
draw.line(imagen, color_sombra, (w - 2, h - 2), (w - 2, 0), 2)
draw.lines(imagen, color_luz, 0, [(w - 2, 0), (0, 0), (0, h - 4... | random_line_split | |
basewidget.py | from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indi... | elf):
self.hasMouseOver = False
def on_key_down(self, keydata):
pass
def on_key_up(self, keydata):
pass
def on_destruction(self):
# esta funcion se llama cuando el widget es quitado del renderer.
pass
@staticmethod
def _biselar(imagen, color_... | _mouse_out(s | identifier_name |
tyencode.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 ... | ty::ty_vec(mt, v) => {
mywrite!(w, "V");
enc_mt(w, cx, mt);
enc_vstore(w, cx, v);
}
ty::ty_str(v) => {
mywrite!(w, "v");
enc_vstore(w, cx, v);
}
ty::ty_unboxed_vec(mt) => { mywrite!(w, "U"); enc_mt(w, cx, mt); }
... | enc_mt(w, cx, mt);
} | random_line_split |
tyencode.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 ... | (w: &mut MemWriter, fmt: &fmt::Arguments) {
fmt::write(&mut *w as &mut io::Writer, fmt);
}
pub fn enc_ty(w: &mut MemWriter, cx: @ctxt, t: ty::t) {
match cx.abbrevs {
ac_no_abbrevs => {
let result_str_opt;
{
let short_names_cache = cx.tcx.short_names_cache.borrow();
... | mywrite | identifier_name |
tyencode.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 ... |
ty::BrFresh(id) => {
mywrite!(w, "f{}|", id);
}
}
}
pub fn enc_vstore(w: &mut MemWriter, cx: @ctxt, v: ty::vstore) {
mywrite!(w, "/");
match v {
ty::vstore_fixed(u) => mywrite!(w, "{}|", u),
ty::vstore_uniq => mywrite!(w, "~"),
ty::vstore_box => mywrite!... | {
mywrite!(w, "[{}|{}]",
(cx.ds)(d),
cx.tcx.sess.str_of(s));
} | conditional_block |
tyencode.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 ... |
fn enc_region_substs(w: &mut MemWriter, cx: @ctxt, substs: &ty::RegionSubsts) {
match *substs {
ty::ErasedRegions => {
mywrite!(w, "e");
}
ty::NonerasedRegions(ref regions) => {
mywrite!(w, "n");
for &r in regions.iter() {
enc_region(w, c... | {
enc_region_substs(w, cx, &substs.regions);
enc_opt(w, substs.self_ty, |w, t| enc_ty(w, cx, t));
mywrite!(w, "[");
for t in substs.tps.iter() { enc_ty(w, cx, *t); }
mywrite!(w, "]");
} | identifier_body |
note-service.ts | import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {BaseService} from "./base-service";
import {Note} from "../classes/note";
import {Status} from "../classes/status";
@Injectable()
export class NoteService extends BaseService {
constructor... | .map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteApplicationId(noteApplicationId: number) : Observable<Note[]> {
return(this.http.get(this.noteUrl + "?noteApplicationId=" + noteApplicationId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteProspectId(noteProspectId... |
getNoteByNoteId(noteId: number) : Observable<Note> {
return(this.http.get(this.noteUrl + noteId) | random_line_split |
note-service.ts | import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {BaseService} from "./base-service";
import {Note} from "../classes/note";
import {Status} from "../classes/status";
@Injectable()
export class NoteService extends BaseService {
constructor... | (noteId: number) : Observable<Note> {
return(this.http.get(this.noteUrl + noteId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteApplicationId(noteApplicationId: number) : Observable<Note[]> {
return(this.http.get(this.noteUrl + "?noteApplicationId=" + noteApplicationId)
.map(this.ext... | getNoteByNoteId | identifier_name |
note-service.ts | import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {BaseService} from "./base-service";
import {Note} from "../classes/note";
import {Status} from "../classes/status";
@Injectable()
export class NoteService extends BaseService {
constructor... |
getNoteByNoteId(noteId: number) : Observable<Note> {
return(this.http.get(this.noteUrl + noteId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteApplicationId(noteApplicationId: number) : Observable<Note[]> {
return(this.http.get(this.noteUrl + "?noteApplicationId=" + noteApplicationId... | {
return(this.http.get(this.noteUrl)
.map(this.extractData)
.catch(this.handleError));
} | identifier_body |
id.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (full_id: ClientFullId) -> Self {
Self::Client(Arc::new(full_id))
}
/// Creates an app full ID.
pub fn app(full_id: AppFullId) -> Self {
Self::App(Arc::new(full_id))
}
/// Signs a given message using the App / Client full id as required.
pub fn sign(&self, msg: &[u8]) -> Signat... | client | identifier_name |
id.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | }
}
/// Returns a corresponding public ID.
pub fn public_id(&self) -> PublicId {
match self {
Self::App(app_full_id) => PublicId::App(app_full_id.public_id().clone()),
Self::Client(client_full_id) => PublicId::Client(client_full_id.public_id().clone()),
}
... | match self {
Self::App(app_full_id) => app_full_id.sign(msg),
Self::Client(client_full_id) => client_full_id.sign(msg), | random_line_split |
id.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
/// Creates an app full ID.
pub fn app(full_id: AppFullId) -> Self {
Self::App(Arc::new(full_id))
}
/// Signs a given message using the App / Client full id as required.
pub fn sign(&self, msg: &[u8]) -> Signature {
match self {
Self::App(app_full_id) => app_full_id.si... | {
Self::Client(Arc::new(full_id))
} | identifier_body |
pkgid.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
#[derive(RustcDecodable)]
struct Options {
flag_verbose: bool,
flag_quiet: bool,
flag_manifest_path: Option<String>,
arg_spec: Option<String>,
}
pub const USAGE: &'static str... | (options: Options,
config: &Config) -> CliResult<Option<()>> {
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path.clone()));
let spec = options.arg_spec.as_ref().map(|s| &s[..]);
let spec = t... | execute | identifier_name |
pkgid.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
#[derive(RustcDecodable)]
struct Options {
flag_verbose: bool,
flag_quiet: bool,
flag_manifest_path: Option<String>,
arg_spec: Option<String>,
}
pub const USAGE: &'static str... | crates.io/foo | foo | * | *://crates.io/foo
crates.io/foo#1.2.3 | foo | 1.2.3 | *://crates.io/foo
crates.io/bar#foo:1.2.3 | foo | 1.2.3 | *://crates.io/bar
http://crates.io/foo#1.2.3 | foo | 1.2.3 | http://crates.io/foo
";
pub fn execu... | foo:1.2.3 | foo | 1.2.3 | * | random_line_split |
question_6.rs | pub fn compress(string: &str) -> String {
let mut character_count = 0;
let mut previous_char = string.chars().nth(0).unwrap(); // Starts at first char
let mut new_string_parts: Vec<String> = vec![];
for c in string.chars() {
if previous_char == c {
character_count = character_count ... |
}
#[test]
fn example_compress() {
assert_eq!(compress("aabcccccaaa"), "a2b1c5a3");
}
#[test]
fn compress_should_return_original_string_when_not_smaller() {
assert_eq!(compress("aa"), "aa");
}
#[test]
fn compress_should_return_original_string_when_not_smaller_with_larger_example() {
assert_eq!(compress("... | {
return new_string_parts.join("");
} | conditional_block |
question_6.rs | pub fn compress(string: &str) -> String {
let mut character_count = 0;
let mut previous_char = string.chars().nth(0).unwrap(); // Starts at first char
let mut new_string_parts: Vec<String> = vec![];
for c in string.chars() {
if previous_char == c {
character_count = character_count ... | () {
assert_eq!(compress("aa"), "aa");
}
#[test]
fn compress_should_return_original_string_when_not_smaller_with_larger_example() {
assert_eq!(compress("aabbccddeeffgg"), "aabbccddeeffgg");
}
#[test]
fn compress_should_return_original_string_when_compression_generates_larger_string() {
// if compress() ha... | compress_should_return_original_string_when_not_smaller | identifier_name |
question_6.rs | pub fn compress(string: &str) -> String {
let mut character_count = 0;
let mut previous_char = string.chars().nth(0).unwrap(); // Starts at first char
let mut new_string_parts: Vec<String> = vec![];
for c in string.chars() {
if previous_char == c {
character_count = character_count ... | previous_char = c;
}
new_string_parts.push(previous_char.to_string());
new_string_parts.push(character_count.to_string());
let new_string = new_string_parts.join("");
if string.len() <= new_string.len() {
return string.to_string();
} else {
return new_string_parts.join(... | } | random_line_split |
question_6.rs | pub fn compress(string: &str) -> String {
let mut character_count = 0;
let mut previous_char = string.chars().nth(0).unwrap(); // Starts at first char
let mut new_string_parts: Vec<String> = vec![];
for c in string.chars() {
if previous_char == c {
character_count = character_count ... |
#[test]
fn compress_should_return_original_string_when_not_smaller() {
assert_eq!(compress("aa"), "aa");
}
#[test]
fn compress_should_return_original_string_when_not_smaller_with_larger_example() {
assert_eq!(compress("aabbccddeeffgg"), "aabbccddeeffgg");
}
#[test]
fn compress_should_return_original_string_... | {
assert_eq!(compress("aabcccccaaa"), "a2b1c5a3");
} | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { Product } from './product.model';
/**
* @InventoryApp: the top-level component for our application
*/
@Component({
selector: 'inventory-app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
products: Product[];
| 'MYSHOES',
'Black Running Shoes',
'/assets/images/products/black-shoes.jpg',
['Men', 'Shoes', 'Running Shoes'],
109.99),
new Product(
'NEATOJACKET',
'Blue Jacket',
'/assets/images/products/blue-jacket.jpg',
['Women', 'Apparel', 'Jackets & Ves... | constructor() {
this.products = [
new Product( | random_line_split |
app.component.ts | import { Component } from '@angular/core';
import { Product } from './product.model';
/**
* @InventoryApp: the top-level component for our application
*/
@Component({
selector: 'inventory-app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
products: Product[];
constructor() {
... |
}
| {
console.log('Product clicked: ', product);
} | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { Product } from './product.model';
/**
* @InventoryApp: the top-level component for our application
*/
@Component({
selector: 'inventory-app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
products: Product[];
constructor() {
... | (product: Product): void {
console.log('Product clicked: ', product);
}
}
| productWasSelected | identifier_name |
html.py | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text, force_str
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeData, mark_safe
from django.utils import six
from django.utils.six.moves.urlli... |
return ''.join(words)
urlize = allow_lazy(urlize, six.text_type)
def avoid_wrapping(value):
"""
Avoid text wrapping in the middle of a phrase by adding non-breaking
spaces where there previously were normal spaces.
"""
return value.replace(" ", "\xa0")
| if '.' in word or '@' in word or ':' in word:
# Deal with punctuation.
lead, middle, trail = '', word, ''
for punctuation in TRAILING_PUNCTUATION:
if middle.endswith(punctuation):
middle = middle[:-len(punctuation)]
trail = punc... | conditional_block |
html.py | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text, force_str
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeData, mark_safe
from django.utils import six
from django.utils.six.moves.urlli... | if hasattr(text, '__html__'):
return text.__html__()
else:
return escape(text)
def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
... | random_line_split | |
html.py | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text, force_str
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeData, mark_safe
from django.utils import six
from django.utils.six.moves.urlli... |
urlize = allow_lazy(urlize, six.text_type)
def avoid_wrapping(value):
"""
Avoid text wrapping in the middle of a phrase by adding non-breaking
spaces where there previously were normal spaces.
"""
return value.replace(" ", "\xa0")
| """
Converts any URLs in text into clickable links.
Works on http://, https://, www. links, and also on links ending in one of
the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
Links can have trailing punctuation (periods, commas, close-parens) and
leading punctuation (openin... | identifier_body |
html.py | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text, force_str
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeData, mark_safe
from django.utils import six
from django.utils.six.moves.urlli... | (format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(conditional_escape, a... | format_html | identifier_name |
nthday.js |
/*
Parameters:
index: n’th occurrence of the specified day
1 - first
2 - second
3 - third
4 - fourth
5 - fifth
6 - last
day: daynumber – javascript way where sunday is 0 and is saturday is 6
month: which is 1-12 [optional – defaults to current]
year: Full year – four digits [optional – defaults to current]
var ... | lied – set the year
if (year !== '' && year !== undefined) {
// Set year
date.setFullYear(year);
} else {
year = date.getFullYear();
}
// Find daynumber
firstDay = date.getDay();
// Find first friday.
while (date.getDay() != day) {
date.setDate(date.getDate() + 1);
}
switch (index) {
case 2:
date.... | date.getMonth();
}
// If supp | conditional_block |
nthday.js |
/*
Parameters:
index: n’th occurrence of the specified day
1 - first
2 - second
3 - third
4 - fourth
5 - fifth
6 - last
day: daynumber – javascript way where sunday is 0 and is saturday is 6
month: which is 1-12 [optional – defaults to current]
year: Full year – four digits [optional – defaults to current]
var ... | y, month, year) {
// Create date object
var date = new Date();
// Set to first day of month
date.setDate(1);
// If supplied – set the month
if (month !== '' && month !== undefined) {
// Set month
month -=1;
date.setMonth(month);
} else {
month = date.getMonth();
}
// If supplied – set the year
if (yea... | fMonth(index, da | identifier_name |
nthday.js | /*
Parameters:
index: n’th occurrence of the specified day | 4 - fourth
5 - fifth
6 - last
day: daynumber – javascript way where sunday is 0 and is saturday is 6
month: which is 1-12 [optional – defaults to current]
year: Full year – four digits [optional – defaults to current]
var myDay = getNthDayOfMonth(1, 0, 9, '');
console.log("first sunday in September "+myDay);
var m... | 1 - first
2 - second
3 - third | random_line_split |
nthday.js |
/*
Parameters:
index: n’th occurrence of the specified day
1 - first
2 - second
3 - third
4 - fourth
5 - fifth
6 - last
day: daynumber – javascript way where sunday is 0 and is saturday is 6
month: which is 1-12 [optional – defaults to current]
year: Full year – four digits [optional – defaults to current]
var ... | te date object
var date = new Date();
// Set to first day of month
date.setDate(1);
// If supplied – set the month
if (month !== '' && month !== undefined) {
// Set month
month -=1;
date.setMonth(month);
} else {
month = date.getMonth();
}
// If supplied – set the year
if (year !== '' && year !== undef... | identifier_body | |
settings.py | """
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
For example your project's `settings.py` file might look like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.YAMLRenderer', | 'rest_framework.parsers.YAMLParser',
)
}
This module provides the `api_setting` object, that is used to access
REST framework settings, checking for user settings first, then falling
back to the defaults.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.utils import... | )
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser', | random_line_split |
settings.py | """
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
For example your project's `settings.py` file might look like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.YAMLRenderer',
)
'DEFAULT... |
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
| val() | conditional_block |
settings.py | """
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
For example your project's `settings.py` file might look like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.YAMLRenderer',
)
'DEFAULT... |
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
| if attr == 'FILTER_BACKEND' and val is not None:
# Make sure we can initialize the class
val() | identifier_body |
settings.py | """
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
For example your project's `settings.py` file might look like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.YAMLRenderer',
)
'DEFAULT... | (val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
# Nod to tastypie's use of importlib.
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return ge... | import_from_string | identifier_name |
type_name.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::type_name;
// pub fn type_name<T>() -> usize;
macro_rules! type_name_test {
($T:ty, $message:expr) => ({
let message: &'static str = unsafe { type_name::<$T>() };
assert_eq!(message, $message)... | () {
type_name_test!( u8, "u8" );
type_name_test!( u16, "u16" );
type_name_test!( u32, "u32" );
type_name_test!( u64, "u64" );
type_name_test!( i8, "i8" );
type_name_test!( i16, "i16" );
type_name_test!( i32, "i32" );
type_name_test!( i64, "i64" );
type_name_test!( f32, "f32" );
type_name_test!( f64, "f64" )... | type_name_test1 | identifier_name |
type_name.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::type_name;
// pub fn type_name<T>() -> usize;
macro_rules! type_name_test {
($T:ty, $message:expr) => ({
let message: &'static str = unsafe { type_name::<$T>() };
assert_eq!(message, $message)... |
}
| {
type_name_test!( u8, "u8" );
type_name_test!( u16, "u16" );
type_name_test!( u32, "u32" );
type_name_test!( u64, "u64" );
type_name_test!( i8, "i8" );
type_name_test!( i16, "i16" );
type_name_test!( i32, "i32" );
type_name_test!( i64, "i64" );
type_name_test!( f32, "f32" );
type_name_test!( f64, "f64" );
... | identifier_body |
type_name.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::type_name;
// pub fn type_name<T>() -> usize;
macro_rules! type_name_test {
($T:ty, $message:expr) => ({
let message: &'static str = unsafe { type_name::<$T>() };
assert_eq!(message, $message)... | type_name_test!( i8, "i8" );
type_name_test!( i16, "i16" );
type_name_test!( i32, "i32" );
type_name_test!( i64, "i64" );
type_name_test!( f32, "f32" );
type_name_test!( f64, "f64" );
type_name_test!( [u8; 0], "[u8; 0]" );
type_name_test!( [u8; 68], "[u8; 68]" );
type_name_test!( [u32; 0], "[u32; 0]" );
ty... | type_name_test!( u8, "u8" );
type_name_test!( u16, "u16" );
type_name_test!( u32, "u32" );
type_name_test!( u64, "u64" ); | random_line_split |
pike.py | ###############################################################################
# Name: pike.py #
# Purpose: Define highlighting/syntax for Pike programming language #
# Author: Cody Precord <cprecord@editra.org> #
... | @keyword lang_id: used to select specific subset of keywords
"""
if lang_id == synglob.ID_LANG_PIKE:
return [PIKE_KW, PIKE_TYPE, PIKE_DOC]
else:
return list()
def SyntaxSpec(lang_id=0):
"""Syntax Specifications
@keyword lang_id: used for selecting a specific subset of syntax sp... | def Keywords(lang_id=0):
"""Returns Specified Keywords List | random_line_split |
pike.py | ###############################################################################
# Name: pike.py #
# Purpose: Define highlighting/syntax for Pike programming language #
# Author: Cody Precord <cprecord@editra.org> #
... |
else:
return list()
def CommentPattern(lang_id=0):
"""Returns a list of characters used to comment a block of code
@keyword lang_id: used to select a specific subset of comment pattern(s)
"""
if lang_id == synglob.ID_LANG_PIKE:
return cpp.CommentPattern(synglob.ID_LANG_CPP)
el... | return cpp.Properties(synglob.ID_LANG_CPP) | conditional_block |
pike.py | ###############################################################################
# Name: pike.py #
# Purpose: Define highlighting/syntax for Pike programming language #
# Author: Cody Precord <cprecord@editra.org> #
... |
def Properties(lang_id=0):
"""Returns a list of Extra Properties to set
@keyword lang_id: used to select a specific set of properties
"""
if lang_id == synglob.ID_LANG_PIKE:
return cpp.Properties(synglob.ID_LANG_CPP)
else:
return list()
def CommentPattern(lang_id=0):
"""Retur... | """Syntax Specifications
@keyword lang_id: used for selecting a specific subset of syntax specs
"""
if lang_id == synglob.ID_LANG_PIKE:
return SYNTAX_ITEMS
else:
return list() | identifier_body |
pike.py | ###############################################################################
# Name: pike.py #
# Purpose: Define highlighting/syntax for Pike programming language #
# Author: Cody Precord <cprecord@editra.org> #
... | (lang_id=0):
"""Returns Specified Keywords List
@keyword lang_id: used to select specific subset of keywords
"""
if lang_id == synglob.ID_LANG_PIKE:
return [PIKE_KW, PIKE_TYPE, PIKE_DOC]
else:
return list()
def SyntaxSpec(lang_id=0):
"""Syntax Specifications
@keyword lang_i... | Keywords | identifier_name |
image_interpolation_params.py | # Copyright 2018 The Lucid 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 applicable l... | (n_objectives=6, n_interp_steps=5, width=128,
channels=3):
"""A paramaterization for interpolating between each pair of N objectives.
Sometimes you want to interpolate between optimizing a bunch of objectives,
in a paramaterization that encourages images to align.
Args:
n_obj... | multi_interpolation_basis | identifier_name |
image_interpolation_params.py | # Copyright 2018 The Lucid 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 applicable l... |
interp_basis = []
for n in range(N):
col = [interp_basis[m][N-n][::-1] for m in range(n)]
col.append(tf.zeros([M, W, W, 3]))
for m in range(n+1, N):
interp = sum([lowres_tensor([M, W, W, Ch], [M, W//k, W//k, Ch])
for k in [1, 2]])
col.append(interp)
interp_basis.app... | col = []
for m in range(N):
interp = example_interps[n] + example_interps[m][::-1]
col.append(interp)
example_basis.append(col) | conditional_block |
image_interpolation_params.py | # Copyright 2018 The Lucid 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
# | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import numpy as np
import tensorflow as tf
from lucid.optvi... | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
image_interpolation_params.py | # Copyright 2018 The Lucid 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 applicable l... | """A paramaterization for interpolating between each pair of N objectives.
Sometimes you want to interpolate between optimizing a bunch of objectives,
in a paramaterization that encourages images to align.
Args:
n_objectives: number of objectives you want interpolate between
n_interp_steps: number of in... | identifier_body | |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | (_: libc::c_int, description: ~str) {
println(fmt!("GLFW Error: %s", description));
}
| error_callback | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
fn key_callback(window: &glfw::Window, key: libc::c_int, _: libc::c_int, action: libc::c_int, _: glfw::KeyMods) {
if action == glfw::PRESS && key == glfw::KEY_ESCAPE {
window.set_should_close(true);
}
}
fn error_callback(_: libc::c_int, description: ~str) {
println(fmt!("GLFW Error: %s", descript... | {
glfw::set_error_callback(error_callback);
if glfw::init().is_err() {
fail!(~"Failed to initialize GLFW");
} else {
(||{
let window = glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed).unwrap();
window.set_key_callback(key_callback);
... | identifier_body |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | } else {
(||{
let window = glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed).unwrap();
window.set_key_callback(key_callback);
window.make_context_current();
while !window.should_close() {
window.poll_events();
... | random_line_split | |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | else {
(||{
let window = glfw::Window::create(300, 300, "Hello this is window", glfw::Windowed).unwrap();
window.set_key_callback(key_callback);
window.make_context_current();
while !window.should_close() {
window.poll_events();
... | {
fail!(~"Failed to initialize GLFW");
} | conditional_block |
annulus_distribution.rs | //! Implementation of a uniform distribuition of points on a two-dimensional
//! annulus.
use rand::distributions::Distribution;
use rand::Rng;
use std::f64::consts::PI;
pub use Point;
/// The uniform distribution of 2D points on an annulus `{x: r_1 <= |x| <= r_2}`.
pub struct AnnulusDist {
r1_sq: f64,
r2_sq: ... | }
impl Distribution<Point> for AnnulusDist {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Point {
// For points to be uniformly distributed in the annulus, the area of the disk with radius
// equal to the distance of the point from the origin is distributed uniformly between r₁²
// and... | r1_sq: r1 * r1,
r2_sq: r2 * r2,
}
} | random_line_split |
annulus_distribution.rs | //! Implementation of a uniform distribuition of points on a two-dimensional
//! annulus.
use rand::distributions::Distribution;
use rand::Rng;
use std::f64::consts::PI;
pub use Point;
/// The uniform distribution of 2D points on an annulus `{x: r_1 <= |x| <= r_2}`.
pub struct | {
r1_sq: f64,
r2_sq: f64,
}
impl AnnulusDist {
/// Construct a new `AnnulusDist` with the given inner and outer radius
/// `r1`, `r2`. Panics if not `0 < r1 < r2`.
pub fn new(r1: f64, r2: f64) -> AnnulusDist {
assert!(0. < r1, "AnnulusDist::new called with `r1 <= 0`");
assert!(r1 <... | AnnulusDist | identifier_name |
annulus_distribution.rs | //! Implementation of a uniform distribuition of points on a two-dimensional
//! annulus.
use rand::distributions::Distribution;
use rand::Rng;
use std::f64::consts::PI;
pub use Point;
/// The uniform distribution of 2D points on an annulus `{x: r_1 <= |x| <= r_2}`.
pub struct AnnulusDist {
r1_sq: f64,
r2_sq: ... |
}
impl Distribution<Point> for AnnulusDist {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Point {
// For points to be uniformly distributed in the annulus, the area of the disk with radius
// equal to the distance of the point from the origin is distributed uniformly between r₁²
// an... | {
assert!(0. < r1, "AnnulusDist::new called with `r1 <= 0`");
assert!(r1 < r2, "AnnulusDist::new called with `r2 <= r1`");
AnnulusDist {
r1_sq: r1 * r1,
r2_sq: r2 * r2,
}
} | identifier_body |
typeid-intrinsic.rs | // Copyright 2013-2014 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... | } |
// check it has a hash
let (a, b) = (TypeId::of::<uint>(), TypeId::of::<uint>());
assert_eq!(hash::hash(&a), hash::hash(&b)); | random_line_split |
typeid-intrinsic.rs | // Copyright 2013-2014 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... | () {
unsafe {
assert_eq!(intrinsics::type_id::<other1::A>(), other1::id_A());
assert_eq!(intrinsics::type_id::<other1::B>(), other1::id_B());
assert_eq!(intrinsics::type_id::<other1::C>(), other1::id_C());
assert_eq!(intrinsics::type_id::<other1::D>(), other1::id_D());
assert... | main | identifier_name |
typeid-intrinsic.rs | // Copyright 2013-2014 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... | {
unsafe {
assert_eq!(intrinsics::type_id::<other1::A>(), other1::id_A());
assert_eq!(intrinsics::type_id::<other1::B>(), other1::id_B());
assert_eq!(intrinsics::type_id::<other1::C>(), other1::id_C());
assert_eq!(intrinsics::type_id::<other1::D>(), other1::id_D());
assert_eq... | identifier_body | |
post_render.js | var util = require('hexo-util');
var code = [
'if tired && night:',
' sleep()'
].join('\n');
var content = [
'# Title',
'``` python',
code,
'```',
'some content',
'',
'## Another title',
'{% blockquote %}',
'quote content',
'{% endblockquote %}',
'',
'{% quote Hello World %}',
'quote co... | ].join(''); | '<blockquote><p>quote content</p>\n',
'<footer><strong>Hello World</strong></footer></blockquote>' | random_line_split |
officemru.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
import unittest
from plaso.formatters import officemru # pylint: disable=unused-import
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib impor... | if __name__ == '__main__':
unittest.main() | random_line_split | |
officemru.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
import unittest
from plaso.formatters import officemru # pylint: disable=unused-import
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib impor... | unittest.main() | conditional_block | |
officemru.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
import unittest
from plaso.formatters import officemru # pylint: disable=unused-import
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib impor... | (test_lib.RegistryPluginTestCase):
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
@shared_test_lib.skipUnlessHasTestFile([u'NTUSER-WIN7.DAT'])
def testProcess(self):
"""Tests the Process function."""
test_file_entry = self._GetTestFileEntry([u'NTUSER-WIN7.DAT'])
key_path = (
... | OfficeMRUPluginTest | identifier_name |
officemru.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
import unittest
from plaso.formatters import officemru # pylint: disable=unused-import
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib impor... |
if __name__ == '__main__':
unittest.main()
| """Tests the Process function."""
test_file_entry = self._GetTestFileEntry([u'NTUSER-WIN7.DAT'])
key_path = (
u'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\14.0\\Word\\'
u'File MRU')
win_registry = self._GetWinRegistryFromFileEntry(test_file_entry)
registry_key = win_registry.GetKey... | identifier_body |
angular-locale_fr-gp.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lu... | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
angular-locale_fr-gp.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lu... | "mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
... | ],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss", | random_line_split |
cpp.py | import hashlib
from tango.ast import *
from tango.builtin import Int, Double, String
from tango.types import FunctionType, NominalType, TypeUnion
def transpile(module, header_stream, source_stream):
transpiler = Transpiler(header_stream, source_stream)
transpiler.visit(module)
def compatibilize(name):
... |
# We should always find at least one valid implementation, unless
# something went wrong with the type solver.
assert False, 'could not find the implementation of {}'.format(node.callee)
| for decl in node.callee.__info__['scope'][node.callee.name]:
# When the object denoted by the identifier is a declaration, it
# means we have to instantiate that declaration.
if isinstance(decl, FunctionDecl):
function_type = decl.__info__['type']
# W... | conditional_block |
cpp.py | import hashlib
from tango.ast import *
from tango.builtin import Int, Double, String
from tango.types import FunctionType, NominalType, TypeUnion
def transpile(module, header_stream, source_stream):
transpiler = Transpiler(header_stream, source_stream)
transpiler.visit(module)
| result = str(str(name.encode())[2:-1]).replace('\\', '')
for punct in '. ()[]<>-:':
result = result.replace(punct, '')
if result[0].isdigit():
result = '_' + result
return result
operator_translations = {
'+': '__add__',
'-': '__sub__',
'*': '__mul__',
'/': '__div__',... | def compatibilize(name): | random_line_split |
cpp.py | import hashlib
from tango.ast import *
from tango.builtin import Int, Double, String
from tango.types import FunctionType, NominalType, TypeUnion
def transpile(module, header_stream, source_stream):
transpiler = Transpiler(header_stream, source_stream)
transpiler.visit(module)
def compatibilize(name):
... | (self, data, end='\n'):
print(' ' * self.indent + data, file=self.source_stream, end=end)
def visit_ModuleDecl(self, node):
self.write_source('#include "tango.hh"')
self.write_source('')
self.write_source('int main(int argc, char* argv[]) {')
self.indent += 4
self.g... | write_source | identifier_name |
cpp.py | import hashlib
from tango.ast import *
from tango.builtin import Int, Double, String
from tango.types import FunctionType, NominalType, TypeUnion
def transpile(module, header_stream, source_stream):
transpiler = Transpiler(header_stream, source_stream)
transpiler.visit(module)
def compatibilize(name):
... |
def translate_expr(self, node):
if isinstance(node, Literal):
if node.__info__['type'] == String:
return '"' + node.value + '"'
return node.value
if isinstance(node, Identifier):
# If the identifier is `true` or `false`, we write it as is.
... | if isinstance(type_instance, NominalType):
return compatibilize(type_instance.scope.name + '_' + type_instance.name)
if isinstance(type_instance, FunctionType):
# Register a new functor for the parsed function type.
functor = self.functors.get(type_instance)
if f... | identifier_body |
mspe-eligibility.e2e-spec.ts | import { browser, element, by } from 'protractor';
import { EligibilityPage, BaseMSPEnrolmentTestPage } from './mspe-enrolment.po';
import { FakeDataEnrolment } from './mspe-enrolment.data';
describe('MSP Enrolment - Check Eligibility', () => { | const PERSONAL_PAGE_URL = `msp/enrolment/personal-info`;
beforeAll(() => {
console.log('START OF E2E ENROLMENT' + '\nThis test uses Seed #: ' + data.getSeed());
});
beforeEach(() => {
page = new EligibilityPage();
basePage = new BaseMSPEnrolmentTestPage();
data.setSeed(... | let page: EligibilityPage;
let basePage: BaseMSPEnrolmentTestPage;
const data = new FakeDataEnrolment();
let eliData;
const ELIGIBILITY_PAGE_URL = `msp/enrolment/prepare` | random_line_split |
category-bucket-comparison.summarization.service.ts | import * as math from 'mathjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { SummarizationDataSourceService } from './summarization-data-source.service';
import { SummarizationService, BaseConfig } from './summarization.service';
... |
return buckets;
}
}
| {
buckets.push(currentBucket);
} | conditional_block |
category-bucket-comparison.summarization.service.ts | import * as math from 'mathjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { SummarizationDataSourceService } from './summarization-data-source.service';
import { SummarizationService, BaseConfig } from './summarization.service';
... | (points: CategoricalPoint[], bucketPercentageTolerance: number) {
const buckets: CategoricalPoint[][] = [];
let currentBucket: CategoricalPoint[] = [];
for (const { x, y } of points) {
// Assumes that points are sorted by greatest y -> least y
const currentBucketYMax = currentBucket[0]?.y... | bucketizePoints | identifier_name |
category-bucket-comparison.summarization.service.ts | import * as math from 'mathjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { SummarizationDataSourceService } from './summarization-data-source.service';
import { SummarizationService, BaseConfig } from './summarization.service';
... |
return this.summarizationDataSourceService.pointsByLabels$(datumLabels)
.pipe(map(pointsArray => {
// datum label should be unique in data, so length of pointsArray is either 0 or 1
const points = (pointsArray.length === 0 ? [] : pointsArray[0]) as CategoricalPoint[];
const max... | */
createSummaries$(config: CategoryBucketComparisonConfig): Observable<SummaryGroup[]> {
// The length of datumLabels should be 1 for this summarization
const { datumLabels, metric, bucketPercentageTolerance } = config;
| random_line_split |
category-bucket-comparison.summarization.service.ts | import * as math from 'mathjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { SummarizationDataSourceService } from './summarization-data-source.service';
import { SummarizationService, BaseConfig } from './summarization.service';
... |
createDataProperties$(config: CategoryBucketComparisonConfig): Observable<CategoryBucketComparisonProperties> {
return of({});
}
/**
* Create summaries that describe the difference of y-values average between buckets.
* The bucket is a subset of data with similar y-values.
*
* Sample ... | {
return { ...defaultConfig, ...config } as CategoryBucketComparisonConfig;
} | identifier_body |
phaserconversionmaps.ts | // 2388 - vertical cave wall
// 2399 - horizontal cave wall
import { invert } from 'lodash';
export const VerticalDoorGids = {
// blue wall door vert
1058: true,
// undead wall door vert
1065: true,
| 1070: true,
// stone wall door vert
1077: true,
// green wall door vert
1088: true,
// town door vert
1095: true,
// town2 door vert
1116: true,
// town3 door vert
1123: true,
// cave green wall door vert
1211: true
};
export const TrueSightMap = {
// blue wall horiz, blue wall vert... | // cave wall door vert | random_line_split |
categories_request_body.py | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CategoriesRequest... | """Returns true if both objects are not equal"""
return not self == other | identifier_body | |
categories_request_body.py | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CategoriesRequest... | (self, other):
"""Returns true if both objects are not equal"""
return not self == other
| __ne__ | identifier_name |
categories_request_body.py | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CategoriesRequest... |
if issubclass(CategoriesRequestBody, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"... | result[attr] = value | conditional_block |
categories_request_body.py | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CategoriesRequest... | if data is not None:
self.data = data
@property
def data(self):
"""Gets the data of this CategoriesRequestBody. # noqa: E501
:return: The data of this CategoriesRequestBody. # noqa: E501
:rtype: CategoriesRequestBodyData
"""
return self._data
... | self.discriminator = None | random_line_split |
PlayerSpec.js | describe("Player", function() {
var Player = require('../src/Player.js'); | player = new Player();
song = new Song();
});
it("should be able to play a Song", function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(song);
//demonstrates use of custom matcher
expect(player).toBePlaying(song);
});
describe("when song has been paused", functio... | var Song = require('../src/Song.js');
var player;
var song;
beforeEach(function() { | random_line_split |
AirFileStorageProvider.js | /*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.storage.AirFileStorageProvider"]){
dojo._hasResource["dojox.storage.AirFileStorageProvider"]=t... |
var _24=[];
for(var i=0;i<_22.length;i++){
_24[i]=this.get(_22[i],_23);
}
return _24;
},removeMultiple:function(_26,_27){
_27=_27||this.DEFAULT_NAMESPACE;
for(var i=0;i<_26.length;i++){
this.remove(_26[i],_27);
}
},isPermanent:function(){
return true;
},getMaximumSize:function(){
return this.SIZE_NO_LIMIT;
},hasSettin... | {
throw new Error("Invalid namespace given: "+_23);
} | conditional_block |
AirFileStorageProvider.js | /*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.storage.AirFileStorageProvider"]){
dojo._hasResource["dojox.storage.AirFileStorageProvider"]=t... | throw new Error("Invalid key given: "+_a);
}
_b=_b||this.DEFAULT_NAMESPACE;
var _c=null;
var _d=_1.File.applicationStorageDirectory.resolvePath(this._storagePath+_b+"/"+_a);
if(_d.exists&&!_d.isDirectory){
var _e=new _1.FileStream();
_e.open(_d,_1.FileMode.READ);
_c=_e.readObject();
_e.close();
}
return _c;
},getNamesp... | _5(this.SUCCESS,_3,null,_6);
}
},get:function(_a,_b){
if(this.isValidKey(_a)==false){ | random_line_split |
definitions.ts | // DRY!
class Form {
settings: object = {
method: undefined,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: undefined
};
get httpMethod() {
return this.settings['method'];
... |
this.send()
.then(response => {
if (response.status == 201 || response.status == 204) {
toggleClasses(submitButton, 'disabled')
console.log(this.messageElement);
toggleClasses(this.messageElement, 'on', 'off', 'animated', ... | {
this.saveAllAttributes();
this.toJson()
} | conditional_block |
definitions.ts | // DRY!
class Form {
settings: object = {
method: undefined,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: undefined
};
get httpMethod() {
return this.settings['method'];
... |
}
class Post extends Form {
title: string;
imagelink: string;
content: string;
tags: string;
constructor(title: string, imagelink: string, content: string, tags: string) {
super()
this.title = title
this.imagelink = imagelink;
this.content = content;
this.t... | {
if (content.length > 0) {
this.pages[`${this.currentPage}`] = content;
}
} | identifier_body |
definitions.ts | // DRY!
class Form {
settings: object = {
method: undefined,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: undefined
};
get httpMethod() {
return this.settings['method'];
... | send(flaskLocation: string) {
return sendJson(flaskLocation, this.settings);
}
} | random_line_split | |
definitions.ts | // DRY!
class Form {
settings: object = {
method: undefined,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: undefined
};
get httpMethod() {
return this.settings['method'];
... | (flaskLocation: string) {
return sendJson(flaskLocation, this.settings);
}
}
| send | identifier_name |
AttributeMarshallingMixin.js | import { booleanAttributeValue, standardBooleanAttributes } from "./dom.js";
import { rendering } from "./internal.js";
// Memoized maps of attribute to property names and vice versa.
// We initialize this with the special case of the tabindex (lowercase "i")
// attribute, which is mapped to the tabIndex (capital "I")... | (propertyName) {
let attribute = propertyNamesToAttributes[propertyName];
if (!attribute) {
// Convert and memoize.
const uppercaseRegEx = /([A-Z])/g;
attribute = propertyName.replace(uppercaseRegEx, "-$1").toLowerCase();
propertyNamesToAttributes[propertyName] = attribute;
}
return attribute;
}... | propertyNameToAttribute | identifier_name |
AttributeMarshallingMixin.js | import { booleanAttributeValue, standardBooleanAttributes } from "./dom.js";
import { rendering } from "./internal.js";
// Memoized maps of attribute to property names and vice versa.
// We initialize this with the special case of the tabindex (lowercase "i")
// attribute, which is mapped to the tabIndex (capital "I")... |
// Because maintaining the mapping of attributes to properties is tedious,
// this provides a default implementation for `observedAttributes` that
// assumes that your component will want to expose all public properties in
// your component's API as properties.
//
// You can override this defa... | {
if (super.attributeChangedCallback) {
super.attributeChangedCallback(attributeName, oldValue, newValue);
}
// Sometimes this callback is invoked when there's not actually any
// change, in which we skip invoking the property setter.
//
// We also skip setting properties if... | identifier_body |
AttributeMarshallingMixin.js | import { booleanAttributeValue, standardBooleanAttributes } from "./dom.js";
import { rendering } from "./internal.js";
// Memoized maps of attribute to property names and vice versa.
// We initialize this with the special case of the tabindex (lowercase "i")
// attribute, which is mapped to the tabIndex (capital "I")... |
}
// Because maintaining the mapping of attributes to properties is tedious,
// this provides a default implementation for `observedAttributes` that
// assumes that your component will want to expose all public properties in
// your component's API as properties.
//
// You can override thi... | {
const propertyName = attributeToPropertyName(attributeName);
// If the attribute name corresponds to a property name, set the property.
if (propertyName in this) {
// Parse standard boolean attributes.
const parsed = standardBooleanAttributes[attributeName]
? bo... | conditional_block |
AttributeMarshallingMixin.js | import { booleanAttributeValue, standardBooleanAttributes } from "./dom.js";
import { rendering } from "./internal.js";
// Memoized maps of attribute to property names and vice versa.
// We initialize this with the special case of the tabindex (lowercase "i")
// attribute, which is mapped to the tabIndex (capital "I")... | } | attribute = propertyName.replace(uppercaseRegEx, "-$1").toLowerCase();
propertyNamesToAttributes[propertyName] = attribute;
}
return attribute; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.