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 |
|---|---|---|---|---|
statisticsUtils.js | /////////////////////////////////////////////////////////////////////////// | // 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 in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WAR... | // Copyright © 2014 - 2016 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License"); | random_line_split |
statisticsUtils.js | ///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 - 2016 Esri. 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
//
// h... | params){
return params.statisticTypes && params.statisticTypes.length > 0 ?
supportTypes.filter(function(t){
return params.statisticTypes.indexOf(t) > -1;
}): supportTypes;
}
function getStddevVal(vals){
var n = vals.length;
if(n <= 1){
return 0;
}
var sum = 0;
vals.for... | etTypesFromParam( | identifier_name |
statisticsUtils.js | ///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 - 2016 Esri. 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
//
// h... | for(var p in attributes){
if(p === 'countField' || !esriLang.isDefined(attributes[p])){
continue;
}
if(attributes[p] === null || typeof attributes[p] === 'undefined'){
attributes[p] = '';
continue;
}
attributes[p] =
jimuUtils.localizeNumberByFieldInfo(a... |
return;
}
| conditional_block |
ng2-header.component.ts | import { Component, EventEmitter, Output, trigger, state, transition, style, animate, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'ng2-header',
styleUrls: ['./ng2-header.scss'],
templateUrl: './ng2-header.html',
animations: [
trigger('isTopOfPage', ... | */
private scrollPage(): void {
this.isTopOfPage = this.scrollY() < window.innerHeight - 100;
this.didScroll = false;
}
/**
* Get Y axis offset
* @returns {number}
*/
private scrollY(): number {
return window.pageYOffset || document.documentElement.scrollTop;
}
} | random_line_split | |
ng2-header.component.ts | import { Component, EventEmitter, Output, trigger, state, transition, style, animate, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'ng2-header',
styleUrls: ['./ng2-header.scss'],
templateUrl: './ng2-header.html',
animations: [
trigger('isTopOfPage', ... | implements OnInit {
@Output() callback = new EventEmitter();
public isTopOfPage: boolean = true;
private didScroll: boolean = false;
constructor() {
}
ngOnInit() {
Observable.fromEvent(window, 'scroll').subscribe(() => {
if (!this.didScroll) {
this.didScroll = true;
setTimeout(... | Ng2Header | identifier_name |
ng2-header.component.ts | import { Component, EventEmitter, Output, trigger, state, transition, style, animate, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'ng2-header',
styleUrls: ['./ng2-header.scss'],
templateUrl: './ng2-header.html',
animations: [
trigger('isTopOfPage', ... |
}
| {
return window.pageYOffset || document.documentElement.scrollTop;
} | identifier_body |
ng2-header.component.ts | import { Component, EventEmitter, Output, trigger, state, transition, style, animate, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'ng2-header',
styleUrls: ['./ng2-header.scss'],
templateUrl: './ng2-header.html',
animations: [
trigger('isTopOfPage', ... |
});
}
/**
* Method to handle click events
*/
public openSidebar(): void {
this.callback.emit();
}
/**
* Modify the header state depending on the offset
*/
private scrollPage(): void {
this.isTopOfPage = this.scrollY() < window.innerHeight - 100;
this.didScroll = false;
}
... | {
this.didScroll = true;
setTimeout(() => this.scrollPage(), 250);
} | conditional_block |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... | (base_note: f64, fractions: &[Frac], step: u64) -> f64 {
let mut sum = 0_f64;
for &Frac(a, b) in fractions {
let freq = (base_note / (b as f64)) * (a as f64);
sum += sine_wave(freq, step);
}
sum / (fractions.len() as f64)
}
fn linear_envelope(sample: f64, duration: u64, progress: u64) ... | sine_waves | identifier_name |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... |
fn remember(note_set: &[Frac], memory: &mut Memory) {
let increase = 0.1_f64;
for note in note_set {
let val = match memory.get(note) {
Some(v) => v + increase,
None => increase,
};
memory.insert(note.clone(), val);
}
}
/// step to a set of notes that minim... | {
for (n, val) in memory.iter_mut() {
*val *= 0.75;
}
} | identifier_body |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... | sum / (fractions.len() as f64)
}
fn linear_envelope(sample: f64, duration: u64, progress: u64) -> f64 {
sample * (progress as f64) / (duration as f64)
}
fn output_pcm() {
let mut notes = vec![Frac(1, 2), Frac(1, 1), Frac(1, 3), Frac(1, 5), Frac(1, 7)];
let mut memory = Memory::new();
let mut j=0;... | random_line_split | |
main.rs | extern crate byteorder;
use std::collections::HashMap;
use std::io::Write;
use byteorder::{LittleEndian, WriteBytesExt};
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct Frac(u64, u64);
type Memory = HashMap<Frac, f64>;
fn simplify(Frac(a, b): Frac) -> Frac {
fn gcd(x: u64, y: u64) -> u64 {
if y == 0... |
}
}
}
best
}
type PCM_Sample = i16;
static PCM_HZ: u64 = 44100_u64;
static STEPS_PER_SEC: u64 = 4;
static BASE_NOTE: f64 = 250_f64;
type Endianness = LittleEndian;
fn sine_wave(freq: f64, step: u64) -> f64 {
(2.0*std::f64::consts::PI*(step as f64)*freq/(PCM_HZ as f64)).sin()
}
fn si... | {
best = note_set2;
best_score = score;
} | conditional_block |
client.ts | import { get, post, stream } from "./http";
import * as URL from "./urls";
import { toArray } from "./util";
export default class Client {
public config: Line.ClientConfig;
constructor(config: Line.Config & Line.ClientConfig) {
if (!config.channelAccessToken) {
throw new Error("no channel access token")... |
private authHeader(): { [key: string]: string } {
return { Authorization: "Bearer " + this.config.channelAccessToken };
}
private get(url: string): Promise<any> {
return get(url, this.authHeader());
}
private post(url: string, body?: any): Promise<any> {
return post(url, this.authHeader(), bod... | {
return this.post(URL.leaveRoom(roomId));
} | identifier_body |
client.ts | import { get, post, stream } from "./http";
import * as URL from "./urls";
import { toArray } from "./util";
export default class Client {
public config: Line.ClientConfig;
constructor(config: Line.Config & Line.ClientConfig) {
if (!config.channelAccessToken) {
throw new Error("no channel access token")... | }
private post(url: string, body?: any): Promise<any> {
return post(url, this.authHeader(), body);
}
private stream(url: string): NodeJS.ReadableStream {
return stream(url, this.authHeader());
}
} |
private get(url: string): Promise<any> {
return get(url, this.authHeader()); | random_line_split |
client.ts | import { get, post, stream } from "./http";
import * as URL from "./urls";
import { toArray } from "./util";
export default class Client {
public config: Line.ClientConfig;
constructor(config: Line.Config & Line.ClientConfig) {
if (!config.channelAccessToken) {
throw new Error("no channel access token")... | (url: string): NodeJS.ReadableStream {
return stream(url, this.authHeader());
}
}
| stream | identifier_name |
client.ts | import { get, post, stream } from "./http";
import * as URL from "./urls";
import { toArray } from "./util";
export default class Client {
public config: Line.ClientConfig;
constructor(config: Line.Config & Line.ClientConfig) {
if (!config.channelAccessToken) |
this.config = config;
}
public pushMessage(to: string, messages: Line.Message | Line.Message[]): Promise<any> {
return this.post(URL.push, {
to,
messages: toArray(messages),
});
}
public replyMessage(replyToken: string, messages: Line.Message | Line.Message[]): Promise<any> {
ret... | {
throw new Error("no channel access token");
} | conditional_block |
group.rs | /*!
Group Icons and Cursors.
References:
* http://msdn.microsoft.com/en-us/library/ms997538.aspx
* https://devblogs.microsoft.com/oldnewthing/20120720-00/?p=7083
* https://github.com/MathewSachin/NIco/wiki/Ico,-Cur-and-PE-Formats
# Examples
The following example prints all group icon resource names which contain a ... |
/// Reassemble the file.
#[cfg(feature = "std")]
pub fn write(&self, dest: &mut dyn io::Write) -> io::Result<()> {
// Start by appending the header
dest.write(self.image.as_bytes())?;
// Write all the icon entries
let entries = self.entries();
let mut image_offset = (6 + entries.len() * 16) as u32;
for ... | {
self.resources.root()?
.get_dir(self.ty().into())?
.get_dir(id.into())?
.first_data()?
.bytes().map_err(FindError::Pe)
} | identifier_body |
group.rs | /*!
Group Icons and Cursors.
References:
* http://msdn.microsoft.com/en-us/library/ms997538.aspx
* https://devblogs.microsoft.com/oldnewthing/20120720-00/?p=7083
* https://github.com/MathewSachin/NIco/wiki/Ico,-Cur-and-PE-Formats
# Examples
The following example prints all group icon resource names which contain a ... | {
pub idReserved: u16,
pub idType: u16,
pub idCount: u16,
pub idEntries: [GRPICONDIRENTRY; 0],
}
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct GRPICONDIRENTRY {
pub bWidth: u8,
pub bHeight: u8,
pub bColorCount: u8,
pub bReserved: u8,
pub wPlanes: u16,
pub wBitCount: u16,
pub dwBytesInRe... | GRPICONDIR | identifier_name |
group.rs | /*!
Group Icons and Cursors.
References:
* http://msdn.microsoft.com/en-us/library/ms997538.aspx
* https://devblogs.microsoft.com/oldnewthing/20120720-00/?p=7083
* https://github.com/MathewSachin/NIco/wiki/Ico,-Cur-and-PE-Formats |
```
// Aqcuire the resources of a Portable Executable file
let resources: pelite::resources::Resources;
# fn example(resources: pelite::resources::Resources<'_>) {
// Iterate over the group icons in the resources and throw away any invalid results
// If the resources contain no group icons the iterator is empty
for (... |
# Examples
The following example prints all group icon resource names which contain a PNG image. | random_line_split |
module.ts | /*
* Copyright 2013 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | export function leaveTimeline(data?: any) {
profile && timelineBuffer && timelineBuffer.leave(null, data);
}
} | }
| random_line_split |
module.ts | /*
* Copyright 2013 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | (data?: any) {
profile && timelineBuffer && timelineBuffer.leave(null, data);
}
}
| leaveTimeline | identifier_name |
module.ts | /*
* Copyright 2013 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
export function leaveTimeline(data?: any) {
profile && timelineBuffer && timelineBuffer.leave(null, data);
}
}
| {
profile && timelineBuffer && timelineBuffer.enter(name, data);
} | identifier_body |
test_context.py | , "python/test_support/hello/hello.txt")
self.sc.addFile(path)
download_path = SparkFiles.get("hello.txt")
self.assertNotEqual(path, download_path)
with open(download_path) as test_file:
self.assertEqual("Hello World!\n", test_file.readline())
def test_add_file_recursive... | from pyspark.tests.test_context import * # noqa: F401
try:
import xmlrunner # type: ignore[import]
testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2)
except ImportError:
testRunner = None
unittest.main(testRunner=testRunner, verbosity=2) | conditional_block | |
test_context.py | test_basic_checkpointing(self):
parCollection = self.sc.parallelize([1, 2, 3, 4])
flatMappedRDD = parCollection.flatMap(lambda x: range(1, x + 1))
self.assertFalse(flatMappedRDD.isCheckpointed())
self.assertTrue(flatMappedRDD.getCheckpointFile() is None)
self.assertFalse(self.s... |
def test_get_or_create(self):
with SparkContext.getOrCreate() as sc:
self.assertTrue(SparkContext.getOrCreate() is sc)
def test_parallelize_eager_cleanup(self):
with SparkContext() as sc:
temp_files = os.listdir(sc._temp_dir)
sc.parallelize([0, 1, 2])
... | self.assertRaises(Exception, lambda: SparkContext("an-invalid-master-name")) | identifier_body |
test_context.py | test_basic_checkpointing(self):
parCollection = self.sc.parallelize([1, 2, 3, 4])
flatMappedRDD = parCollection.flatMap(lambda x: range(1, x + 1))
self.assertFalse(flatMappedRDD.isCheckpointed())
self.assertTrue(flatMappedRDD.getCheckpointFile() is None)
self.assertFalse(self.s... | (self):
# Fail immediately if you try to create a SparkContext
# with an insecure gateway
parameters = namedtuple("MockGatewayParameters", "auth_token")( | test_forbid_insecure_gateway | identifier_name |
test_context.py | test_basic_checkpointing(self):
parCollection = self.sc.parallelize([1, 2, 3, 4])
flatMappedRDD = parCollection.flatMap(lambda x: range(1, x + 1))
self.assertFalse(flatMappedRDD.isCheckpointed())
self.assertTrue(flatMappedRDD.getCheckpointFile() is None)
self.assertFalse(self.s... |
sc.stop()
def test_startTime(self):
with SparkContext() as sc:
self.assertGreater(sc.startTime, 0)
def test_forbid_insecure_gateway(self):
# Fail immediately if you try to create a SparkContext
# with an insecure gateway
parameters = namedtuple("MockGat... | self.assertEqual([], tracker.getActiveJobsIds())
self.assertEqual([], tracker.getActiveStageIds()) | random_line_split |
exhaustive_vec_permutations.rs | use itertools::Itertools;
use malachite_base::vecs::exhaustive_vec_permutations;
fn exhaustive_vec_permutations_helper(cs: &str, out: &[&str]) {
let cs = cs.chars().collect_vec();
let css: Vec<String> = exhaustive_vec_permutations(cs)
.map(|ds| ds.into_iter().collect())
.collect();
assert_e... | "24135", "24153", "24315", "24351", "24513", "24531", "25134", "25143", "25314",
"25341", "25413", "25431", "31245", "31254", "31425", "31452", "31524", "31542",
"32145", "32154", "32415", "32451", "32514", "32541", "34125", "34152", "34215",
"34251", "34512", "34521", "3... | {
exhaustive_vec_permutations_helper("", &[""]);
exhaustive_vec_permutations_helper("1", &["1"]);
exhaustive_vec_permutations_helper("12", &["12", "21"]);
exhaustive_vec_permutations_helper("123", &["123", "132", "213", "231", "312", "321"]);
exhaustive_vec_permutations_helper(
"1234",
... | identifier_body |
exhaustive_vec_permutations.rs | use itertools::Itertools;
use malachite_base::vecs::exhaustive_vec_permutations;
fn | (cs: &str, out: &[&str]) {
let cs = cs.chars().collect_vec();
let css: Vec<String> = exhaustive_vec_permutations(cs)
.map(|ds| ds.into_iter().collect())
.collect();
assert_eq!(css.iter().map(String::as_str).collect_vec().as_slice(), out);
}
#[test]
fn test_exhaustive_vec_permutations() {
... | exhaustive_vec_permutations_helper | identifier_name |
exhaustive_vec_permutations.rs | use itertools::Itertools;
use malachite_base::vecs::exhaustive_vec_permutations;
fn exhaustive_vec_permutations_helper(cs: &str, out: &[&str]) {
let cs = cs.chars().collect_vec();
let css: Vec<String> = exhaustive_vec_permutations(cs)
.map(|ds| ds.into_iter().collect())
.collect();
assert_e... | "abcd",
&[
"abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac",
"bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca",
"dcab", "dcba",
],
);
} | "53124", "53142", "53214", "53241", "53412", "53421", "54123", "54132", "54213",
"54231", "54312", "54321",
],
);
exhaustive_vec_permutations_helper( | random_line_split |
server.py | # main.py: Provides the server client infra for gaming
# python2 server.py <port> <max_clients>
# YES YOU CAN ONLY USE PYTHON "2" and NOT "3".
import os, sys, socket, signal, game, json, humanSocket
if (os.path.realpath('../utils') not in sys.path):
sys.path.insert(0, os.path.realpath('../utils'))
from log import *
... |
def beginGameGod():
while True:
printMenu()
cmd = raw_input(bcolors.OKRED + "At your command: " + bcolors.ENDC)
cmd = cmd.strip()
if (cmd.startswith('q')):
print ('quitting')
quit()
elif ('v' in cmd):
try:
players = list(map(lambda x: getPlayer(x), cmd.split('v')))
except:
Error('Bad In... | name_or_index = name_or_index.strip()
if (DEBUG):
Info('|' + name_or_index + '|')
if (name_or_index == 'h'):
return (humanSocket.HumanSocket(), -1, 'human')
return connections[int(name_or_index)] | identifier_body |
server.py | # main.py: Provides the server client infra for gaming
# python2 server.py <port> <max_clients>
# YES YOU CAN ONLY USE PYTHON "2" and NOT "3".
import os, sys, socket, signal, game, json, humanSocket
if (os.path.realpath('../utils') not in sys.path):
sys.path.insert(0, os.path.realpath('../utils'))
from log import *
... |
keyVal = list( map(lambda x: x.strip(), line.split(':') ) )
config[keyVal[0]] = keyVal[1]
# override config with sys args:
if (len(sys.argv) > 1):
config['port'] = int(sys.argv[1])
if (len(sys.argv) > 2):
config['max_clients'] = sys.argv[2]
# TODO: Some keys are REQUIRED. maybe check that they are pres... | continue | conditional_block |
server.py | # main.py: Provides the server client infra for gaming
# python2 server.py <port> <max_clients>
# YES YOU CAN ONLY USE PYTHON "2" and NOT "3".
import os, sys, socket, signal, game, json, humanSocket
if (os.path.realpath('../utils') not in sys.path):
sys.path.insert(0, os.path.realpath('../utils'))
from log import *
... | ():
for c in connections:
c[0].close()
sock.close()
exit(0)
# can throw exception
def getPlayer(name_or_index):
name_or_index = name_or_index.strip()
if (DEBUG):
Info('|' + name_or_index + '|')
if (name_or_index == 'h'):
return (humanSocket.HumanSocket(), -1, 'human')
return connections[int(name_or_index)... | quit | identifier_name |
server.py | # main.py: Provides the server client infra for gaming
# python2 server.py <port> <max_clients>
# YES YOU CAN ONLY USE PYTHON "2" and NOT "3".
import os, sys, socket, signal, game, json, humanSocket
if (os.path.realpath('../utils') not in sys.path):
sys.path.insert(0, os.path.realpath('../utils'))
from log import *
... | # pass | # thisChar = sys.stdin.read(1)
# else:
# print ('went here')
# except IOError:
# #nothing to read. should really have checked first | random_line_split |
base.py | """Test Logex Initization and Error Handling"""
import subprocess
from unittest import TestCase
from samples import app, api, logex
from samples import bp_app, api_v1, api_v2, bp_logex
class | (TestCase):
DEBUG = True
__blueprints__ = False
@classmethod
def setUpClass(cls):
cls.app = app
cls.api = api
cls.logex = logex
if cls.__blueprints__:
cls.app = bp_app
cls.api = [api_v1, api_v2]
cls.logex = bp_logex
# App test... | BaseTestCase | identifier_name |
base.py | """Test Logex Initization and Error Handling"""
import subprocess
from unittest import TestCase
from samples import app, api, logex
from samples import bp_app, api_v1, api_v2, bp_logex
class BaseTestCase(TestCase):
DEBUG = True
__blueprints__ = False
@classmethod
def setUpClass(cls):
cls.a... |
def setUp(self):
with self.ac:
self.logs = self.logex.logs
def tearDown(self):
pass
| subprocess.call(['rm', '-rf', 'logs']) | identifier_body |
base.py | """Test Logex Initization and Error Handling"""
import subprocess
from unittest import TestCase
from samples import app, api, logex
from samples import bp_app, api_v1, api_v2, bp_logex
class BaseTestCase(TestCase):
DEBUG = True
__blueprints__ = False
@classmethod
def setUpClass(cls):
cls.a... |
# App test client, config, and context
cls.log_name = cls.app.name + ".log"
cls.app.config['DEBUG'] = cls.DEBUG
cls.ac = cls.app.app_context()
cls.test_client = cls.app.test_client()
cls.test_client.testing = True
cls.ctx = cls.app.test_request_context()
... | cls.app = bp_app
cls.api = [api_v1, api_v2]
cls.logex = bp_logex | conditional_block |
base.py | """Test Logex Initization and Error Handling"""
import subprocess
from unittest import TestCase
from samples import app, api, logex
from samples import bp_app, api_v1, api_v2, bp_logex
class BaseTestCase(TestCase):
DEBUG = True
__blueprints__ = False
@classmethod
def setUpClass(cls):
cls.a... | cls.test_client.testing = True
cls.ctx = cls.app.test_request_context()
cls.ctx.push()
@classmethod
def tearDownClass(cls):
subprocess.call(['rm', '-rf', 'logs'])
def setUp(self):
with self.ac:
self.logs = self.logex.logs
def tearDown(self):
... | cls.app.config['DEBUG'] = cls.DEBUG
cls.ac = cls.app.app_context()
cls.test_client = cls.app.test_client() | random_line_split |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F:Foo<Key=i32>>(f: F) -> i32 {
f.fold(0, |a,b| a + b)
}
fn main() {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
}
| sum_foo | identifier_name |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
} | identifier_body | |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub trait Foo: Iterator<Item=<Self as Foo>::Key> {
type Key;
}
impl Foo for IntoIter<i32> {
type Key = i32;
}
fn sum_foo<F:Foo<Key=i32>>(f: F) -> i32 {
f.fold(0, |a,b| a + b)
}
fn main() {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
} | random_line_split | |
test_job_log_url_api.py | from django.core.urlresolvers import reverse
from tests.test_utils import create_generic_job
from treeherder.model.models import JobLog
def | (test_repository, result_set_stored,
failure_classifications,
generic_reference_data, webapp):
job1 = create_generic_job('1234', test_repository, 1, 1,
generic_reference_data)
job2 = create_generic_job('5678', test_repository, 1, ... | test_get_job_log_urls | identifier_name |
test_job_log_url_api.py | from django.core.urlresolvers import reverse
from tests.test_utils import create_generic_job
from treeherder.model.models import JobLog
def test_get_job_log_urls(test_repository, result_set_stored,
failure_classifications,
generic_reference_data, webapp):
job1 ... | kwargs={"project": test_repository.name}) +
'?job_id=1')
assert resp.status_int == 200
assert len(resp.json) == 2
resp = webapp.get(reverse('job-log-url-list',
kwargs={"project": test_repository.name}) +
'?job_id=1&job_... | url='http://yahoo.com',
status=JobLog.PARSED)
resp = webapp.get(reverse('job-log-url-list', | random_line_split |
test_job_log_url_api.py | from django.core.urlresolvers import reverse
from tests.test_utils import create_generic_job
from treeherder.model.models import JobLog
def test_get_job_log_urls(test_repository, result_set_stored,
failure_classifications,
generic_reference_data, webapp):
| '?job_id=1')
assert resp.status_int == 200
assert len(resp.json) == 2
resp = webapp.get(reverse('job-log-url-list',
kwargs={"project": test_repository.name}) +
'?job_id=1&job_id=2')
assert resp.status_int == 200
assert len(resp.json)... | job1 = create_generic_job('1234', test_repository, 1, 1,
generic_reference_data)
job2 = create_generic_job('5678', test_repository, 1, 2,
generic_reference_data)
JobLog.objects.create(job=job1,
name='test_log_1',
... | identifier_body |
panic.rs | //! Intrinsics for panic handling
use interrupt;
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
/// Required to handle panics
#[lang = "panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(fmt: ::core::fmt::Arguments, file: &str, line: u32) -> ! {
println!("PANIC: {}",... | () -> ! {
loop {
unsafe { interrupt::halt(); }
}
}
| _Unwind_Resume | identifier_name |
panic.rs | //! Intrinsics for panic handling
use interrupt;
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
/// Required to handle panics
#[lang = "panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(fmt: ::core::fmt::Arguments, file: &str, line: u32) -> ! |
#[lang = "oom"]
#[no_mangle]
pub extern fn rust_oom() -> ! {
panic!("kernel memory allocation failed");
}
#[allow(non_snake_case)]
#[no_mangle]
/// Required to handle panics
pub extern "C" fn _Unwind_Resume() -> ! {
loop {
unsafe { interrupt::halt(); }
}
}
| {
println!("PANIC: {}", fmt);
println!("FILE: {}", file);
println!("LINE: {}", line);
unsafe { interrupt::stack_trace(); }
println!("HALT");
loop {
unsafe { interrupt::halt(); }
}
} | identifier_body |
panic.rs | //! Intrinsics for panic handling
use interrupt;
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
/// Required to handle panics | #[lang = "panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(fmt: ::core::fmt::Arguments, file: &str, line: u32) -> ! {
println!("PANIC: {}", fmt);
println!("FILE: {}", file);
println!("LINE: {}", line);
unsafe { interrupt::stack_trace(); }
println!("HALT");
loop {
unsafe { i... | random_line_split | |
cssmin.js | 'use strict';
var path = require('path');
exports.name = 'cssmin';
//
// Output a config for the furnished block
// The context variable is used both to take the files to be treated
// (inFiles) and to output the one(s) created (outFiles).
// It aslo conveys whether or not the current process is the last of the pipe
... | cfg.files.push(files);
context.outFiles = [block.dest];
return cfg;
}; | files.dest = outfile;
files.src = [];
context.inFiles.forEach(function(f) { files.src.push(path.join(context.inDir, f));} ); | random_line_split |
no-caller.js | /**
* @fileoverview Tests for no-caller rule.
* @author Nicholas C. Zakas
*/ | //------------------------------------------------------------------------------
const rule = require("../../../lib/rules/no-caller"),
{ RuleTester } = require("../../../lib/rule-tester");
//------------------------------------------------------------------------------
// Tests
//---------------------------------... |
"use strict";
//------------------------------------------------------------------------------
// Requirements | random_line_split |
outputFile.ts | import ava from 'ava';
import { promises as fs } from 'fs';
import { tempFile, tempFileLoc, tempDirLoc } from './lib';
import * as nextra from '../src';
ava('Pre-Existing', async (test): Promise<void> => {
test.plan(2);
const file = tempFile();
const retVal = await nextra.outputFile(file, 'pass');
test.is(retVal... | const retVal = await nextra.outputFile(file, 'pass', true);
test.is(retVal, undefined);
test.is(await fs.readFile(file, 'utf8'), 'pass');
}); | ava('Atomic Shortcut', async (test): Promise<void> => {
test.plan(2);
const file = tempFileLoc(); | random_line_split |
helper.js | const remote = require('electron').remote;
const main = remote.require('./main.js');
const texts = main.getTexts('general');
//const state1Msg = 'Hubo uno o varios problemas, inténtalo de nuevo más tarde o contacta con el administrador a través del correo hector.zaragoza.arranz@gmail.com, ¡no muerdo!';
const state1... | firmFunction, text) {
swal({
//title: '¿Está seguro de realizar esta operación?',
title: texts['confirmation'].title,
text: text,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
//confirmButtonText: 'Sí, est... | irmDialog(con | identifier_name |
helper.js | const remote = require('electron').remote;
const main = remote.require('./main.js');
const texts = main.getTexts('general');
//const state1Msg = 'Hubo uno o varios problemas, inténtalo de nuevo más tarde o contacta con el administrador a través del correo hector.zaragoza.arranz@gmail.com, ¡no muerdo!';
const state1... | swal({
//title: '¿Está seguro de realizar esta operación?',
title: texts['confirmation'].title,
text: text,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
//confirmButtonText: 'Sí, estoy seguro',
confirmBut... | identifier_body | |
helper.js | const remote = require('electron').remote;
const main = remote.require('./main.js'); | const texts = main.getTexts('general');
//const state1Msg = 'Hubo uno o varios problemas, inténtalo de nuevo más tarde o contacta con el administrador a través del correo hector.zaragoza.arranz@gmail.com, ¡no muerdo!';
const state1Msg = texts['messages'].state1Msg;
function confirmDialog(confirmFunction, text) {
... | random_line_split | |
dataflow.rs | (uint) -> bool,
{
//! Iterates through each bit that is set on entry to `id`.
//! Only useful after `propagate()` has been called.
if !self.has_bitset_for_nodeid(id) {
return true;
}
let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index);
self.each_bit_f... | cfg: &cfg::CFG,
cfgidx: CFGIndex) {
cfg.graph.each_outgoing_edge(cfgidx, |_e_idx, edge| { | random_line_split | |
dataflow.rs | expr.id,
pprust::NodeBlock(blk) => blk.id,
pprust::NodeItem(_) => 0,
pprust::NodePat(pat) => pat.id
};
if self.has_bitset_for_nodeid(id) {
assert!(self.bits_per_id > 0);
let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index);
le... | else {
"".to_string()
};
try!(ps.synth_comment(format!("id {}: {}{}{}", id, entry_str,
gens_str, kills_str)));
try!(pp::space(&mut ps.s));
}
Ok(())
}
}
fn build_nodeid_to_index(decl: Option<&ast::FnDecl>... | {
format!(" kill: {}", bits_to_string(kills))
} | conditional_block |
dataflow.rs | // that we store in any given bit set so that
// it is an even multiple of uint::BITS. This
// means that there may be some stray bits at
// the end that do not correspond to any
// actual value. So... | Union | identifier_name | |
thumbnail-process-ar.js | import path from 'path'
import easyimg from 'easyimage'
import {getSavedPictures} from './image-indexer'
import Q from 'q'
import fs from 'fs'
const thumbnailFolder = "../thumbnails"
const thumbnailCount = 30
const width = 250
const height = 250
const quality = 80
function createThumbnail(){
getSavedPictures((err,... |
}
catch(er){
process.stdout.write('Damn error '+er);
}
});
}
function resize(pics){
let current = [];
let top = pics.slice(-thumbnailCount);
let sliced = pics.slice(0, -thumbnailCount);
top.forEach((pic)=>{
let thumbnailPath = path.join(__... | {
process.stdout.write(' WIT '+savedFiles.substring(0, 10));
process.stdout.write(' WIT '+savedFiles.substring(-10, 10));
let pics = JSON.parse(savedFiles);
process.stdout.write('pics '+pics.length);
// resize(pics);
} | conditional_block |
thumbnail-process-ar.js | import path from 'path'
import easyimg from 'easyimage'
import {getSavedPictures} from './image-indexer'
import Q from 'q'
import fs from 'fs'
const thumbnailFolder = "../thumbnails"
const thumbnailCount = 30
const width = 250
const height = 250
const quality = 80
function createThumbnail(){
getSavedPictures((err,... | }
catch(err){
}
console.log('doing');
var prom = easyimg.thumbnail({
src:pic.path,
dst:thumbnailPath,
width:width, height:height,
x:0, y:0,
quality: quality
})
pic.thumbnail = thumbnailPath;
con... | try{
fs.statSync(thumbnailPath);
process.stdout.write('PRESENT');
return; | random_line_split |
thumbnail-process-ar.js | import path from 'path'
import easyimg from 'easyimage'
import {getSavedPictures} from './image-indexer'
import Q from 'q'
import fs from 'fs'
const thumbnailFolder = "../thumbnails"
const thumbnailCount = 30
const width = 250
const height = 250
const quality = 80
function | (){
getSavedPictures((err, savedFiles)=>{
try{
if(err) {
process.stdout.write('error getting pictures '+err);
}else{
process.stdout.write(' WIT '+savedFiles.substring(0, 10));
process.stdout.write(' WIT '+savedFiles.substring(-10, 10));... | createThumbnail | identifier_name |
thumbnail-process-ar.js | import path from 'path'
import easyimg from 'easyimage'
import {getSavedPictures} from './image-indexer'
import Q from 'q'
import fs from 'fs'
const thumbnailFolder = "../thumbnails"
const thumbnailCount = 30
const width = 250
const height = 250
const quality = 80
function createThumbnail(){
getSavedPictures((err,... | dst:thumbnailPath,
width:width, height:height,
x:0, y:0,
quality: quality
})
pic.thumbnail = thumbnailPath;
console.log(thumbnailPath);
current.push(prom);
});
Q.all(current)
.then(()=>{
if(top && top.length)... | {
let current = [];
let top = pics.slice(-thumbnailCount);
let sliced = pics.slice(0, -thumbnailCount);
top.forEach((pic)=>{
let thumbnailPath = path.join(__dirname, thumbnailFolder, pic.file);
try{
fs.statSync(thumbnailPath);
process.stdou... | identifier_body |
detruire_sortie.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | cls):
cls.ajouter_types(cls.detruire_sortie, "Salle", "str")
@staticmethod
def detruire_sortie(salle, direction):
"""Détruit une sortie de salle et sa réciproque de la destination.
La direction est à choisir parmi est, ouest, nord, sud, nord-est,
nord-ouest, sud-est, sud-ouest,... | nit_types( | identifier_name |
detruire_sortie.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | d_salle = salle.sorties[direction].salle_dest
dir_opposee = salle.sorties.get_nom_oppose(direction)
d_salle.sorties.supprimer_sortie(dir_opposee)
salle.sorties.supprimer_sortie(direction)
| e ErreurExecution("sortie {} non définie".format(direction))
| conditional_block |
detruire_sortie.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | salle.sorties.supprimer_sortie(direction) | random_line_split | |
detruire_sortie.py | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | d_salle = salle.sorties[direction].salle_dest
dir_opposee = salle.sorties.get_nom_oppose(direction)
d_salle.sorties.supprimer_sortie(dir_opposee)
salle.sorties.supprimer_sortie(direction)
| """Détruit une sortie d'une salle."""
@classmethod
def init_types(cls):
cls.ajouter_types(cls.detruire_sortie, "Salle", "str")
@staticmethod
def detruire_sortie(salle, direction):
"""Détruit une sortie de salle et sa réciproque de la destination.
La direction est à choisir par... | identifier_body |
server.js | import express from 'express'
import adminOnly from 'desktop/lib/admin_only'
import { buildServerApp } from 'reaction/Router'
import { routes } from './routes'
import { renderLayout } from '@artsy/stitch'
import { Meta } from './components/Meta'
const app = (module.exports = express())
app.get('/isomorphic-relay-exam... |
const layout = await renderLayout({
basePath: __dirname,
layout: '../../components/main_layout/templates/react_index.jade',
config: {
styledComponents: true,
},
blocks: {
head: Meta,
body: ServerApp,
},
locals: {
...res.locals,
asse... | {
res.redirect(302, redirect.url)
return
} | conditional_block |
server.js | import express from 'express'
import adminOnly from 'desktop/lib/admin_only'
import { buildServerApp } from 'reaction/Router'
import { routes } from './routes'
import { renderLayout } from '@artsy/stitch'
import { Meta } from './components/Meta'
const app = (module.exports = express())
app.get('/isomorphic-relay-exam... | }) | random_line_split | |
oas-route.ts | import { edk, GuardItem, HttpMethod } from '@ditsmod/core';
import { makePropDecorator } from '@ts-stack/di';
import { XOperationObject } from '@ts-stack/openapi-spec';
export type OasRouteDecorator = <T>(
target: edk.AnyObj,
propertyName: string,
descriptor: TypedPropertyDescriptor<T>
) => OasRouteDecoratorMeta... |
export interface OasRouteMetadata1 {
httpMethod: HttpMethod;
path?: string;
guards?: GuardItem[];
/**
* OAS `OperationObject`.
*/
operationObject?: XOperationObject;
}
export interface OasRouteMetadata2 {
httpMethod: HttpMethod;
path?: string;
/**
* OAS `OperationObject`.
*/
operationObj... |
export interface OasRouteDecoratorMetadata {
[key: string]: (OasRouteMetadata1 | OasRouteMetadata2)[];
} | random_line_split |
oas-route.ts | import { edk, GuardItem, HttpMethod } from '@ditsmod/core';
import { makePropDecorator } from '@ts-stack/di';
import { XOperationObject } from '@ts-stack/openapi-spec';
export type OasRouteDecorator = <T>(
target: edk.AnyObj,
propertyName: string,
descriptor: TypedPropertyDescriptor<T>
) => OasRouteDecoratorMeta... |
// prettier-ignore
declare function oasRoute(httpMethod: HttpMethod, path?: string, guards?: GuardItem[], operationObject?: XOperationObject): OasRouteDecorator;
// prettier-ignore
declare function oasRoute(httpMethod: HttpMethod, path?: string, operationObject?: XOperationObject): OasRouteDecorator;
/**
* Open API... | {
if (Array.isArray(guardsOrOperationObj)) {
return { httpMethod, path, guards: guardsOrOperationObj, operationObject };
} else if (guardsOrOperationObj) {
return { httpMethod, path, operationObject: guardsOrOperationObj };
} else {
return { httpMethod, path };
}
} | identifier_body |
oas-route.ts | import { edk, GuardItem, HttpMethod } from '@ditsmod/core';
import { makePropDecorator } from '@ts-stack/di';
import { XOperationObject } from '@ts-stack/openapi-spec';
export type OasRouteDecorator = <T>(
target: edk.AnyObj,
propertyName: string,
descriptor: TypedPropertyDescriptor<T>
) => OasRouteDecoratorMeta... | (
httpMethod: HttpMethod,
path?: string,
guardsOrOperationObj?: XOperationObject | GuardItem[],
operationObject?: XOperationObject
): OasRouteMetadata1 | OasRouteMetadata2 {
if (Array.isArray(guardsOrOperationObj)) {
return { httpMethod, path, guards: guardsOrOperationObj, operationObject };
} else if (... | oasRouteCallback | identifier_name |
testlibbind_ns_msg.py | #!/usr/bin/env python
#
# testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper
#
# This file is part of Strangle.
#
# Strangle 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 2 of t... |
def testParseValidQuery(self):
"""Test whether ns_msg initialization parses valid NS queries"""
packetData = file("data/www.company.example-query").read()
n = libbind.ns_msg(packetData)
assert(type(n) is libbind.ns_msg)
def testParseValidResponse(self):
"""Test whether ns_msg initialization parses v... | packetLength = random.randrange(20, 80)
packetVal = rng.read(packetLength)
self.assertRaises(TypeError, libbind.ns_msg, packetVal) | conditional_block |
testlibbind_ns_msg.py | #!/usr/bin/env python
#
# testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper
#
# This file is part of Strangle.
#
# Strangle 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 2 of t... | (self):
"""Test whether ns_msg initialization parses valid NS queries"""
packetData = file("data/www.company.example-response").read()
n = libbind.ns_msg(packetData)
assert(type(n) is libbind.ns_msg)
def suite():
s = unittest.TestSuite()
s.addTest( unittest.makeSuite(ns_msgTestCase, 'test') )
return s
... | testParseValidResponse | identifier_name |
testlibbind_ns_msg.py | #!/usr/bin/env python
#
# testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper
#
# This file is part of Strangle.
#
# Strangle 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 2 of t... |
def testNoticeInvalid(self):
"""Test whether the ns_msg type can handle bad data"""
rng = testutils.rng
for testNum in range(0, 50):
packetLength = random.randrange(20, 80)
packetVal = rng.read(packetLength)
self.assertRaises(TypeError, libbind.ns_msg, packetVal)
def testParseValidQ... | random_line_split | |
testlibbind_ns_msg.py | #!/usr/bin/env python
#
# testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper
#
# This file is part of Strangle.
#
# Strangle 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 2 of t... |
if __name__ == "__main__":
unittest.main()
| s = unittest.TestSuite()
s.addTest( unittest.makeSuite(ns_msgTestCase, 'test') )
return s | identifier_body |
round_manager_fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::BlockStore,
liveness::{
proposal_generator::ProposalGenerator,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, NewRoundEvent, NewRoundReaso... | {
// generate a proposal
let proposal = generate_corpus_proposal();
// successfully parse it
fuzz_proposal(&proposal);
} | identifier_body | |
round_manager_fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::BlockStore,
liveness::{
proposal_generator::ProposalGenerator,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, NewRoundEvent, NewRoundReaso... | };
use futures::{channel::mpsc, executor::block_on};
use network::{
peer_manager::{ConnectionRequestSender, PeerManagerRequestSender},
protocols::network::NewNetworkSender,
};
use once_cell::sync::Lazy;
use safety_rules::{test_utils, SafetyRules, TSafetyRules};
use std::{collections::BTreeMap, sync::Arc, time::... | ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
on_chain_config::ValidatorSet,
validator_info::ValidatorInfo,
validator_signer::ValidatorSigner,
validator_verifier::ValidatorVerifier, | random_line_split |
round_manager_fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::BlockStore,
liveness::{
proposal_generator::ProposalGenerator,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, NewRoundEvent, NewRoundReaso... | (
storage: Arc<dyn PersistentLivenessStorage>,
initial_data: RecoveryData,
) -> Arc<BlockStore> {
let (_commit_cb_sender, _commit_cb_receiver) = mpsc::unbounded::<LedgerInfoWithSignatures>();
Arc::new(BlockStore::new(
storage,
initial_data,
Arc::new(EmptyStateComputer),
... | build_empty_store | identifier_name |
utils.py | (obj, datetime.datetime):
r = obj.isoformat()
if obj.microsecond:
r = r[:23] + r[26:]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance... | return key, value
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(se... | '''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is
true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root[0]
... | identifier_body |
utils.py | .tzinfo.utcoffset(obj) is not None:
raise ValueError("JSON can't represent timezone-aware times.")
r = obj.isoformat()
if obj.microsecond:
r = r[:12]
return r
return super(DateTimeJsonEncoder, self).default(obj)
# Backport of OrderedDict() cl... | random_line_split | ||
utils.py | (obj, datetime.datetime):
r = obj.isoformat()
if obj.microsecond:
r = r[:23] + r[26:]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance... | (cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).
'''
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
'''od.__eq__(y) <==... | fromkeys | identifier_name |
utils.py | (obj, datetime.datetime):
r = obj.isoformat()
if obj.microsecond:
r = r[:23] + r[26:]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance... |
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> Ne... | inst_dict.pop(k, None) | conditional_block |
App.js | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import firebase from 'firebase';
import ReduxThunk from 'redux-thunk';
import reducers from './src/reducers';
// import LoginForm from './src/components/LoginForm';
import Router from ... |
}
export default App;
| {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<Router />
</Provider>
);
} | identifier_body |
App.js | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import firebase from 'firebase';
import ReduxThunk from 'redux-thunk';
import reducers from './src/reducers';
// import LoginForm from './src/components/LoginForm';
import Router from ... | <Provider store={store}>
<Router />
</Provider>
);
}
}
export default App; | render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return ( | random_line_split |
App.js | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import firebase from 'firebase';
import ReduxThunk from 'redux-thunk';
import reducers from './src/reducers';
// import LoginForm from './src/components/LoginForm';
import Router from ... | extends Component {
componentWillMount() {
// Initialize Firebase
const config = {
apiKey: 'AIzaSyBlE5TJxuDiBiGmhGH1eLymxCmAer7d5Rg',
authDomain: 'manager-bab0a.firebaseapp.com',
databaseURL: 'https://manager-bab0a.firebaseio.com',
projectId: 'manager-bab0a',
storageBucket: 'manager-bab0a.apps... | App | identifier_name |
color.js | const HEX_SHORT = /^#([a-fA-F0-9]{3})$/;
const HEX = /^#([a-fA-F0-9]{6})$/;
function roundColors(obj, round) {
if (!round) return obj;
const o = {};
for (let k in obj) {
o[k] = Math.round(obj[k]);
}
return o;
}
function hasProp(obj, key) {
return obj.hasOwnProperty(key);
}
function isRgb(obj) {
re... | else {
hsv.s = (delta / max * 1000) / 10;
}
if (max === min) {
hsv.h = 0;
} else if (r === max) {
hsv.h = (g - b) / delta;
} else if (g === max) {
hsv.h = 2 + (b - r) / delta;
} else {
hsv.h = 4 + (r - g) / delta;
}
hsv.h = Math.min(hsv.h * 60, 360);
hsv.... | {
hsv.s = 0;
} | conditional_block |
color.js | const HEX_SHORT = /^#([a-fA-F0-9]{3})$/;
const HEX = /^#([a-fA-F0-9]{6})$/;
function roundColors(obj, round) {
if (!round) return obj;
const o = {};
for (let k in obj) {
o[k] = Math.round(obj[k]);
}
return o;
}
function hasProp(obj, key) {
return obj.hasOwnProperty(key);
}
function isRgb(obj) {
re... |
hsv.h = Math.min(hsv.h * 60, 360);
hsv.h = hsv.h < 0 ? hsv.h + 360 : hsv.h;
hsv.v = ((max / 255) * 1000) / 10;
return roundColors(hsv, round);
}
static rgbToXyz(rgb, round = true) {
const r = rgb.r / 255;
const g = rgb.g / 255;
const b = rgb.b / 255;
const rr = r > 0.04045 ? Mat... | random_line_split | |
color.js | const HEX_SHORT = /^#([a-fA-F0-9]{3})$/;
const HEX = /^#([a-fA-F0-9]{6})$/;
function roundColors(obj, round) {
if (!round) return obj;
const o = {};
for (let k in obj) {
o[k] = Math.round(obj[k]);
}
return o;
}
function hasProp(obj, key) {
return obj.hasOwnProperty(key);
}
function isRgb(obj) {
re... |
static rgbToHsv(rgb, round = true) {
const { r, g, b } = rgb;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
const hsv = {};
if (max === 0) {
hsv.s = 0;
} else {
hsv.s = (delta / max * 1000) / 10;
}
if (max === min) {
hs... | {
const { r, g, b} = rgb;
const i = ((Math.round(r) & 0xFF) << 16) + ((Math.round(g) & 0xFF) << 8) + (Math.round(b) & 0xFF);
const s = i.toString(16).toLowerCase();
return `#${"000000".substring(s.length) + s}`;
} | identifier_body |
color.js | const HEX_SHORT = /^#([a-fA-F0-9]{3})$/;
const HEX = /^#([a-fA-F0-9]{6})$/;
function roundColors(obj, round) {
if (!round) return obj;
const o = {};
for (let k in obj) {
o[k] = Math.round(obj[k]);
}
return o;
}
function hasProp(obj, key) {
return obj.hasOwnProperty(key);
}
function isRgb(obj) {
re... | (hex) {
const normalizedHex = this.normalizeHex(hex);
if (normalizedHex == null) {
return null;
}
const m = normalizedHex.match(HEX);
const i = parseInt(m[1], 16);
const r = (i >> 16) & 0xFF;
const g = (i >> 8) & 0xFF;
const b = i & 0xFF;
return { r, g, b };
}
static rg... | hexToRgb | identifier_name |
TacticNotationsLexer.py | 3\3\2\3\2\3\2\3\3\3\3")
buf.write("\3\3\3\3\3\3\3\3\5\3!\n\3\3\4\3\4\3\5\3\5\3\6\3\6\3\6")
buf.write("\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3")
buf.write("\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6")
buf.write("\3\6\5\6F\n\6\3\7\3\7\3\b\3\b\6\bL\n\b\r\b\16\bM\5... | super().__init__(input, output)
self.checkVersion("4.7.2")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None | identifier_body | |
TacticNotationsLexer.py | buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\f")
buf.write("f\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\3\2\3\2\3\2\3\3\3\3")
buf.write("\3\3\3\3\3\3\3\3\5\3!\n\3\3\4\3\4\3\5\3\5\3\6\3\6\3\6")
buf.write("\3\6\3... | class TacticNotationsLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
LALT = 1
LGROUP = 2
LBRACE = 3
RBRACE = 4
ESCAPED = 5
PIPE = 6
ATOM = 7
ID = 8
SUB = 9
WHITESPACE = 10
... | random_line_split | |
TacticNotationsLexer.py | ():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\f")
buf.write("f\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\3\2\3\2\3\2\3\3\3\3")
buf.write("\3\3\3\3\3\3\3\3\5\3!\n\3\3\4\3\4\3\5\3\5\... | serializedATN | identifier_name | |
auth-container.component.spec.ts | import { HttpClientModule } from '@angular/common/http';
import { ChangeDetectorRef } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatCardModule, MatIconModule, MatToolbarModule } from '@angular/material';
import { StoreModule } from '@ngrx/store';
import { co... | declarations: [ AuthContainerComponent ],
providers: [ { provide: CONFIG_TOKEN, useValue: config }, AppSandbox, ChangeDetectorRef ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthContainerComponent);
component = fixture.componentInstance;
... | TestBed.configureTestingModule({
imports: [ HttpClientModule, MatIconModule, MatToolbarModule,
MatCardModule, StoreModule.forRoot({}) ], | random_line_split |
mod.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer 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... | pub use self::proxy::Proxy; | random_line_split | |
styles.tsx | require('normalize.css');
require('./fonts/fonts.css');
require('./styles.css');
const Prefixer = require('inline-style-prefixer');
export const prefixer = new Prefixer();
// export const statusBarHeight = () => {
// if (window.cordova && cordova.platformId === 'ios' &&
// (window.orientation === 0 || window.orie... | height: STYLE_CONST.BOTTOM_PANEL_HEIGHT_MOBILE/3,
},
sliderToolTip: {
position: 'absolute',
zIndex: 10,
right: 0,
marginRight: 15,
fontSize: STYLE_CONST.SLIDER_FONT_SIZE,
fontFamily: STYLE_CONST.FONT_FAMILY,
fontWeight: 300,
lineHeight: `${STYLE_CONST.BOTTOM_PANEL_HEIGHT/3}px`,
pointerEvents: 'no... | height: STYLE_CONST.BOTTOM_PANEL_HEIGHT/3,
},
sliderContainer_smallScreen: { | random_line_split |
SinglePeak.py | # -*- uft-8 -*-
import matplotlib
class SinglePeak():
"""Creat a class as a Peak Container"""
def __init__(self,StandardPeak):
self.StandardPeak=StandardPeak
self.Indicator=False
self.RecordIntegrationTime=0
self.MaxCounts=0
self.PeakPixel=0
self.pixel=[]
self.CountsRange=[20000,50000]
def GetPixel(se... | (self,CountsRange):
# if MaxCounts is between CountsRange[0] and CountsRange[1]
# then Indicator = True pass the check
self.CountsRange=CountsRange
if self.MaxCounts>self.CountsRange[0] and self.MaxCounts<self.CountsRange[1]:
self.Indicator=True
return self.Indicator | UpdateIndicator | identifier_name |
SinglePeak.py | # -*- uft-8 -*-
import matplotlib
class SinglePeak():
"""Creat a class as a Peak Container"""
def __init__(self,StandardPeak):
self.StandardPeak=StandardPeak
self.Indicator=False
self.RecordIntegrationTime=0
self.MaxCounts=0
self.PeakPixel=0
self.pixel=[]
self.CountsRange=[20000,50000]
def GetPixel(se... |
return self.MaxCounts
def UpdateIndicator(self,CountsRange):
# if MaxCounts is between CountsRange[0] and CountsRange[1]
# then Indicator = True pass the check
self.CountsRange=CountsRange
if self.MaxCounts>self.CountsRange[0] and self.MaxCounts<self.CountsRange[1]:
self.Indicator=True
return self.Ind... | if self.MaxCounts<self.Spectrum[i]:
self.MaxCounts=self.Spectrum[i]
self.MaxCountsPixel=i+self.pixel[0] | conditional_block |
SinglePeak.py | # -*- uft-8 -*-
import matplotlib
class SinglePeak():
"""Creat a class as a Peak Container"""
def __init__(self,StandardPeak):
self.StandardPeak=StandardPeak
self.Indicator=False
self.RecordIntegrationTime=0
self.MaxCounts=0
self.PeakPixel=0
self.pixel=[]
self.CountsRange=[20000,50000]
def GetPixel(se... |
def GetMaxCounts(self):
# get max counts of the peak
for i in range(0,len(self.Spectrum)-1):
if self.MaxCounts<self.Spectrum[i]:
self.MaxCounts=self.Spectrum[i]
self.MaxCountsPixel=i+self.pixel[0]
return self.MaxCounts
def UpdateIndicator(self,CountsRange):
# if MaxCounts is between CountsRange[0... | def GetSingleSpectrum(self,Spectrum):
# get spectrum of the peak
Spectrum=list(Spectrum)
self.Spectrum=Spectrum[self.pixel[0]:self.pixel[1]]
return self.Spectrum | random_line_split |
SinglePeak.py | # -*- uft-8 -*-
import matplotlib
class SinglePeak():
"""Creat a class as a Peak Container"""
def __init__(self,StandardPeak):
self.StandardPeak=StandardPeak
self.Indicator=False
self.RecordIntegrationTime=0
self.MaxCounts=0
self.PeakPixel=0
self.pixel=[]
self.CountsRange=[20000,50000]
def GetPixel(se... | self.CountsRange=CountsRange
if self.MaxCounts>self.CountsRange[0] and self.MaxCounts<self.CountsRange[1]:
self.Indicator=True
return self.Indicator | identifier_body | |
json_data.py | """
@file
@brief This file loads and saves settings (as JSON)
@author Ted Lazaros <tedlaz@gmail.com>
@section LICENSE
"""
try:
import json
except ImportError:
import simplejson as json
import copy
from classes.logger import log
class JsonDataStore:
"""
This class which allow... | if "setting" in item and "value" in item:
user_values[item["setting"]] = item["value"]
# Update default values to match user values
for item in default:
user_value = user_values.get(item["setting"], None)
if user_value:
... | # pass
# Load user setting's values (for easy merging)
user_values = {}
for item in user:
| random_line_split |
json_data.py | """
@file
@brief This file loads and saves settings (as JSON)
@author Ted Lazaros <tedlaz@gmail.com>
@section LICENSE
"""
try:
import json
except ImportError:
import simplejson as json
import copy
from classes.logger import log
class JsonDataStore:
"""
This class which allow... | (self, file_path):
""" Load JSON settings from a file """
# log.debug("loading {}".format(file_path))
try:
with open(file_path.encode('UTF-8'), 'r') as f:
contents = f.read()
if contents:
# log.debug("loaded", contents)
... | read_from_file | identifier_name |
json_data.py | """
@file
@brief This file loads and saves settings (as JSON)
@author Ted Lazaros <tedlaz@gmail.com>
@section LICENSE
"""
try:
import json
except ImportError:
import simplejson as json
import copy
from classes.logger import log
class JsonDataStore:
"""
This class which allow... |
def get(self, key):
""" Get copied value of a given key in data store """
key = key.lower()
# Determine if the root element is a dictionary or list
# (i.e. project data or settings data)
if type(self._data) == list:
# Settings data, search for matching... | self._data = {}
self.data_type = "json data" | identifier_body |
json_data.py | """
@file
@brief This file loads and saves settings (as JSON)
@author Ted Lazaros <tedlaz@gmail.com>
@section LICENSE
"""
try:
import json
except ImportError:
import simplejson as json
import copy
from classes.logger import log
class JsonDataStore:
"""
This class which allow... |
def read_from_file(self, file_path):
""" Load JSON settings from a file """
# log.debug("loading {}".format(file_path))
try:
with open(file_path.encode('UTF-8'), 'r') as f:
contents = f.read()
if contents:
# log.debug... | for key in default:
if key not in user:
# Add missing key to user dictionary
user[key] = default[key]
# Return merged dictionary
return user | conditional_block |
A_evolve_outer_star_to_giant.py | import os
import os.path
from amuse.units import units
from amuse.datamodel import Particle
from amuse.ext.star_to_sph import pickle_stellar_model
from amuse.community.mesa.interface import MESA as stellar_evolution_code
from xiTau_parameters import triple_parameters
def evolve_giant(giant, stop_radius):
stell... |
print "Giant starts to ascend the giant branch, now saving model every step..."
print giant_in_code.as_set()
i = 0
while (giant_in_code.radius < stop_radius):
giant_in_code.evolve_one_step()
print giant_in_code.radius, giant_in_code.age
pickle_file_name = "./model_{0:... | giant_in_code.evolve_one_step() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.