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 |
|---|---|---|---|---|
tuple.rs |
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct | {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for Tuple {
fn as_any(&self) -> &dyn Any {self}
fn type_name(&self, _env: &mut Env) -> String {
"Tuple".to_string()
}
fn to_string(sel... | Tuple | identifier_name |
tuple.rs |
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct Tuple {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for... |
fn eq_plain(&self, b: &Object) -> bool {
if let Some(b) = downcast::<Tuple>(b) {
if self.v.len() == b.v.len() {
for i in 0..self.v.len() {
if self.v[i] != b.v[i] {return false;}
}
true
} else {
false... | {
match indices.len() {
1 => {}, n => return env.argc_error(n,1,1,"tuple indexing")
}
let i = match indices[0] {
Object::Int(i) => if i<0 {0} else {i as usize},
ref i => return env.type_error1(
"Type error in t[i]: i is not an integer.",
... | identifier_body |
uuid.rs | //! MC Protocol UUID data type.
use std::io::ErrorKind::InvalidInput;
use std::io::prelude::*;
use std::io;
use std::str::FromStr;
use packet::Protocol;
use util::ReadExactly;
use uuid::{ParseError, Uuid};
/// UUID read/write wrapper.
impl Protocol for Uuid {
type Clean = Uuid;
fn proto_len(_: &Uuid) -> us... | (value: &Uuid, dst: &mut Write) -> io::Result<()> {
<String as Protocol>::proto_encode(&value.to_hyphenated_string(), dst)
}
fn proto_decode(src: &mut Read) -> io::Result<Uuid> {
// Unfortunately we can't implement `impl FromError<ParseError> for io::Error`
let s = try!(<String as Proto... | proto_encode | identifier_name |
uuid.rs | //! MC Protocol UUID data type.
use std::io::ErrorKind::InvalidInput;
use std::io::prelude::*;
use std::io;
use std::str::FromStr;
use packet::Protocol;
use util::ReadExactly;
use uuid::{ParseError, Uuid};
/// UUID read/write wrapper.
impl Protocol for Uuid {
type Clean = Uuid;
fn proto_len(_: &Uuid) -> us... | let s = try!(<String as Protocol>::proto_decode(src));
Uuid::from_str(&s).map_err(|err| match err {
ParseError::InvalidLength(length) => io::Error::new(InvalidInput, &format!("Invalid length: {}", length)[..]),
ParseError::InvalidCharacter(_, _) => io::Error::new(InvalidInput, "i... | fn proto_decode(src: &mut Read) -> io::Result<Uuid> {
// Unfortunately we can't implement `impl FromError<ParseError> for io::Error` | random_line_split |
uuid.rs | //! MC Protocol UUID data type.
use std::io::ErrorKind::InvalidInput;
use std::io::prelude::*;
use std::io;
use std::str::FromStr;
use packet::Protocol;
use util::ReadExactly;
use uuid::{ParseError, Uuid};
/// UUID read/write wrapper.
impl Protocol for Uuid {
type Clean = Uuid;
fn proto_len(_: &Uuid) -> us... |
}
pub struct UuidString;
impl Protocol for UuidString {
type Clean = Uuid;
fn proto_len(value: &Uuid) -> usize {
<String as Protocol>::proto_len(&value.to_hyphenated_string())
}
fn proto_encode(value: &Uuid, dst: &mut Write) -> io::Result<()> {
<String as Protocol>::proto_encode(&va... | {
let v = try!(src.read_exactly(16));
Uuid::from_bytes(&v).ok_or(io::Error::new(io::ErrorKind::InvalidInput, &format!("Invalid UUID value: {:?} can't be used to create UUID", v)[..]))
} | identifier_body |
animation-constructor.js | // Copyright 2014 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 required by applicable... | (node) {
return node._timing.delay + node.activeDuration + node._timing.endDelay;
};
function KeyframeEffect(effect) {
this._frames = shared.normalizeKeyframes(effect);
}
KeyframeEffect.prototype = {
getFrames: function() { return this._frames; }
};
scope.Animation = function(target, effect, ... | groupChildDuration | identifier_name |
animation-constructor.js | // Copyright 2014 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 required by applicable... | ;
function KeyframeEffect(effect) {
this._frames = shared.normalizeKeyframes(effect);
}
KeyframeEffect.prototype = {
getFrames: function() { return this._frames; }
};
scope.Animation = function(target, effect, timingInput) {
this.target = target;
// TODO: Store a clone, not the same instan... | {
return node._timing.delay + node.activeDuration + node._timing.endDelay;
} | identifier_body |
animation-constructor.js | // Copyright 2014 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 required by applicable... | };
scope.Animation = function(target, effect, timingInput) {
this.target = target;
// TODO: Store a clone, not the same instance.
this._timingInput = timingInput;
this._timing = shared.normalizeTimingInput(timingInput);
// TODO: Make modifications to timing update the underlying player
th... | KeyframeEffect.prototype = {
getFrames: function() { return this._frames; } | random_line_split |
generations.js | "use strict";
const utils = require('../utils/utils');
const ruleRegexp = /^S?([0-9]*)\/B?([0-9]*)\/C?([1-9][0-9]*)([MV]?)([0-9]*)$/i;
function getNeighbourMethod (methodId) {
if (methodId === 'V' || methodId === 'v' || methodId === 'von-neumann') {
return 'von-neumann';
} else {
return 'moore';
}
}
fu... | neighbourhoodType: getNeighbourMethod(extractedRule[4]),
neighbourhoodRange: parseInt(extractedRule[5], 10) || 1
} : null;
}; | ruleString: ruleString,
survival: utils.splitStringInNumberArray(extractedRule[1]),
birth: utils.splitStringInNumberArray(extractedRule[2]),
stateCount: parseInt(extractedRule[3], 10) || 1, | random_line_split |
generations.js | "use strict";
const utils = require('../utils/utils');
const ruleRegexp = /^S?([0-9]*)\/B?([0-9]*)\/C?([1-9][0-9]*)([MV]?)([0-9]*)$/i;
function getNeighbourMethod (methodId) {
if (methodId === 'V' || methodId === 'v' || methodId === 'von-neumann') {
return 'von-neumann';
} else {
return 'moore';
}
}
fu... |
return result;
}
module.exports = function parseRuleString (ruleString) {
const extractedRule = ruleRegexp.exec(utils.stripWhitespaces(ruleString));
return extractedRule ? {
process: generationsFunction,
ruleFormat: 'generations',
ruleString: ruleString,
survival: utils.splitStringInNumberArra... | {
result = (currentValue + 1) % this.stateCount;
} | conditional_block |
generations.js | "use strict";
const utils = require('../utils/utils');
const ruleRegexp = /^S?([0-9]*)\/B?([0-9]*)\/C?([1-9][0-9]*)([MV]?)([0-9]*)$/i;
function getNeighbourMethod (methodId) |
function generationsFunction (currentValue, neighbours) {
let sum = 0;
let result = 0;
for (let index = 0; index < neighbours.length; index++) {
sum = sum + (neighbours[index] === 1 ? 1 : 0);
}
if (currentValue === 0 && this.birth.indexOf(sum) > -1) {
result = 1;
} else if (currentValue === 1 &&... | {
if (methodId === 'V' || methodId === 'v' || methodId === 'von-neumann') {
return 'von-neumann';
} else {
return 'moore';
}
} | identifier_body |
generations.js | "use strict";
const utils = require('../utils/utils');
const ruleRegexp = /^S?([0-9]*)\/B?([0-9]*)\/C?([1-9][0-9]*)([MV]?)([0-9]*)$/i;
function | (methodId) {
if (methodId === 'V' || methodId === 'v' || methodId === 'von-neumann') {
return 'von-neumann';
} else {
return 'moore';
}
}
function generationsFunction (currentValue, neighbours) {
let sum = 0;
let result = 0;
for (let index = 0; index < neighbours.length; index++) {
sum = sum ... | getNeighbourMethod | identifier_name |
XHR.js | CAAT.Module({
defines : "CAAT.Module.Preloader.XHR",
extendsWith : {
/**
*
* @param callback function({string},{object}) a callback function. string will be "ok" or "error"
* @param url {string} a url
* @param asynch {bool} load synchronous or asynchronously
... | }
if(req) {
req.open(method, url, false);
req.onreadystatechange = function(e) {
if( req.status != 200 )
return callback("error");
var text= e.currentTarget ? e.currentTarget.responseText : e.targe... | } | random_line_split |
XHR.js | CAAT.Module({
defines : "CAAT.Module.Preloader.XHR",
extendsWith : {
/**
*
* @param callback function({string},{object}) a callback function. string will be "ok" or "error"
* @param url {string} a url
* @param asynch {bool} load synchronous or asynchronously
... | else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
... | {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} | conditional_block |
EditDisruptionBudgetModal.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import {
Application,
TaskMonitor,
IJob,
IModalComponentProps,
ModalClose,
SubmitButton,
SpinFormik,
NgReact,
ReactModal,
TaskExecutor,
} from '@spinnaker/core';
import { JobDisruptionBudget } from '../../configure/wizard/pages/di... | taskMonitor.submit(() =>
TaskExecutor.executeTask({
job: [job],
application,
description: `Update Disruption Budget for ${serverGroup.name}`,
}),
);
}
public render() {
const { application, command, dismissModal } = this.props;
const { TaskMonitorWrapper } = NgRe... | random_line_split | |
EditDisruptionBudgetModal.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import {
Application,
TaskMonitor,
IJob,
IModalComponentProps,
ModalClose,
SubmitButton,
SpinFormik,
NgReact,
ReactModal,
TaskExecutor,
} from '@spinnaker/core';
import { JobDisruptionBudget } from '../../configure/wizard/pages/di... | (values: ITitusServerGroupCommand, taskMonitor: TaskMonitor): void {
const { application, serverGroup } = this.props;
const job: IJob = {
type: 'upsertDisruptionBudget',
cloudProvider: 'titus',
credentials: serverGroup.account,
region: serverGroup.region,
jobId: serverGroup.id,
... | submit | identifier_name |
EditDisruptionBudgetModal.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import {
Application,
TaskMonitor,
IJob,
IModalComponentProps,
ModalClose,
SubmitButton,
SpinFormik,
NgReact,
ReactModal,
TaskExecutor,
} from '@spinnaker/core';
import { JobDisruptionBudget } from '../../configure/wizard/pages/di... |
private submit(values: ITitusServerGroupCommand, taskMonitor: TaskMonitor): void {
const { application, serverGroup } = this.props;
const job: IJob = {
type: 'upsertDisruptionBudget',
cloudProvider: 'titus',
credentials: serverGroup.account,
region: serverGroup.region,
jobId: s... | {
return ReactModal.show(EditDisruptionBudgetModal, props);
} | identifier_body |
union_pooler_test.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | self.unionPooler._poolingActivation = numpy.array([0, 0, 0, 3, 4],
dtype=REAL_DTYPE)
self.unionPooler._maxUnionCells = 3
result = self.unionPooler._getMostActiveCells()
self.assertEquals(len(result), 2)
self.assertEquals(result[0], 3)
self.... |
def testGetMostActiveCellsIgnoreZeros(self): | random_line_split |
union_pooler_test.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
def testGetMostActiveCellsRegular(self):
self.unionPooler._poolingActivation = numpy.array([0, 1, 2, 3, 4],
dtype=REAL_DTYPE)
result = self.unionPooler._getMostActiveCells()
self.assertEquals(len(result), 1)
self.assertEquals(result[0], 4)
... | self.unionPooler._poolingActivation = numpy.array([0, 1, 2, 3, 4],
dtype=REAL_DTYPE)
self.unionPooler._maxUnionCells = 0
result = self.unionPooler._getMostActiveCells()
self.assertEquals(len(result), 0) | identifier_body |
union_pooler_test.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | unittest.main() | conditional_block | |
union_pooler_test.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | (self):
self.unionPooler._poolingActivation = numpy.array([0, 1, 2, 3, 4],
dtype=REAL_DTYPE)
self.unionPooler._maxUnionCells = 0
result = self.unionPooler._getMostActiveCells()
self.assertEquals(len(result), 0)
def testGetMostActiveCellsRegular... | testGetMostActiveCellsUnionSizeZero | identifier_name |
lib.rs | //! Internal library for data-encoding-macro
//!
//! Do **not** use this library. Use [data-encoding-macro] instead.
//!
//! This library is for internal use by data-encoding-macro because procedural
//! macros require a separate crate.
//!
//! [data-encoding-macro]: https://crates.io/crates/data-encoding-macro
#![war... | {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
format!("{:?}", encoding.decode(input.as_bytes()).unwrap()).parse().unwrap()
} | identifier_body | |
lib.rs | //! Internal library for data-encoding-macro
//!
//! Do **not** use this library. Use [data-encoding-macro] instead.
//!
//! This library is for internal use by data-encoding-macro because procedural
//! macros require a separate crate.
//!
//! [data-encoding-macro]: https://crates.io/crates/data-encoding-macro
#![war... | (input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_empty(hash_map);
format!("{:?}", encoding.internal_implementation()).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_array(input: TokenStream) ... | internal_new_encoding | identifier_name |
lib.rs | //! Internal library for data-encoding-macro
//!
//! Do **not** use this library. Use [data-encoding-macro] instead.
//!
//! This library is for internal use by data-encoding-macro because procedural
//! macros require a separate crate.
//!
//! [data-encoding-macro]: https://crates.io/crates/data-encoding-macro
#![war... | pub fn internal_new_encoding(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_empty(hash_map);
format!("{:?}", encoding.internal_implementation()).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decod... | }
#[proc_macro]
#[doc(hidden)] | random_line_split |
simple.rs | #![feature(plugin)]
#![plugin(must_assert)]
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
fn str_contains() |
#[test]
fn simple() {
assume!("" == "");
assume!("" == "" || "" == "");
assume!("" == "" && "" == "");
}
#[test]
#[should_panic(expected = "Diff:
foo
-bar
baz
+bar
quux")]
fn str_fail_diff() {
env::set_var(COLOR_ENV, "none");
assume!("foo
bar
baz
quux" ==
"foo
baz
bar
quux... | {
assume!("Banana".contains("nana"));
} | identifier_body |
simple.rs | #![feature(plugin)]
#![plugin(must_assert)]
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
fn | () {
assume!("Banana".contains("nana"));
}
#[test]
fn simple() {
assume!("" == "");
assume!("" == "" || "" == "");
assume!("" == "" && "" == "");
}
#[test]
#[should_panic(expected = "Diff:
foo
-bar
baz
+bar
quux")]
fn str_fail_diff() {
env::set_var(COLOR_ENV, "none");
assume!("foo
bar
... | str_contains | identifier_name |
simple.rs | #![feature(plugin)]
#![plugin(must_assert)]
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
fn str_contains() {
assume!("Banana".contains("nana"));
}
#[test]
fn simple() {
assume!("" == "");
assume!("" == "" || "" == "");
assume!("" == "" && "" == "");
}
#[test]
#[should_panic(... | | 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
env::set_var(COLOR_ENV, "none");
assume!(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"] == vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"]);
} | #[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
| random_line_split |
htmltrackelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrack... | document: &Document) -> Root<HTMLTrackElement> {
let element = HTMLTrackElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap)
}
} | prefix: Option<DOMString>, | random_line_split |
htmltrackelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrack... | (localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLTrackElement {
HTMLTrackElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMStr... | new_inherited | identifier_name |
index.ts | import { Injectable } from '@angular/core';
import { Plugin, Cordova } from '@ionic-native/core';
/**
* @beta
* @name Backlight
* @description
* This plugin adds turning on/off the device backlight.
*
* @usage
* ```
* import { Backlight } from '@ionic-native/backlight';
*
* constructor(private backlight: Ba... | (): Promise<any> { return; }
}
| off | identifier_name |
index.ts | import { Injectable } from '@angular/core';
import { Plugin, Cordova } from '@ionic-native/core';
/**
* @beta
* @name Backlight
* @description
* This plugin adds turning on/off the device backlight.
*
* @usage
* ```
* import { Backlight } from '@ionic-native/backlight';
*
* constructor(private backlight: Ba... | * @return {Promise<any>} Returns a promise that resolves when the backlight is on
*/
@Cordova()
on(): Promise<any> { return; }
/**
* This function turns backlight off
* @return {Promise<any>} Returns a promise that resolves when the backlight is off
*/
@Cordova()
off(): Promise<any> { return; ... | * This function turns backlight on | random_line_split |
RiftSlash.ts |
import { Skill } from '../../../../../base/Skill';
import { Character } from '../../../../../../shared/models/character';
import { CombatHelper } from '../../../../../helpers/world/combat-helper';
import { MessageHelper } from '../../../../../helpers/world/message-helper';
import { Player } from '../../../../../../s... | (user: Player) { return 10; }
range(attacker: Character) {
return this.calcPlainAttackRange(attacker, 5);
}
execute(user: Player, { args }) {
if(!args) return false;
if(!this.tryToConsumeMP(user)) return;
const range = this.range(user);
if(range === -1) return user.sendClientMessage('You n... | mpCost | identifier_name |
RiftSlash.ts |
import { Skill } from '../../../../../base/Skill';
import { Character } from '../../../../../../shared/models/character';
import { CombatHelper } from '../../../../../helpers/world/combat-helper';
import { MessageHelper } from '../../../../../helpers/world/message-helper';
import { Player } from '../../../../../../s... |
}
| {
user.$$room.teleport(user, { x: target.x, y: target.y });
user.$$room.updatePos(user);
if((user.baseClass === 'Warrior' || user.getTraitLevel('LearnedStrikes'))
&& user.isValidTargetForSkillGain(target)) user.gainSkill(user.rightHand ? user.rightHand.itemClass : SkillClassNames.Martial, 1);
Com... | identifier_body |
RiftSlash.ts | import { Skill } from '../../../../../base/Skill';
import { Character } from '../../../../../../shared/models/character';
import { CombatHelper } from '../../../../../helpers/world/combat-helper';
import { MessageHelper } from '../../../../../helpers/world/message-helper';
import { Player } from '../../../../../../shar... | range(attacker: Character) {
return this.calcPlainAttackRange(attacker, 5);
}
execute(user: Player, { args }) {
if(!args) return false;
if(!this.tryToConsumeMP(user)) return;
const range = this.range(user);
if(range === -1) return user.sendClientMessage('You need to have your left hand empt... | public format = 'Target';
public unableToLearnFromStealing = true;
mpCost(user: Player) { return 10; }
| random_line_split |
ArtistSeriesHeader.tsx | import React from "react"
import {
Box,
Clickable,
Col,
EntityHeader,
Flex,
HTML,
Image,
ReadMore,
Row,
Separator,
Text,
} from "@artsy/palette"
import { Media } from "v2/Utils/Responsive"
import { createFragmentContainer, graphql } from "react-relay"
import { FollowArtistButtonFragmentContainer a... | }
@media (min-width: ${unitlessBreakpoints.sm}px) {
max-height: 400px;
width: 100%;
object-fit: cover;
}
`
export const ArtistSeriesHeaderFragmentContainer = createFragmentContainer(
ArtistSeriesHeader,
{
artistSeries: graphql`
fragment ArtistSeriesHeader_artistSeries on ArtistSeries {... | @media (max-width: ${unitlessBreakpoints.sm - 1}px) {
max-width: 180px;
max-height: 180px;
margin: auto; | random_line_split |
NamespaceTestCase.js | /*
* Copyright 2012 Amadeus s.a.s.
* Licensed under the Apache License, Version 2.0 (the "License"); | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governi... | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* | random_line_split |
NamespaceTestCase.js | /*
* Copyright 2012 Amadeus s.a.s.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
},
/**
* Verify if the events are raised correctly
*/
testNamespaceEvents : function () {
if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) {
this.$GeneralNamespaceBase.testNamespaceEvents.call(this);
}
}
}
});... | {
this.$GeneralNamespaceBase.testNamespaceAPI.call(this);
} | conditional_block |
types.ts | table durability; 'hard' is the default
fields : # every field *must* be listed here or user queries won't work.
the_table_primary_key :
type : 'uuid'
desc : 'This is the primary key of the table.'
...
pg_indexes : [array of column names] # also some more complicated ... | fields:
id : true
...
*/
export const SCHEMA: DBSchema = {};
export function Table<F extends Fields>({
name,
rules,
fields,
}: {
name: string;
fields?: F;
rules: PartialSchema<F>;
}): void {
if (!rules.virtual) {
// runtime check that fields and primary_key are ... | schema.stats =
primary_key: 'id'
anonymous : true # allow user access, even if not signed in | random_line_split |
types.ts | durability; 'hard' is the default
fields : # every field *must* be listed here or user queries won't work.
the_table_primary_key :
type : 'uuid'
desc : 'This is the primary key of the table.'
...
pg_indexes : [array of column names] # also some more complicated ways t... | const T: TableSchema<F> = { ...rules, fields };
SCHEMA[name] = T;
}
export interface DBSchema {
[key: string]: TableSchema<any>;
}
interface Fields {
[key: string]:
| boolean
| {
type:
| "uuid"
| "timestamp"
| "string"
| "boolean"
| "map"
... | // runtime check that fields and primary_key are set.
// If there is a way to do this at compile time with typescript, that would be better.
if (fields == null || rules.primary_key == null) {
throw Error(
"db-schema error; fields and primary_key must be set for non-virtual tables"
);
... | conditional_block |
types.ts | ; 'hard' is the default
fields : # every field *must* be listed here or user queries won't work.
the_table_primary_key :
type : 'uuid'
desc : 'This is the primary key of the table.'
...
pg_indexes : [array of column names] # also some more complicated ways to define in... | extends Fields>({
name,
rules,
fields,
}: {
name: string;
fields?: F;
rules: PartialSchema<F>;
}): void {
if (!rules.virtual) {
// runtime check that fields and primary_key are set.
// If there is a way to do this at compile time with typescript, that would be better.
if (fields == null || rul... | le<F | identifier_name |
types.ts | ; 'hard' is the default
fields : # every field *must* be listed here or user queries won't work.
the_table_primary_key :
type : 'uuid'
desc : 'This is the primary key of the table.'
...
pg_indexes : [array of column names] # also some more complicated ways to define in... | xport interface DBSchema {
[key: string]: TableSchema<any>;
}
interface Fields {
[key: string]:
| boolean
| {
type:
| "uuid"
| "timestamp"
| "string"
| "boolean"
| "map"
| "array"
| "integer"
| "number"
| "Buf... | if (!rules.virtual) {
// runtime check that fields and primary_key are set.
// If there is a way to do this at compile time with typescript, that would be better.
if (fields == null || rules.primary_key == null) {
throw Error(
"db-schema error; fields and primary_key must be set for non-virtu... | identifier_body |
index.js | else if (match = segment.match(/^\*([^\/]+)$/)) {
results.push(new StarSegment(match[1]));
names.push(match[1]);
types.stars++;
}
else if (segment === "") {
results.push(new EpsilonSegment());
}
else {
results.push(new S... | {
output += this.generateQueryString(params.queryParams, route.handlers);
} | conditional_block | |
index.js | function (callback) {
callback({ invalidChars: "", repeat: true });
},
regex: function () {
return "(.+)";
},
generate: function (params) {
return params[this.name];
}
};
function EpsilonSegment() { }
EpsilonSegment.prototype = {
eachChar: function () { },
regex: fun... | (states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var oCreate = Object.create || function (proto) {
function F() { }
F.prototype = proto;
return n... | recognizeChar | identifier_name |
index.js | function (callback) {
callback({ invalidChars: "", repeat: true });
},
regex: function () {
return "(.+)";
},
generate: function (params) {
return params[this.name];
}
};
function EpsilonSegment() |
EpsilonSegment.prototype = {
eachChar: function () { },
regex: function () { return ""; },
generate: function () { return ""; }
};
function parse(route, names, types) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.charAt(0) === "/") {
rout... | { } | identifier_body |
index.js | return "([^/]+)";
},
generate: function (params) {
return params[this.name];
}
};
function StarSegment(name) { this.name = name; }
StarSegment.prototype = {
eachChar: function (callback) {
callback({ invalidChars: "", repeat: true });
},
regex: function () {
retur... | },
regex: function () { | random_line_split | |
ref.groupbycloud.com_tm.js | // ==UserScript==
// @name GBI Ref App Styling
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://ref.groupbycloud.com/*
// @grant none
// @require http://ajax.googleapis.com/ajax/libs/jquery/1/jqu... | .replace(/<tbody/gi, "<section")
.replace(/<tr/gi, "<div class='row'")
.replace(/<\/tr>/gi, "</div>")
.replace(/<td width="160" valign="top"/gi, "<div class='col _25'")
.replace(/<\/td>/gi, "</div>")
.replace(/<td/gi, "<div class='col'")
... | $('td[style]').removeAttr('style');
$('table').each(function (){
$(this).replaceWith( $(this).html() | random_line_split |
boot-delay.rs | use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn | () {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
return;
}
};
let mut buf = [0u8; 1024];
let uptime = File::open("/proc/uptime")
.and_then(|ref ... | main | identifier_name |
boot-delay.rs | use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn main() {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
... | })
.unwrap();
if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
} | buf.iter()
.position(|&c| c == 0x20)
.and_then(|p| if p < sz { unsafe { transmute::<_, &str>(&buf[..p]) }.parse::<f32>().ok() } else { None })
.unwrap() | random_line_split |
boot-delay.rs | use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn main() {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
... | )
.unwrap()
})
.unwrap();
if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
}
| { None } | conditional_block |
boot-delay.rs | use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn main() | if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
}
| {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
return;
}
};
let mut buf = [0u8; 1024];
let uptime = File::open("/proc/uptime")
.and_then(|ref mut... | identifier_body |
gen_png_app.py | import glob, os
dir_name = "icons"
| "108x108": 108,
"128x128": 128,
"150x150": 150,
"172x172": 172,
"256x256": 256
}
svg = app_name + ".svg"
if not os.path.exists(dir_name):
os.makedirs(dir_name)
for name in sizes.keys():
d = dir_name + "/" + name
if not os.path.exists(d):
os.makedirs(d)
png = d + "/harbou... | app_name = "kaktus"
# "dir_name": size
sizes = {
"86x86": 86, | random_line_split |
gen_png_app.py | import glob, os
dir_name = "icons"
app_name = "kaktus"
# "dir_name": size
sizes = {
"86x86": 86,
"108x108": 108,
"128x128": 128,
"150x150": 150,
"172x172": 172,
"256x256": 256
}
svg = app_name + ".svg"
if not os.path.exists(dir_name):
os.makedirs(dir_name)
for name in sizes.keys():
... | d = dir_name + "/" + name
if not os.path.exists(d):
os.makedirs(d)
png = d + "/harbour-" + app_name + ".png"
if not os.path.isfile(png):
size = sizes[name]
print "File name: %s, size: %d" % (png, size)
print ("inkscape -f {} -e {} -C -w {:.0f} -h {:.0f}"
... | conditional_block | |
lifetime-elision-return-type-requires-explicit-lifetime.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (_x: &Foo) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
panic!()
}
fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP this function's return type contains a borrowed value
panic!()
}
fn ... | h | identifier_name |
lifetime-elision-return-type-requires-explicit-lifetime.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP this function's return type contains a borrowed value
panic!()
}
fn main() {}
| { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
panic!()
} | identifier_body |
lifetime-elision-return-type-requires-explicit-lifetime.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //~^ HELP this function's return type contains a borrowed value
panic!()
}
fn main() {} |
fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier | random_line_split |
Checkbox.stories.js | import React from 'react';
import { action } from '@storybook/addon-actions';
import Checkbox from '.';
const onChange = action('onChange');
const defaultProps = {
id: 'id1',
onChange,
};
const intermediate = {
id: 'id2',
onChange,
intermediate: true, | checked: true,
};
const disabled = {
id: 'id4',
onChange,
disabled: true,
};
const withLabel = {
id: 'id5',
onChange,
label: 'Some label',
};
export default {
title: 'Form/Controls/Checkbox',
};
export const Default = () => (
<div style={{ padding: 30 }}>
<h1>Checkbox</h1>
<h2>Definition</h2>
<p>The Ch... | };
const checked = {
id: 'id3',
onChange, | random_line_split |
test-whatwg-url-searchparams-set.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_equals, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
... | () { throw new Error('valueOf'); }
};
const sym = Symbol();
assert.throws(() => params.append(obj, 'b'), /^Error: toString$/);
assert.throws(() => params.append('a', obj), /^Error: toString$/);
assert.throws(() => params.append(sym, 'b'),
/^TypeError: Cannot convert a Symbol value to a string$... | valueOf | identifier_name |
test-whatwg-url-searchparams-set.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_equals, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
... | assert.throws(() => params.append('a', sym),
/^TypeError: Cannot convert a Symbol value to a string$/);
} | assert.throws(() => params.append(sym, 'b'),
/^TypeError: Cannot convert a Symbol value to a string$/); | random_line_split |
test-whatwg-url-searchparams-set.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_equals, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
... |
};
const sym = Symbol();
assert.throws(() => params.append(obj, 'b'), /^Error: toString$/);
assert.throws(() => params.append('a', obj), /^Error: toString$/);
assert.throws(() => params.append(sym, 'b'),
/^TypeError: Cannot convert a Symbol value to a string$/);
assert.throws(() => params.a... | { throw new Error('valueOf'); } | identifier_body |
terminalEnvironment.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
if (line.indexOf('PPid:') === 0) {
ppid = parseInt(line.replace(/^PPid:\s+/, ''));
}
});
} while (name === codeProcessName);
const rawEnv = await readFile(`/proc/${pid}/environ`, 'utf8');
const env: IProcessEnvironment = {};
rawEnv.split('\0').forEach(e => {
const i = e.indexOf('=');
... | {
if (mainProcessParentEnv) {
return mainProcessParentEnv;
}
// For Linux use /proc/<pid>/status to get the parent of the main process and then fetch its
// env using /proc/<pid>/environ.
if (isLinux) {
const mainProcessId = process.ppid;
const codeProcessName = path.basename(process.argv[0]);
let pid: nu... | identifier_body |
terminalEnvironment.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): Promise<IProcessEnvironment> {
if (mainProcessParentEnv) {
return mainProcessParentEnv;
}
// For Linux use /proc/<pid>/status to get the parent of the main process and then fetch its
// env using /proc/<pid>/environ.
if (isLinux) {
const mainProcessId = process.ppid;
const codeProcessName = path.basenam... | getMainProcessParentEnv | identifier_name |
terminalEnvironment.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | cwd = process.cwd();
}
const dir = path.dirname(command);
if (dir !== '.') {
// We have a directory and the directory is relative (see above). Make the path absolute
// to the current working directory.
const fullPath = path.join(cwd, command);
return await exists(fullPath) ? fullPath : undefined;
}
if (... | // If we have an absolute path then we take it.
if (path.isAbsolute(command)) {
return await exists(command) ? command : undefined;
}
if (cwd === undefined) { | random_line_split |
terminalEnvironment.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
});
}
// TODO: Windows should return a fresh environment block, might need native code?
if (isWindows) {
mainProcessParentEnv = process.env as IProcessEnvironment;
}
return mainProcessParentEnv!;
}
export async function findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string | undef... | {
mainProcessParentEnv![k] = process.env[k]!;
} | conditional_block |
KmlRegion.js | /*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
define([
'../../geom/BoundingBox',
'../../util/Color',
'./KmlElements',
'./KmlLatLonAltBox',
'./KmlLod',
'./KmlObject',
'./s... | * @param options {Object}
* @param options.objectNode {Node} Node representing region in the document.
* @constructor
* @throws {ArgumentError} If the node is null or undefined.
* @see https://developers.google.com/kml/documentation/kmlreference#region
*/
var KmlRegion = function (opti... | random_line_split | |
4d8d18f311aa_add_deleted_bool_to_.py | """add deleted bool to things
Revision ID: 4d8d18f311aa
Revises: 4e34b4290fbc
Create Date: 2019-02-27 21:31:09.575521
"""
# revision identifiers, used by Alembic.
revision = '4d8d18f311aa'
down_revision = '4e34b4290fbc'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated ... | op.drop_column('radio_program', 'deleted')
op.drop_column('radio_person', 'deleted')
op.drop_column('content_track', 'deleted')
op.drop_column('content_stream', 'deleted')
op.drop_column('content_podcast', 'deleted')
op.drop_column('content_musicplaylist', 'deleted')
### end Alembic commands ### | identifier_body | |
4d8d18f311aa_add_deleted_bool_to_.py | """add deleted bool to things
Revision ID: 4d8d18f311aa
Revises: 4e34b4290fbc
Create Date: 2019-02-27 21:31:09.575521
"""
# revision identifiers, used by Alembic.
revision = '4d8d18f311aa'
down_revision = '4e34b4290fbc'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated ... | op.add_column('content_track', sa.Column('deleted', sa.Boolean(), nullable=True))
op.add_column('radio_person', sa.Column('deleted', sa.Boolean(), nullable=True))
op.add_column('radio_program', sa.Column('deleted', sa.Boolean(), nullable=True))
### end Alembic commands ###
def downgrade():
### com... | random_line_split | |
4d8d18f311aa_add_deleted_bool_to_.py | """add deleted bool to things
Revision ID: 4d8d18f311aa
Revises: 4e34b4290fbc
Create Date: 2019-02-27 21:31:09.575521
"""
# revision identifiers, used by Alembic.
revision = '4d8d18f311aa'
down_revision = '4e34b4290fbc'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated ... | ():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('radio_program', 'deleted')
op.drop_column('radio_person', 'deleted')
op.drop_column('content_track', 'deleted')
op.drop_column('content_stream', 'deleted')
op.drop_column('content_podcast', 'deleted')
op.drop_col... | downgrade | identifier_name |
webgl.js | this.cameraY = 0,
this.cameraZ = this.cameraRadius,
this.particleSystem,
this.particleSystemHeight = 100.0,
this.wind = 2.5,
this.clock,
this.controls,
this.parameters,
this.onParametersUpdate,
this.texture,
this.loader;
this.init();
}
init() {
var self = this;
this.renderer = ... |
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
this.cameraTarget = new THREE.Vector3( 0, 0, 0 );
this.loader = new THREE.TextureLoader();
this.loader.crossOrigin = '';
this.texture = this.loader.load(
'../asse... | this.renderer.setClearColor( 0x000000, 0 );
this.renderer.sortObjects = false; | random_line_split |
webgl.js | this.cameraY = 0,
this.cameraZ = this.cameraRadius,
this.particleSystem,
this.particleSystemHeight = 100.0,
this.wind = 2.5,
this.clock,
this.controls,
this.parameters,
this.onParametersUpdate,
this.texture,
this.loader;
this.init();
}
init() {
var self = this;
this.renderer = ... | ( tex ) {
var numParticles = 2000,
width = 70,
height = this.particleSystemHeight,
depth = 80,
parameters = {
// color: 0xffffff,
color: 0xffffff,
height: this.particleSystemHeight,
radiusX: this.wind,
radiusZ: 2.5,
size: 100,
scale: 4.0,
opacity:... | createParticles | identifier_name |
webgl.js | this.cameraY = 0,
this.cameraZ = this.cameraRadius,
this.particleSystem,
this.particleSystemHeight = 100.0,
this.wind = 2.5,
this.clock,
this.controls,
this.parameters,
this.onParametersUpdate,
this.texture,
this.loader;
this.init();
}
init() {
var self = this;
this.renderer = ... |
var s = navigator.userAgent;
if ( s.match( /iPhone/i )
|| s.match( /iPod/i )
|| s.match( /webOS/i )
|| s.match( /BlackBerry/i )
|| ( s.match( /Windows/i ) && s.match( /Phone/i ) )
|| ( s.match( /Android/i ) && s.match( /Mobile/i ) ) ) {
return true;
}
return false;
... | {
return true;
} | conditional_block |
sortController.d.ts | // Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { Column } from "./entities/column";
export declare class SortController {
private static DEFAULT_SORTING_ORDER;
private gridOptionsWrapper;
private columnController;
private eventService;
private columnApi;
private gridApi;
... | // Type definitions for ag-grid v15.0.0
// Project: http://www.ag-grid.com/ | random_line_split | |
sortController.d.ts | // Type definitions for ag-grid v15.0.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { Column } from "./entities/column";
export declare class | {
private static DEFAULT_SORTING_ORDER;
private gridOptionsWrapper;
private columnController;
private eventService;
private columnApi;
private gridApi;
progressSort(column: Column, multiSort: boolean): void;
setSortForColumn(column: Column, sort: string, multiSort: boolean): void;
o... | SortController | identifier_name |
utils.py | #!/usr/bin/python
# coding: utf-8
"""
...
~~~~~~~~~~~~~~~~~~~~~~~~~~
Author: YuJun <cuteuy@gmail.com>
"""
import struct
import numpy
import array
def load_mnist_images(file_name):
""" Loads the images from the provided file name """
image_file = open(file_name, 'rb') # Open the file
# Re... |
# Normalize and return the dataset
return dataset / 255
def load_mnist_labels(file_name):
""" Loads the image labels from the provided file name """
# Open the file
label_file = open(file_name, 'rb')
# Read header information from the file
head1 = label_file.read(4)
head2 = label_f... | limit1 = num_rows * num_cols * i
limit2 = num_rows * num_cols * (i + 1)
dataset[:, i] = images_raw[limit1: limit2] | conditional_block |
utils.py | #!/usr/bin/python
# coding: utf-8
"""
...
~~~~~~~~~~~~~~~~~~~~~~~~~~
Author: YuJun <cuteuy@gmail.com>
"""
import struct
import numpy
import array
def | (file_name):
""" Loads the images from the provided file name """
image_file = open(file_name, 'rb') # Open the file
# Read header information from the file
head1 = image_file.read(4)
head2 = image_file.read(4)
head3 = image_file.read(4)
head4 = image_file.read(4)
# Format the header... | load_mnist_images | identifier_name |
utils.py | #!/usr/bin/python
# coding: utf-8
""" |
import struct
import numpy
import array
def load_mnist_images(file_name):
""" Loads the images from the provided file name """
image_file = open(file_name, 'rb') # Open the file
# Read header information from the file
head1 = image_file.read(4)
head2 = image_file.read(4)
head3 = image_file... | ...
~~~~~~~~~~~~~~~~~~~~~~~~~~
Author: YuJun <cuteuy@gmail.com>
"""
| random_line_split |
utils.py | #!/usr/bin/python
# coding: utf-8
"""
...
~~~~~~~~~~~~~~~~~~~~~~~~~~
Author: YuJun <cuteuy@gmail.com>
"""
import struct
import numpy
import array
def load_mnist_images(file_name):
""" Loads the images from the provided file name """
image_file = open(file_name, 'rb') # Open the file
# Re... | labels[:, 0] = labels_raw[:]
return labels
| """ Loads the image labels from the provided file name """
# Open the file
label_file = open(file_name, 'rb')
# Read header information from the file
head1 = label_file.read(4)
head2 = label_file.read(4)
# Format the header information for useful data
num_examples = struct.unpack('>I', he... | identifier_body |
Rosenblatt_perceptron.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, clf, res=0.02):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, res),
np.arang... | plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.8)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
class Perceptron(object):
def __init__(self, eta=0.01, epochs=50):
self.eta = eta
self.epochs = epochs
def train(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
... | random_line_split | |
Rosenblatt_perceptron.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def | (X, y, clf, res=0.02):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, res),
np.arange(y_min, y_max, res))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.s... | plot_decision_regions | identifier_name |
Rosenblatt_perceptron.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, clf, res=0.02):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, res),
np.arang... |
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
# Корректные выходы перцептрона для данной выборки
y = np.array([[1],[1],[1],[1],[-1],[-1],[-1],[-1]]).reshape(8,1)
# Массив входных данных для перцептро... | self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.epochs):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
... | identifier_body |
Rosenblatt_perceptron.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, clf, res=0.02):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, res),
np.arang... |
self.errors_.append(errors)
return self
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
# Корректные выходы перцептрона для данной выборки
y = np.array([[1],[1],[1],[1],[-1],[-1],[-1... | update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0) | conditional_block |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Alexandre Lissy
#
# This file is part of weboob.
#
# weboob 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 op... | self, departure, arrival, filters):
with self.browser:
roadmap = self.browser.get_roadmap(departure, arrival, filters)
for s in roadmap['steps']:
step = RoadStep(s['id'])
step.line = s['line']
step.start_time = s['start_time']
step.end_time = ... | ter_roadmap( | identifier_name |
module.py | # This file is part of weboob.
#
# weboob 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.
#
# weboob is distributed in the hope ... | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Alexandre Lissy
# | random_line_split | |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Alexandre Lissy
#
# This file is part of weboob.
#
# weboob 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 op... | ith self.browser:
roadmap = self.browser.get_roadmap(departure, arrival, filters)
for s in roadmap['steps']:
step = RoadStep(s['id'])
step.line = s['line']
step.start_time = s['start_time']
step.end_time = s['end_time']
step.departure = s[... | identifier_body | |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Alexandre Lissy
#
# This file is part of weboob.
#
# weboob 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 op... | tep = RoadStep(s['id'])
step.line = s['line']
step.start_time = s['start_time']
step.end_time = s['end_time']
step.departure = s['departure']
step.arrival = s['arrival']
step.duration = s['duration']
yield step
| conditional_block | |
__init__.py | import click
def incomplete(package):
click.echo('{} packages not yet implemented'.format(package))
@click.group()
def run():
'''Build packages inside Docker containers.'''
pass
@click.command()
@click.option('--image', '-i', help='image to build in', required=True)
def rpm(image):
package = click.st... | def arch(image):
package = click.style('Arch', fg='cyan', bold=True)
incomplete(package)
run.add_command(rpm)
run.add_command(deb)
run.add_command(arch)
# vim: ft=python sw=4 ts=4 et |
@click.command()
@click.option('--image', '-i', help='image to build in', required=True) | random_line_split |
__init__.py | import click
def incomplete(package):
click.echo('{} packages not yet implemented'.format(package))
@click.group()
def run():
'''Build packages inside Docker containers.'''
pass
@click.command()
@click.option('--image', '-i', help='image to build in', required=True)
def rpm(image):
package = click.st... |
run.add_command(rpm)
run.add_command(deb)
run.add_command(arch)
# vim: ft=python sw=4 ts=4 et
| package = click.style('Arch', fg='cyan', bold=True)
incomplete(package) | identifier_body |
__init__.py | import click
def incomplete(package):
click.echo('{} packages not yet implemented'.format(package))
@click.group()
def run():
'''Build packages inside Docker containers.'''
pass
@click.command()
@click.option('--image', '-i', help='image to build in', required=True)
def | (image):
package = click.style('RPM', fg='red', bold=True)
incomplete(package)
@click.command()
@click.option('--image', '-i', help='image to build in', required=True)
def deb(image):
package = click.style('Debian', fg='magenta', bold=True)
incomplete(package)
@click.command()
@click.option('--image',... | rpm | identifier_name |
test_failures_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIA... | random_line_split | |
test_failures_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
def test_equals(self):
self.assertEqual(FailureCrash(), FailureCrash())
self.assertNotEqual(FailureCrash(), FailureTimeout())
crash_set = set([FailureCrash(), FailureCrash()])
self.assertEqual(len(crash_set), 1)
# The hash happens to be the name of the class, but sets still... | self.assert_loads(c) | conditional_block |
test_failures_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | (self):
failure_obj = TestFailure()
self.assertRaises(NotImplementedError, failure_obj.message)
def test_loads(self):
for c in ALL_FAILURE_CLASSES:
self.assert_loads(c)
def test_equals(self):
self.assertEqual(FailureCrash(), FailureCrash())
self.assertNotEqu... | test_message_is_virtual | identifier_name |
test_failures_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | self.assertEqual(FailureCrash().message(), 'DumpRenderTree crashed')
self.assertEqual(FailureCrash(process_name='foo', pid=1234).message(), 'foo crashed [pid=1234]') | identifier_body | |
unwrap.ts | import { Associative, unwrap as _unwrap, unwrapKey } from '@collectable/core';
import { BRANCH, Node, RedBlackTreeStructure, isNone } from '../internals';
export function unwrap<K, V> (tree: RedBlackTreeStructure<K, V>, target: Associative<V>): Associative<V> | if(!isNone(node._right)) {
stack[i++] = [node, BRANCH.NONE];
node = node._right;
branch = BRANCH.LEFT;
continue;
}
else {
branch = BRANCH.NONE;
}
}
if(branch === BRANCH.NONE && i > 0) {
--i;
node = stack[i][0];
branch = stack[i][1... | {
if(tree._size === 0) {
return {};
}
var stack = new Array<[Node<K, V>, BRANCH]>(Math.ceil(Math.log(tree._size))*2);
var i = 0, node = tree._root, branch = BRANCH.LEFT;
do {
target[unwrapKey(node.key)] = _unwrap<V>(node.value);
if(branch === BRANCH.LEFT) {
if(!isNone(node._left)) {
... | identifier_body |
unwrap.ts | import { Associative, unwrap as _unwrap, unwrapKey } from '@collectable/core';
import { BRANCH, Node, RedBlackTreeStructure, isNone } from '../internals';
export function unwrap<K, V> (tree: RedBlackTreeStructure<K, V>, target: Associative<V>): Associative<V> {
if(tree._size === 0) {
return {};
}
var stack =... | } while(i > 0 || branch !== BRANCH.NONE);
return target;
} | } | random_line_split |
unwrap.ts | import { Associative, unwrap as _unwrap, unwrapKey } from '@collectable/core';
import { BRANCH, Node, RedBlackTreeStructure, isNone } from '../internals';
export function unwrap<K, V> (tree: RedBlackTreeStructure<K, V>, target: Associative<V>): Associative<V> {
if(tree._size === 0) {
return {};
}
var stack =... |
}
if(branch === BRANCH.RIGHT) {
if(!isNone(node._right)) {
stack[i++] = [node, BRANCH.NONE];
node = node._right;
branch = BRANCH.LEFT;
continue;
}
else {
branch = BRANCH.NONE;
}
}
if(branch === BRANCH.NONE && i > 0) {
--i;
node... | {
branch = BRANCH.RIGHT;
} | conditional_block |
unwrap.ts | import { Associative, unwrap as _unwrap, unwrapKey } from '@collectable/core';
import { BRANCH, Node, RedBlackTreeStructure, isNone } from '../internals';
export function | <K, V> (tree: RedBlackTreeStructure<K, V>, target: Associative<V>): Associative<V> {
if(tree._size === 0) {
return {};
}
var stack = new Array<[Node<K, V>, BRANCH]>(Math.ceil(Math.log(tree._size))*2);
var i = 0, node = tree._root, branch = BRANCH.LEFT;
do {
target[unwrapKey(node.key)] = _unwrap<V>(nod... | unwrap | identifier_name |
exam.py |
def __eq__(self, value):
'''Evalue two `Quest`s as equal.'''
if type(value) != type(self): return False
for i in ['q', 'sel', 'ta', 'args']:
if self.__getattribute__(i) != value.__getattribute__(i):
return False
return True
def __hash__(self):
... | '''Visualize the `Quest`.'''
return '{\n\tq: %s,\n\tsel: %s,\n\tta: %s,\n\targs: %s\n}' % \
(self.q, self.sel, self.ta, self.args) | identifier_body | |
exam.py | attern
self.tapattern = tapattern
self.argpattern = dict(argpattern)
self.is_cached = False
def get_cached_qf(self, togo='Curdata.data'):
'''Load cached QuestForm.'''
if togo in os.listdir():
if InteractiveAnswer(
'Cached data found.Continue?'... | index += j | conditional_block | |
exam.py | else None
argitem = {
pat: quest[self.argpattern[pat]]
for pat in self.argpattern
} if self.argpattern else {}
qitem = None if qitem is None else ([qitem] if isinstance(
qitem, str) else list(qitem))
selitem = None if seli... | raise_ta | identifier_name | |
exam.py |
BOARDER_LENGTH = 40
class Quest():
def __init__(self, q, sel=None, ta=None, args={}):
'''
Class representing a Question.
Parameters
----------
basic arguments:
q : question. necessary. list.
sel : selections. list.
ta : true answer. lis... | split_wrd) | random_line_split | |
publisher.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is av... | # | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.