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 |
|---|---|---|---|---|
group-types-panel.module.ts | import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import {
WidgetsModule
} from 'ngx-widgets';
import { TruncateModule } from 'ng2-truncate';
import { TooltipModule } from 'ngx-boots... | TooltipModule.forRoot(),
InfotipModule,
TruncateModule,
WidgetsModule,
IterationModule,
RouterModule
],
declarations: [
GroupTypesComponent
],
exports: [GroupTypesComponent],
providers: [GroupTypesService]
})
export class GroupTypesModule { } | ModalModule, | random_line_split |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... |
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
... | {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
} | identifier_body |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... | for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\n\r\n{}", response.body);
}
fn save_to_file(response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path()... |
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
| random_line_split |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... | (response: &Response, path: &str) {
let mut file = match File::create(path) {
Ok(file) => file,
Err(_) => {
errors::invalid_save_path();
process::exit(0);
}
};
let content = response.as_str();
match file.write_all(content.as_bytes()) {
Ok(_) => p... | save_to_file | identifier_name |
sender.rs | extern crate knock;
use std::process;
use Request;
use errors;
use self::knock::*;
use std::fs::File;
use std::io::Write;
use self::knock::response::Response;
pub fn send(request: self::Request, path: &str) {
let mut http = match HTTP::new(&request.url) {
Ok(http) => http,
Err(_) => {
... |
}
Err(_) => {
errors::invalid_response();
process::exit(0);
}
}
}
fn print_response(response: &Response) {
println!("Status: {}\r\n", response.status);
for (key, val) in response.header.iter() {
println!("{}: {}", key, val);
}
println!("\r\... | {
save_to_file(&response, path);
} | conditional_block |
er.js | var erbium = require('./build/Release/erbium');
//var pkt = new erbium.Erbium(new Buffer([0x60,0x45,0x04,0xd2,0xc2,0x00,0x00,0xff,0x68,0x65,0x6c,0x6c,0x6f]));
var pkt = new erbium.Erbium(new Buffer([0x50,0x01,0xe0,0xd6,0x33,0x6d,0x62,0x6b,0x85,0x68,0x65,0x6c,0x6c,0x6f]));
console.log(pkt.getHeaderUriPath().toString()... | console.log("urihost", obj.getHeaderUriHost());
obj.setHeaderUriHost("server.com");
console.log("urihost", obj.getHeaderUriHost());
console.log("uripath", obj.getHeaderUriPath());
console.log(obj.setHeaderUriPath("/bob"));
console.log("uripath", obj.getHeaderUriPath());
*/
console.log("uriquery", obj.getHeaderUriQuery... | //console.log("proxyuri", obj.getHeaderProxyUri());
| random_line_split |
output-path_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Architect } from '@angular-devkit/architect';
import { getSystemPath, join, virtualFs } from '@angular-devk... | await host.delete(join(host.root(), 'src', 'app', 'app.component.ts')).toPromise();
const run = await architect.scheduleTarget(target);
const output = await run.result;
expect(output.success).toBe(false);
expect(await host.exists(join(host.root(), 'dist')).toPromise()).toBe(false);
expect(await... |
// Delete an app file to force a failed compilation.
// Failed compilations still delete files, but don't output any. | random_line_split |
test_finite_field.py | from crpyto_tool.libs.finite_field_op import FiniteFieldNumber
if __name__ == '__main__':
| magical_number = FiniteFieldNumber(FiniteFieldNumber.magical_number, False)
print 'p(x): ' + str(magical_number)
number2 = FiniteFieldNumber('0')
number3 = FiniteFieldNumber('1000110')
print 'Q5-(1):' + str(number2 - number3)
number0 = FiniteFieldNumber('1000110')
number1 = FiniteFieldNumber('... | conditional_block | |
test_finite_field.py | from crpyto_tool.libs.finite_field_op import FiniteFieldNumber
if __name__ == '__main__':
magical_number = FiniteFieldNumber(FiniteFieldNumber.magical_number, False)
print 'p(x): ' + str(magical_number) |
number0 = FiniteFieldNumber('1000110')
number1 = FiniteFieldNumber('10001011')
print 'Q5-(2):' + str(number0 + number1)
print 'Q5-(3):' + str(number0 * number1)
number4 = FiniteFieldNumber('10000111111010')
print number4 / magical_number
print FiniteFieldNumber('11110101') * FiniteFieldN... |
number2 = FiniteFieldNumber('0')
number3 = FiniteFieldNumber('1000110')
print 'Q5-(1):' + str(number2 - number3) | random_line_split |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y |
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable borrowed content `*z` as mutable
println!("{} {}",*z,z);
//reference:
let x = 5;
let y = &x;
println!("{}", *y);
print... | {
println!("{:p} {} {}",z,*z, z);
} | conditional_block |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow imm... | println!("{}", succ(&*x));
println!("{}", succ(&*x));
println!("{}", succ(&*x));
//recursive data structure
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
println!("{:?}", list);
let x = &mut 5;
if *x < 10 {
let y = ... |
//boxes:
let x = Box::new(5);//Boxes are appropriate to use in two situations: Recursive data structures, and occasionally, when returning data. | random_line_split |
main.rs | fn | () {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow immutable ... | main | identifier_name |
main.rs | fn main() {
println!("Hello, world!");
let x = 5;
let y = 8;
let z = &y;
if *z == y {
println!("{:p} {} {}",z,*z, z);
}
let mut i: i32 = 1;
// foo(&mut i);//error: cannot borrow immutable borrowed content `*z` as mutable
let z=&mut i;
foo(z);//error: cannot borrow imm... | { x + 1 } | identifier_body | |
create_treasures_json.py | #!/usr/bin/python
import json
f = file('treasures.json', 'r')
try:
foo = json.load(f)
json_contents = foo
except ValueError:
json_contents = dict()
f.close()
print 'Type \'q\' to [q]uit'
while True:
name = raw_input('Treasure Name: ')
if name == 'q':
break
print 'Type \'n\' to stop e... |
json_contents[name] = set_contents
if hero == 'q':
break
f = open('treasures.json', 'w')
json.dump(json_contents, f, indent=4)
f.close() | bundle_rating = raw_input('Item set rating [1-3]: ')
set_contents[hero] = bundle_rating | conditional_block |
create_treasures_json.py | #!/usr/bin/python
import json
f = file('treasures.json', 'r')
try:
foo = json.load(f)
json_contents = foo
except ValueError:
json_contents = dict()
f.close()
print 'Type \'q\' to [q]uit'
while True:
name = raw_input('Treasure Name: ')
if name == 'q':
break | hero = raw_input('Hero name: ')
if hero == 'n' or hero == 'q':
break
else:
bundle_rating = raw_input('Item set rating [1-3]: ')
set_contents[hero] = bundle_rating
json_contents[name] = set_contents
if hero == 'q':
break
f = open('treasures.jso... | print 'Type \'n\' to stop entering heroes and go to [n]ext treasure'
set_contents = dict()
hero = ''
while True: | random_line_split |
decorators.py | from __future__ import absolute_import, division, print_function, unicode_literals
from django.contrib.auth.decorators import user_passes_test
from django_otp import user_has_device
from django_otp.conf import settings
def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False):
... | (user):
return user.is_verified() or (if_configured and user.is_authenticated() and not user_has_device(user))
decorator = user_passes_test(test, login_url=login_url, redirect_field_name=redirect_field_name)
return decorator if (view is None) else decorator(view)
| test | identifier_name |
decorators.py | from __future__ import absolute_import, division, print_function, unicode_literals
from django.contrib.auth.decorators import user_passes_test
from django_otp import user_has_device
from django_otp.conf import settings
def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False):
... |
def test(user):
return user.is_verified() or (if_configured and user.is_authenticated() and not user_has_device(user))
decorator = user_passes_test(test, login_url=login_url, redirect_field_name=redirect_field_name)
return decorator if (view is None) else decorator(view)
| login_url = settings.OTP_LOGIN_URL | conditional_block |
decorators.py | from __future__ import absolute_import, division, print_function, unicode_literals
from django.contrib.auth.decorators import user_passes_test
from django_otp import user_has_device
from django_otp.conf import settings
|
def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False):
"""
Similar to :func:`~django.contrib.auth.decorators.login_required`, but
requires the user to be :term:`verified`. By default, this redirects users
to :setting:`OTP_LOGIN_URL`.
:param if_configured: If ... | random_line_split | |
decorators.py | from __future__ import absolute_import, division, print_function, unicode_literals
from django.contrib.auth.decorators import user_passes_test
from django_otp import user_has_device
from django_otp.conf import settings
def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False):
... | """
Similar to :func:`~django.contrib.auth.decorators.login_required`, but
requires the user to be :term:`verified`. By default, this redirects users
to :setting:`OTP_LOGIN_URL`.
:param if_configured: If ``True``, an authenticated user with no confirmed
OTP devices will be allowed. Default is `... | identifier_body | |
tendermint.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
| {
let s = r#"{
"params": {
"gasLimitBoundDivisor": "0x0400",
"validators": {
"list": ["0xc6d9d2cd449a754c494264e1809c50e34d64562b"]
},
"blockReward": "0x50"
}
}"#;
let deserialized: Tendermint = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.gas_limit_bound_divisor,... | identifier_body |
tendermint.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | mod tests {
use serde_json;
use uint::Uint;
use util::U256;
use hash::Address;
use util::hash::H160;
use spec::tendermint::Tendermint;
use spec::validator_set::ValidatorSet;
#[test]
fn tendermint_deserialization() {
let s = r#"{
"params": {
"gasLimitBoundDivisor": "0x0400",
"validators": {
"... |
#[cfg(test)] | random_line_split |
tendermint.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
/// Gas limit divisor.
#[serde(rename="gasLimitBoundDivisor")]
pub gas_limit_bound_divisor: Uint,
/// Valid validators.
pub validators: ValidatorSet,
/// Propose step timeout in milliseconds.
#[serde(rename="timeoutPropose")]
pub timeout_propose: Option<Uint>,
/// Prevote step timeout in milliseconds.
#[se... | TendermintParams | identifier_name |
teamspaces.contants.ts | /**
* Copyright (C) 2017 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This pro... | { value: 'Other' }
];
export const TEAMSPACE_FILTER_RELATED_FIELDS = {
DATA_TYPE: 'type',
MODEL_TYPE: 'modelType',
MODEL_CODE: 'code'
};
export const TEAMSPACES_FILTERS = [
{
label: 'By model type',
relatedField: TEAMSPACE_FILTER_RELATED_FIELDS.MODEL_TYPE,
type: FILTER_TYPES.UNDEFINED
},
{
label: 'By m... | { value: 'Survey' }, | random_line_split |
local-modularized-tricky-pass-2.rs | // check-pass
//
// `#[macro_export] macro_rules` that doesn't originate from macro expansions can be placed
// into the root module soon enough to act as usual items and shadow globs and preludes.
#![feature(decl_macro)]
// `macro_export` shadows globs
use inner1::*;
mod inner1 {
pub macro exported() {}
}
expo... |
mod inner3 {
#[macro_export]
macro_rules! panic {
() => ( struct Г; )
}
}
// `macro_export` shadows builtin macros
include!();
mod inner4 {
#[macro_export]
macro_rules! include {
() => ( struct Д; )
}
}
|
panic!();
}
| identifier_body |
local-modularized-tricky-pass-2.rs | // check-pass
//
// `#[macro_export] macro_rules` that doesn't originate from macro expansions can be placed
// into the root module soon enough to act as usual items and shadow globs and preludes.
#![feature(decl_macro)]
// `macro_export` shadows globs
use inner1::*;
mod inner1 {
pub macro exported() {}
}
expo... | () {
type Deeper = [u8; {
#[macro_export]
macro_rules! exported {
() => ( struct Б; )
}
0
}];
}
}
// `macro_export` shadows std prelude
fn main() {
panic!();
}
mod inner3 {
#[macro_export]
macro_rules! panic {
() ... | deep | identifier_name |
local-modularized-tricky-pass-2.rs | // check-pass
//
// `#[macro_export] macro_rules` that doesn't originate from macro expansions can be placed
// into the root module soon enough to act as usual items and shadow globs and preludes.
| // `macro_export` shadows globs
use inner1::*;
mod inner1 {
pub macro exported() {}
}
exported!();
mod deep {
fn deep() {
type Deeper = [u8; {
#[macro_export]
macro_rules! exported {
() => ( struct Б; )
}
0
}];
}
}
// `macr... | #![feature(decl_macro)]
| random_line_split |
boxlift_api.py | import json
# This is to keep this imports to a minimum and work on
# Python 2.x and 3.x
try:
import urllib.request as urllib2
except ImportError:
import urllib2
PYCON2016_EVENT_NAME = 'pycon2016'
class Command(object):
def __init__(self, id, direction, speed):
"""A command to an elevator
... | (self, commands=None):
"""Send commands to advance the clock. Returns the new state of
the world.
:param commands:
list of commands to elevators. If no commands are sent the
clock does not advance.
:type commands:
`iterable` of `Command`
:retu... | send_commands | identifier_name |
boxlift_api.py | import json
# This is to keep this imports to a minimum and work on
# Python 2.x and 3.x
try:
import urllib.request as urllib2
except ImportError:
import urllib2
PYCON2016_EVENT_NAME = 'pycon2016'
class Command(object):
def __init__(self, id, direction, speed):
"""A command to an elevator
... |
else:
print('no token this turn')
if 'requests' not in state:
state['requests'] = []
for elevator_data in state.get('elevators', []):
if 'buttons_pressed' not in elevator_data:
elevator_data['buttons_pressed'] = []
return state
@... | self.token = state['token'] | conditional_block |
boxlift_api.py | import json
# This is to keep this imports to a minimum and work on
# Python 2.x and 3.x
try:
import urllib.request as urllib2
except ImportError:
import urllib2
PYCON2016_EVENT_NAME = 'pycon2016'
class Command(object):
def __init__(self, id, direction, speed):
"""A command to an elevator
... | state = self._post(self.building_url, data)
print("status: {}".format(state['status']))
if state['status'].lower() == 'error':
print("message: {}".format(state['message']))
if 'token' in state:
self.token = state['token']
else:
print('no token ... | 'speed': command.speed, 'direction': command.direction
}
data = {'token': self.token, 'commands': command_list} | random_line_split |
boxlift_api.py | import json
# This is to keep this imports to a minimum and work on
# Python 2.x and 3.x
try:
import urllib.request as urllib2
except ImportError:
import urllib2
PYCON2016_EVENT_NAME = 'pycon2016'
class Command(object):
def __init__(self, id, direction, speed):
"""A command to an elevator
... | state = self._post(self.building_url, data)
print("status: {}".format(state['status']))
if state['status'].lower() == 'error':
print("message: {}".format(state['message']))
if 'token' in state:
self.token = state['token']
else:
print('no token ... | """Send commands to advance the clock. Returns the new state of
the world.
:param commands:
list of commands to elevators. If no commands are sent the
clock does not advance.
:type commands:
`iterable` of `Command`
:return:
The new state o... | identifier_body |
interactive.js | // =SECTION Setup
// Local config overrides
var config = localStorage.getItem("interactiveOverrides");
if (config) {
config = JSON.parse(config);
window.TogetherJSConfig = config;
for (var a in config) {
TogetherJS.config(a, config[a]);
}
}
Test.require("ui", "chat", "util", "session", "jquery", "storage"... | (seq) {
if (! seq) {
seq = peers.getAllPeers(true);
}
return seq[Math.floor(Math.random() * seq.length)];
}
addPeer();
// => ...
// =SECTION Controls
Test.addControl(
$("<button>Animate in cursor/box</button>").click(function () {
//$(".togetherjs-cursor").fadeOut();
}),
$("<button>Animate out ... | pick | identifier_name |
interactive.js | // =SECTION Setup
// Local config overrides
var config = localStorage.getItem("interactiveOverrides");
if (config) {
config = JSON.parse(config);
window.TogetherJSConfig = config;
for (var a in config) {
TogetherJS.config(a, config[a]);
}
}
Test.require("ui", "chat", "util", "session", "jquery", "storage"... |
}));
| {
TogetherJS.config("toolName", el.val() || null);
el.val("");
} | conditional_block |
interactive.js | // =SECTION Setup
// Local config overrides
var config = localStorage.getItem("interactiveOverrides");
if (config) {
config = JSON.parse(config);
window.TogetherJSConfig = config;
for (var a in config) {
TogetherJS.config(a, config[a]);
}
}
Test.require("ui", "chat", "util", "session", "jquery", "storage"... | clientId: id
});
Test.incoming({
type: "scroll-update",
clientId: id,
position: {
location: "body",
offset: 20,
absoluteTop: 20,
documentHeight: $(document).height()
}
});
}
function pick(seq) {
if (! seq) {
seq = peers.getAllPeers(true);
}
return seq[Math.f... | {
var name = "Faker";
if (id) {
name += " " + id;
}
id = id || 'faker';
var color = "#" + Math.floor(Math.random() * 0xffffff).toString(16);
Test.newPeer({
name: name,
color: color,
clientId: id
});
var len = peers.getAllPeers().length;
var pageHeight = $(document).height();
var left... | identifier_body |
interactive.js | // =SECTION Setup
// Local config overrides
var config = localStorage.getItem("interactiveOverrides");
if (config) {
config = JSON.parse(config);
window.TogetherJSConfig = config;
for (var a in config) {
TogetherJS.config(a, config[a]);
}
}
Test.require("ui", "chat", "util", "session", "jquery", "storage"... | if (focused[peer.id]) {
Test.incoming({
type: "form-focus",
element: null,
clientId: peer.id,
url: peer.url
});
focused[peer.id] = null;
return;
}
var els = $("#controls textarea:visible, #controls input:visible, #controls select:visible");
var el = $(els[Math.floor(els.... |
var focused = {};
Test.addControl($('<button>Focus something</button>').click(function () {
var peer = pick(); | random_line_split |
gallery_upload.js | // Product gallery file uploads
jQuery( function( $ ){
var product_gallery_frame;
var $image_gallery_ids = $('#product_image_gallery');
var $product_images = $('#product_images_container ul.product_images');
jQuery('.add_product_images').on( 'click', 'a', function( event ) {
var $el = $(this);
var attachment_i... | product_gallery_frame = wp.media.frames.product_gallery = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
button: {
text: $el.data('update'),
},
states : [
new wp.media.controller.Library({
title: $el.data('choose'),
filterable : 'all',
multiple: true,
})... |
// Create the media frame. | random_line_split |
gallery_upload.js | // Product gallery file uploads
jQuery( function( $ ){
var product_gallery_frame;
var $image_gallery_ids = $('#product_image_gallery');
var $product_images = $('#product_images_container ul.product_images');
jQuery('.add_product_images').on( 'click', 'a', function( event ) {
var $el = $(this);
var attachment_i... |
});
$image_gallery_ids.val( attachment_ids );
});
// Finally, open the modal.
product_gallery_frame.open();
});
// Image ordering
$product_images.sortable({
items: 'li.image',
cursor: 'move',
scrollSensitivity:40,
forcePlaceholderSize: true,
forceHelperSize: false,
helper: 'clone',
opa... | {
attachment_ids = attachment_ids ? attachment_ids + "," + attachment.id : attachment.id;
attachment_image = attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
$product_images.append('\
<li class="image" data-attachment_id="' + attachment.id + '">\
<img src="' +... | conditional_block |
helpscreen.js | var Screen = require('./basescreen');
var Game = require('../game');
var helpScreen = new Screen('Help');
// Define our winning screen
helpScreen.render = function (display) {
var text = 'jsrogue help';
var border = '-------------';
var y = 0;
display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++,... |
helpScreen.handleInput = function (inputType, inputData) {
// Switch back to the play screen.
this.getParentScreen().setSubScreen(undefined);
};
module.exports = helpScreen; | random_line_split | |
inspector_timeline.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import timeline_recorder
from telemetry.timeline import inspector_timeline_data
class TabBackendException(Exception):
... | (self):
"""Handler called when a domain is unregistered."""
pass
| _OnClose | identifier_name |
inspector_timeline.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import timeline_recorder
from telemetry.timeline import inspector_timeline_data
class TabBackendException(Exception):
... |
return response['result']
def _OnNotification(self, msg):
"""Handler called when a message is received."""
# Since 'Timeline.start' was invoked with the 'bufferEvents' parameter,
# there will be no timeline notifications while recording.
pass
def _OnClose(self):
"""Handler called when a d... | raise TabBackendException(response['error']['message']) | conditional_block |
inspector_timeline.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import timeline_recorder
from telemetry.timeline import inspector_timeline_data
class TabBackendException(Exception):
... |
def __enter__(self):
self._tab.StartTimelineRecording()
def __exit__(self, *args):
self._tab.StopTimelineRecording()
def __init__(self, inspector_backend):
super(InspectorTimeline, self).__init__()
self._inspector_backend = inspector_backend
self._is_recording = False
@property
... | self._tab = tab | identifier_body |
inspector_timeline.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import timeline_recorder
from telemetry.timeline import inspector_timeline_data
class TabBackendException(Exception):
... | return None
request = {'method': 'Timeline.stop'}
result = self._SendSyncRequest(request)
self._inspector_backend.UnregisterDomain('Timeline')
self._is_recording = False
raw_events = result['events']
return inspector_timeline_data.InspectorTimelineData(raw_events)
def _SendSyncRequest(... | if not self._is_recording: | random_line_split |
set_map_velocity.rs | use specs::{ReadStorage, System, WriteStorage};
use crate::campaign::components::MapIntent;
use crate::campaign::components::map_intent::{MapCommand, XAxis, YAxis};
use crate::combat::components::{Velocity};
pub struct SetMapVelocity;
impl<'a> System<'a> for SetMapVelocity {
type SystemData = (ReadStorage<'a, Ma... | }
} | random_line_split | |
set_map_velocity.rs | use specs::{ReadStorage, System, WriteStorage};
use crate::campaign::components::MapIntent;
use crate::campaign::components::map_intent::{MapCommand, XAxis, YAxis};
use crate::combat::components::{Velocity};
pub struct | ;
impl<'a> System<'a> for SetMapVelocity {
type SystemData = (ReadStorage<'a, MapIntent>, WriteStorage<'a, Velocity>);
fn run(&mut self, (intent, mut velocity): Self::SystemData) {
use specs::Join;
for (intent, velocity) in (&intent, &mut velocity).join() {
match intent.command {
... | SetMapVelocity | identifier_name |
set_map_velocity.rs | use specs::{ReadStorage, System, WriteStorage};
use crate::campaign::components::MapIntent;
use crate::campaign::components::map_intent::{MapCommand, XAxis, YAxis};
use crate::combat::components::{Velocity};
pub struct SetMapVelocity;
impl<'a> System<'a> for SetMapVelocity {
type SystemData = (ReadStorage<'a, Ma... | }
}
| {
use specs::Join;
for (intent, velocity) in (&intent, &mut velocity).join() {
match intent.command {
MapCommand::Move { x, y } => {
if x == XAxis::Centre && y == YAxis::Centre {
velocity.x = 0;
velocity.y =... | identifier_body |
tool.py | #!/usr/bin/env python
import os
import sys
import inspect
from functools import update_wrapper
import getpass
import copy
import click
import signals
from .config_reader import read_config
from .utils import version, dict_merge
from .defaults import DEFAULT_CONFIG
# add fixture feature to pocoo-click
def _make_comm... | help = help.decode('utf-8')
else:
help = inspect.cleandoc(help)
attrs['help'] = help
click.decorators._check_for_unicode_literals()
return cls(name=name or new_func.__name__.lower(),
callback=new_func, params=params, **attrs)
# patch in the custom command maker
click.... | params = []
help = attrs.get('help')
if help is None:
help = inspect.getdoc(f)
if isinstance(help, bytes): | random_line_split |
tool.py | #!/usr/bin/env python
import os
import sys
import inspect
from functools import update_wrapper
import getpass
import copy
import click
import signals
from .config_reader import read_config
from .utils import version, dict_merge
from .defaults import DEFAULT_CONFIG
# add fixture feature to pocoo-click
def | (f, name, attrs, cls):
if isinstance(f, click.Command):
raise TypeError('Attempted to convert a callback into a '
'command twice.')
new_func = f
if 'fixture' in attrs:
fixture = attrs['fixture']
if not inspect.isgeneratorfunction(fixture):
raise Ty... | _make_command | identifier_name |
tool.py | #!/usr/bin/env python
import os
import sys
import inspect
from functools import update_wrapper
import getpass
import copy
import click
import signals
from .config_reader import read_config
from .utils import version, dict_merge
from .defaults import DEFAULT_CONFIG
# add fixture feature to pocoo-click
def _make_comm... | dict_merge(tool_config, config[context['tool']])
# TODO lookups
# run the command and provide context and config
signals.command_init.send((context, tool_config))
yield context, tool_config
signals.command_finalized.send((context, tool_config))
signals.finalized.send(context)
| """Tool lifecycle which provides hooks into the different stages of the
command execution. See signals for hook details.
"""
context = _get_context()
signals.initialized.send(context)
config, ok = read_config(context, DEFAULT_CONFIG)
if not ok:
signals.exit_on_error.send(context)
... | identifier_body |
tool.py | #!/usr/bin/env python
import os
import sys
import inspect
from functools import update_wrapper
import getpass
import copy
import click
import signals
from .config_reader import read_config
from .utils import version, dict_merge
from .defaults import DEFAULT_CONFIG
# add fixture feature to pocoo-click
def _make_comm... |
attrs.pop('fixture')
def new_func(*args, **kwargs):
it = fixture()
val = next(it)
res = f(val, *args[1:], **kwargs)
try:
next(it)
except StopIteration:
pass
else:
raise RuntimeError(... | raise TypeError('fixture does not yield anything.') | conditional_block |
decode.rs | // Claxon -- A FLAC decoding library in Rust
// Copyright 2015 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This file implements a... | () {
let mut no_args = true;
for fname in env::args().skip(1) {
no_args = false;
print!("{}", fname);
decode_file(&Path::new(&fname));
println!(": done");
}
if no_args {
println!("no files to decode");
}
}
| main | identifier_name |
decode.rs | // Claxon -- A FLAC decoding library in Rust
// Copyright 2015 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This file implements a... | let mut wav_writer = WavWriter::create(fname_wav, spec).expect("failed to create wav file");
let mut frame_reader = reader.blocks();
let mut block = Block::empty();
loop {
// Read a single frame. Recycle the buffer from the previous frame to
// avoid allocations as much as possible.
... | bits_per_sample: reader.streaminfo().bits_per_sample as u16,
sample_format: hound::SampleFormat::Int,
};
let fname_wav = fname.with_extension("wav"); | random_line_split |
decode.rs | // Claxon -- A FLAC decoding library in Rust
// Copyright 2015 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This file implements a... | // Read a single frame. Recycle the buffer from the previous frame to
// avoid allocations as much as possible.
match frame_reader.read_next_or_eof(block.into_buffer()) {
Ok(Some(next_block)) => block = next_block,
Ok(None) => break, // EOF.
Err(error) => pani... | {
let mut reader = FlacReader::open(fname).expect("failed to open FLAC stream");
// TODO: Write fallback for other sample widths and channel numbers.
assert!(reader.streaminfo().bits_per_sample == 16);
assert!(reader.streaminfo().channels == 2);
let spec = WavSpec {
channels: reader.stream... | identifier_body |
extract_to_srv.py |
# small script for
from optparse import OptionParser
import sqlite3
import time
import string
import arnovich.core as core
def parse_command_args():
parser = OptionParser()
parser.add_option("-t", "--ticker", action="append", type="string", dest="tickers")
parser.add_option("--from", action="store", type="string... |
if __name__ == "__main__":
main()
| (dbfile, tickers, fromdate, todate, wait) = parse_command_args()
find_dates(dbfile, tickers, fromdate, todate, wait) | identifier_body |
extract_to_srv.py |
# small script for
from optparse import OptionParser
import sqlite3
import time
import string
import arnovich.core as core
def | ():
parser = OptionParser()
parser.add_option("-t", "--ticker", action="append", type="string", dest="tickers")
parser.add_option("--from", action="store", type="string", dest="fromdate", default="")
parser.add_option("--to", action="store", type="string", dest="todate", default="")
parser.add_option("--db", acti... | parse_command_args | identifier_name |
extract_to_srv.py | # small script for
from optparse import OptionParser
import sqlite3
import time
import string
import arnovich.core as core
def parse_command_args():
parser = OptionParser() | parser.add_option("--from", action="store", type="string", dest="fromdate", default="")
parser.add_option("--to", action="store", type="string", dest="todate", default="")
parser.add_option("--db", action="store", dest="dbfile")
parser.add_option("--wait", action="store", type="int", dest="wait", default=1)
(opti... |
parser.add_option("-t", "--ticker", action="append", type="string", dest="tickers") | random_line_split |
extract_to_srv.py |
# small script for
from optparse import OptionParser
import sqlite3
import time
import string
import arnovich.core as core
def parse_command_args():
parser = OptionParser()
parser.add_option("-t", "--ticker", action="append", type="string", dest="tickers")
parser.add_option("--from", action="store", type="string... |
else:
d.execute("select date, data from stocks_data where ticker_id="+str(ticker_id[0])+" and (date > "+str(fromtime)+" AND date < "+str(totime)+")")
for r in d:
rowdate = str(r[0])
rowdata = str(r[1])
rowtime = float(r[0])
if prevtime == 0:
prevtime = rowtime
connection.push_ticker(srv_id, r... | d.execute("select date, data from stocks_data where ticker_id="+str(ticker_id[0])+" ORDER BY date") | conditional_block |
dst-tuple.rs | // run-pass
#![allow(type_alias_bounds)]
#![feature(unsized_tuple_coercion)]
type Fat<T: ?Sized> = (isize, &'static str, T);
// x is a fat pointer
fn foo(x: &Fat<[isize]>) {
let y = &x.2;
assert_eq!(x.2.len(), 3);
assert_eq!(y[0], 1);
assert_eq!(x.2[1], 2);
assert_eq!(x.0, 5);
assert_eq!(x.1,... | foo(f5);
// With a vec of Bars.
let bar = Bar;
let f1 = (5, "some str", [bar, bar, bar]);
foo2(&f1);
let f2 = &f1;
foo2(f2);
let f3: &Fat<[Bar]> = f2;
foo2(f3);
let f4: &Fat<[Bar]> = &f1;
foo2(f4);
let f5: &Fat<[Bar]> = &(5, "some str", [bar, bar, bar]);
foo2(f5);
... | random_line_split | |
dst-tuple.rs | // run-pass
#![allow(type_alias_bounds)]
#![feature(unsized_tuple_coercion)]
type Fat<T: ?Sized> = (isize, &'static str, T);
// x is a fat pointer
fn foo(x: &Fat<[isize]>) |
fn foo2<T:ToBar>(x: &Fat<[T]>) {
let y = &x.2;
let bar = Bar;
assert_eq!(x.2.len(), 3);
assert_eq!(y[0].to_bar(), bar);
assert_eq!(x.2[1].to_bar(), bar);
assert_eq!(x.0, 5);
assert_eq!(x.1, "some str");
}
fn foo3(x: &Fat<Fat<[isize]>>) {
let y = &(x.2).2;
assert_eq!(x.0, 5);
a... | {
let y = &x.2;
assert_eq!(x.2.len(), 3);
assert_eq!(y[0], 1);
assert_eq!(x.2[1], 2);
assert_eq!(x.0, 5);
assert_eq!(x.1, "some str");
} | identifier_body |
dst-tuple.rs | // run-pass
#![allow(type_alias_bounds)]
#![feature(unsized_tuple_coercion)]
type Fat<T: ?Sized> = (isize, &'static str, T);
// x is a fat pointer
fn foo(x: &Fat<[isize]>) {
let y = &x.2;
assert_eq!(x.2.len(), 3);
assert_eq!(y[0], 1);
assert_eq!(x.2[1], 2);
assert_eq!(x.0, 5);
assert_eq!(x.1,... | ;
trait ToBar {
fn to_bar(&self) -> Bar;
}
impl ToBar for Bar {
fn to_bar(&self) -> Bar {
*self
}
}
pub fn main() {
// With a vec of ints.
let f1 = (5, "some str", [1, 2, 3]);
foo(&f1);
let f2 = &f1;
foo(f2);
let f3: &Fat<[isize]> = f2;
foo(f3);
let f4: &Fat<[isize... | Bar | identifier_name |
test_bed_common.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Directive, InjectFlags, InjectionToken, NgModule, Pipe, PlatformRef, SchemaMetadata, Type} from '... | (rootElementId: string) {}
}
/**
* @publicApi
*/
export const ComponentFixtureAutoDetect =
new InjectionToken<boolean[]>('ComponentFixtureAutoDetect');
/**
* @publicApi
*/
export const ComponentFixtureNoNgZone = new InjectionToken<boolean[]>('ComponentFixtureNoNgZone');
/**
* @publicApi
*/
export type Test... | insertRootElement | identifier_name |
test_bed_common.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Directive, InjectFlags, InjectionToken, NgModule, Pipe, PlatformRef, SchemaMetadata, Type} from '... | export const ComponentFixtureNoNgZone = new InjectionToken<boolean[]>('ComponentFixtureNoNgZone');
/**
* @publicApi
*/
export type TestModuleMetadata = {
providers?: any[],
declarations?: any[],
imports?: any[],
schemas?: Array<SchemaMetadata|any[]>,
aotSummaries?: () => any[],
};
/**
* Static methods im... | * @publicApi
*/ | random_line_split |
NotificationsView.js | /**
* @license
* Copyright 2015 Google Inc. 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 requir... | }); | random_line_split | |
svgPngExport.tsx | import * as fs from 'fs-extra'
import * as sharp from 'sharp'
import * as path from 'path'
declare var global: any
global.window = { location: { search: "" }}
global.App = { isEditor: false }
global.Global = { rootUrl: "https://ourworldindata.org/grapher" }
require('module-alias').addAliases({
'react' : 'preact-... | {
const chart = new ChartConfig(jsonConfig)
chart.isLocalExport = true
chart.vardata.receiveData(vardata)
const outPath = path.join(outDir, chart.props.slug as string)
return Promise.all([
fs.writeFile(`${outPath}.svg`, chart.staticSVG).then(_ => console.log(`${outPath}.svg`)),
shar... | identifier_body | |
svgPngExport.tsx | import * as fs from 'fs-extra'
import * as sharp from 'sharp'
import * as path from 'path'
declare var global: any
global.window = { location: { search: "" }}
global.App = { isEditor: false }
global.Global = { rootUrl: "https://ourworldindata.org/grapher" }
require('module-alias').addAliases({
'react' : 'preact-... | import ChartConfig, { ChartConfigProps } from '../js/charts/ChartConfig'
export async function bakeImageExports(outDir: string, jsonConfig: ChartConfigProps, vardata: any) {
const chart = new ChartConfig(jsonConfig)
chart.isLocalExport = true
chart.vardata.receiveData(vardata)
const outPath = path.join... | random_line_split | |
svgPngExport.tsx | import * as fs from 'fs-extra'
import * as sharp from 'sharp'
import * as path from 'path'
declare var global: any
global.window = { location: { search: "" }}
global.App = { isEditor: false }
global.Global = { rootUrl: "https://ourworldindata.org/grapher" }
require('module-alias').addAliases({
'react' : 'preact-... | (outDir: string, jsonConfig: ChartConfigProps, vardata: any) {
const chart = new ChartConfig(jsonConfig)
chart.isLocalExport = true
chart.vardata.receiveData(vardata)
const outPath = path.join(outDir, chart.props.slug as string)
return Promise.all([
fs.writeFile(`${outPath}.svg`, chart.stat... | bakeImageExports | identifier_name |
rpath.rs | // Copyright 2012-2015 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... | fn test_minimize1() {
let res = minimize_rpaths(&[
"rpath1".to_string(),
"rpath2".to_string(),
"rpath1".to_string()
]);
assert!(res == [
"rpath1",
"rpath2",
]);
}
#[test]
fn test_minimize2() {
let res = ... | ["-Wl,-rpath,path1",
"-Wl,-rpath,path2"]);
}
#[test] | random_line_split |
rpath.rs | // Copyright 2012-2015 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... | (config: &mut RPathConfig, lib: &Path) -> String {
// Mac doesn't appear to support $ORIGIN
let prefix = if config.is_like_osx {
"@loader_path"
} else {
"$ORIGIN"
};
let cwd = env::current_dir().unwrap();
let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or(cwd.join(lib));
... | get_rpath_relative_to_output | identifier_name |
rpath.rs | // Copyright 2012-2015 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... |
fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
// Mac doesn't appear to support $ORIGIN
let prefix = if config.is_like_osx {
"@loader_path"
} else {
"$ORIGIN"
};
let cwd = env::current_dir().unwrap();
let mut lib = fs::canonicalize(&cwd.join(... | {
libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
} | identifier_body |
scope.js | (function() {
var Scope, extend, last, _ref;
_ref = require('./helpers'), extend = _ref.extend, last = _ref.last;
exports.Scope = Scope = (function() {
Scope.root = null;
function Scope(parent, expressions, method) {
this.parent = parent;
this.expressions = expressions;
t... | Scope.prototype.type = function(name) {
var v, _i, _len, _ref2;
_ref2 = this.variables;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
v = _ref2[_i];
if (v.name === name) return v.type;
}
return null;
};
Scope.prototype.freeVariable = function(n... | random_line_split | |
scope.js | (function() {
var Scope, extend, last, _ref;
_ref = require('./helpers'), extend = _ref.extend, last = _ref.last;
exports.Scope = Scope = (function() {
Scope.root = null;
function | (parent, expressions, method) {
this.parent = parent;
this.expressions = expressions;
this.method = method;
this.variables = [
{
name: 'arguments',
type: 'arguments'
}
];
this.positions = {};
if (!this.parent) Scope.root = this;
... | Scope | identifier_name |
scope.js | (function() {
var Scope, extend, last, _ref;
_ref = require('./helpers'), extend = _ref.extend, last = _ref.last;
exports.Scope = Scope = (function() {
Scope.root = null;
function Scope(parent, expressions, method) |
Scope.prototype.add = function(name, type, immediate) {
if (this.shared && !immediate) return this.parent.add(name, type, immediate);
if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
return this.variables[this.positions[name]].type = type;
} else {
return ... | {
this.parent = parent;
this.expressions = expressions;
this.method = method;
this.variables = [
{
name: 'arguments',
type: 'arguments'
}
];
this.positions = {};
if (!this.parent) Scope.root = this;
} | identifier_body |
MockPromise.ts | import { TestScheduler } from "./TestScheduler";
import { Record } from "./Record";
import { IObserver } from "../observer/IObserver";
export class MockPromise {
public static create(scheduler: TestScheduler, messages: [Record]) {
var obj = new this(scheduler, messages);
return obj;
}... |
} | {
//var scheduler = <TestScheduler>(this.scheduler);
this._scheduler.setStreamMap(observer, this._messages);
} | identifier_body |
MockPromise.ts | import { TestScheduler } from "./TestScheduler";
import { Record } from "./Record";
import { IObserver } from "../observer/IObserver";
export class MockPromise {
public static create(scheduler: TestScheduler, messages: [Record]) {
var obj = new this(scheduler, messages);
return obj;
}... | // this._messages = messages;
//}
private _scheduler: TestScheduler = null;
constructor(scheduler: TestScheduler, messages: [Record]) {
this._scheduler = scheduler;
this._messages = messages;
}
public then(successCb: Function, errorCb: Function, observer: IObserve... | //}
//set messages(messages:[Record]){
| random_line_split |
MockPromise.ts | import { TestScheduler } from "./TestScheduler";
import { Record } from "./Record";
import { IObserver } from "../observer/IObserver";
export class MockPromise {
public static create(scheduler: TestScheduler, messages: [Record]) {
var obj = new this(scheduler, messages);
return obj;
}... | (successCb: Function, errorCb: Function, observer: IObserver) {
//var scheduler = <TestScheduler>(this.scheduler);
this._scheduler.setStreamMap(observer, this._messages);
}
} | then | identifier_name |
lib.rs | use std::fmt::{Display, Error, Formatter};
pub struct Game {
intended_word: String,
guessed: Vec<CharState>,
}
impl Game {
pub fn new(intended_word: String) -> Game {
let guessed = intended_word.chars().map(|ch| CharState::new(ch, false)).collect();
Game {
intended_word: intend... | }
pub type Guessed = Option<char>;
#[derive(Debug)]
pub struct CurrentProgress {
vec : Vec<Guessed>,
}
impl Display for CurrentProgress {
fn fmt(&self, f : &mut Formatter) -> Result<(), Error> {
let mut result = String::with_capacity(self.vec.len() * 2);
for guess in self.vec.iter() {
... | }
} | random_line_split |
lib.rs | use std::fmt::{Display, Error, Formatter};
pub struct Game {
intended_word: String,
guessed: Vec<CharState>,
}
impl Game {
pub fn new(intended_word: String) -> Game {
let guessed = intended_word.chars().map(|ch| CharState::new(ch, false)).collect();
Game {
intended_word: intend... | {
ch : char,
is_guessed : bool,
}
impl CharState {
fn new(ch : char, is_guessed : bool) -> CharState {
CharState {
ch : ch,
is_guessed : is_guessed,
}
}
fn to_enum(&self) -> Guessed {
if self.is_guessed {
Some(self.ch)
} else {
... | CharState | identifier_name |
lib.rs | use std::fmt::{Display, Error, Formatter};
pub struct Game {
intended_word: String,
guessed: Vec<CharState>,
}
impl Game {
pub fn new(intended_word: String) -> Game {
let guessed = intended_word.chars().map(|ch| CharState::new(ch, false)).collect();
Game {
intended_word: intend... |
fn to_enum(&self) -> Guessed {
if self.is_guessed {
Some(self.ch)
} else {
None
}
}
}
pub type Guessed = Option<char>;
#[derive(Debug)]
pub struct CurrentProgress {
vec : Vec<Guessed>,
}
impl Display for CurrentProgress {
fn fmt(&self, f : &mut Format... | {
CharState {
ch : ch,
is_guessed : is_guessed,
}
} | identifier_body |
slides.js | ._updateClassName = function () {
elem.className = this.toString();
};
}
, classListProto = ClassList[protoProp] = []
, classListGetter = function () {
return new ClassList(this);
}
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error'... | slideNo, className) {
var el = getSlideEl(slideNo);
if (!el) {
return;
}
if (className) {
el.classList.add(className);
}
for (var i in SLIDE_CLASSES) {
if (className != SLIDE_CLASSES[i]) {
el.classList.remove(SLIDE_CLASSES[i]);
}
}
};
function updateSlides() {
for (var ... | pdateSlideClass( | identifier_name |
slides.js | /* Touch events */
function handleTouchStart(event) {
if (event.touches.length == 1) {
touchDX = 0;
touchDY = 0;
touchStartX = event.touches[0].pageX;
touchStartY = event.touches[0].pageY;
document.body.addEventListener('touchmove', handleTouchMove, true);
document.body.addEventListener('to... | random_line_split | ||
slides.js | ._updateClassName = function () {
elem.className = this.toString();
};
}
, classListProto = ClassList[protoProp] = []
, classListGetter = function () {
return new ClassList(this);
}
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error'... |
function cancelTouch() {
document.body.removeEventListener('touchmove', handleTouchMove, true);
document.body.removeEventListener('touchend', handleTouchEnd, true);
};
/* Preloading frames */
function disableSlideFrames(no) {
var el = getSlideEl(no);
if (!el) {
return;
}
var frames = el.getElemen... |
var dx = Math.abs(touchDX);
var dy = Math.abs(touchDY);
if ((dx > PM_TOUCH_SENSITIVITY) && (dy < (dx * 2 / 3))) {
if (touchDX > 0) {
prevSlide();
} else {
nextSlide();
}
}
cancelTouch();
}; | identifier_body |
participant.model.ts | import { Converter, json } from './../../helpers';
import { Mastery, Rune } from './../general';
import { MatchSummoner, ParticipantStats, ParticipantTimeline } from './';
import { Tier } from './../../enums';
export class | {
public participantId: number;
public championId: number;
@json(MatchSummoner)
public summoner: MatchSummoner;
public spell1Id: number;
public spell2Id: number;
@json('highestAchievedSeasonTier', Converter.TierConverter)
public highestSeasonLeague: Tier;
@json(ParticipantStats)
public stats: Parti... | Participant | identifier_name |
participant.model.ts | import { Converter, json } from './../../helpers';
import { Mastery, Rune } from './../general';
import { MatchSummoner, ParticipantStats, ParticipantTimeline } from './';
import { Tier } from './../../enums';
export class Participant {
public participantId: number;
public championId: number;
@json(MatchSummone... |
} | {
this.participantId = void 0;
this.championId = void 0;
this.summoner = void 0;
this.spell1Id = void 0;
this.spell2Id = void 0;
this.highestSeasonLeague = void 0;
this.stats = void 0;
this.timeline = void 0;
this.runes = void 0;
this.masteries = void 0;
} | identifier_body |
participant.model.ts | import { Converter, json } from './../../helpers';
import { Mastery, Rune } from './../general';
import { MatchSummoner, ParticipantStats, ParticipantTimeline } from './';
import { Tier } from './../../enums';
export class Participant {
public participantId: number;
public championId: number;
@json(MatchSummone... | @json(Mastery)
public masteries: Mastery[];
constructor() {
this.participantId = void 0;
this.championId = void 0;
this.summoner = void 0;
this.spell1Id = void 0;
this.spell2Id = void 0;
this.highestSeasonLeague = void 0;
this.stats = void 0;
this.timeline = void 0;
this.runes... | @json(Rune)
public runes: Rune[]; | random_line_split |
errorHandlers.js | exports.catchErrors = (fn) => {
return function(req, res, next) {
return fn(req, res, next).catch(next)
}
}
exports.notFound = (req, res, next) => {
const err = new Error('Not Found')
err.status = 404
next(err)
}
exports.flashValidationErrors = (err, req, res, next) => {
if (!err.errors) return next(e... |
exports.productionErrors = (err, req, res, next) => {
res.status(err.status || 500)
res.render('error', {
message: err.message,
error: {}
})
} | 'application/json': () => res.json(errorDetails)
})
} | random_line_split |
read_message.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | <A> {
ReadHeader(ReadHeader<A>),
ReadPayload(ReadPayload<A>),
Finished,
}
/// Future for read single message from the stream.
pub struct ReadMessage<A> {
key: Option<KeyPair>,
state: ReadMessageState<A>,
}
impl<A> Future for ReadMessage<A> where A: AsyncRead {
type Item = (A, Result<Message, Error>);
type Erro... | ReadMessageState | identifier_name |
read_message.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | // by polling again, we register new future
Async::NotReady => self.poll(),
result => Ok(result)
}
}
} |
self.state = next;
match result { | random_line_split |
read_message.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | ,
ReadMessageState::Finished => panic!("poll ReadMessage after it's done"),
};
self.state = next;
match result {
// by polling again, we register new future
Async::NotReady => self.poll(),
result => Ok(result)
}
}
}
| {
let (read, payload) = try_ready!(future.poll());
(ReadMessageState::Finished, Async::Ready((read, payload)))
} | conditional_block |
Loader.tsx | import * as React from 'react'
import Base from '../../libs/Base'
import './Loader.less'
export interface ILoaderProps {
loading?: boolean,
text?: string,
children?: React.ReactNode
}
export interface ILoaderState {}
export default class Loader extends Base<ILoaderProps, ILoaderState> {
constructor (props: ... | </div>
)
: this.renderChildren()
)
}
} | {children && <span className='whc-loader__container'>{children}</span>} | random_line_split |
Loader.tsx | import * as React from 'react'
import Base from '../../libs/Base'
import './Loader.less'
export interface ILoaderProps {
loading?: boolean,
text?: string,
children?: React.ReactNode
}
export interface ILoaderState {}
export default class Loader extends Base<ILoaderProps, ILoaderState> {
constructor (props: ... |
}
| {
const {loading, text, children} = this.props
return (
loading
? (
<div {...this.rootProps(['whc-loader'])}>
<div className='whc-loader__core'>{text}</div>
{children && <span className='whc-loader__container'>{children}</span>}
</div>
)
... | identifier_body |
Loader.tsx | import * as React from 'react'
import Base from '../../libs/Base'
import './Loader.less'
export interface ILoaderProps {
loading?: boolean,
text?: string,
children?: React.ReactNode
}
export interface ILoaderState {}
export default class Loader extends Base<ILoaderProps, ILoaderState> {
| (props: ILoaderProps) {
super(props)
this.state = {}
}
renderChildren = () => {
const children = this.props.children
return typeof children === 'string'
? React.createElement('span', {}, children)
: children as any || null
}
render () {
const {loading, text, children} = this.p... | constructor | identifier_name |
products.js | const REQUEST_FETCH = 'products/REQUEST_FETCH';
const RESPONSE_FETCH = 'products/RESPONSE_FETCH';
const RESET_FILTER = 'products/RESET_FILTER';
const INVALIDATE = 'products/INVALIDATE';
const PRODUCT_DELETED = 'products/PRODUCT_DELETED';
const PRODUCT_FETCHED = 'products/PRODUCT_FETCHED';
import {
Map,
fromJS
} f... |
export function saveProduct(productId, data) {
return dispatch => {
let url, method;
if (typeof productId === 'undefined') {
url = '/products';
method = 'post';
}
else {
url = `/products/${productId}`;
method = 'put';
}
const ajaxPromise = $.ajax({
url,
me... | {
return dispatch => {
$.ajax({
url: '/products/' + productId,
method: 'get',
success: function(data) {
dispatch(responseFetchProduct(productId, data));
}
});
};
} | identifier_body |
products.js | const REQUEST_FETCH = 'products/REQUEST_FETCH';
const RESPONSE_FETCH = 'products/RESPONSE_FETCH';
const RESET_FILTER = 'products/RESET_FILTER';
const INVALIDATE = 'products/INVALIDATE';
const PRODUCT_DELETED = 'products/PRODUCT_DELETED';
const PRODUCT_FETCHED = 'products/PRODUCT_FETCHED';
import {
Map,
fromJS
} f... | (filterText) {
return (dispatch, getState) => {
if (shouldFetchProducts(getState(), filterText)) {
return dispatch(fetchProducts(filterText));
}
};
}
function invalidateProducts() {
return {
type: INVALIDATE
};
}
function productDeleted(productId) {
return {
type: PRODUCT_DELETED,
... | fetchProductsIfNeeded | identifier_name |
products.js | const REQUEST_FETCH = 'products/REQUEST_FETCH';
const RESPONSE_FETCH = 'products/RESPONSE_FETCH';
const RESET_FILTER = 'products/RESET_FILTER';
const INVALIDATE = 'products/INVALIDATE';
const PRODUCT_DELETED = 'products/PRODUCT_DELETED';
const PRODUCT_FETCHED = 'products/PRODUCT_FETCHED';
import {
Map,
fromJS
} f... | default:
return state;
}
}
function requestFetchProducts(filterText) {
return {
type: REQUEST_FETCH,
payload: filterText
};
}
function responseFetchProducts(products) {
return {
type: RESPONSE_FETCH,
payload: products
};
}
function fetchProducts(filterText) {
return dispatch => {
... | random_line_split | |
products.js | const REQUEST_FETCH = 'products/REQUEST_FETCH';
const RESPONSE_FETCH = 'products/RESPONSE_FETCH';
const RESET_FILTER = 'products/RESET_FILTER';
const INVALIDATE = 'products/INVALIDATE';
const PRODUCT_DELETED = 'products/PRODUCT_DELETED';
const PRODUCT_FETCHED = 'products/PRODUCT_FETCHED';
import {
Map,
fromJS
} f... |
return false;
}
export function fetchProductsIfNeeded(filterText) {
return (dispatch, getState) => {
if (shouldFetchProducts(getState(), filterText)) {
return dispatch(fetchProducts(filterText));
}
};
}
function invalidateProducts() {
return {
type: INVALIDATE
};
}
function productDelete... | {
return true;
} | conditional_block |
views.py | # -*- coding: utf-8 -*-
'''
Copyright 2014 FreshPlanet (http://freshplanet.com | opensource@freshplanet.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... | @ndb.toplevel
def get(self):
"""
Increments some Counters to play with the feature.
"""
# Fill datastore with data to show case in admin view
otherSliceId = (datetime.datetime.utcnow() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
for client in ['iOS', 'Android',... | identifier_body | |
views.py | # -*- coding: utf-8 -*-
'''
Copyright 2014 FreshPlanet (http://freshplanet.com | opensource@freshplanet.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... | Increments some Counters to play with the feature.
"""
# Fill datastore with data to show case in admin view
otherSliceId = (datetime.datetime.utcnow() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
for client in ['iOS', 'Android', 'Windows']:
Counter.increment('n... | random_line_split | |
views.py | # -*- coding: utf-8 -*-
'''
Copyright 2014 FreshPlanet (http://freshplanet.com | opensource@freshplanet.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... | (webapp2.RequestHandler):
@ndb.toplevel
def get(self):
"""
Increments some Counters to play with the feature.
"""
# Fill datastore with data to show case in admin view
otherSliceId = (datetime.datetime.utcnow() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
... | SampleHandler | identifier_name |
views.py | # -*- coding: utf-8 -*-
'''
Copyright 2014 FreshPlanet (http://freshplanet.com | opensource@freshplanet.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... |
self.response.write("""
Counters updated!
Query for counters <a href="/admin/counters/?prefix=newInstalls">here</a>.
""")
| Counter.increment('newInstalls_' + client, random.randint(1, 5))
Counter.increment('newInstalls_' + client, random.randint(1, 5), sliceId=otherSliceId) | conditional_block |
mod.rs | //! First set construction and computation.
use collections::{map, Map};
use grammar::repr::*;
use lr1::lookahead::{Token, TokenSet};
#[cfg(test)]
mod test;
#[derive(Clone)]
pub struct FirstSets {
map: Map<NonterminalString, TokenSet>,
}
impl FirstSets {
pub fn new(grammar: &Grammar) -> FirstSets {
... |
set
}
}
| {
set.union_with(&lookahead);
} | conditional_block |
mod.rs | //! First set construction and computation.
use collections::{map, Map};
use grammar::repr::*;
use lr1::lookahead::{Token, TokenSet};
#[cfg(test)]
mod test;
#[derive(Clone)]
pub struct FirstSets {
map: Map<NonterminalString, TokenSet>,
}
impl FirstSets {
pub fn new(grammar: &Grammar) -> FirstSets |
/// Returns `FIRST(...symbols)`. If `...symbols` may derive
/// epsilon, then this returned set will include EOF. (This is
/// kind of repurposing EOF to serve as a binary flag of sorts.)
pub fn first0<'s, I>(&self, symbols: I) -> TokenSet
where
I: IntoIterator<Item = &'s Symbol>,
{
... | {
let mut this = FirstSets { map: map() };
let mut changed = true;
while changed {
changed = false;
for production in grammar.nonterminals.values().flat_map(|p| &p.productions) {
let nt = &production.nonterminal;
let lookahead = this.first0... | identifier_body |
mod.rs | //! First set construction and computation.
use collections::{map, Map};
use grammar::repr::*;
use lr1::lookahead::{Token, TokenSet};
#[cfg(test)]
mod test;
#[derive(Clone)]
pub struct FirstSets {
map: Map<NonterminalString, TokenSet>,
}
impl FirstSets {
pub fn new(grammar: &Grammar) -> FirstSets {
... | (&self, symbols: &[Symbol], lookahead: &TokenSet) -> TokenSet {
let mut set = self.first0(symbols);
// we use EOF as the signal that `symbols` derives epsilon:
let epsilon = set.take_eof();
if epsilon {
set.union_with(&lookahead);
}
set
}
}
| first1 | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.