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 |
|---|---|---|---|---|
lib.rs | //! Huffman
//!
//! A library for huffman coding written in Rust.
//!
extern crate bit_vec;
mod encode;
mod decode;
use bit_vec::BitVec;
use std::collections::HashMap;
pub use encode::*;
pub use decode::*;
/// Alias for the type of frequency.
pub type Frequency = usize;
/// Alias for the hashmap
pub type BinMap = H... | assert_eq!(freq_map[&b'H'], 1);
assert_eq!(freq_map[&b'e'], 1);
assert_eq!(freq_map[&b'l'], 2);
assert_eq!(freq_map[&b'o'], 1);
}
} | assert_eq!(freq_map.len(), 4);
| random_line_split |
lib.rs | //! Huffman
//!
//! A library for huffman coding written in Rust.
//!
extern crate bit_vec;
mod encode;
mod decode;
use bit_vec::BitVec;
use std::collections::HashMap;
pub use encode::*;
pub use decode::*;
/// Alias for the type of frequency.
pub type Frequency = usize;
/// Alias for the hashmap
pub type BinMap = H... |
} | {
// "Hello" should yield: {'H': 1, 'e': 1, 'l': 2, 'o': 3}
let message = b"Hello";
let freq_map = freq_analysis(message);
assert_eq!(freq_map.len(), 4);
assert_eq!(freq_map[&b'H'], 1);
assert_eq!(freq_map[&b'e'], 1);
assert_eq!(freq_map[&b'l'], 2);
asse... | identifier_body |
heroes.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { HeroDetailComponent } from './hero-detail.component';
@Component({
selector: 'my-heroes',
templateUrl... |
}
deleteHero(hero: Hero, event: any) {
event.stopPropagation();
this.heroService
.delete(hero)
.then(res => {
this.heroes = this.heroes.filter(h => h !== hero);
if (this.selectedHero === hero) { this.selectedHero = null; }
})
.catch(error => this.error =... | { this.getHeroes(); } | conditional_block |
heroes.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { HeroDetailComponent } from './hero-detail.component';
@Component({
selector: 'my-heroes',
templateUrl... |
}
/*
Copyright 2016 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 http://angular.io/license
*/ | {
this.router.navigate(['/detail', this.selectedHero.id]);
} | identifier_body |
heroes.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { HeroDetailComponent } from './hero-detail.component';
@Component({
selector: 'my-heroes',
templateUrl... | () {
this.getHeroes();
}
onSelect(hero: Hero) {
this.selectedHero = hero;
this.addingHero = false;
}
gotoDetail() {
this.router.navigate(['/detail', this.selectedHero.id]);
}
}
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license th... | ngOnInit | identifier_name |
heroes.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { HeroDetailComponent } from './hero-detail.component';
@Component({
selector: 'my-heroes',
templateUrl... | constructor(
private router: Router,
private heroService: HeroService) { }
getHeroes() {
this.heroService
.getHeroes()
.then(heroes => this.heroes = heroes)
.catch(error => this.error = error);
}
addHero() {
this.addingHero = true;
this.selectedHero = null;
}
c... | random_line_split | |
item_ring_set_commando_utility_b_01_01.py | import sys
def | (core, object):
object.setAttachment('radial_filename', 'ring/unity')
object.setAttachment('objType', 'ring')
object.setStfFilename('static_item_n')
object.setStfName('item_ring_set_commando_utility_b_01_01')
object.setDetailFilename('static_item_d')
object.setDetailName('item_ring_set_commando_utility_b_01_01')
... | setup | identifier_name |
item_ring_set_commando_utility_b_01_01.py | import sys
def setup(core, object):
| object.setAttachment('radial_filename', 'ring/unity')
object.setAttachment('objType', 'ring')
object.setStfFilename('static_item_n')
object.setStfName('item_ring_set_commando_utility_b_01_01')
object.setDetailFilename('static_item_d')
object.setDetailName('item_ring_set_commando_utility_b_01_01')
object.setIntAtt... | identifier_body | |
item_ring_set_commando_utility_b_01_01.py | import sys
def setup(core, object):
object.setAttachment('radial_filename', 'ring/unity')
object.setAttachment('objType', 'ring') | object.setStfFilename('static_item_n')
object.setStfName('item_ring_set_commando_utility_b_01_01')
object.setDetailFilename('static_item_d')
object.setDetailName('item_ring_set_commando_utility_b_01_01')
object.setIntAttribute('required_combat_level', 85)
object.setStringAttribute('class_required', 'Commando')
o... | random_line_split | |
angular_base.js | /**
* Created by Administrator on 2016/5/6.
*/
var app = angular.module("myApp",[]).config(function($httpProvider) {
$httpProvider.defaults.headers
.common['Accept'] = 'application/json; charset=utf-8';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
$htt... | $scope.gid.gridPromptTxt="数据加载中......";
$scope.gid.checkAllVal=false;
$scope.gid.param.currentPage=$scope.gid.param.currentPage?$scope.gid.param.currentPage:1;
$scope.gid.param.pageSize=$scope.gid.param.pageSize?$scope.gid.param.pageSize:10;
$sc... | $scope.gid.listItems=function() {
$scope.gid.gridPrompt=true; | random_line_split |
angular_base.js | /**
* Created by Administrator on 2016/5/6.
*/
var app = angular.module("myApp",[]).config(function($httpProvider) {
$httpProvider.defaults.headers
.common['Accept'] = 'application/json; charset=utf-8';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
$htt... | '@headtext',
datafield: '@datafield',
width: '@width',
align: '@align',
itemrender: '@itemrender'
},
link: function ($scope, iElement, iAttrs, controller) {
//console.log("come in link<<<<<<<");
var columnObj = {};
colu... | require : '^myGrid',
scope: {
headtext: | conditional_block |
ai.py | _/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation;... |
def setRoll(self, roll):
self.roll = roll
self.repaint()
def setPitch(self, pitch):
self.pitch = pitch
self.repaint()
def setHover(self, target):
self.hoverTargetASL = target
self.hover = target > 0
self.repaint()
def setBaro(self, asl):
... | super(AttitudeIndicator, self).__init__()
self.roll = 0
self.pitch = 0
self.hover = False
self.hoverASL = 0.0
self.hoverTargetASL = 0.0
self.setMinimumSize(30, 30)
# self.setMaximumSize(240,240) | identifier_body |
ai.py | _/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation;... |
hbox = QtGui.QHBoxLayout()
hbox.addLayout(vbox)
sldPitch = QtGui.QSlider(QtCore.Qt.Vertical, self)
sldPitch.setFocusPolicy(QtCore.Qt.NoFocus)
sldPitch.setRange(0, 180)
sldPitch.setValue(90)
sldPitch.valueChanged[int].connect(self.upda... | sld.valueChanged[int].connect(self.updateRoll)
vbox.addWidget(self.wid) | random_line_split |
ai.py | _/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation;... | (self, roll, pitch):
self.roll = roll
self.pitch = pitch
self.repaint()
def paintEvent(self, e):
qp = QtGui.QPainter()
qp.begin(self)
self.drawWidget(qp)
qp.end()
def drawWidget(self, qp):
size = self.size()
w = size.width()
h = s... | setRollPitch | identifier_name |
ai.py | /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundatio... |
qp.drawLine((w / 2) - (length / 2), pos,
(w / 2) + (length / 2), pos)
qp.setWorldMatrixEnabled(False)
pen = QtGui.QPen(QtGui.QColor(0, 0, 0), 2,
QtCore.Qt.SolidLine)
qp.setBrush(QtGui.QColor(0, 0, 0))
qp.setPen(pen)... | length = 0.1 * w | conditional_block |
socialshare.js | /*
* Spreed WebRTC.
* Copyright (C) 2013-2014 struktur AG
*
* This file is part of Spreed WebRTC.
*
* 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... | else {
$window.open(url, "social_" + nw, "menubar=no,toolbar=no,resizable=yes,width=600,height=600,scrollbars=yes");
}
} else {
if (nw === "link") {
//$window.alert("Room link: " + $scope.roomlink);
alertify.dialog.notify(translation._("Room link"), '<a href="'+$scope.roomlink+'" ... | {
// Hack our way to disable unload popup for mail links.
$scope.manualReloadApp(url);
} | conditional_block |
socialshare.js | /*
* Spreed WebRTC.
* Copyright (C) 2013-2014 struktur AG
*
* This file is part of Spreed WebRTC.
*
* 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... | }
}];
}); | });
} | random_line_split |
window.js | // const Positioner = require('electron-positioner')
export const windowSizes = {
mini: {
width: 100,
height: 30
},
list: {
width: 200,
height: 400
},
normal: {
width: 900,
height: 600
}
}
// const positioner = new Positioner(windows.main)
// const getWinPosition = size => {
// i... | (win, size, shouldAnimate = true) {
const { width, height } = windowSizes[size]
win.setSize(width, height, shouldAnimate)
}
| resizeWindowEffect | identifier_name |
window.js | // const Positioner = require('electron-positioner')
export const windowSizes = {
mini: {
width: 100,
height: 30
},
list: {
width: 200,
height: 400
},
normal: {
width: 900,
height: 600
}
}
// const positioner = new Positioner(windows.main)
// const getWinPosition = size => {
// i... | else {
win.hide()
}
}
export function resizeWindowEffect(win, size, shouldAnimate = true) {
const { width, height } = windowSizes[size]
win.setSize(width, height, shouldAnimate)
}
| {
win.show()
} | conditional_block |
window.js | // const Positioner = require('electron-positioner')
export const windowSizes = {
mini: {
width: 100,
height: 30
},
list: {
width: 200,
height: 400
},
normal: {
width: 900,
height: 600
}
}
// const positioner = new Positioner(windows.main)
// const getWinPosition = size => {
// i... | {
const { width, height } = windowSizes[size]
win.setSize(width, height, shouldAnimate)
} | identifier_body | |
window.js | // const Positioner = require('electron-positioner')
export const windowSizes = {
mini: {
width: 100,
height: 30
},
list: {
width: 200,
height: 400
}, | }
}
// const positioner = new Positioner(windows.main)
// const getWinPosition = size => {
// if (size === WindowSizes.NORMAL) {
// return positioner.calculate('center')
// }
// // Do not cache tray position since it can change over time
// return positioner.calculate('trayCenter', tray.getBounds())
// }... | normal: {
width: 900,
height: 600 | random_line_split |
postings.rs | use docset::DocSet;
/// Postings (also called inverted list)
///
/// For a given term, it is the list of doc ids of the doc
/// containing the term. Optionally, for each document,
/// it may also give access to the term frequency
/// as well as the list of term positions.
///
/// Its main implementation is `SegmentPos... |
/// Returns the positions offseted with a given value.
/// The output vector will be resized to the `term_freq`.
fn positions_with_offset(&mut self, offset: u32, output: &mut Vec<u32>);
/// Returns the positions of the term in the given document.
/// The output vector will be resized to the `term_... | /// Returns the term frequency
fn term_freq(&self) -> u32; | random_line_split |
postings.rs | use docset::DocSet;
/// Postings (also called inverted list)
///
/// For a given term, it is the list of doc ids of the doc
/// containing the term. Optionally, for each document,
/// it may also give access to the term frequency
/// as well as the list of term positions.
///
/// Its main implementation is `SegmentPos... |
}
| {
self.positions_with_offset(0u32, output);
} | identifier_body |
postings.rs | use docset::DocSet;
/// Postings (also called inverted list)
///
/// For a given term, it is the list of doc ids of the doc
/// containing the term. Optionally, for each document,
/// it may also give access to the term frequency
/// as well as the list of term positions.
///
/// Its main implementation is `SegmentPos... | (&mut self, output: &mut Vec<u32>) {
self.positions_with_offset(0u32, output);
}
}
| positions | identifier_name |
notification-events.ts | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
/* eslint-disable max-classes-per-file */
import DispatcherAction from 'actions/dispatcher-action';
import NotificationJson, { NotificationBun... | (eventData: NotificationEventReadJson): NotificationEventRead {
const data = eventData.data.notifications.map((json) => fromJson(json));
return new NotificationEventRead(data, eventData.data.read_count);
}
}
| fromJson | identifier_name |
notification-events.ts | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
/* eslint-disable max-classes-per-file */
import DispatcherAction from 'actions/dispatcher-action';
import NotificationJson, { NotificationBun... | export class NotificationEventMoreLoaded extends DispatcherAction {
constructor(readonly data: NotificationBundleJson, readonly context: NotificationEventMoreLoadedContext) {
super();
}
}
export class NotificationEventNew extends DispatcherAction {
constructor(readonly data: NotificationJson) {
super();
... | }
| random_line_split |
bans_gline.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... | self.initializeLineStorage()
def verifyConfig(self, config):
if "client_ban_msg" in config and not isinstance(config["client_ban_msg"], basestring):
raise ConfigValidationError("client_ban_msg", "value must be a string")
def checkUserMatch(self, user, mask, data):
banMask = self.normalizeMask(mask)
user... | random_line_split | |
bans_gline.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... |
return False
def killUser(self, user, reason):
self.ircd.log.info("Matched user {user.uuid} ({user.ident}@{user.host()}) against a g:line: {reason}", user=user, reason=reason)
user.sendMessage(irc.ERR_YOUREBANNEDCREEP, self.ircd.config.get("client_ban_msg", "You're banned! Email abuse@example.com for assistan... | return True | conditional_block |
bans_gline.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... | (self, user, reason):
self.ircd.log.info("Matched user {user.uuid} ({user.ident}@{user.host()}) against a g:line: {reason}", user=user, reason=reason)
user.sendMessage(irc.ERR_YOUREBANNEDCREEP, self.ircd.config.get("client_ban_msg", "You're banned! Email abuse@example.com for assistance."))
user.disconnect("G:Lin... | killUser | identifier_name |
bans_gline.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... |
def checkIdentChange(self, user, oldIdent, fromServer):
self.checkLines(user)
def checkHostChange(self, user, hostType, oldHost, fromServer):
if user.uuid[:3] == self.ircd.serverID:
self.checkLines(user)
def restrictToOper(self, user, data):
if not self.ircd.runActionUntilValue("userhasoperpermission... | banReason = self.matchUser(user)
if banReason is not None:
self.killUser(user, banReason)
return False
return True | identifier_body |
middleware.test.js | import { LOCAL_STORAGE_REMOVE_ITEM, LOCAL_STORAGE_SET_ITEM } from './actionTypes'
import createMiddleware from './middleware'
describe('middleware', () => {
let removeItem
let setItem
let middleware
let next
let store
beforeEach(() => {
removeItem = jest.fn()
setItem = jest.fn()
middleware = c... | expect(setItem.mock.calls.length).toBe(1)
})
}) | }
middleware(store)(next)(action) | random_line_split |
attr-stmt-expr.rs | // Copyright 2018 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 ... |
#[proc_macro_attribute]
pub fn no_output(attr: TokenStream, item: TokenStream) -> TokenStream {
assert!(attr.to_string().is_empty());
assert!(!item.to_string().is_empty());
"".parse().unwrap()
}
| {
assert!(attr.to_string().is_empty());
format!("{}, {}", item, item).parse().unwrap()
} | identifier_body |
attr-stmt-expr.rs | // Copyright 2018 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 ... | (attr: TokenStream, item: TokenStream) -> TokenStream {
assert!(attr.to_string().is_empty());
assert_eq!(item.to_string(), "println!(\"{}\" , string)");
item
}
#[proc_macro_attribute]
pub fn duplicate(attr: TokenStream, item: TokenStream) -> TokenStream {
assert!(attr.to_string().is_empty());
forma... | expect_print_expr | identifier_name |
attr-stmt-expr.rs | // Copyright 2018 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 expect_expr(attr: TokenStream, item: TokenStream) -> TokenStream {
assert!(attr.to_string().is_empty());
assert_eq!(item.to_string(), "print_str(\"string\")");
item
}
#[proc_macro_attribute]
pub fn expect_print_expr(attr: TokenStream, item: TokenStream) -> TokenStream {
assert!(attr.to_string().... | }
#[proc_macro_attribute] | random_line_split |
iglineargauge.component.spec.ts | // tslint:disable-next-line:max-line-length
// modeled after https://github.com/angular/angular/blob/cee2318110eeea115e5f6fc5bfc814cbaa7d90d8/modules/angular2/test/common/directives/ng_for_spec.ts
import { TestBed } from '@angular/core/testing';
import { Component, ViewChild } from '@angular/core';
import * as Infragis... | TestBed.configureTestingModule({
declarations: [Infragistics.IgLinearGaugeComponent, TestComponent]
});
});
it('should initialize correctly', (done) => {
const template = '<div><ig-linear-gauge widgetId="lGauge" [(options)]="opts"></ig-linear-gauge></div>';
TestBed.o... | describe('Infragistics Angular Linear Gauge', () => {
beforeEach(() => { | random_line_split |
iglineargauge.component.spec.ts | // tslint:disable-next-line:max-line-length
// modeled after https://github.com/angular/angular/blob/cee2318110eeea115e5f6fc5bfc814cbaa7d90d8/modules/angular2/test/common/directives/ng_for_spec.ts
import { TestBed } from '@angular/core/testing';
import { Component, ViewChild } from '@angular/core';
import * as Infragis... | () {
this.opts = {
height: '80px',
width: '100%',
value: 27,
maximumValue: 30,
ranges: [{ startValue: 0, endValue: 22, name: 'target' }]
};
}
}
| constructor | identifier_name |
bitstring.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 dinowernli
//
// 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... | (value: &str) -> Self {
let mut bits = Vec::new();
for b in value.chars() {
bits.push(match b {
'0' => Bit::Zero,
'1' => Bit::One,
_ => panic!("Could not extract bitstring from {}", value),
});
}
return Bitstring::create_from_bits(bits);
}
fn create_from_bits(bit... | create_from_string | identifier_name |
bitstring.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 dinowernli
//
// 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... | }
return Bitstring::create_from_bits(bits);
}
fn create_from_bits(bits: Vec<Bit>) -> Self {
return Bitstring {
bits: bits
};
}
pub fn bits(&self) -> &Vec<Bit> { &self.bits }
pub fn len(&self) -> usize { self.bits().len() }
pub fn bit(&self, i: usize) -> Bit { self.bits[i] }
pub fn... | '0' => Bit::Zero,
'1' => Bit::One,
_ => panic!("Could not extract bitstring from {}", value),
}); | random_line_split |
lmmanalysisave_septcut4and2ifsame.py | "],["Night early prepulse tap", "Day early prepulse tap"], ["Night all prepulse tap", "Day all prepulse tap"], ["Day all strong tap", "Night all strong tap"], ["Day early strong tap","Night early strong tap"],["Night early weak tap", "Day early weak tap"], ["Day all weak tap", "Night all weak tap"], ["Dark flash block ... |
list.append((float(pvalue), float(coef), lines[line- | pvalue = 0.001 | conditional_block |
lmmanalysisave_septcut4and2ifsame.py | ": ["bdaytaphab102", "bdaytaphab1"],
"Day light flash": ["lightflash104"],
#"Day light flash": ["lightflash104", "lightflash0"],
"Night light flash": ["nightlightflash104"],
#"Night light flash": ["nightlightflash104", "nightlightflash0"],
"Night early prepulse tap": ["shortnightprepulseinhibition100b"],
#"Night ... | for k in pdict:
# k = ribgraph_mean_ribbonbout_dpixavebouttime_min_day1taps.png
# section = day1taps
# or section = adaytappostbdaytappre102
if k.startswith("ratio"): | random_line_split | |
authSession.ts | /*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
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... | <TSuccess, TError>(
promise: Promise<SDKResponse<TSuccess, TError>>
) {
const result = await promise
if (result.ok) {
return result.value
} else {
if (result instanceof Buffer) {
throw sdkError({ message: result.toString('utf8') })
} else {
throw sdkError(result)
... | ok | identifier_name |
authSession.ts | /*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
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... |
}
}
| {
if (result instanceof Buffer) {
throw sdkError({ message: result.toString('utf8') })
} else {
throw sdkError(result)
}
} | conditional_block |
authSession.ts | /*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
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... |
/**
* Is a sudo user active for this session?
*/
isSudo(): boolean {
return this.sudoId !== '' && this.isAuthenticated()
}
/**
* Resets all authentication status, but standard implementations do NOT log out an API session
*/
reset(): void {
this.sudoId = ''
}
protected async ok<TSu... | {
return Promise.resolve(false)
} | identifier_body |
authSession.ts | /*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
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... | */
export interface IError {
/**
* Error details (read-only)
*/
message: string | null
/**
* Documentation link (read-only)
*/
documentation_url: string | null
}
/**
* Basic authorization session interface for most API authentication scenarios
*/
export interface IAuthSession {
settings: IApiS... |
/**
* Same as the Looker API error object
* Re-declared here to be independent of model generation | random_line_split |
errors-and-warnings.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Show errors and warnings.
*/
import { sortBy } from "lodash";
import { capitalize, is_different, path_split } from "smc-util/misc";
import { React, Rendered, useRedux } fro... | React.SyntheticEvent<any>): void {
e.stopPropagation();
if (!item.get("file")) return; // not known
const line: number = parseInt(item.get("line"));
let path = item.get("file");
const head = path_split(actions.path).head;
if (head != "") {
path = head + "/" + path;
}
... | t_source(e: | identifier_name |
errors-and-warnings.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Show errors and warnings.
*/
import { sortBy } from "lodash";
import { capitalize, is_different, path_split } from "smc-util/misc";
import { React, Rendered, useRedux } fro... | {
const w: Rendered[] = [];
content.forEach((item) => {
w.push(render_item(item, w.length));
});
return <div>{w}</div>;
}
}
function render_group(
tool: string,
group: string,
num: number
): MsgGroup | undefined {
if (tool == "knitr" ... | return <div>None</div>;
} else | conditional_block |
errors-and-warnings.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Show errors and warnings.
*/
import { sortBy } from "lodash";
import { capitalize, is_different, path_split } from "smc-util/misc";
import { React, Rendered, useRedux } fro... | num: number
): MsgGroup | undefined {
if (tool == "knitr" && !knitr) {
return undefined;
}
const level = group_to_level(group);
const spec: SpecItem = SPEC[level];
const content = build_logs.getIn([tool, "parse", group]);
if (!content) {
return;
}
... | function render_group(
tool: string,
group: string, | random_line_split |
errors-and-warnings.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Show errors and warnings.
*/
import { sortBy } from "lodash";
import { capitalize, is_different, path_split } from "smc-util/misc";
import { React, Rendered, useRedux } fro... | the function above is used for React.memo, see bottom
export const ErrorsAndWarnings: React.FC<ErrorsAndWarningsProps> = React.memo(
(props) => {
const {
/*id,*/
name,
actions,
/*editor_state,*/
/*is_fullscreen,*/
/*project_id,*/
/*path,*/
/*reload,*/
/*font_s... | const props_diff = is_different(prev, next, ["status", "font_size", "knitr"]);
// if props are different → don't memoize
return !props_diff;
}
// | identifier_body |
int.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | () {
fn sum(args: &[TVMArgValue]) -> Result<TVMRetValue, Error> {
let mut ret = 0i64;
for arg in args.iter() {
let val: i64 = arg.try_into()?;
ret += val;
}
Ok(TVMRetValue::from(ret))
}
tvm::function::register(sum, "mysum".to_owned(), false).unwrap();... | main | identifier_name |
int.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | .unwrap();
assert_eq!(ret, 60);
}
| {
fn sum(args: &[TVMArgValue]) -> Result<TVMRetValue, Error> {
let mut ret = 0i64;
for arg in args.iter() {
let val: i64 = arg.try_into()?;
ret += val;
}
Ok(TVMRetValue::from(ret))
}
tvm::function::register(sum, "mysum".to_owned(), false).unwrap();
... | identifier_body |
int.rs | /* | * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. ... | * Licensed to the Apache Software Foundation (ASF) under one | random_line_split |
assign-polyfill.js | /**
* Object.assign的polyfill
* 解决webview等不支持ES6的浏览器兼容性
*/
'use strict';
(function() {
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
if (target === undefined || target === null) {... | ct(nextSource);
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== unde... | }
nextSource = Obje | conditional_block |
assign-polyfill.js | /**
* Object.assign的polyfill
* 解决webview等不支持ES6的浏览器兼容性
*/
'use strict';
(function() {
if (!Object.assign) { | Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(targe... | random_line_split | |
report.js | __report = {
"reports": [
{
"info": {
"file": "lib/DataType.js",
"fileShort": "lib/DataType.js",
"fileSafe": "lib_DataType_js",
"link": "files/lib_DataType_js/index.html"
},
"jshint": {
"messages": 19
},
"complexity": {
"aggregate": {
... | "operators": {
"distinct": 39,
"total": 571,
"identifiers": [
"__stripped__"
]
},
"operands": {
"distinct": 157,
"total": 796,
"identifiers": [
... | "cyclomatic": 62,
"halstead": { | random_line_split |
fontSelector.js | /**
* Created by kapale on 08.05.17.
*/
$( document ).ready(function () {
var fonts = {},
savedValues = [],
_$formSelects = $('.cm-neos-thememodule-custom-font-family-selector'),
htmlCheckboxOpen = '<div class="checkbox"><label>',
htmlCheckboxClose = '</label></div>';
function... | (font) {
return font.family === item.family;
}
var fontDetails = fonts[item.category].find(findFont),
checked = false,
savedValueVariantsLength = 0;
if (typeof item.variants !== 'undefined' && item.variants !==... | findFont | identifier_name |
fontSelector.js | /**
* Created by kapale on 08.05.17.
*/
$( document ).ready(function () {
var fonts = {},
savedValues = [],
_$formSelects = $('.cm-neos-thememodule-custom-font-family-selector'),
htmlCheckboxOpen = '<div class="checkbox"><label>',
htmlCheckboxClose = '</label></div>';
function... |
fontDetails = fonts[selectCategory].find(findFont);
_$this.parent().find('.cm-neos-thememodule-custom-font-family-hidden.variants').val(null);
buildHtml(fontDetails,selectId);
});
}
function init () {
getDataFromForm();
buildHtml();
bin... | {
return font.family === selectedFont;
} | identifier_body |
fontSelector.js | /**
* Created by kapale on 08.05.17.
*/
$( document ).ready(function () {
var fonts = {},
savedValues = [],
_$formSelects = $('.cm-neos-thememodule-custom-font-family-selector'),
htmlCheckboxOpen = '<div class="checkbox"><label>',
htmlCheckboxClose = '</label></div>';
function... | function init () {
getDataFromForm();
buildHtml();
bindOnChangeToSelects();
}
init();
}); | random_line_split | |
fontSelector.js | /**
* Created by kapale on 08.05.17.
*/
$( document ).ready(function () {
var fonts = {},
savedValues = [],
_$formSelects = $('.cm-neos-thememodule-custom-font-family-selector'),
htmlCheckboxOpen = '<div class="checkbox"><label>',
htmlCheckboxClose = '</label></div>';
function... |
});
$(this).parents('.font-extra-root').find('.cm-neos-thememodule-custom-font-family-hidden.variants').val(JSON.stringify(hiddenVariants));
});
});
}
}
function getDataFromForm() {
_$formSelects.each(function () {
... | {
hiddenVariants.push($(this).val());
} | conditional_block |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... | () {
$('input.date_picker').datepicker({
autoclose: true,
todayHighlight: true,
dateFormat: 'mm/dd/yyyy'
});
}
$(document).ready(initializeDatePicker);
$(document).on('page:change', initializeDatePicker);
// whenever the bootstrap modal closes, reset it's contents
$(function() {
$('#myModal').on('hi... | initializeDatePicker | identifier_name |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... |
// handle link_to remote and replace contents into data-replace id element
$(function() {
$(document)
.data('type', 'html')
.delegate('[data-remote][data-replace]', 'ajax:success', function(event, data) {
var $this = $(this);
$($this.data('replace')).html(data);
$this.trigger('ajax:replaced... | $('#myModalLabel').text('');
});
}); | random_line_split |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... |
$(document).ready(initializeDatePicker);
$(document).on('page:change', initializeDatePicker);
// whenever the bootstrap modal closes, reset it's contents
$(function() {
$('#myModal').on('hidden', function () {
$('#myModal div.modal-body').html("<p>Loading... <i class=\"icon-refresh\"></i></p>");
$('#myModalL... | {
$('input.date_picker').datepicker({
autoclose: true,
todayHighlight: true,
dateFormat: 'mm/dd/yyyy'
});
} | identifier_body |
gr-attribute-helper.js | // Copyright (C) 2017 The Android Open Source Project
//
// 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 ... | (element) {
this.element = element;
this._promises = {};
}
GrAttributeHelper.prototype._getChangedEventName = function(name) {
return name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() + '-changed';
};
/**
* Returns true if the property is defined on wrapped element.
* @param {string} na... | GrAttributeHelper | identifier_name |
gr-attribute-helper.js | // Copyright (C) 2017 The Android Open Source Project
//
// 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 ... | * @param {function(?)} callback
* @return {function()} Unbind function.
*/
GrAttributeHelper.prototype.bind = function(name, callback) {
const attributeChangedEventName = this._getChangedEventName(name);
const changedHandler = e => this._reportValue(callback, e.detail.value);
const unbind = () =>... | /**
* Binds callback to property updates.
*
* @param {string} name Property name. | random_line_split |
gr-attribute-helper.js | // Copyright (C) 2017 The Android Open Source Project
//
// 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 ... |
GrAttributeHelper.prototype._getChangedEventName = function(name) {
return name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() + '-changed';
};
/**
* Returns true if the property is defined on wrapped element.
* @param {string} name
* @return {boolean}
*/
GrAttributeHelper.prototype._eleme... | {
this.element = element;
this._promises = {};
} | identifier_body |
gr-attribute-helper.js | // Copyright (C) 2017 The Android Open Source Project
//
// 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 ... |
return this._promises[name];
};
window.GrAttributeHelper = GrAttributeHelper;
})(window);
| {
let resolve;
const promise = new Promise(r => resolve = r);
const unbind = this.bind(name, value => {
resolve(value);
unbind();
});
this._promises[name] = promise;
} | conditional_block |
index.ts | import {
parseProgrammes,
parseSubjects,
parseCourses,
} from "@education-data/parser";
import { join } from "path";
import { writeFileSync } from "fs";
import { format } from "date-fns";
import { sv } from "date-fns/locale";
import { sourceDirectory, outputDirectory, replacementsDirectory } from "./cfg";
async... | ,
} as Map<string, any>,
sourceDirectory,
outputDirectory,
replacementsDirectory
);
console.info("\n[parsing program data]");
await parseProgrammes(
sourceDirectory + "/../gyP1_6_S1_4",
outputDirectory,
replacementsDirectory
);
p;
writeFileSync(
"./out/meta.json",
JSON.... | {
const subjects = require("./out/subjects.json");
const name = subjects.find((el) => el.code === code);
return require(join(process.cwd(), "./out", name.file));
} | identifier_body |
index.ts | import {
parseProgrammes,
parseSubjects,
parseCourses,
} from "@education-data/parser";
import { join } from "path";
import { writeFileSync } from "fs";
import { format } from "date-fns";
import { sv } from "date-fns/locale";
import { sourceDirectory, outputDirectory, replacementsDirectory } from "./cfg";
async... |
console.info("\n[parsing program data]");
await parseProgrammes(
sourceDirectory + "/../gyP1_6_S1_4",
outputDirectory,
replacementsDirectory
);
p;
writeFileSync(
"./out/meta.json",
JSON.stringify({
fetchTime: new Date().toISOString(),
humanizedFetchTime: format(new Date(), "d... | replacementsDirectory
); | random_line_split |
index.ts | import {
parseProgrammes,
parseSubjects,
parseCourses,
} from "@education-data/parser";
import { join } from "path";
import { writeFileSync } from "fs";
import { format } from "date-fns";
import { sv } from "date-fns/locale";
import { sourceDirectory, outputDirectory, replacementsDirectory } from "./cfg";
async... | (code: string) {
const subjects = require("./out/subjects.json");
const name = subjects.find((el) => el.code === code);
return require(join(process.cwd(), "./out", name.file));
},
} as Map<string, any>,
sourceDirectory,
outputDirectory,
replacementsDirectory
);
console... | get | identifier_name |
layout.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | (self):
event = self._conf.as_event
if not event.has_stylesheet:
raise NotFound
data = BytesIO(event.stylesheet.encode('utf-8'))
return send_file(event.stylesheet_metadata['filename'], data, mimetype='text/css', conditional=True)
| _process | identifier_name |
layout.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
image_bytes = BytesIO()
img.save(image_bytes, 'PNG')
image_bytes.seek(0)
content = image_bytes.read()
self.event.logo = content
self.event.logo_metadata = {
'hash': crc32(content),
'size': len(content),
'filename': os.path.splitext(sec... | flash(_('The logo you uploaded is using the CMYK colorspace and has been converted to RGB. Please check if '
'the colors are correct and convert it manually if necessary.'), 'warning')
img = img.convert('RGB') | conditional_block |
layout.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
class RHLayoutEdit(RHLayoutBase):
def _checkProtection(self):
RHLayoutBase._checkProtection(self)
if self._conf.getType() != 'conference':
raise NotFound('Only conferences have layout settings')
def _process(self):
defaults = FormDefaults(**layout_settings.get_all(self._c... | RHConferenceModifBase._checkParams(self, params)
self.event = self._conf.as_event | identifier_body |
layout.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | 'size': len(self.event.stylesheet),
'filename': secure_filename(f.filename, 'stylesheet.css')
}
db.session.flush()
flash(_('New CSS file saved. Do not forget to enable it ("Use custom CSS") after verifying that it is correct '
'using the preview.'), 'succe... | def _process(self):
f = request.files['file']
self.event.stylesheet = to_unicode(f.read()).strip()
self.event.stylesheet_metadata = {
'hash': crc32(self.event.stylesheet), | random_line_split |
sunos.py | """engine.SCons.Platform.sunos
Platform-specific initialization for Sun systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is h... |
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| posix.generate(env)
# Based on sunSparc 8:32bit
# ARG_MAX=1048320 - 3000 for environment expansion
env['MAXLINELENGTH'] = 1045320
env['PKGINFO'] = 'pkginfo'
env['PKGCHK'] = '/usr/sbin/pkgchk'
env['ENV']['PATH'] = env['ENV']['PATH'] + ':/opt/SUNWspro/bin:/usr/ccs/bin' | identifier_body |
sunos.py | """engine.SCons.Platform.sunos
Platform-specific initialization for Sun systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is h... | (env):
posix.generate(env)
# Based on sunSparc 8:32bit
# ARG_MAX=1048320 - 3000 for environment expansion
env['MAXLINELENGTH'] = 1045320
env['PKGINFO'] = 'pkginfo'
env['PKGCHK'] = '/usr/sbin/pkgchk'
env['ENV']['PATH'] = env['ENV']['PATH'] + ':/opt/SUNWspro/bin:/usr/ccs/bin'
# Local Variabl... | generate | identifier_name |
sunos.py | """engine.SCons.Platform.sunos
Platform-specific initialization for Sun systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is h... | #
__revision__ = "src/engine/SCons/Platform/sunos.py rel_2.5.0:3543:937e55cd78f7 2016/04/09 11:29:54 bdbaddog"
import posix
def generate(env):
posix.generate(env)
# Based on sunSparc 8:32bit
# ARG_MAX=1048320 - 3000 for environment expansion
env['MAXLINELENGTH'] = 1045320
env['PKGINFO'] = 'pkgin... | # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE O... | random_line_split |
index.js | import React from 'react'
const EditableText = React.createClass({
propTypes: {
onSubmit: React.PropTypes.func.isRequired,
validator: React.PropTypes.func,
enableEditing: React.PropTypes.bool,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
])
},
... | else {
return (<span>{this.props.value}</span>);
}
}
});
export default EditableText
| {
return (
<div className="inline-edit">
{this.state.editing
? this.renderInputForm()
: <a onClick={this.edit} title="Edit" className={'inline-editable'}>{this.props.value || 'Add'}</a>
}
</div>
);
} | conditional_block |
index.js | import React from 'react'
const EditableText = React.createClass({
propTypes: {
onSubmit: React.PropTypes.func.isRequired,
validator: React.PropTypes.func,
enableEditing: React.PropTypes.bool,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
])
},
... | (e) {
this.setState({newValue: e.target.value});
},
cancelEdit() {
this.setState({
editing: false,
invalid: false,
});
},
submit(e) {
e.preventDefault();
if (!this.props.validator || this.props.validator(this.state.newValue)) {
this.props.onSubmit(this.state.newValue);
... | handleChange | identifier_name |
index.js | import React from 'react'
const EditableText = React.createClass({
propTypes: {
onSubmit: React.PropTypes.func.isRequired,
validator: React.PropTypes.func,
enableEditing: React.PropTypes.bool,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
])
},
... | ,
render: function() {
if (this.props.enableEditing) {
return (
<div className="inline-edit">
{this.state.editing
? this.renderInputForm()
: <a onClick={this.edit} title="Edit" className={'inline-editable'}>{this.props.value || 'Add'}</a>
}
</div>
... | {
const inputForm = (
<form onSubmit={this.submit}
className={this.state.invalid ? 'has-error' : ''} >
<input type="text" autoFocus
onChange={this.handleChange}
onBlur={this.cancelEdit}
value={this.state.newValue}
className="form-control inline-editable" />
... | identifier_body |
index.js | import React from 'react'
const EditableText = React.createClass({
propTypes: {
onSubmit: React.PropTypes.func.isRequired,
validator: React.PropTypes.func,
enableEditing: React.PropTypes.bool,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
])
},
... |
export default EditableText | random_line_split | |
whitespace.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[test]
fn test_trim_http_whitespace() {
fn test_trim(in_: &[u8], out: &[u8]) |
test_trim(b"", b"");
test_trim(b" ", b"");
test_trim(b"a", b"a");
test_trim(b" a", b"a");
test_trim(b"a ", b"a");
test_trim(b" a ", b"a");
test_trim(b"\t", b"");
test_trim(b"a", b"a");
test_trim(b"\ta", b"a");
test_trim(b"a\t", b"a");
test_trim(b"\ta\t", b"a");
}
| {
let b = net_traits::trim_http_whitespace(in_);
assert_eq!(b, out);
} | identifier_body |
whitespace.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[test]
fn test_trim_http_whitespace() {
fn | (in_: &[u8], out: &[u8]) {
let b = net_traits::trim_http_whitespace(in_);
assert_eq!(b, out);
}
test_trim(b"", b"");
test_trim(b" ", b"");
test_trim(b"a", b"a");
test_trim(b" a", b"a");
test_trim(b"a ", b"a");
test_trim(b" a ", b"a");
test_trim(b"\t", b"");
test_tr... | test_trim | identifier_name |
whitespace.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[test]
fn test_trim_http_whitespace() {
fn test_trim(in_: &[u8], out: &[u8]) {
let b = net_traits::t... |
test_trim(b" ", b"");
test_trim(b"a", b"a");
test_trim(b" a", b"a");
test_trim(b"a ", b"a");
test_trim(b" a ", b"a");
test_trim(b"\t", b"");
test_trim(b"a", b"a");
test_trim(b"\ta", b"a");
test_trim(b"a\t", b"a");
test_trim(b"\ta\t", b"a");
} | test_trim(b"", b""); | random_line_split |
test_move_gripper.py | #!/usr/bin/env python
import time
import roslib;
import rospy
import actionlib
from control_msgs.msg import *
from std_msgs.msg import Float64
JOINT_NAME = ['PhantomXPincher_gripperClose_joint']
client = None
def move1():
g = GripperCommandGoal()
g.command = GripperCommand()
g.command.position = 0.15
... | main() | conditional_block | |
test_move_gripper.py | #!/usr/bin/env python
import time
import roslib;
import rospy
import actionlib
from control_msgs.msg import *
from std_msgs.msg import Float64
JOINT_NAME = ['PhantomXPincher_gripperClose_joint']
client = None
def move1():
g = GripperCommandGoal()
g.command = GripperCommand()
g.command.position = 0.15
... |
if __name__ == '__main__': main()
| global client
try:
rospy.init_node("test_move", anonymous=True, disable_signals=True)
client = actionlib.SimpleActionClient('gripper_command', GripperCommandAction)
print "Waiting for server..."
client.wait_for_server()
print "Connected to server"
mo... | identifier_body |
test_move_gripper.py | #!/usr/bin/env python
import time
import roslib;
import rospy
import actionlib
from control_msgs.msg import *
from std_msgs.msg import Float64
JOINT_NAME = ['PhantomXPincher_gripperClose_joint']
client = None
def | ():
g = GripperCommandGoal()
g.command = GripperCommand()
g.command.position = 0.15
print JOINT_NAME
client.send_goal(g)
try:
client.wait_for_result()
except KeyboardInterrupt:
client.cancel_goal()
raise
def main():
global client
try:
rospy.init_node(... | move1 | identifier_name |
test_move_gripper.py | #!/usr/bin/env python
import time
import roslib;
import rospy
import actionlib
from control_msgs.msg import *
from std_msgs.msg import Float64
JOINT_NAME = ['PhantomXPincher_gripperClose_joint']
client = None
def move1():
g = GripperCommandGoal()
g.command = GripperCommand()
g.command.position = 0.15
... | move1()
except KeyboardInterrupt:
rospy.signal_shutdown("KeyboardInterrupt")
raise
if __name__ == '__main__': main() | client.wait_for_server()
print "Connected to server"
| random_line_split |
user-login.component.ts | import { Component, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Router } from '@angular/router';
import { loginUser, userInfo } from './../../api';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'app-login',
templateUrl: './user-login.component.html',
st... | () {
this.handlingLogin = true;
this.error = { messages: null };
let payload = {
email: this.email,
password: this.password
}
this.http.post(loginUser, payload)
.toPromise()
.then(response => {
// Otrzymaliśmy od serwera nasze userID oraz wygenerowany sessionToken.... | handleLogin | identifier_name |
user-login.component.ts | import { Component, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Router } from '@angular/router';
import { loginUser, userInfo } from './../../api';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'app-login',
templateUrl: './user-login.component.html',
st... | })
})
.catch(response => {
this.error.messages = response.json().messages
this.handlingLogin = false;
scroll(0,0)
})
}
} | .catch(response => {
this.error.messages = response.json().messages
this.handlingLogin = false;
scroll(0,0) | random_line_split |
index.d.ts | // Type definitions for wanakana 4.0
// Project: https://github.com/WaniKani/WanaKana
// Definitions by: Ross Hendry <https://github.com/chooban>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace wanakana;
... | export const VERSION: string;
export const TO_KANA_METHODS: Record<string, string>;
export const ROMANIZATIONS: Record<string, string>;
export function bind(el: HTMLInputElement | HTMLTextAreaElement, options?: WanakanaOptions): void;
export function unbind(el: HTMLInputElement | HTMLTextAreaElement): void;
export fu... | }
| random_line_split |
graphql-async-class.spec.ts | import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as request from 'supertest';
import { AsyncClassApplicationModule } from '../src/async-options-class.module';
describe('GraphQL (async class)', () => {
let app: INestApplication;
beforeEach(async () => {
ap... | operationName: null,
variables: {},
query: '{\n getCats {\n id\n }\n}\n',
})
.expect(200, {
data: {
getCats: [
{
id: 1,
},
],
},
});
});
afterEach(async () => {
await app.close();
});
}); | it(`should return query result`, () => {
return request(app.getHttpServer())
.post('/graphql')
.send({ | random_line_split |
jbossPlugin.ts | /**
* @module JBoss
* @main JBoss
*/
/// <reference path="jbossHelpers.ts"/>
module JBoss {
var pluginName = 'jboss';
export var _module = angular.module(pluginName, ['bootstrap', 'ngResource', 'ui.bootstrap.dialog', 'hawtioCore']);
_module.config(["$routeProvider", ($routeProvider) => {
$routeProvider.
... | workspace.treeContainsDomainAndProperties("jboss.jta") ||
workspace.treeContainsDomainAndProperties("jboss.modules"),
href: () => "#/jboss/applications",
isActive: (workspace: Workspace) => workspace.isTopTabActive("jboss")
});
}]);
hawtioPluginLoader.addModule(pluginNa... | random_line_split | |
lib.rs | #![feature(entry_and_modify)]
use std::collections::HashMap;
use std::cmp::Ordering;
const HEADER: &str = "Team | MP | W | D | L | P";
#[derive(Default, Eq, PartialEq)]
struct Team {
name: String,
wins: u32,
losses: u32,
drawns: u32,
matches: u32,
}
fn oposite(resul... |
}
impl PartialOrd for Team {
fn partial_cmp(&self, other: &Team) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Default)]
struct ScoreTable<'a> {
registry: HashMap<&'a str, Team>,
}
impl<'a> ScoreTable<'a> {
pub fn record_match(&mut self, one_match: &'a str) {
for row in on... | {
match other.points().cmp(&self.points()) {
Ordering::Equal => self.name.partial_cmp(&other.name).unwrap(),
other => other,
}
} | identifier_body |
lib.rs | #![feature(entry_and_modify)]
use std::collections::HashMap;
use std::cmp::Ordering;
const HEADER: &str = "Team | MP | W | D | L | P";
#[derive(Default, Eq, PartialEq)]
struct Team {
name: String,
wins: u32,
losses: u32,
drawns: u32,
matches: u32,
}
fn oposite(resul... | let header = String::from(HEADER);
let summaries: String = ScoreTable::from(input)
.teams()
.iter()
.map(|team| team.summary())
.collect::<Vec<_>>()
.join("\n");
if summaries.is_empty() {
return header;
}
header + "\n" + &summaries
} |
pub fn tally(input: &str) -> String { | random_line_split |
lib.rs | #![feature(entry_and_modify)]
use std::collections::HashMap;
use std::cmp::Ordering;
const HEADER: &str = "Team | MP | W | D | L | P";
#[derive(Default, Eq, PartialEq)]
struct Team {
name: String,
wins: u32,
losses: u32,
drawns: u32,
matches: u32,
}
fn oposite(resul... | (name: &str) -> Self {
Self {
name: String::from(name),
wins: 0,
losses: 0,
drawns: 0,
matches: 0,
}
}
pub fn points(&self) -> u32 {
self.wins * 3 + self.drawns
}
pub fn record_result(&mut self, result: &str) {
... | new | identifier_name |
suppress_ga.py | """
SUPPRESS-GO-AHEAD
This supports suppressing or activating Evennia
the GO-AHEAD telnet operation after every server reply.
If the client sends no explicit DONT SUPRESS GO-AHEAD,
Evennia will default to supressing it since many clients
will fail to use it and has no knowledge of this standard.
It is set as the NOG... |
def dont_suppress_ga(self, option):
"""
Called when client requests to not suppress GA.
Args:
option (Option): Not used.
"""
self.protocol.protocol_flags["NOGOAHEAD"] = True
self.protocol.handshake_done()
def do_suppress_ga(self, option):
"... | self.protocol.will(SUPPRESS_GA).addCallbacks(self.do_suppress_ga, self.dont_suppress_ga)
# ... but also accept if the client really wants not to.
self.protocol.do(SUPPRESS_GA).addCallbacks(self.do_suppress_ga, self.dont_suppress_ga) | random_line_split |
suppress_ga.py | """
SUPPRESS-GO-AHEAD
This supports suppressing or activating Evennia
the GO-AHEAD telnet operation after every server reply.
If the client sends no explicit DONT SUPRESS GO-AHEAD,
Evennia will default to supressing it since many clients
will fail to use it and has no knowledge of this standard.
It is set as the NOG... | (object):
"""
Implements the SUPRESS-GO-AHEAD protocol. Add this to a variable on the telnet
protocol to set it up.
"""
def __init__(self, protocol):
"""
Initialize suppression of GO-AHEADs.
Args:
protocol (Protocol): The active protocol instance.
"""
... | SuppressGA | identifier_name |
suppress_ga.py | """
SUPPRESS-GO-AHEAD
This supports suppressing or activating Evennia
the GO-AHEAD telnet operation after every server reply.
If the client sends no explicit DONT SUPRESS GO-AHEAD,
Evennia will default to supressing it since many clients
will fail to use it and has no knowledge of this standard.
It is set as the NOG... |
def dont_suppress_ga(self, option):
"""
Called when client requests to not suppress GA.
Args:
option (Option): Not used.
"""
self.protocol.protocol_flags["NOGOAHEAD"] = True
self.protocol.handshake_done()
def do_suppress_ga(self, option):
"... | """
Implements the SUPRESS-GO-AHEAD protocol. Add this to a variable on the telnet
protocol to set it up.
"""
def __init__(self, protocol):
"""
Initialize suppression of GO-AHEADs.
Args:
protocol (Protocol): The active protocol instance.
"""
self.pr... | identifier_body |
api.py | import json
import bottle
from pyrouted.util import make_spec
def route(method, path):
def decorator(f):
f.http_route = path
f.http_method = method
return f
return decorator
class APIv1(object):
prefix = '/v1'
def __init__(self, ndb, config):
self.ndb = ndb
... |
@route('GET', '/query/<name:re:(%s|%s|%s|%s)>' % ('nodes',
'p2p_edges',
'l2_edges',
'l3_edges'))
def query(self, name):
ret = []
obj... | ret = []
obj = getattr(self.ndb, name)
for line in obj.dump():
ret.append(line)
return bottle.template('{{!ret}}', ret=json.dumps(ret)) | identifier_body |
api.py | import json
import bottle
from pyrouted.util import make_spec
def route(method, path):
def decorator(f):
f.http_route = path
f.http_method = method
return f
return decorator
class | (object):
prefix = '/v1'
def __init__(self, ndb, config):
self.ndb = ndb
self.config = config
@route('GET', '/sources')
def sources_list(self, mode='short'):
ret = {}
mode = bottle.request.query.mode or mode
for name, spec in self.ndb.sources.items():
... | APIv1 | identifier_name |
api.py | import json
import bottle
from pyrouted.util import make_spec
def route(method, path):
def decorator(f):
f.http_route = path
f.http_method = method
return f
return decorator
class APIv1(object):
prefix = '/v1' | def __init__(self, ndb, config):
self.ndb = ndb
self.config = config
@route('GET', '/sources')
def sources_list(self, mode='short'):
ret = {}
mode = bottle.request.query.mode or mode
for name, spec in self.ndb.sources.items():
ret[name] = {'class': spec.n... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.