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
util.rs
use std::io::{Cursor, Read}; use std::io; use psoserial::Serial; use psomsg::util::*; static COLOR_RED: &'static str = "\x1B[31m"; static COLOR_RESET: &'static str = "\x1B[0m"; /// Creates a 3-column view of the buffer with index, bytes, and ASCII /// representation. pub fn hex_view(buf: &[u8]) -> String { let r...
else { leftover = row * 16 + 16 - array.len(); array.len() } }; for i in (row * 16)..end { if (buf.len() > i && buf[i] != array[i]) || buf.len() <= i { output.push_str(&format!("{}{:02X}{} ", COLOR_RED, array[i], COLOR_RESET)); ...
{ leftover = 0; row * 16 + 16 }
conditional_block
util.rs
use std::io::{Cursor, Read}; use std::io; use psoserial::Serial; use psomsg::util::*; static COLOR_RED: &'static str = "\x1B[31m"; static COLOR_RESET: &'static str = "\x1B[0m"; /// Creates a 3-column view of the buffer with index, bytes, and ASCII /// representation. pub fn hex_view(buf: &[u8]) -> String { let r...
<S: Serial>(s: &S, buf: &[u8]) -> String { let mut cursor = Cursor::new(Vec::new()); s.serialize(&mut cursor).unwrap(); let array = cursor.into_inner(); let rows = array.len() / 16 + { if array.len() % 16 > 0 {1} else {0} }; let mut output = String::new(); for row in 0..rows { // First ...
hex_view_diff
identifier_name
util.rs
use std::io::{Cursor, Read}; use std::io; use psoserial::Serial; use psomsg::util::*; static COLOR_RED: &'static str = "\x1B[31m"; static COLOR_RESET: &'static str = "\x1B[0m"; /// Creates a 3-column view of the buffer with index, bytes, and ASCII /// representation. pub fn hex_view(buf: &[u8]) -> String { let r...
hex_view(&array) } /// Shows the serialized hex view of the first argument, with different bytes /// in ANSI escaped red. pub fn hex_view_diff<S: Serial>(s: &S, buf: &[u8]) -> String { let mut cursor = Cursor::new(Vec::new()); s.serialize(&mut cursor).unwrap(); let array = cursor.into_inner(); let...
let mut cursor = Cursor::new(Vec::new()); s.serialize(&mut cursor).unwrap(); let array = cursor.into_inner();
random_line_split
about_classes.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutClasses(Koan): class Dog: "Dogs need regular walkies. Never, ever let them drive." def test_instances_of_classes_can_be_created_adding_parentheses(self): # NOTE: The .__name__ attribute will convert the class ...
(self): fido = self.Dog5("Fido") self.assertEqual("Fido", fido.name) def test_args_must_match_init(self): with self.assertRaises(TypeError): self.Dog5() # THINK ABOUT IT: # Why is this so? # # Because __init__ requires 1 argument and none were gi...
test_init_provides_initial_values_for_instance_variables
identifier_name
about_classes.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutClasses(Koan): class Dog: "Dogs need regular walkies. Never, ever let them drive." def test_instances_of_classes_can_be_created_adding_parentheses(self): # NOTE: The .__name__ attribute will convert the class ...
def test_str_provides_a_string_version_of_the_object(self): fido = self.Dog6("Fido") self.assertEqual("Fido", str(fido)) def test_str_is_used_explicitly_in_string_interpolation(self): fido = self.Dog6("Fido") self.assertEqual("My dog is Fido", "My dog is " + str(fido)) de...
# self.assertEqual("<Dog named 'Fido'>", fido.get_self()) # Not a string!
random_line_split
about_classes.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutClasses(Koan): class Dog: "Dogs need regular walkies. Never, ever let them drive." def test_instances_of_classes_can_be_created_adding_parentheses(self): # NOTE: The .__name__ attribute will convert the class ...
def set_name(self, a_name): self._name = a_name def test_init_method_is_the_constructor(self): dog = self.Dog2() self.assertEqual('Paul', dog._name) def test_private_attributes_are_not_really_private(self): dog = self.Dog2() dog.set_name("Fido") se...
self._name = 'Paul'
identifier_body
slider_spec.ts
import {Component, ViewChild} from "@angular/core"; import {MockReactNativeWrapper} from "./../../src/wrapper/wrapper_mock"; import {fireFunctionalEvent, configureTestingModule, initTest} from "../../src/test_helpers/utils"; import {Slider} from "../../src/components/common/slider"; describe('Slider component', () => ...
(event: any) { this.log.push(event); } }
handleChange
identifier_name
slider_spec.ts
import {Component, ViewChild} from "@angular/core"; import {MockReactNativeWrapper} from "./../../src/wrapper/wrapper_mock"; import {fireFunctionalEvent, configureTestingModule, initTest} from "../../src/test_helpers/utils"; import {Slider} from "../../src/components/common/slider"; describe('Slider component', () => ...
}); }); @Component({ selector: 'test-cmp', template: `to be overriden` }) class TestComponent { @ViewChild(Slider) slider: Slider; log: Array<boolean> = []; handleChange(event: any) { this.log.push(event); } }
expect(fixture.componentInstance.log.join(',')).toEqual('0.55'); });
random_line_split
character-service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Storage, LocalStorage } from 'ionic-angular'; import {Charakter} from '../../models/models' import {UUID} from 'angular2-uuid'; /* Generated class for the CharacterService provider. See https:...
findAll(): Promise<Charakter[]> { return new Promise((resolve, reject) => { this.storage.getJson(CharacterService.storageName).then((data) => { if (!data) { data = new Array<Charakter>(); } resolve(data); }) }) } saveAll(data: Charakter[]): Promise<Charakter[...
} }) }) }
random_line_split
character-service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Storage, LocalStorage } from 'ionic-angular'; import {Charakter} from '../../models/models' import {UUID} from 'angular2-uuid'; /* Generated class for the CharacterService provider. See https:...
(data: Charakter) { return new Promise(resolve => { this.http.post('/api/characters', JSON.stringify(data)) .subscribe(data => { resolve(data); }); }); } }
saveOnline
identifier_name
character-service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Storage, LocalStorage } from 'ionic-angular'; import {Charakter} from '../../models/models' import {UUID} from 'angular2-uuid'; /* Generated class for the CharacterService provider. See https:...
else { var idx = charList.findIndex((c) => { return c.uuid == char.uuid }) charList.splice(idx, 1, char) } this.saveAll(charList) resolve(char) }) }) } private loadOnline(): Promise<Charakter[]> { // don't have the data yet return new Promise(resolve ...
{ char.uuid = UUID.UUID(); charList.push(char) }
conditional_block
character-service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Storage, LocalStorage } from 'ionic-angular'; import {Charakter} from '../../models/models' import {UUID} from 'angular2-uuid'; /* Generated class for the CharacterService provider. See https:...
private saveOnline(data: Charakter) { return new Promise(resolve => { this.http.post('/api/characters', JSON.stringify(data)) .subscribe(data => { resolve(data); }); }); } }
{ // don't have the data yet return new Promise(resolve => { // We're using Angular HTTP provider to request the data, // then on the response, it'll map the JSON data to a parsed JS object. // Next, we process the data and resolve the promise with the new data. this.http.get('/api/char...
identifier_body
AndRule.test.ts
let assert = require('chai').assert;
import { AndRule } from '../../src/validate/AndRule'; import { AtLeastOneExistRule } from '../../src/validate/AtLeastOneExistRule'; suite('AndRule', ()=> { test('Only One Exist Rule', (done) => { var obj = new TestObject(); var schema = new Schema().withRule(new AndRule(new AtLeastOneExis...
let async = require('async'); import { TestObject } from './TestObject'; import { TestSubObject } from './TestSubObject'; import { Schema } from '../../src/validate/Schema';
random_line_split
quiz_id.test.js
var chai = require('chai'); var expect = chai.expect; var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var app = require('../../../app.js'); var models = require('../../../models'); var utils = require('../../utils'); var server; describe('/quiz/:id', function() { var qd; before(funct...
}); describe('Start Quiz', function() { beforeEach(function(done) { browser.get('/quiz/'+qd.id); done(); }); it('should go to /quiz/:id/:seed when the user clicks the Start Quiz button', function() { element(by.button...
done(); }); it('should display the quiz title on the page', function() { expect(element(by.binding('quizStarter.qd.title')).getText()).to.eventually.equal(qd.title); });
random_line_split
content.py
return self.location.category == 'thumbnail' @staticmethod def generate_thumbnail_name(original_name, dimensions=None): """ - original_name: Name of the asset (typically its location.name) - dimensions: `None` or a tuple of (width, height) in pixels """ name_root, ext =...
(asset_key): """ Legacy code expects the serialized asset key to start w/ a slash; so, do that in one place :param asset_key: """ url = unicode(asset_key) if not url.startswith('/'): url = '/' + url # TODO - re-address this once LMS-11198 is tackled. ...
serialize_asset_key_with_slash
identifier_name
content.py
^/]+)/ (?P<course>[^/]+)/ (?P<category>[^/]+)/ (?P<name>[^/]+) """, re.VERBOSE | re.IGNORECASE) @staticmethod def is_c4x_path(path_string): """ Returns a boolean if a path is believed to be a c4x link based on the leading element """ return StaticCont...
# if we're uploading an image, then let's generate a thumbnail so that we can
random_line_split
content.py
location identifier and create a 'durable' /static/.. URL representation of it. This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of courses. In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format ...
im = Image.open(StringIO.StringIO(content.data))
conditional_block
content.py
a tuple of (width, height) in pixels """ name_root, ext = os.path.splitext(original_name) if not ext == XASSET_THUMBNAIL_TAIL_NAME: name_root = name_root + ext.replace(u'.', u'-') if dimensions: width, height = dimensions # pylint: disable=unpacking-non-sequenc...
''' Abstraction for all ContentStore providers (e.g. MongoDB) ''' def save(self, content): raise NotImplementedError def find(self, filename): raise NotImplementedError def get_all_content_for_course(self, course_key, start=0, maxresults=-1, sort=None, filter_params=None): ...
identifier_body
list_organism_data.py
#!/usr/bin/env python import json import argparse from webapollo import WAAuth, WebApolloInstance, AssertUser, accessible_organisms if __name__ == "__main__": parser = argparse.ArgumentParser( description="List all organisms available in an Apollo instance" ) WAAuth(parser) parser.add_argument(...
print(json.dumps(cleanedOrgs, indent=2))
org = { "name": organism["commonName"], "id": organism["id"], "annotations": organism["annotationCount"], "sequences": organism["sequences"], } cleanedOrgs.append(org)
conditional_block
list_organism_data.py
#!/usr/bin/env python import json import argparse from webapollo import WAAuth, WebApolloInstance, AssertUser, accessible_organisms if __name__ == "__main__": parser = argparse.ArgumentParser( description="List all organisms available in an Apollo instance"
wa = WebApolloInstance(args.apollo, args.username, args.password) gx_user = AssertUser(wa.users.loadUsers(email=args.email)) all_orgs = wa.organisms.findAllOrganisms() orgs = accessible_organisms(gx_user, all_orgs) cleanedOrgs = [] for organism in all_orgs: org = { "name":...
) WAAuth(parser) parser.add_argument("email", help="User Email") args = parser.parse_args()
random_line_split
20191119112846_update_capcodes_oracle.js
var nconf = require('nconf'); var confFile = './config/config.json'; var dbtype = nconf.get('database:type');
return db.schema.hasTable('capcodes').then(function(exists) { if (!exists) { return db.schema.createTable('capcodes', table => { table.charset('utf8'); table.collate('utf8_general_ci'); table.increments('id').primary().unique().notNullable(); table.string('addre...
exports.up = function(db, Promise) { if (dbtype == 'oracledb') {
random_line_split
20191119112846_update_capcodes_oracle.js
var nconf = require('nconf'); var confFile = './config/config.json'; var dbtype = nconf.get('database:type'); exports.up = function(db, Promise) { if (dbtype == 'oracledb') { return db.schema.hasTable('capcodes').then(function(exists) { if (!exists)
else { return db.schema.table('capcodes', table => { table.dropColumn('alias'); table.dropColumn('agency'); table.dropColumn('icon'); table.dropColumn('color'); }).then(function () { return db.schema.table('capcodes', table => { table.string...
{ return db.schema.createTable('capcodes', table => { table.charset('utf8'); table.collate('utf8_general_ci'); table.increments('id').primary().unique().notNullable(); table.string('address', [255]).notNullable(); table.string('alias', [1000]).notNullable(); ...
conditional_block
noiseProceduralTexture.ts
import { Nullable } from "../../../types"; import { Scene } from "../../../scene"; import { EngineStore } from "../../../Engines/engineStore"; import { Texture } from "../../../Materials/Textures/texture"; import { ProceduralTexture } from "./proceduralTexture"; import { RegisterClass } from '../../../Misc/typeSto...
(): string { return "#define OCTAVES " + (this.octaves | 0); } /** Generate the current state of the procedural texture */ public render(useCameraPostProcess?: boolean) { this._updateShaderUniforms(); super.render(useCameraPostProcess); } /** * Serializes th...
_getDefines
identifier_name
noiseProceduralTexture.ts
import { Nullable } from "../../../types"; import { Scene } from "../../../scene"; import { EngineStore } from "../../../Engines/engineStore"; import { Texture } from "../../../Materials/Textures/texture"; import { ProceduralTexture } from "./proceduralTexture"; import { RegisterClass } from '../../../Misc/typeSto...
newTexture.level = this.level; // RenderTarget Texture newTexture.coordinatesMode = this.coordinatesMode; // Noise Specifics newTexture.brightness = this.brightness; newTexture.octaves = this.octaves; newTexture.persistence = this.persistence; n...
var textureSize = this.getSize(); var newTexture = new NoiseProceduralTexture(this.name, textureSize.width, this.getScene(), this._fallbackTexture ? this._fallbackTexture : undefined, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha;
random_line_split
noiseProceduralTexture.ts
import { Nullable } from "../../../types"; import { Scene } from "../../../scene"; import { EngineStore } from "../../../Engines/engineStore"; import { Texture } from "../../../Materials/Textures/texture"; import { ProceduralTexture } from "./proceduralTexture"; import { RegisterClass } from '../../../Misc/typeSto...
this.time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01; this.setFloat("brightness", this.brightness); this.setFloat("persistence", this.persistence); this.setFloat("timeScale", this.time); } protected _getDefines(): string { return "#defin...
{ return; }
conditional_block
text_quotations_test.py
ova <support@example.com> > Cool beans, scro""" eq_("Replying ok", quotations.extract_from_plain(msg_body)) def test_english_from_block(): eq_('Allo! Follow up MIME!', quotations.extract_from_plain("""Allo! Follow up MIME! From: somebody@example.com Sent: March-19-11 5:42 PM To: Somebody Subject: The manag...
def test_process_marked_lines(): # quotations and last message lines are mixed
random_line_split
text_quotations_test.py
Ticket #50] test from bob > > View ticket (http://example.com/action _nonce=3dd518) > """ eq_("Blah", quotations.extract_from_plain(msg_body)) def test_from_block_starts_with_date(): msg_body = """Blah Date: Wed, 16 May 2012 00:15:02 -0600 To: klizhentas@example.com """ eq_('Blah', quotations.extract_fr...
k1> <http://link2>" eq_(msg_body, quotations.extract_from_plain(msg_body)) def body_iterator(ms
identifier_body
text_quotations_test.py
Fri=2C 28 Sep 2012 10:55:48 +0000 From: tickets@example.com To: bob@example.com Subject: [Ticket #8] Test """ eq_('Blah', quotations.extract_from_plain(msg_body)) def test_dont_parse_quotations_for_forwarded_messages(): msg_body = """FYI ---------- Forwarded message ---------- From: bob@example.com Date: T...
yield eq_,
conditional_block
text_quotations_test.py
wrote: > Hello""" eq_("Hi", quotations.extract_from_plain(msg_body)) def test_with_indent(): msg_body = """YOLO salvia cillum kogi typewriter mumblecore cardigan skateboard Austin. ------On 12/29/1987 17:32 PM, Julius Caesar wrote----- Brunch mumblecore pug Marfa tofu, irure taxidermy hoodie readymade pari...
(): # e - empty lin
identifier_name
last-use-in-block.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 ...
<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T { fn g<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {f(s)} g(s, |v| { let r = f(v); r }) } pub fn main() {}
apply
identifier_name
last-use-in-block.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 apply<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T { fn g<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {f(s)} g(s, |v| { let r = f(v); r }) } pub fn main() {}
panic!();
random_line_split
last-use-in-block.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 ...
pub fn main() {}
{ fn g<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {f(s)} g(s, |v| { let r = f(v); r }) }
identifier_body
test-stream-pipe-error-handling.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
// // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR...
// distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions:
random_line_split
layout.rs
use super::{FractionalHex,Hex}; use std::f32::consts::PI; pub struct Orientation { f: Vec<f32>, b: Vec<f32>, start_angle: f32 } impl Orientation { pub fn new(f: Vec<f32>,b: Vec<f32>,start_angle: f32) -> Orientation { Orientation { f: f, b: b, start_angle: st...
Orientation::new(vec![3.0 / 2.0, 0.0, (3.0 as f32).sqrt() / 2.0, (3.0 as f32).sqrt()], vec![2.0 / 3.0, 0.0, -1.0 / 3.0, (3.0 as f32).sqrt() / 3.0], 0.0) } } pub struct Point { pub x: f32, pub y: f32 } impl Point { pub fn new(x: f32,y: f32) -> Point { Poi...
} pub fn flat() -> Orientation {
random_line_split
layout.rs
use super::{FractionalHex,Hex}; use std::f32::consts::PI; pub struct Orientation { f: Vec<f32>, b: Vec<f32>, start_angle: f32 } impl Orientation { pub fn
(f: Vec<f32>,b: Vec<f32>,start_angle: f32) -> Orientation { Orientation { f: f, b: b, start_angle: start_angle } } pub fn pointy() -> Orientation { Orientation::new( vec![(3.0 as f32).sqrt(), (3.0 as f32).sqrt() / 2.0, 0.0, 3.0 / 2.0], ...
new
identifier_name
InlineResponse200.js
/**
* AvaTax Brazil * The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by business wi...
random_line_split
InlineResponse200.js
/** * AvaTax Brazil * The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by busines...
else { // Browser globals (root is window) if (!root.AvaTaxBrazil) { root.AvaTaxBrazil = {}; } root.AvaTaxBrazil.InlineResponse200 = factory(root.AvaTaxBrazil.ApiClient); } }(this, function(ApiClient) { 'use strict'; /** * The InlineResponse200 model module. * @module model/Inline...
{ // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); }
conditional_block
folio.js
/* written by Joe Wallace, October 2017 the code below adds the concordance functionality also the listeners for the "reset", "home", "previous" and "next" buttons the html texts themselves were generated by a Python script I wrote, which uses regular expressions to extract plays from Shakespeare's First Folio and ...
() { var args = {}; var query = location.search.substring(1); var pos = query.indexOf('='); var nom = query.substring(0, pos); var val = query.substring(pos+1); val = decodeURIComponent(val); args[nom] = val; return args; } var args = urlArgs(); // only executes if the concordance form has a valu...
urlArgs
identifier_name
folio.js
/* written by Joe Wallace, October 2017 the code below adds the concordance functionality also the listeners for the "reset", "home", "previous" and "next" buttons the html texts themselves were generated by a Python script I wrote, which uses regular expressions to extract plays from Shakespeare's First Folio and ...
onLoad.loaded = false; onLoad(function(){onLoad.loaded=true;}); onLoad(setup);
{ if (onLoad.loaded) { window.setTimeout(f, 0); } else if (window.addEventListener) { window.addEventListener("load", f, false); } else if (window.attachEvent) { window.attachEvent("onload", f); } }
identifier_body
folio.js
/* written by Joe Wallace, October 2017 the code below adds the concordance functionality also the listeners for the "reset", "home", "previous" and "next" buttons the html texts themselves were generated by a Python script I wrote, which uses regular expressions to extract plays from Shakespeare's First Folio and ...
// in this case tokens[i+padding] would be undefined and therefore word is near the end else { var line = tokens.slice(i-padding, tokens.length); /* finds position of word by checking it against length of the tokens array and length of the line array; word will be i back from end of token...
{ var line = tokens.slice(0, i+padding); // in this case i simply denotes position of word line[i] = "<span style='color:red'>"+line[i]+"</span>"; output.push(line); }
conditional_block
folio.js
/* written by Joe Wallace, October 2017 the code below adds the concordance functionality also the listeners for the "reset", "home", "previous" and "next" buttons the html texts themselves were generated by a Python script I wrote, which uses regular expressions to extract plays from Shakespeare's First Folio and ...
line[i] = "<span style='color:red'>"+line[i]+"</span>"; output.push(line); } // in this case tokens[i+padding] would be undefined and therefore word is near the end else { var line = tokens.slice(i-padding, tokens.length); /* finds position of word by checking it against length o...
// in this case the word is near the beginning else if (!tokens[i-padding]) { var line = tokens.slice(0, i+padding); // in this case i simply denotes position of word
random_line_split
maildir.rs
use std::time::Duration; use crossbeam_channel::Sender; use maildir::Maildir as ExtMaildir; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::scheduler::Task; use crate::widgets::text::...
}
{ self.id }
identifier_body
maildir.rs
use std::time::Duration; use crossbeam_channel::Sender; use maildir::Maildir as ExtMaildir; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::scheduler::Task; use crate::widgets::text::...
(&self) -> Vec<&dyn I3BarWidget> { vec![&self.text] } fn id(&self) -> usize { self.id } }
view
identifier_name
maildir.rs
use std::time::Duration; use crossbeam_channel::Sender; use maildir::Maildir as ExtMaildir; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::scheduler::Task; use crate::widgets::text::...
display_type: MailType, } //TODO add `format` #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields, default)] pub struct MaildirConfig { /// Update interval in seconds #[serde(deserialize_with = "deserialize_duration")] pub interval: Duration, pub inboxes: Vec<String>, pub threshold...
threshold_critical: usize,
random_line_split
maildir.rs
use std::time::Duration; use crossbeam_channel::Sender; use maildir::Maildir as ExtMaildir; use serde_derive::Deserialize; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::errors::*; use crate::scheduler::Task; use crate::widgets::text::...
, inboxes: block_config.inboxes, threshold_warning: block_config.threshold_warning, threshold_critical: block_config.threshold_critical, display_type: block_config.display_type, }) } } impl Block for Maildir { fn update(&mut self) -> Result<Option<Update>...
{ widget }
conditional_block
main.rs
#![feature(bool_to_option)] use std::path::Path; use log::*; use simplelog::*; use std::time::{Instant}; use clap::{Arg, App}; mod checkloc; use checkloc::checkloc; mod average; use average::average_all_images; #[macro_use] extern crate lalrpop_util; fn
() { CombinedLogger::init( vec![ TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed), ] ).unwrap(); let mut app = App::new("krtools") .version("1.0") .author("Pedro M. <pmgberm@gmail.com>") .about("Does things the KR way") ...
main
identifier_name
main.rs
#![feature(bool_to_option)] use std::path::Path; use log::*; use simplelog::*; use std::time::{Instant}; use clap::{Arg, App}; mod checkloc; use checkloc::checkloc; mod average; use average::average_all_images; #[macro_use] extern crate lalrpop_util; fn main() { CombinedLogger::init( vec![ Te...
} info!(target: "kr_style_transfer", "Finished in {:?} seconds", start.elapsed().as_secs()); }
{ error!(target: "kr_style_transfer", "Unknown or unimplemented subcommand"); app.print_long_help(); }
conditional_block
main.rs
#![feature(bool_to_option)] use std::path::Path; use log::*; use simplelog::*; use std::time::{Instant}; use clap::{Arg, App}; mod checkloc; use checkloc::checkloc; mod average; use average::average_all_images; #[macro_use] extern crate lalrpop_util; fn main()
let path = Path::new(e); average_all_images(path); Some(e) }); } Some(("checkloc", args)) => { args.value_of("pdx_directory").and_then(|e| { let path = Path::new(e); checkloc(path); So...
{ CombinedLogger::init( vec![ TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed), ] ).unwrap(); let mut app = App::new("krtools") .version("1.0") .author("Pedro M. <pmgberm@gmail.com>") .about("Does things the KR way") .su...
identifier_body
main.rs
#![feature(bool_to_option)] use std::path::Path; use log::*; use simplelog::*; use std::time::{Instant}; use clap::{Arg, App}; mod checkloc; use checkloc::checkloc; mod average; use average::average_all_images; #[macro_use] extern crate lalrpop_util; fn main() { CombinedLogger::init( vec![ Te...
} info!(target: "kr_style_transfer", "Finished in {:?} seconds", start.elapsed().as_secs()); }
_ => { error!(target: "kr_style_transfer", "Unknown or unimplemented subcommand"); app.print_long_help(); }
random_line_split
diagnostic.rs
mut self, msg: &str); fn bump_err_count(@mut self); fn err_count(@mut self) -> uint; fn has_errors(@mut self) -> bool; fn abort_if_errors(@mut self); fn warn(@mut self, msg: &str); fn note(@mut self, msg: &str); // used to indicate a bug in the compiler: fn bug(@mut self, msg: &str) -> !...
// a span-handler is like a handler but also // accepts span information for source-location // reporting. pub trait span_handler { fn span_fatal(@mut self, sp: Span, msg: &str) -> !; fn span_err(@mut self, sp: Span, msg: &str); fn span_warn(@mut self, sp: Span, msg: &str); fn span_note(@mut self, sp: ...
msg: &str, lvl: level); }
random_line_split
diagnostic.rs
mut self, msg: &str); fn bump_err_count(@mut self); fn err_count(@mut self) -> uint; fn has_errors(@mut self) -> bool; fn abort_if_errors(@mut self); fn warn(@mut self, msg: &str); fn note(@mut self, msg: &str); // used to indicate a bug in the compiler: fn bug(@mut self, msg: &str) -> !...
(@mut self, msg: &str) { self.emit.emit(None, msg, note); } fn bug(@mut self, msg: &str) -> ! { self.fatal(ice_msg(msg)); } fn unimpl(@mut self, msg: &str) -> ! { self.bug(~"unimplemented " + msg); } fn emit(@mut self, cmsp: Option<(@codemap::CodeMap, Span)>, ...
note
identifier_name
diagnostic.rs
mut self, msg: &str); fn bump_err_count(@mut self); fn err_count(@mut self) -> uint; fn has_errors(@mut self) -> bool; fn abort_if_errors(@mut self); fn warn(@mut self, msg: &str); fn note(@mut self, msg: &str); // used to indicate a bug in the compiler: fn bug(@mut self, msg: &str) -> !...
&Some(ref term) => { term.attr(color); stderr.write_str(msg); term.reset(); }, _ => stderr.write_str(msg) } } else { stderr.write_str(msg); } } fn print_diagnostic(topic: &str, lvl: level, msg: &str) { let ...
{ local_data_key!(tls_terminal: @Option<term::Terminal>) let stderr = io::stderr(); if stderr.get_type() == io::Screen { let t = match local_data::get(tls_terminal, |v| v.map_move(|k| *k)) { None => { let t = term::Terminal::new(stderr); let tls = @match...
identifier_body
simple.py
# -*- coding: utf-8 -*- from sitemaps import SiteMapRoot, SiteMap from datetime import datetime def generate_sitemap(): """ build the sitemap """ sitemap = SiteMap() sitemap.append("http://www.xxx.com", datetime.now(), "weekly", 0.9) sitemap.append("http://www.xxx.com/a1", datetime.now(), "mo...
if __name__ == "__main__": generate_sitemap() generate_sitemap_gz()
random_line_split
simple.py
# -*- coding: utf-8 -*- from sitemaps import SiteMapRoot, SiteMap from datetime import datetime def generate_sitemap(): """ build the sitemap """ sitemap = SiteMap() sitemap.append("http://www.xxx.com", datetime.now(), "weekly", 0.9) sitemap.append("http://www.xxx.com/a1", datetime.now(), "mo...
generate_sitemap() generate_sitemap_gz()
conditional_block
simple.py
# -*- coding: utf-8 -*- from sitemaps import SiteMapRoot, SiteMap from datetime import datetime def generate_sitemap():
def generate_sitemap_gz(): """ get the gzip sitemap format """ sitemap = SiteMap() sitemap.append("http://www.xxx.com", datetime.now(), "weekly", 0.9) sitemap.append("http://www.xxx.com/a1", datetime.now(), "monthly", 0.7) xml_string = sitemap.to_string sitemap_root = SiteMapRoot("h...
""" build the sitemap """ sitemap = SiteMap() sitemap.append("http://www.xxx.com", datetime.now(), "weekly", 0.9) sitemap.append("http://www.xxx.com/a1", datetime.now(), "monthly", 0.7) sitemap.save_xml("sitemap.xml")
identifier_body
simple.py
# -*- coding: utf-8 -*- from sitemaps import SiteMapRoot, SiteMap from datetime import datetime def
(): """ build the sitemap """ sitemap = SiteMap() sitemap.append("http://www.xxx.com", datetime.now(), "weekly", 0.9) sitemap.append("http://www.xxx.com/a1", datetime.now(), "monthly", 0.7) sitemap.save_xml("sitemap.xml") def generate_sitemap_gz(): """ get the gzip sitemap format ...
generate_sitemap
identifier_name
App.js
import React from 'react'; import AppBar from 'material-ui/AppBar'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton/IconButton'; import MenuIcon from 'material-ui/svg-ico...
'/registry': 'Registry' } const menuItems = Object.keys(options).map(key => { const link = <Link to={key}>{options[key]}</Link>; return (<MenuItem key={key} primaryText={link} />); }); const menu = ( <IconMenu children={menuItems} iconButtonElement={<IconButton>...
'/rsvp': 'RSVP', '/hotel': 'Hotels',
random_line_split
App.js
import React from 'react'; import AppBar from 'material-ui/AppBar'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton/IconButton'; import MenuIcon from 'material-ui/svg-ico...
() { const options = { '/': 'Home', '/rsvp': 'RSVP', '/hotel': 'Hotels', '/registry': 'Registry' } const menuItems = Object.keys(options).map(key => { const link = <Link to={key}>{options[key]}</Link>; return (<MenuItem key={key} primaryText={link} />); }); cons...
render
identifier_name
version.ts
const Command = require('../ember-cli/lib/models/command'); import * as path from 'path'; import * as child_process from 'child_process'; import * as chalk from 'chalk'; const VersionCommand = Command.extend({ name: 'version', description: 'outputs Angular CLI version', aliases: ['v', '--version', '-v'], works...
} }, getDependencyVersions: function(pkg: any, prefix: string): any { const modules: any = {}; Object.keys(pkg.dependencies || {}) .concat(Object.keys(pkg.devDependencies || {})) .filter(depName => depName && depName.startsWith(prefix)) .forEach(key => modules[key] = this.getVersion...
{ this.printVersion(module, versions[module]); }
conditional_block
version.ts
const Command = require('../ember-cli/lib/models/command'); import * as path from 'path'; import * as child_process from 'child_process'; import * as chalk from 'chalk'; const VersionCommand = Command.extend({ name: 'version', description: 'outputs Angular CLI version', aliases: ['v', '--version', '-v'], works...
} ngCliVersion = `local (v${pkg.version}, branch: ${gitBranch})`; } if (projPkg) { roots.forEach(root => { versions = Object.assign(versions, this.getDependencyVersions(projPkg, root)); }); } const asciiArt = ` _ _ ...
} catch (e) {
random_line_split
__init__.py
# # Extensible User Folder # # (C) Copyright 2000-2004 The Internet (Aust) Pty Ltd # ACN: 082 081 472 ABN: 83 082 081 472 # All Rights Reserved # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MER...
# If this fails due to NUG being absent, just skip it try: import zodbGroupSource except ImportError: pass
random_line_split
borrowck-borrow-of-mut-base-ptr-safe.rs
// Copyright 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-MIT or ...
() { }
main
identifier_name
borrowck-borrow-of-mut-base-ptr-safe.rs
// Copyright 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-MIT or ...
// pretty-expanded FIXME #23616 fn foo<'a>(mut t0: &'a mut isize, mut t1: &'a mut isize) { let p: &isize = &*t0; // Freezes `*t0` let mut t2 = &t0; let q: &isize = &**t2; // Freezes `*t0`, but that's ok... let r: &isize = &*t0; // ...after all, could do same thing directly. } pub fn main() ...
random_line_split
borrowck-borrow-of-mut-base-ptr-safe.rs
// Copyright 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-MIT or ...
{ }
identifier_body
user_data.py
# Copyright 2012 OpenStack Foundation # # 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 ...
(extensions.ExtensionDescriptor): """Add user_data to the Create Server v1.1 API.""" name = "UserData" alias = "os-user-data" namespace = ("http://docs.openstack.org/compute/ext/" "userdata/api/v1.1") updated = "2012-08-07T00:00:00+00:00"
User_data
identifier_name
user_data.py
# Copyright 2012 OpenStack Foundation # # 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 ...
"""Add user_data to the Create Server v1.1 API.""" name = "UserData" alias = "os-user-data" namespace = ("http://docs.openstack.org/compute/ext/" "userdata/api/v1.1") updated = "2012-08-07T00:00:00+00:00"
identifier_body
user_data.py
# Copyright 2012 OpenStack Foundation # # 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 ...
# under the License. from nova.api.openstack import extensions class User_data(extensions.ExtensionDescriptor): """Add user_data to the Create Server v1.1 API.""" name = "UserData" alias = "os-user-data" namespace = ("http://docs.openstack.org/compute/ext/" "userdata/api/v1.1") ...
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations
random_line_split
content_length.rs
use std::fmt; use header::{Header, Raw, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) /// /// When a message does not have a `Transfer-Encoding` header field, a /// Content-Length header field can provide the anticipated size, as a /// decimal numbe...
/// headers.set(ContentLength(1024u64)); /// ``` #[derive(Clone, Copy, Debug, PartialEq)] pub struct ContentLength(pub u64); //static NAME: &'static str = "Content-Length"; impl Header for ContentLength { #[inline] fn header_name() -> &'static str { static NAME: &'static str = "Content-Length"; ...
/// ``` /// use hyper::header::{Headers, ContentLength}; /// /// let mut headers = Headers::new();
random_line_split
content_length.rs
use std::fmt; use header::{Header, Raw, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) /// /// When a message does not have a `Transfer-Encoding` header field, a /// Content-Length header field can provide the anticipated size, as a /// decimal numbe...
fn parse_header(raw: &Raw) -> ::Result<ContentLength> { // If multiple Content-Length headers were sent, everything can still // be alright if they all contain the same value, and all parse // correctly. If not, then it's an error. raw.iter() .map(parsing::from_raw_str)...
{ static NAME: &'static str = "Content-Length"; NAME }
identifier_body
content_length.rs
use std::fmt; use header::{Header, Raw, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) /// /// When a message does not have a `Transfer-Encoding` header field, a /// Content-Length header field can provide the anticipated size, as a /// decimal numbe...
(&self, f: &mut ::header::Formatter) -> fmt::Result { f.fmt_line(self) } } impl fmt::Display for ContentLength { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } __hyper__deref!(ContentLength => u64); __hyper__tm!(ContentLength, tests ...
fmt_header
identifier_name
issue-request.js
(function(module){ 'use strict'; //this comment set up here to turn off eslint warnings about unused vars /*global issues issueView helpers d3Chart:true*/ //set up constructor for easier use of data function
(opts){ this.repoOwner = opts.html_url.split('/')[3]; this.repoName = opts.html_url.split('/')[4]; this.issueUser = opts.user.login; this.issueUserAvatarURL = opts.user.avatar_url; this.issueUserAcctURL = opts.user.html_url; this.dateCreated = helpers.parseGitHubDate(opts.created_at), this....
RepoIssue
identifier_name
issue-request.js
(function(module){ 'use strict'; //this comment set up here to turn off eslint warnings about unused vars /*global issues issueView helpers d3Chart:true*/ //set up constructor for easier use of data function RepoIssue (opts)
let issues = {}; module.issues = issues; issues.data = []; issues.owner; issues.repo; issues.pageNumber = 1; issues.perPage = 100; issues.getIt = function(num, callback){ return $.ajax({ type: 'GET', url: `/github/repos/${issues.owner}/${issues.repo}/issues?page=${num}&per_page=100`...
{ this.repoOwner = opts.html_url.split('/')[3]; this.repoName = opts.html_url.split('/')[4]; this.issueUser = opts.user.login; this.issueUserAvatarURL = opts.user.avatar_url; this.issueUserAcctURL = opts.user.html_url; this.dateCreated = helpers.parseGitHubDate(opts.created_at), this.daysAgo...
identifier_body
issue-request.js
(function(module){ 'use strict'; //this comment set up here to turn off eslint warnings about unused vars /*global issues issueView helpers d3Chart:true*/ //set up constructor for easier use of data function RepoIssue (opts){ this.repoOwner = opts.html_url.split('/')[3]; this.repoName = opts.html_...
issues.data.push(issue); }); callback(issues.data); }, error: function () { issueView.badRequest(); }, }); }; issues.fetchData = function(num){ $.when( $.get(`/github/repos/Automattic/mongoose/issues?page=${num}&per_page=100`) .done((data) =...
data.forEach((element) => { let issue = new RepoIssue(element);
random_line_split
issue-request.js
(function(module){ 'use strict'; //this comment set up here to turn off eslint warnings about unused vars /*global issues issueView helpers d3Chart:true*/ //set up constructor for easier use of data function RepoIssue (opts){ this.repoOwner = opts.html_url.split('/')[3]; this.repoName = opts.html_...
else { console.log('no more data'); } }) .fail(() => { issues.success = false; }) ); }; })(window);
{ data.forEach((element) => { let issue = new RepoIssue(element); issues.data.push(issue); }); num++; issues.fetchData(num); console.log(num, issues.data); }
conditional_block
caches.py
""" Various caching help functions and classes. """ from django.core.cache import cache DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long. USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not. class _AbstractCache(object): ...
super(UserAccountCache, self).__init__("UA%d" % useraccount_or_id) # Online information def get_online(self): return self._get("online", False) def set_online(self, v): return self._set("online", v) online = property(get_online, set_online)
useraccount_or_id = useraccount_or_id.id
conditional_block
caches.py
""" Various caching help functions and classes. """ from django.core.cache import cache DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long. USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not. class _AbstractCache(object): ...
delay = USERACCOUNT_CACHE_DELAY def __init__(self, useraccount_or_id): """ Instanciate a cache from given user (or userid) """ # Instanciate cache from twistranet.twistapp import Twistable if isinstance(useraccount_or_id, Twistable): useraccount_or_id...
identifier_body
caches.py
""" Various caching help functions and classes. """ from django.core.cache import cache DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long. USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not. class _AbstractCache(object): ...
(self): return self._get("online", False) def set_online(self, v): return self._set("online", v) online = property(get_online, set_online)
get_online
identifier_name
caches.py
""" Various caching help functions and classes. """ from django.core.cache import cache DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long. USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not. class _AbstractCache(object): ...
online = property(get_online, set_online)
random_line_split
routing.py
(u"Routing - Notification:{y} successfully routed".format(y=unrouted.id)) return True else: # log the failure app.logger.error(u"Routing - Notification:{y} was not routed".format(y=unrouted.id)) # if config says so, convert the unrouted notification to a failed notification, enhance...
return len(provenance.provenance) > 0 def enhance(routed, metadata): """ Enhance the routed notification with the extracted metadata :param routed: a RoutedNotification whose metadata is to be enhanced :param metadata: a NotificationMetadata object :return: """ # some of the fields a...
trip = False for rc in rc.content_types: for mc in md.content_types: m = exact(rc, mc) if m is True: trip = True provenance.add_provenance("content_types", rc, "content_types", mc, m) if not trip: return Fals...
conditional_block
routing.py
.debug(u"Routing - Notification:{y} successfully routed".format(y=unrouted.id)) return True else: # log the failure app.logger.error(u"Routing - Notification:{y} was not routed".format(y=unrouted.id)) # if config says so, convert the unrouted notification to a failed notification, e...
provenance.add_provenance(repo_property, rval, match_property, mval, m) # if none of the required matches hit, then no need to look at the optional refinements if not matched: return False # do the match refinements # if the configuration specifies a keyword, it must ma...
# convert the values that have matched to string values suitable for provenance rval = repo_property_values.get(repo_property)(rprop) if repo_property in repo_property_values else rprop mval = match_property_values.get(match_property)(mprop) if mat...
random_line_split
routing.py
(u"Routing - Notification:{y} successfully routed".format(y=unrouted.id)) return True else: # log the failure app.logger.error(u"Routing - Notification:{y} was not routed".format(y=unrouted.id)) # if config says so, convert the unrouted notification to a failed notification, enhance...
"name_variants" : { "affiliations" : exact_substring }, "author_emails" : { "emails" : exact }, "author_ids" : { "author_ids" : author_match }, "postcodes" : { "postcodes" : postcode_match }, "grants"...
""" Match the incoming notification data, to the repository config and determine if there is a match. If there is a match, all criteria for the match will be added to the provenance object :param notification_data: models.RoutingMetadata :param repository_config: models.RepositoryConfig ...
identifier_body
routing.py
name matches, add any missing affiliation/identifiers mas = metadata.authors ras = routed.authors for ma in mas: merged = False # first run through all the existing authors, and see if any of them merge for ra in ras: merged = _merge_entities(ra, ma, "name", other_proper...
domain_email
identifier_name
datasets.py
""" Simple datasets to be used for unit tests. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import numpy as np from theano.compat.six.move...
def random_dense_design_matrix(rng, num_examples, dim, num_classes): """ Creates a random dense design matrix that has class labels. Parameters ---------- rng : numpy.random.RandomState The random number generator used to generate the dataset. num_examples : int The number of...
""" A dataset where example i is just the number i. Makes it easy to track which sets of examples are visited. Parameters ---------- num_examples : WRITEME To see the other parameters, look at the DenseDesignMatrix class documentation """ def __init__(self, num_examples, *args, **kw...
identifier_body
datasets.py
""" Simple datasets to be used for unit tests. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import numpy as np from theano.compat.six.move...
(self, num_examples, *args, **kwargs): X = np.zeros((num_examples, 1)) X[:, 0] = np.arange(num_examples) super(ArangeDataset, self).__init__(X, *args, **kwargs) def random_dense_design_matrix(rng, num_examples, dim, num_classes): """ Creates a random dense design matrix that has class ...
__init__
identifier_name
datasets.py
""" Simple datasets to be used for unit tests. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import numpy as np from theano.compat.six.move...
return DenseDesignMatrix(X=X, y=Y) def random_one_hot_topological_dense_design_matrix(rng, num_examples, shape, channels, ...
Y[i, idx[i]] = 1
conditional_block
datasets.py
""" Simple datasets to be used for unit tests. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import numpy as np from theano.compat.six.move...
idx = rng.randint(0, num_classes, (num_examples, )) Y = np.zeros((num_examples, num_classes)) for i in xrange(num_examples): Y[i, idx[i]] = 1 return DenseDesignMatrix(X=X, y=Y) def random_one_hot_topological_dense_design_matrix(rng, num_examp...
def random_one_hot_dense_design_matrix(rng, num_examples, dim, num_classes): X = rng.randn(num_examples, dim)
random_line_split
setup.py
from setuptools import setup version = '1.4' testing_extras = ['nose', 'coverage'] docs_extras = ['Sphinx'] setup( name='WebOb', version=version, description="WSGI request and response object", long_description="""\ WebOb provides wrappers around the WSGI request environment, and an object to help c...
"Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], keywords='wsgi request web http', author='Ian Bicking', author_email='ianb@colorstudy.com', maintainer='Pylons Project', url='http://webob.org/', lice...
"Programming Language :: Python :: 3.4",
random_line_split
224621d9edde_timezone_at_metavj_level.py
"""timezone at metavj level Revision ID: 224621d9edde Revises: 14346346596e Create Date: 2015-12-21 16:52:30.275508 """ # revision identifiers, used by Alembic. revision = '224621d9edde' down_revision = '5a590ae95255' from alembic import op import sqlalchemy as sa import geoalchemy2 as ga def upgrade(): op.cr...
op.drop_column(u'vehicle_journey', 'utc_to_local_offset', schema=u'navitia') def downgrade(): op.drop_column(u'meta_vj', 'timezone', schema=u'navitia') op.drop_table('tz_dst', schema='navitia') op.drop_table('timezone', schema='navitia') op.add_column(u'vehicle_journey', sa.Column('utc_to_local_of...
) op.add_column(u'meta_vj', sa.Column('timezone', sa.BIGINT(), nullable=True), schema=u'navitia')
random_line_split
224621d9edde_timezone_at_metavj_level.py
"""timezone at metavj level Revision ID: 224621d9edde Revises: 14346346596e Create Date: 2015-12-21 16:52:30.275508 """ # revision identifiers, used by Alembic. revision = '224621d9edde' down_revision = '5a590ae95255' from alembic import op import sqlalchemy as sa import geoalchemy2 as ga def upgrade(): op.cr...
(): op.drop_column(u'meta_vj', 'timezone', schema=u'navitia') op.drop_table('tz_dst', schema='navitia') op.drop_table('timezone', schema='navitia') op.add_column(u'vehicle_journey', sa.Column('utc_to_local_offset', sa.BIGINT(), nullable=True), schema=u'navitia')
downgrade
identifier_name
224621d9edde_timezone_at_metavj_level.py
"""timezone at metavj level Revision ID: 224621d9edde Revises: 14346346596e Create Date: 2015-12-21 16:52:30.275508 """ # revision identifiers, used by Alembic. revision = '224621d9edde' down_revision = '5a590ae95255' from alembic import op import sqlalchemy as sa import geoalchemy2 as ga def upgrade(): op.cr...
op.drop_column(u'meta_vj', 'timezone', schema=u'navitia') op.drop_table('tz_dst', schema='navitia') op.drop_table('timezone', schema='navitia') op.add_column(u'vehicle_journey', sa.Column('utc_to_local_offset', sa.BIGINT(), nullable=True), schema=u'navitia')
identifier_body
property_get.ts
/** @module @ember/object */ import { descriptorFor } from '@ember/-internals/meta'; import { HAS_NATIVE_PROXY, symbol } from '@ember/-internals/utils'; import { EMBER_METAL_TRACKED_PROPERTIES } from '@ember/canary-features'; import { assert } from '@ember/debug'; import { DEBUG } from '@glimmer/env'; import { isPath }...
(obj: object, keyName: string): any { assert( `Get must be called with two arguments; an object and a property key`, arguments.length === 2 ); assert( `Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null ); assert( `The key provided to get must be ...
get
identifier_name
property_get.ts
/** @module @ember/object */ import { descriptorFor } from '@ember/-internals/meta'; import { HAS_NATIVE_PROXY, symbol } from '@ember/-internals/utils'; import { EMBER_METAL_TRACKED_PROPERTIES } from '@ember/canary-features'; import { assert } from '@ember/debug'; import { DEBUG } from '@glimmer/env'; import { isPath }...
let isObject = type === 'object'; let isFunction = type === 'function'; let isObjectLike = isObject || isFunction; let value: any; if (isObjectLike) { if (EMBER_METAL_TRACKED_PROPERTIES) { let tracker = getCurrentTracker(); if (tracker) tracker.add(tagForProperty(obj, keyName)); } l...
{ assert( `Get must be called with two arguments; an object and a property key`, arguments.length === 2 ); assert( `Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null ); assert( `The key provided to get must be a string or number, you passed ${key...
identifier_body
property_get.ts
/** @module @ember/object */ import { descriptorFor } from '@ember/-internals/meta'; import { HAS_NATIVE_PROXY, symbol } from '@ember/-internals/utils'; import { EMBER_METAL_TRACKED_PROPERTIES } from '@ember/canary-features'; import { assert } from '@ember/debug'; import { DEBUG } from '@glimmer/env'; import { isPath }...
else { value = obj[keyName]; } if (value === undefined) { if (isPath(keyName)) { return _getPath(obj, keyName); } if ( isObject && !(keyName in obj) && typeof (obj as MaybeHasUnknownProperty).unknownProperty === 'function' ) { return (obj as MaybeHasUnknownPropert...
{ if (EMBER_METAL_TRACKED_PROPERTIES) { let tracker = getCurrentTracker(); if (tracker) tracker.add(tagForProperty(obj, keyName)); } let descriptor = descriptorFor(obj, keyName); if (descriptor !== undefined) { return descriptor.get(obj, keyName); } if (DEBUG && HAS_NATIVE_PR...
conditional_block
property_get.ts
/** @module @ember/object */ import { descriptorFor } from '@ember/-internals/meta'; import { HAS_NATIVE_PROXY, symbol } from '@ember/-internals/utils'; import { EMBER_METAL_TRACKED_PROPERTIES } from '@ember/canary-features'; import { assert } from '@ember/debug'; import { DEBUG } from '@glimmer/env'; import { isPath }...
assert( `'this' in paths is not supported`, typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0 ); let type = typeof obj; let isObject = type === 'object'; let isFunction = type === 'function'; let isObjectLike = isObject || isFunction; let value: any; if (isObjectLike) { ...
random_line_split
HorizontalLine.js
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, } from 'react-native'; const propTypes = { bottom: PropTypes.number.isRequired, displayText: PropTypes.string, color: PropTypes.string, opacity: PropTypes.number, width: PropTypes.number.isRequired
}; class HorizontalLine extends React.Component { render() { const { color, opacity, bottom, displayText, width } = this.props; return ( <View style={{ opacity: opacity, backgroundColor: 'transparent', width: wi...
}; const defaultProps = { color: 'gray', opacity: .7
random_line_split
HorizontalLine.js
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, } from 'react-native'; const propTypes = { bottom: PropTypes.number.isRequired, displayText: PropTypes.string, color: PropTypes.string, opacity: PropTypes.number, width: PropTypes.number.isRequired }; c...
extends React.Component { render() { const { color, opacity, bottom, displayText, width } = this.props; return ( <View style={{ opacity: opacity, backgroundColor: 'transparent', width: width, ...
HorizontalLine
identifier_name
markdown-to-jsx-tests.tsx
import Markdown, { compiler } from 'markdown-to-jsx'; import * as React from 'react'; import { render } from 'react-dom'; render(<Markdown># Hello world!</Markdown>, document.body); <Markdown options={{ forceBlock: true }}>Hello there old chap!</Markdown>; compiler('Hello there old chap!', { forceBlock: true }); <Ma...
} render( <Markdown options={{ overrides: { h1: { component: MyParagraph, props: { className: 'foo', }, }, h2: { component: 'div', ...
{ let width: string | undefined; let height: string | undefined; if (this.props.size) { width = `${this.props.size}px`; height = `${this.props.size}px`; } return <img alt={this.props.alt} src={this.props.src} width={width} height={height} />; }
identifier_body
markdown-to-jsx-tests.tsx
import Markdown, { compiler } from 'markdown-to-jsx'; import * as React from 'react'; import { render } from 'react-dom'; render(<Markdown># Hello world!</Markdown>, document.body); <Markdown options={{ forceBlock: true }}>Hello there old chap!</Markdown>; compiler('Hello there old chap!', { forceBlock: true }); <Ma...
() { let width: string | undefined; let height: string | undefined; if (this.props.size) { width = `${this.props.size}px`; height = `${this.props.size}px`; } return <img alt={this.props.alt} src={this.props.src} width={width} height={height} />; } } i...
render
identifier_name
markdown-to-jsx-tests.tsx
import Markdown, { compiler } from 'markdown-to-jsx'; import * as React from 'react'; import { render } from 'react-dom'; render(<Markdown># Hello world!</Markdown>, document.body); <Markdown options={{ forceBlock: true }}>Hello there old chap!</Markdown>; compiler('Hello there old chap!', { forceBlock: true }); <Ma...
alt?: string; size?: number; } const MySquareImage = (props: MySquareImageProps) => { let width: string | undefined; let height: string | undefined; if (props.size) { width = `${props.size}px`; height = `${props.size}px`; } return <img alt={props.alt} src={props.src} width={...
const MyParagraph: React.SFC = ({ children, ...props }) => <div {...props}>{children}</div>; interface MySquareImageProps { src: string;
random_line_split
markdown-to-jsx-tests.tsx
import Markdown, { compiler } from 'markdown-to-jsx'; import * as React from 'react'; import { render } from 'react-dom'; render(<Markdown># Hello world!</Markdown>, document.body); <Markdown options={{ forceBlock: true }}>Hello there old chap!</Markdown>; compiler('Hello there old chap!', { forceBlock: true }); <Ma...
return <img alt={props.alt} src={props.src} width={width} height={height} />; }; interface MyStatelessRoundImageProps { src: string; alt?: string; size?: number; } class MyStatelessRoundImage extends React.Component<MyStatelessRoundImageProps> { render() { let width: string | undefined; ...
{ width = `${props.size}px`; height = `${props.size}px`; }
conditional_block