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 |
|---|---|---|---|---|
extern-call-scrub.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with smal... | cb | identifier_name |
settings.rs | // The MIT License (MIT)
// Copyright © 2014-2018 Miguel Peláez <kernelfreeze@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction, including without limitation... | &Vec<String> { &self.resourcepacks }
}
| cks(&self) -> | identifier_name |
settings.rs | // The MIT License (MIT)
// Copyright © 2014-2018 Miguel Peláez <kernelfreeze@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction, including without limitation... | gameplay: GameplaySettings { fov: 90, vsync: true },
resourcepacks: Vec::new(),
}
}
/// Get window width
pub fn width(&self) -> u32 { self.window.width }
/// Set window width
pub fn set_width(&mut self, value: u32) { self.window.width = value }
/// Get window h... | fullscreen: false,
maximized: true,
multisampling: 0,
gui_scale: 1.0,
}, | random_line_split |
settings.rs | // The MIT License (MIT)
// Copyright © 2014-2018 Miguel Peláez <kernelfreeze@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction, including without limitation... | Get user GUI scale
pub fn scale(&self) -> f64 { self.window.gui_scale }
/// Get enabled resourcepacks by filename
pub fn resourcepacks(&self) -> &Vec<String> { &self.resourcepacks }
}
| eplay.fov }
/// | identifier_body |
mod.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/. */
//! Common [values][values] used in CSS.
//!
//! [values]: https://drafts.csswg.org/css-values/
#![deny(missing_d... | use selectors::parser::SelectorParseErrorKind;
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::fmt::{self, Debug};
use std::hash;
use style_traits::{ToCss, ParseError, StyleParseErrorKind};
pub mod animated;
pub mod computed;
pub mod distance;
pub mod generics;
pub mod specified;
/// A CSS float value.
pu... | use Atom;
pub use cssparser::{RGBA, Token, Parser, serialize_identifier, CowRcStr, SourceLocation};
use parser::{Parse, ParserContext}; | random_line_split |
mod.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/. */
//! Common [values][values] used in CSS.
//!
//! [values]: https://drafts.csswg.org/css-values/
#![deny(missing_d... | (&self, other: &Self) -> bool {
self.as_atom() == other.as_atom()
}
}
impl hash::Hash for KeyframesName {
fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
self.as_atom().hash(state)
}
}
impl Parse for KeyframesName {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser... | eq | identifier_name |
test_otp.py | 764535,
1.697360211099, 2.317229950712, 4.823998989452,
2.283487958310, 1.840698306602, 4.168734267290,
1.393303387573, 2.635037001113, 3.925918744272
])
class TestOTPExplicit(unittest.TestCase):
... | (self):
get_thermodynamic_information(self.system, self.db, nproc=None, recalculate=True)
self.assertIsNotNone | test_thermodynamics | identifier_name |
test_otp.py | self.assertAlmostEqual(e1, e2, 4)
for g1, g2 in zip(grad1, grad2):
self.assertAlmostEqual(g1, g2, 3)
# print "energy cpp"
# print e1, e2
# print grad1
# print grad2
_x1 = np.array([ 1.9025655 , 0.39575842, 2.70994994, 1.12711741, 0.63413933,
... | for v1, v2 in izip(ev, cev):
self.assertAlmostEqual(v1, v2, 5) | conditional_block | |
test_otp.py | 764535,
1.697360211099, 2.317229950712, 4.823998989452,
2.283487958310, 1.840698306602, 4.168734267290,
1.393303387573, 2.635037001113, 3.925918744272
])
class TestOTPExplicit(unittest.TestCase):
... | self.assertAlmostEqual(e, self.e0, delta=1e-4)
def test_energy_gradient(self):
e = self.pot.getEnergy(self.x0)
gnum = self.pot.NumericalDerivative(self.x0)
e2, g = self.pot.getEnergyGradient(self.x0)
self.assertAlmostEqual(e, e2, delta=1e-4)
for i... | def test_energy(self):
e = self.pot.getEnergy(self.x0) | random_line_split |
test_otp.py | def test_site_to_atomistic(self):
rf = self.make_otp()
p = np.array([1., 2, 3])
p /= np.linalg.norm(p)
com = np.array([4., 5, 6])
print "otp to atomistic"
print rf.to_atomistic(com, p)
print "otp transform grad"
g = np.array(range(9), dtype=floa... | print "\ntest rotate"
x = self.x0.copy()
p = np.array(range(1,4), dtype=float)
p /= np.linalg.norm(p)
self.transform.rotate(x, rotations.aa2mx(p))
xnewtrue = np.array([ 0.48757698, 0.61588594, 2.09355038, 2.02484605, 4.76822812,
4.81289924... | identifier_body | |
main.rs | extern crate piston;
extern crate piston_window;
extern crate vecmath;
extern crate camera_controllers;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate glfw_window;
use std::cell::RefCell;
use std::rc::Rc;
use piston_window::*;
use piston::event::*;
use piston::window::{ AdvancedWindow, WindowS... | Vertex::new([-1, -1, -1], [1, 1]),
Vertex::new([ 1, -1, -1], [0, 1]),
//right (1, 0, 0)
Vertex::new([ 1, -1, -1], [0, 0]),
Vertex::new([ 1, 1, -1], [1, 0]),
Vertex::new([ 1, 1, 1], [1, 1]),
Vertex::new([ 1, -1, 1], [0, 1]),
//left (-1, 0, 0)
Ve... | {
let (win_width, win_height) = (640, 480);
let window = Rc::new(RefCell::new(GlfwWindow::new(
OpenGL::_3_2,
WindowSettings::new("piston-example-gfx_cube", [win_width, win_height])
.exit_on_esc(true)
.samples(4)
).capture_cursor(true)));
let events = PistonWindow::new(wi... | identifier_body |
main.rs | extern crate piston;
extern crate piston_window;
extern crate vecmath;
extern crate camera_controllers;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate glfw_window;
use std::cell::RefCell;
use std::rc::Rc;
use piston_window::*;
use piston::event::*;
use piston::window::{ AdvancedWindow, WindowS... |
}
}
| {
projection = get_projection(&e);
} | conditional_block |
main.rs | extern crate piston;
extern crate piston_window;
extern crate vecmath;
extern crate camera_controllers;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate glfw_window;
use std::cell::RefCell;
use std::rc::Rc;
use piston_window::*;
use piston::event::*;
use piston::window::{ AdvancedWindow, WindowS... | () {
let (win_width, win_height) = (640, 480);
let window = Rc::new(RefCell::new(GlfwWindow::new(
OpenGL::_3_2,
WindowSettings::new("piston-example-gfx_cube", [win_width, win_height])
.exit_on_esc(true)
.samples(4)
).capture_cursor(true)));
let events = PistonWindow::new... | main | identifier_name |
main.rs | extern crate piston;
extern crate piston_window;
extern crate vecmath;
extern crate camera_controllers;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate glfw_window;
use std::cell::RefCell;
use std::rc::Rc;
use piston_window::*;
use piston::event::*;
use piston::window::{ AdvancedWindow, WindowS... | use piston::window::Window;
let draw_size = w.window.borrow().draw_size();
CameraPerspective {
fov: 90.0, near_clip: 0.1, far_clip: 1000.0,
aspect_ratio: (draw_size.width as f32) / (draw_size.height as f32)
}.projection()
};
let model = vecmath::mat4_id(... | let get_projection = |w: &PistonWindow<GlfwWindow>| { | random_line_split |
oesvertexarrayobject.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 canvas_traits::webgl::WebGLVersion;
use dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::{self, ... | fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESVertexArrayObject> {
reflect_dom_object(
Box::new(OESVertexArrayObject::new_inherited(ctx)),
&*ctx.global(),
OESVertexArrayObjectBinding::Wrap,
)
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionS... | impl WebGLExtension for OESVertexArrayObject {
type Extension = OESVertexArrayObject; | random_line_split |
oesvertexarrayobject.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 canvas_traits::webgl::WebGLVersion;
use dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::{self, ... | {
reflector_: Reflector,
ctx: Dom<WebGLRenderingContext>,
}
impl OESVertexArrayObject {
fn new_inherited(ctx: &WebGLRenderingContext) -> OESVertexArrayObject {
Self {
reflector_: Reflector::new(),
ctx: Dom::from_ref(ctx),
}
}
}
impl OESVertexArrayObjectMethods ... | OESVertexArrayObject | identifier_name |
test_disambiguate.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
import unittest
from ..morf import analyze, disambiguate
# EINO SANTANEN. Muodon vanhimmat
# http://luulet6lgendus.blogspot.com/
sentences = '''KÕIGE VANEM MUDEL
Pimedas luusivad robotid,
originaalsed tšehhi robotid kahe... | se):
"""Test the separate disambiguate function
against the built in disambiguate=True function.
Both must work the same."""
def test_disambiguator(self):
for sentence in sentences:
an_with = analyze(sentence)
an_without = analyze(sentence, disambiguate=False)
... | r(unittest.TestCa | identifier_name |
test_disambiguate.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
import unittest
from ..morf import analyze, disambiguate
# EINO SANTANEN. Muodon vanhimmat
# http://luulet6lgendus.blogspot.com/
sentences = '''KÕIGE VANEM MUDEL
Pimedas luusivad robotid,
originaalsed tšehhi robotid kahe... | e(sentence)
an_without = analyze(sentence, disambiguate=False)
disamb = disambiguate(an_without)
self.assertListEqual(an_with, disamb)
| conditional_block | |
test_disambiguate.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
import unittest
from ..morf import analyze, disambiguate
# EINO SANTANEN. Muodon vanhimmat
# http://luulet6lgendus.blogspot.com/
sentences = '''KÕIGE VANEM MUDEL
Pimedas luusivad robotid,
originaalsed tšehhi robotid kahe... |
class TestDisambiguator(unittest.TestCase):
"""Test the separate disambiguate function
against the built in disambiguate=True function.
Both must work the same."""
def test_disambiguator(self):
for sentence in sentences:
an_with = analyze(sentence)
an_without = analyze... | random_line_split | |
test_disambiguate.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
import unittest
from ..morf import analyze, disambiguate
# EINO SANTANEN. Muodon vanhimmat
# http://luulet6lgendus.blogspot.com/
sentences = '''KÕIGE VANEM MUDEL
Pimedas luusivad robotid,
originaalsed tšehhi robotid kahe... | sentences:
an_with = analyze(sentence)
an_without = analyze(sentence, disambiguate=False)
disamb = disambiguate(an_without)
self.assertListEqual(an_with, disamb)
| identifier_body | |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | .context("Error writing header")?;
}
match coordinates {
Ok(None) => Ok(None),
Ok(Some(some)) => Ok(Some(Ok(some))),
Err(e) => Ok(Some(Err(e))),
}
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use libimagsto... | {
let coordinates = self.get_coordinates();
let patterns = [
"gps.coordinates.latitude.degree",
"gps.coordinates.latitude.minutes",
"gps.coordinates.latitude.seconds",
"gps.coordinates.longitude.degree",
"gps.coordinates.longitude.minutes",
... | identifier_body |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | let coordinates = Coordinates {
latitude: GPSValue::new(0, 0, 0),
longitude: GPSValue::new(0, 0, 0),
};
let res = entry.set_coordinates(coordinates);
assert!(res.is_ok());
}
#[test]
fn test_setget_gps() {
setup_logging();
let store ... |
let mut entry = store.create(PathBuf::from("test_set_gps")).unwrap();
| random_line_split |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | () {
setup_logging();
let store = get_store();
let mut entry = store.create(PathBuf::from("test_setget_gps")).unwrap();
let coordinates = Coordinates {
latitude: GPSValue::new(0, 0, 0),
longitude: GPSValue::new(0, 0, 0),
};
let res = entry.set_... | test_setget_gps | identifier_name |
greedy.py | '''
Implementation of the locally greedy approach similar with DuVerle & Predinger
(2009, 2010) (but adapted for SDRT, where the notion of adjacency includes
embedded segments)
July 2012
@author: stergos
'''
from __future__ import print_function
import sys
from .interface import Decoder
from .util import (convert_p... | (self):
'''
Single pass of the locally greedy algorithm: pick the
highest probability link between any two neighbours.
Remove the source EDU from future consideration.
:rtype: None
'''
highest = 0.0
to_remove = None
attachment = None
new_s... | _attach_best | identifier_name |
greedy.py | '''
Implementation of the locally greedy approach similar with DuVerle & Predinger
(2009, 2010) (but adapted for SDRT, where the notion of adjacency includes
embedded segments)
July 2012
@author: stergos
'''
from __future__ import print_function
import sys
from .interface import Decoder
from .util import (convert_p... |
if is_embedded(one, two) or is_embedded(two, one):
if two.id not in one_neighbours_ids:
one_neighbours_ids.add(two.id)
one_neighbours.append(two)
neighbours[one] = one_neighbours
return neighbours
class LocallyGreedySta... | one_neighbours_ids.add(two.id)
one_neighbours.append(two) | conditional_block |
greedy.py | '''
Implementation of the locally greedy approach similar with DuVerle & Predinger
(2009, 2010) (but adapted for SDRT, where the notion of adjacency includes
embedded segments)
July 2012
@author: stergos
'''
from __future__ import print_function
import sys
from .interface import Decoder
from .util import (convert_p... |
def get_neighbours(edus):
'''
Return a mapping from each EDU to its neighbours
:type edus: [Edu]
:rtype: Dict Edu [Edu]
'''
neighbours = dict()
for one in edus:
one_neighbours = []
one_neighbours_ids = set()
for two in edus:
if one.id != two.id:
... |
returns False in all other cases
"""
return two.id != one.id and two.start <= one.start and one.end <= two.end | random_line_split |
greedy.py | '''
Implementation of the locally greedy approach similar with DuVerle & Predinger
(2009, 2010) (but adapted for SDRT, where the notion of adjacency includes
embedded segments)
July 2012
@author: stergos
'''
from __future__ import print_function
import sys
from .interface import Decoder
from .util import (convert_p... | one_neighbours.append(two)
neighbours[one] = one_neighbours
return neighbours
class LocallyGreedyState(object):
'''
the mutable parts of the locally greedy algorithm
'''
def __init__(self, instances):
self._edus = get_sorted_edus(instances)
self._... | '''
Return a mapping from each EDU to its neighbours
:type edus: [Edu]
:rtype: Dict Edu [Edu]
'''
neighbours = dict()
for one in edus:
one_neighbours = []
one_neighbours_ids = set()
for two in edus:
if one.id != two.id:
if are_strictly_adjace... | identifier_body |
group.rs | //! Fuctions and Structs for dealing with /etc/group
use std::path::Path;
use std::num::ParseIntError;
use libc::gid_t;
use entries::{Entries,Entry};
/// An entry from /etc/group
#[derive(Debug, PartialEq, PartialOrd)]
pub struct | {
/// Group Name
pub name: String,
/// Group Password
pub passwd: String,
/// Group ID
pub gid: gid_t,
/// Group Members
pub members: Vec<String>,
}
impl Entry for GroupEntry {
fn from_line(line: &str) -> Result<GroupEntry, ParseIntError> {
let parts: Vec<&str> = lin... | GroupEntry | identifier_name |
group.rs | //! Fuctions and Structs for dealing with /etc/group
use std::path::Path;
use std::num::ParseIntError;
use libc::gid_t;
use entries::{Entries,Entry};
/// An entry from /etc/group
#[derive(Debug, PartialEq, PartialOrd)]
pub struct GroupEntry {
/// Group Name
pub name: String,
/// Group Password
pub ... | get_entry_by_name_from_path(&Path::new("/etc/group"), name)
}
/// Return a `Vec<`[`GroupEntry`](struct.GroupEntry.html)`>` containing all
/// [`GroupEntry`](struct.GroupEntry.html)'s for a given `&Path`
pub fn get_all_entries_from_path(path: &Path) -> Vec<GroupEntry> {
Entries::new(path).collect()
}
/// Ret... |
/// Return a [`GroupEntry`](struct.GroupEntry.html)
/// for a given `name` from `/etc/group`
pub fn get_entry_by_name(name: &str) -> Option<GroupEntry> { | random_line_split |
widget.js | function WPATH(s) |
module.exports = [ {
isApi: true,
priority: 1000.0001,
key: "window",
style: {
layout: "vertical"
}
}, {
isApi: true,
priority: 1000.0003,
key: "View",
style: {
width: 320
}
}, {
isClass: true,
priority: 10000.0002,
key: "container",
style: {
... | {
var index = s.lastIndexOf("/");
var path = -1 === index ? "titlebar/" + s : s.substring(0, index) + "/titlebar/" + s.substring(index + 1);
return path;
} | identifier_body |
widget.js | function WPATH(s) {
var index = s.lastIndexOf("/");
var path = -1 === index ? "titlebar/" + s : s.substring(0, index) + "/titlebar/" + s.substring(index + 1);
return path;
}
module.exports = [ {
isApi: true,
priority: 1000.0001,
key: "window",
style: {
layout: "vertical"
}
}, {
... | priority: 100000.0003,
key: "titlebar",
style: {
backgroundColor: "#EDEDED",
height: 65,
top: 0,
zIndex: 99
}
}, {
isId: true,
priority: 100000.0004,
key: "back",
style: {
backgroundColor: "#FF0000",
height: 45,
width: 60,
t... | }
}, {
isId: true, | random_line_split |
widget.js | function | (s) {
var index = s.lastIndexOf("/");
var path = -1 === index ? "titlebar/" + s : s.substring(0, index) + "/titlebar/" + s.substring(index + 1);
return path;
}
module.exports = [ {
isApi: true,
priority: 1000.0001,
key: "window",
style: {
layout: "vertical"
}
}, {
isApi: tru... | WPATH | identifier_name |
__openerp__.py | # -*- coding: utf-8 -*-
#
#
# Author: Nicolas Bessi
# Copyright 2013-2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify | # License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# ... | # it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the | random_line_split |
callbacks.js | //////////////////////////////////////////////////////
// Collection Hooks //
//////////////////////////////////////////////////////
/**
* Generate HTML body from Markdown on user bio insert
*/
Users.after.insert(function (userId, user) {
// run create user async callbacks
Telesc... | escope.callbacks.add("profileCompletedChecks", hasCompletedProfile);
| return Users.hasCompletedProfile(user);
}
Tel | identifier_body |
callbacks.js | //////////////////////////////////////////////////////
// Collection Hooks //
//////////////////////////////////////////////////////
/**
* Generate HTML body from Markdown on user bio insert
*/
Users.after.insert(function (userId, user) {
// run create user async callbacks
Telesc... |
});
/**
* If user.telescope.email has changed, check for existing emails and change user.emails and email hash if needed
*/
if (Meteor.isServer) {
Users.before.update(function (userId, doc, fieldNames, modifier) {
var user = doc;
// if email is being modified, update user.emails too
if (Meteor.isSe... | {
throw new Meteor.Error("illegal $rename operator detected!");
} | conditional_block |
callbacks.js | //////////////////////////////////////////////////////
// Collection Hooks //
//////////////////////////////////////////////////////
/**
* Generate HTML body from Markdown on user bio insert
*/
Users.after.insert(function (userId, user) {
// run create user async callbacks
Telesc... | er, options) {
// ------------------------------ Properties ------------------------------ //
var userProperties = {
profile: options.profile || {},
telescope: {
karma: 0,
isInvited: false,
postCount: 0,
commentCount: 0,
invitedCount: 0,
upvotedPosts: [],
downvotedP... | pUser (us | identifier_name |
callbacks.js | //////////////////////////////////////////////////////
// Collection Hooks //
//////////////////////////////////////////////////////
/**
* Generate HTML body from Markdown on user bio insert
*/
Users.after.insert(function (userId, user) {
// run create user async callbacks
Telesc... | */
Users.before.update(function (userId, doc, fieldNames, modifier) {
// if bio is being modified, update htmlBio too
if (Meteor.isServer && modifier.$set && modifier.$set["telescope.bio"]) {
modifier.$set["telescope.htmlBio"] = Telescope.utils.sanitize(marked(modifier.$set["telescope.bio"]));
}
});
/**
* ... | /**
* Generate HTML body from Markdown when user bio is updated | random_line_split |
GoogleDistances.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib
import time
import datetime
#From PatMap by Jason Young, available on GitHub at github.com/JasYoung314/PatMap
#Function to get distance between 2 points from google maps. By default route is by car, distance is given in miles and time in minutes... |
return time,distance
else:
return result["rows"][0]["elements"][0]["status"],result["rows"][0]["elements"][0]["status"]
else:
return result["status"]
| distance = distance*0.000621371192 | conditional_block |
GoogleDistances.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib
import time
import datetime
#From PatMap by Jason Young, available on GitHub at github.com/JasYoung314/PatMap
#Function to get distance between 2 points from google maps. By default route is by car, distance is given in miles and time in minutes... | try:
result= json.load(urllib.urlopen(url))
except:
return 'ERROR','ERROR'
#Reads the status code and takes the appropriate action
if result["status"] == "OK":
if result["rows"][0]["elements"][0]["status"] == "OK":
time = result["rows"][0]["elements"][0]["duration"]["value"]
distance = result["rows"]... | url = base.decode('utf-8') + urlorigin.decode('utf-8') + urldestination.decode('utf-8') + urlmethod.decode('utf-8') + urlunits.decode('utf-8') + "language=en-EN&sensor=false".decode('utf-8')
#Interprets the json data recieved | random_line_split |
GoogleDistances.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib
import time
import datetime
#From PatMap by Jason Young, available on GitHub at github.com/JasYoung314/PatMap
#Function to get distance between 2 points from google maps. By default route is by car, distance is given in miles and time in minutes... | (Origin = False,Destination = False, Method = "driving",TimeUnits = "Minutes",DistUnits = "Miles"):
#this is the start of a distnace matrix url
base = "https://maps.googleapis.com/maps/api/distancematrix/json?"
#Converts the variables to the required format
urlorigin = "origins=%s&".encode('utf-8') %(Origin)
u... | CalculateDistance | identifier_name |
GoogleDistances.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib
import time
import datetime
#From PatMap by Jason Young, available on GitHub at github.com/JasYoung314/PatMap
#Function to get distance between 2 points from google maps. By default route is by car, distance is given in miles and time in minutes... | if result["status"] == "OK":
if result["rows"][0]["elements"][0]["status"] == "OK":
time = result["rows"][0]["elements"][0]["duration"]["value"]
distance = result["rows"][0]["elements"][0]["distance"]["value"]
if TimeUnits == "Minutes":
time = time/60.0
elif TimeUnits == "Hours":
time = time... | base = "https://maps.googleapis.com/maps/api/distancematrix/json?"
#Converts the variables to the required format
urlorigin = "origins=%s&".encode('utf-8') %(Origin)
urldestination = "destinations=%s&".encode('utf-8') %(Destination)
urlmethod = "mode=%s&" %(Method)
if DistUnits == "Kilometers" or DistUnits == "M... | identifier_body |
buttonload.js | (function () {
// Main module
var app = angular.module('odalic-app');
/** button-load
* Description:
* A button which changes to spinner icon upon a click.
* Serves for visual representation of long operations. Once the executed operation finishes, the button may
* be c... | restrict: 'E',
templateUrl: currentFolder + 'buttonload.html',
transclude: true,
scope: {
action: '=',
disabled: '=',
bind: '=',
buttonClass: '@',
buttonType: '@',
tooltipMsg: ... | random_line_split | |
buttonload.js | (function () {
// Main module
var app = angular.module('odalic-app');
/** button-load
* Description:
* A button which changes to spinner icon upon a click.
* Serves for visual representation of long operations. Once the executed operation finishes, the button may
* be c... |
// Button action
scope.buttonClick = function () {
actionCall();
};
}
}
});
})(); | {
// Submit action
scope.bind.loading = false;
// Define function setLoading
setLoading = function (isLoading) {
scope.bind.loading = isLoading;
};
// Public method - the spe... | conditional_block |
simplify.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 ... | (bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> {
bounds
}
fn trait_is_same_or_supertrait(cx: &DocContext, child: ast::DefId,
trait_: ast::DefId) -> bool {
if child == trait_ {
return true
}
let def = ty::lookup_trait_def(cx.tcx(), child);
let p... | ty_bounds | identifier_name |
simplify.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 ... | clean::ResolvedPath { did, .. } => {
trait_is_same_or_supertrait(cx, did, trait_)
}
_ => false,
}
})
} | };
match poly_trait.trait_ { | random_line_split |
simplify.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 ... |
};
true
})
});
// And finally, let's reassemble everything
let mut clauses = Vec::new();
clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| {
WP::RegionPredicate { lifetime: lt, bounds: bounds }
}));
clauses.extend(params.into_iter().map(|(k, v)| {
... | {
assert!(output.is_none());
*output = Some(rhs.clone());
} | conditional_block |
simplify.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 ... |
fn trait_is_same_or_supertrait(cx: &DocContext, child: ast::DefId,
trait_: ast::DefId) -> bool {
if child == trait_ {
return true
}
let def = ty::lookup_trait_def(cx.tcx(), child);
let predicates = ty::lookup_predicates(cx.tcx(), child);
let generics = (&def.... | {
bounds
} | identifier_body |
control_flow_util.py | != "0")
def EnableControlFlowV2(graph):
"""Returns whether control flow v2 should be used in `graph`."""
# Enable new control flow in FuncGraphs (but not legacy _FuncGraphs).
# TODO(skyewm): do something better than hasattr without messing up imports.
return ENABLE_CONTROL_FLOW_V2 or (
graph.building_f... | (ctxt, stop_ctxt=None):
"""Returns the first ancestor WhileContext of `ctxt`.
Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a
while loop.
Args:
ctxt: ControlFlowContext
stop_ctxt: ControlFlowContext, optional. If provided, the search will end
if it sees stop_ctxt.
Re... | GetContainingWhileContext | identifier_name |
control_flow_util.py | != "0")
def EnableControlFlowV2(graph):
"""Returns whether control flow v2 should be used in `graph`."""
# Enable new control flow in FuncGraphs (but not legacy _FuncGraphs).
# TODO(skyewm): do something better than hasattr without messing up imports.
return ENABLE_CONTROL_FLOW_V2 or (
graph.building_f... |
def GraphOrParentsInXlaContext(graph):
while True:
if InXlaContext(graph): return True
try:
graph = graph.outer_graph
except AttributeError:
return False
def IsInWhileLoop(op):
ctxt = op._get_control_flow_context() # pylint: disable=protected-access
return GetContainingWhileContext(ctx... | def InXlaContext(graph):
ctxt = graph._get_control_flow_context() # pylint: disable=protected-access
return GetContainingXLAContext(ctxt) is not None
| random_line_split |
control_flow_util.py | != "0")
def EnableControlFlowV2(graph):
"""Returns whether control flow v2 should be used in `graph`."""
# Enable new control flow in FuncGraphs (but not legacy _FuncGraphs).
# TODO(skyewm): do something better than hasattr without messing up imports.
return ENABLE_CONTROL_FLOW_V2 or (
graph.building_f... |
def IsContainingContext(ctxt, maybe_containing_ctxt):
"""Returns true if `maybe_containing_ctxt` is or contains `ctxt`."""
while ctxt is not maybe_containing_ctxt:
if ctxt is None: return False
ctxt = ctxt.outer_context
return True
def OpInContext(op, ctxt):
return IsContainingContext(op._get_contr... | """Returns the first ancestor CondContext of `ctxt`.
Returns `ctxt` if `ctxt` is a CondContext, or None if `ctxt` is not in a cond.
Args:
ctxt: ControlFlowContext
Returns:
`ctxt` if `ctxt` is a CondContext, the most nested CondContext containing
`ctxt`, or None if `ctxt` is not in a cond.
"""
w... | identifier_body |
control_flow_util.py | != "0")
def EnableControlFlowV2(graph):
"""Returns whether control flow v2 should be used in `graph`."""
# Enable new control flow in FuncGraphs (but not legacy _FuncGraphs).
# TODO(skyewm): do something better than hasattr without messing up imports.
return ENABLE_CONTROL_FLOW_V2 or (
graph.building_f... |
return False
def IsLoopConstantEnter(op):
"""Return true iff op is a loop invariant."""
return IsLoopEnter(op) and op.get_attr("is_constant")
def GetLoopConstantEnter(value):
"""Return the enter op if we can infer `value` to be a loop invariant."""
id_ops = {"Switch", "RefSwitch", "Identity", "RefIdentit... | ctxt = op._get_control_flow_context() # pylint: disable=protected-access
return ctxt is not None and ctxt.IsWhileContext() and not IsCondMerge(op) | conditional_block |
mailer.js | /*
UTILIZZO DEL MODULO:
var mailer = require('percorso/per/questoFile.js');
mailer.inviaEmail(nome, cognome, emailDestinatario, oggetto, corpoInHtml);
OPPURE
mailer.inviaEmail(opzioniEmail);
dove opzioniEmail è un oggetto JSON formato così:
{
from: '"Nome Visualizzato" <mail@example.com>', // mail del mittente
... | }
L'indirizzo email usato per l'invio nel primo caso è quello del gruppo dei developer (creato ad hoc per il progetto) , ovvero
mail.sitotranquillo@gmail.com
Eventualmente basta cambiare i settaggi nel transporter
Un futuro lavoro potrebbe essere quello di fare in modo che anche il
transporter sia settabile a pia... | text: 'Ciao', // email solo testo
html: '<h3>Ciao</h3>' // email HTML | random_line_split |
mailer.js | /*
UTILIZZO DEL MODULO:
var mailer = require('percorso/per/questoFile.js');
mailer.inviaEmail(nome, cognome, emailDestinatario, oggetto, corpoInHtml);
OPPURE
mailer.inviaEmail(opzioniEmail);
dove opzioniEmail è un oggetto JSON formato così:
{
from: '"Nome Visualizzato" <mail@example.com>', // mail del mittente
... | xports.scriviSettaggi = function(obj) {
// se non ci sono settaggi li creo dummy
if (obj === null)
scriviFileDummy()
else jsonfile.writeFile(file, obj, function(err) {
if (err) return console.log('ERRORE NELLA SCRITTURA DEI SETTAGGI EMAIL');
impostaTransporter();
});
}
exports.i... | // file does not exist
return scriviFileDummy();
}
}
e | conditional_block |
wolframAlphaTrigger.js | var util = require('util');
var wolfram = require('wolfram');
var BaseTrigger = require('./baseTrigger.js').BaseTrigger;
/*
Trigger that responds to messages using Wolfram Alpha.
command = string - a message must start with this + a space before a response will be given
appId = string - the app ID to use when creatin... |
return trigger;
};
// Return true if a message was sent
WolframAlphaTrigger.prototype._respondToFriendMessage = function(userId, message) {
return this._respond(userId, message);
}
// Return true if a message was sent
WolframAlphaTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
ret... | trigger.client = trigger.options.client || wolfram.createClient(trigger.options.appId); | random_line_split |
wolframAlphaTrigger.js | var util = require('util');
var wolfram = require('wolfram');
var BaseTrigger = require('./baseTrigger.js').BaseTrigger;
/*
Trigger that responds to messages using Wolfram Alpha.
command = string - a message must start with this + a space before a response will be given
appId = string - the app ID to use when creatin... | urn null;
}
var _extractResult = function(result) {
if (result.subpods[0] && result.subpods[0].value) {
return result.subpods[0].value;
}
else if (result.subpods[0] && result.subpods[0].image) {
return result.subpods[0].image;
}
return null;
} | text = _extractResult(results[1]);
if (text) {
return text;
}
}
}
ret | conditional_block |
debugQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return true;
}
}
class StartDebugEntry extends Model.QuickOpenEntry {
constructor(private debugService: IDebugService, private contextService: IWorkspaceContextService, private messageService: IMessageService, private launch: ILaunch, private configurationName: string, highlights: Model.IHighlight[] = []) {
su... | this.commandService.executeCommand('debug.addConfiguration', this.launch.uri.toString()).done(undefined, errors.onUnexpectedError); | random_line_split |
debugQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): string {
return this.label;
}
public getDescription(): string {
return this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE ? this.launch.name : '';
}
public getAriaLabel(): string {
return nls.localize('entryAriaLabel', "{0}, debug", this.getLabel());
}
public run(mode: QuickOpen.Mod... | getLabel | identifier_name |
debugQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
configurations.push(entry);
}
});
return TPromise.as(new Model.QuickOpenModel(configurations));
}
public getAutoFocus(input: string): QuickOpen.IAutoFocus {
return {
autoFocusFirstEntry: !!input,
autoFocusIndex: this.autoFocusIndex
};
}
public getEmptyLabel(searchString: string): st... | {
configurations.push(new QuickOpenEntryGroup(entry, undefined, true));
} | conditional_block |
string.js | /**
* @file 字符串相关的函数
* @author mengke01(kekee000@gmail.com)
*/
define(
function (require) {
var string = {
/**
* HTML解码字符串
*
* @param {string} source 源字符串
* @return {string}
*/
decodeHTML: function (source) {
... | return string;
}
);
| return hash;
}
};
| conditional_block |
string.js | /**
* @file 字符串相关的函数
* @author mengke01(kekee000@gmail.com)
*/
define(
function (require) {
var string = {
/**
* HTML解码字符串
*
* @param {string} source 源字符串
* @return {string}
*/
decodeHTML: function (source) {
... | /**
* 获取字符串哈希编码
* @param {string} str 字符串
* @return {number} 哈希值
*/
hashcode: function (str) {
if (!str) {
return 0;
}
var hash = 0;
for (var i = 0, l = str.le... | return new Array(size - str.length + 1).join(ch || '0') + str;
},
| random_line_split |
test_metric.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | import nose
nose.runmodule() | conditional_block | |
test_metric.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
if __name__ == '__main__':
import nose
nose.runmodule()
| metric = mx.metric.create('nll_loss')
pred = mx.nd.array([[0.2, 0.3, 0.5], [0.6, 0.1, 0.3]])
label = mx.nd.array([2, 1])
metric.update([label], [pred])
_, loss = metric.get()
expected_loss = 0.0
expected_loss = -(np.log(pred[0][2].asscalar()) + np.log(pred[1][1].asscalar())) / 2
assert loss ... | identifier_body |
test_metric.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | def check_metric(metric, *args, **kwargs):
metric = mx.metric.create(metric, *args, **kwargs)
str_metric = json.dumps(metric.get_config())
metric2 = mx.metric.create(str_metric)
assert metric.get_config() == metric2.get_config()
def test_metrics():
check_metric('acc', axis=0)
check_metric('f1... | import json
| random_line_split |
test_metric.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ():
check_metric('acc', axis=0)
check_metric('f1')
check_metric('perplexity', -1)
check_metric('pearsonr')
check_metric('nll_loss')
composite = mx.metric.create(['acc', 'f1'])
check_metric(composite)
def test_nll_loss():
metric = mx.metric.create('nll_loss')
pred = mx.nd.array([[0.2... | test_metrics | identifier_name |
tests_forms.py | """Tests for forms in eCommerce app."""
from django.test import TestCase
from ecommerce.forms import OrderForm
required_fields = {
'phone': '123456789',
'email': 'valid@email.ru',
}
invalid_form_email = {
'email': 'clearly!not_@_email',
'phone': '123456789'
}
no_phone = {'email': 'sss@sss.sss'}
cla... | form = OrderForm(data=required_fields)
self.assertTrue(form.is_valid())
def test_from_validation_on_email_field(self):
"""Form should validate user's email if it is filled."""
form = OrderForm(data=invalid_form_email)
self.assertFalse(form.is_valid()) | """Form is valid, if there all required fields are filled.""" | random_line_split |
tests_forms.py | """Tests for forms in eCommerce app."""
from django.test import TestCase
from ecommerce.forms import OrderForm
required_fields = {
'phone': '123456789',
'email': 'valid@email.ru',
}
invalid_form_email = {
'email': 'clearly!not_@_email',
'phone': '123456789'
}
no_phone = {'email': 'sss@sss.sss'}
cla... |
def test_valid_form(self):
"""Form is valid, if there all required fields are filled."""
form = OrderForm(data=required_fields)
self.assertTrue(form.is_valid())
def test_from_validation_on_email_field(self):
"""Form should validate user's email if it is filled."""
form... | """Form is still not valid, if there are some required fields left unfilled."""
form = OrderForm(data=no_phone)
self.assertFalse(form.is_valid()) | identifier_body |
tests_forms.py | """Tests for forms in eCommerce app."""
from django.test import TestCase
from ecommerce.forms import OrderForm
required_fields = {
'phone': '123456789',
'email': 'valid@email.ru',
}
invalid_form_email = {
'email': 'clearly!not_@_email',
'phone': '123456789'
}
no_phone = {'email': 'sss@sss.sss'}
cla... | (self):
"""Form is valid, if there all required fields are filled."""
form = OrderForm(data=required_fields)
self.assertTrue(form.is_valid())
def test_from_validation_on_email_field(self):
"""Form should validate user's email if it is filled."""
form = OrderForm(data=invalid... | test_valid_form | identifier_name |
br.js | //! moment.js locale configuration
//! locale : breton (br)
//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou
import moment from '../moment';
function relativeTimeWithMutation(number, withoutSuffix, key) {
var format = {
'mm': 'munutenn',
'MM': 'miz',
'dd': 'devezh'
... |
return text;
}
function softMutation(text) {
var mutationTable = {
'm': 'v',
'b': 'v',
'd': 'z'
};
if (mutationTable[text.charAt(0)] === undefined) {
return text;
}
return mutationTable[text.charAt(0)] + text.substring(1);
}
export default moment.defineLocale('b... | {
return softMutation(text);
} | conditional_block |
br.js | //! moment.js locale configuration
//! locale : breton (br)
//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou
import moment from '../moment';
function relativeTimeWithMutation(number, withoutSuffix, key) {
var format = {
'mm': 'munutenn',
'MM': 'miz',
'dd': 'devezh'
... |
function lastNumber(number) {
if (number > 9) {
return lastNumber(number % 10);
}
return number;
}
function mutation(text, number) {
if (number === 2) {
return softMutation(text);
}
return text;
}
function softMutation(text) {
var mutationTable = {
'm': 'v',
... | {
switch (lastNumber(number)) {
case 1:
case 3:
case 4:
case 5:
case 9:
return number + ' bloaz';
default:
return number + ' vloaz';
}
} | identifier_body |
br.js | //! moment.js locale configuration
//! locale : breton (br)
//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou
import moment from '../moment';
function relativeTimeWithMutation(number, withoutSuffix, key) {
var format = {
'mm': 'munutenn',
'MM': 'miz',
'dd': 'devezh'
... | 'd': 'z'
};
if (mutationTable[text.charAt(0)] === undefined) {
return text;
}
return mutationTable[text.charAt(0)] + text.substring(1);
}
export default moment.defineLocale('br', {
months : 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'),
... | random_line_split | |
br.js | //! moment.js locale configuration
//! locale : breton (br)
//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou
import moment from '../moment';
function relativeTimeWithMutation(number, withoutSuffix, key) {
var format = {
'mm': 'munutenn',
'MM': 'miz',
'dd': 'devezh'
... | (text) {
var mutationTable = {
'm': 'v',
'b': 'v',
'd': 'z'
};
if (mutationTable[text.charAt(0)] === undefined) {
return text;
}
return mutationTable[text.charAt(0)] + text.substring(1);
}
export default moment.defineLocale('br', {
months : 'Genver_C\'hwevrer_Meu... | softMutation | identifier_name |
course-add.component.spec.ts | /* tslint:disable:no-unused-variable */
import { TestBed, inject, async } from "@angular/core/testing";
import { Router } from "@angular/router";
import { CourseAddComponent } from "./course-add.component";
import { TestModule } from "../../../test.module";
import { StubCourseService } from "../course.service.stub";
... |
component.createCourse({
date: "2017-01-05",
organiser: "99c1d6dc-3f05-40e9-b842-dbcabc99f5ff",
numSpaces: StubCourseService.createDontCompleteNumSpaces
});
expect(component.showThrobber).toBeTruthy();
StubCourseService.createDontCompleteSubject.next(
new Cours... | });
it("should show a throbber while the request is running", async(
inject([CourseAddComponent], (component: CourseAddComponent) => {
expect(component.showThrobber).toBeFalsy(); | random_line_split |
course-add.component.spec.ts | /* tslint:disable:no-unused-variable */
import { TestBed, inject, async } from "@angular/core/testing";
import { Router } from "@angular/router";
import { CourseAddComponent } from "./course-add.component";
import { TestModule } from "../../../test.module";
import { StubCourseService } from "../course.service.stub";
... |
}
},
{ provide: CourseService, useValue: new StubCourseService([]) },
CourseAddComponent
]
});
});
it("should show a throbber while the request is running", async(
inject([CourseAddComponent], (component: CourseAddComponent) => {
expect(component.showThrobber)... | {} | identifier_body |
course-add.component.spec.ts | /* tslint:disable:no-unused-variable */
import { TestBed, inject, async } from "@angular/core/testing";
import { Router } from "@angular/router";
import { CourseAddComponent } from "./course-add.component";
import { TestModule } from "../../../test.module";
import { StubCourseService } from "../course.service.stub";
... | (args) {}
}
},
{ provide: CourseService, useValue: new StubCourseService([]) },
CourseAddComponent
]
});
});
it("should show a throbber while the request is running", async(
inject([CourseAddComponent], (component: CourseAddComponent) => {
expect(component.show... | navigate | identifier_name |
python_memcached_tests.py | from functools import partial
from django.test import TestCase
import mock
import memcache
import opbeat
from tests.contrib.django.django_tests import get_client
class InstrumentMemcachedTest(TestCase):
def setUp(self):
self.client = get_client()
opbeat.instrumentation.control.instrument(self.cli... | traces = [sig_dict[k] for k in expected_signatures]
self.assertEqual(traces[0]['signature'], 'transaction')
self.assertEqual(traces[0]['kind'], 'transaction')
self.assertEqual(traces[0]['transaction'], 'test')
self.assertEqual(traces[1]['signature'], 'test_memcached')
s... | should_collect.return_value = False
self.client.begin_transaction()
with self.client.capture_trace("test_memcached", "test"):
conn = memcache.Client(['127.0.0.1:11211'], debug=0)
conn.set("mykey", "a")
assert "a" == conn.get("mykey")
assert {"mykey": "a"} ... | identifier_body |
python_memcached_tests.py | from functools import partial
from django.test import TestCase
import mock
import memcache
import opbeat
from tests.contrib.django.django_tests import get_client
class | (TestCase):
def setUp(self):
self.client = get_client()
opbeat.instrumentation.control.instrument(self.client)
@mock.patch("opbeat.traces.RequestsStore.should_collect")
def test_memcached(self, should_collect):
should_collect.return_value = False
self.client.begin_transactio... | InstrumentMemcachedTest | identifier_name |
python_memcached_tests.py | from functools import partial
from django.test import TestCase
import mock
import memcache
import opbeat
from tests.contrib.django.django_tests import get_client
class InstrumentMemcachedTest(TestCase):
def setUp(self):
self.client = get_client()
opbeat.instrumentation.control.instrument(self.cli... | self.assertEqual(traces[2]['kind'], 'cache.memcached')
self.assertEqual(traces[2]['transaction'], 'test')
self.assertEqual(len(traces), 5) | random_line_split | |
problem_14.rs | fn collatz(num: u32) -> u32 {
if num == 1 {
return num;
}
if num % 2 == 0 {
num / 2
} else {
(num * 3) + 1
}
}
fn main() {
let mut max_terms: u32 = 0;
let mut max_terms_number: u32 = 0;
for i in 2..1_000_001 {
let mut current_terms: u32 = 0;
let... | current_terms += 1;
if current_terms > max_terms {
max_terms = current_terms;
max_terms_number = i;
}
}
// println!("collatz({}) -> {}", i, current_terms);
}
println!("Result: {}", max_terms_number);
} | random_line_split | |
problem_14.rs | fn | (num: u32) -> u32 {
if num == 1 {
return num;
}
if num % 2 == 0 {
num / 2
} else {
(num * 3) + 1
}
}
fn main() {
let mut max_terms: u32 = 0;
let mut max_terms_number: u32 = 0;
for i in 2..1_000_001 {
let mut current_terms: u32 = 0;
let mut resul... | collatz | identifier_name |
problem_14.rs | fn collatz(num: u32) -> u32 {
if num == 1 |
if num % 2 == 0 {
num / 2
} else {
(num * 3) + 1
}
}
fn main() {
let mut max_terms: u32 = 0;
let mut max_terms_number: u32 = 0;
for i in 2..1_000_001 {
let mut current_terms: u32 = 0;
let mut result: u32 = i;
while result != 1 {
result = co... | {
return num;
} | conditional_block |
problem_14.rs | fn collatz(num: u32) -> u32 {
if num == 1 {
return num;
}
if num % 2 == 0 {
num / 2
} else {
(num * 3) + 1
}
}
fn main() | {
let mut max_terms: u32 = 0;
let mut max_terms_number: u32 = 0;
for i in 2..1_000_001 {
let mut current_terms: u32 = 0;
let mut result: u32 = i;
while result != 1 {
result = collatz(result);
current_terms += 1;
if current_terms > max_terms {
... | identifier_body | |
test_prometheus_transformer.py | # Copyright 2018 - Nokia
#
# 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 in writing, sof... | event_on_host = self._generate_event_on_host(host1)
event_on_instance = self._generate_event_on_instance(host1,
instance_id)
self.assertIsNotNone(event_on_host)
self.assertIsNotNone(event_on_instance)
# Test action
... | OPTS = [
cfg.StrOpt(DSOpts.UPDATE_METHOD,
default=UpdateMethod.PUSH),
]
def setUp(self):
super(PrometheusTransformerTest, self).setUp()
self.transformers = {}
self.conf_reregister_opts(self.OPTS, group=PROMETHEUS_DATASOURCE)
self.transformers[NOVA_HOST... | identifier_body |
test_prometheus_transformer.py | # Copyright 2018 - Nokia
#
# 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 in writing, sof... | (self, vertex, event):
self._validate_alarm_vertex_props(
vertex, get_label(event, PLabels.ALERT_NAME),
PROMETHEUS_DATASOURCE, event[DSProps.SAMPLE_DATE])
def _generate_event_on_host(self, hostname):
# fake query result to be used by the transformer for determining
#... | _validate_vertex_props | identifier_name |
test_prometheus_transformer.py | # Copyright 2018 - Nokia
#
# 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 in writing, sof... | def _generate_event_on_instance(self, hostname, instance_name):
# fake query result to be used by the transformer for determining
# the neighbor
query_result = [{VProps.VITRAGE_TYPE: NOVA_INSTANCE_DATASOURCE,
VProps.ID: instance_name}]
labels = {PLabels.SEVER... | return self._generate_event(update_vals)
| random_line_split |
mailman.py | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from livesettings imp... | """Remove a Satchmo contact from a Mailman mailing list
Parameters:
- `contact`: A Satchmo contact
- `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME
- `userack`: True or False, whether to notify the user, defaulting to the list default
... | mm.Unlock()
def mailman_remove(contact, listname=None, userack=None, admin_notify=None): | random_line_split |
mailman.py | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from livesettings imp... |
else:
result = _("Already removed %(email)s.")
else:
if not sub:
sub, created = Subscription.objects.get_or_create(email=email)
sub.subscribed = subscribe
sub.save()
if subscribe:
mailman_add(contact)
result =... | if attributesChanged:
result = _("Updated subscription for %(email)s.")
else:
result = _("Already subscribed %(email)s.") | conditional_block |
mailman.py | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from livesettings imp... | if subscribe:
if attributesChanged:
result = _("Updated subscription for %(email)s.")
else:
result = _("Already subscribed %(email)s.")
else:
result = _("Already removed %(email)s.")
else:
if not sub:
... | email = contact.email
current = Subscription.email_is_subscribed(email)
attributesChanged = False
sub = None
if attributes:
sub, created = Subscription.objects.get_or_create(email=email)
if created:
attributesChanged = True
else:
oldAttr = [(a.name,a.... | identifier_body |
mailman.py | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from livesettings imp... | : pass
def is_subscribed(contact):
return Subscription.email_is_subscribed(contact.email)
def update_contact(contact, subscribe, attributes={}):
email = contact.email
current = Subscription.email_is_subscribed(email)
attributesChanged = False
sub = None
if attributes:
sub, created... | UserDesc | identifier_name |
client.rs | hackerbots.net>
*
* 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 in writing, softw... | (&mut self, token: Option<&str>) -> AsyncPoll {
let mut args = HashMap::new();
if let Some(next) = token {
args.insert("since", next);
args.insert("timeout", "5000");
} else {
args.insert("full_state", "true");
}
let url = self.url(ApiVersion::... | sync | identifier_name |
client.rs | *
* 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 in writing, software
* distribut... | * Copyright 2015-2016 Torrie Fischer <tdfischer@hackerbots.net> | random_line_split | |
client.rs | hackerbots.net>
*
* 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 in writing, softw... |
fn url(&self, version: ApiVersion, endpoint: &str, args: &HashMap<&str, &str>) -> hyper::Url {
let mut ret = self.baseurl.clone();
ret.path_mut().unwrap().append(&mut vec!["client".to_string()]);
ret.path_mut().unwrap().append(&mut match version {
ApiVersion::R0 =>
... | {
let mut d = BTreeMap::new();
d.insert("user".to_string(), Json::String(username.to_string()));
d.insert("password".to_string(), Json::String(password.to_string()));
d.insert("type".to_string(), Json::String("m.login.password".to_string()));
debug!("Logging in to matrix");
... | identifier_body |
hide-own-stars.tsx | import select from 'select-dom';
import elementReady from 'element-ready';
import features from '../libs/features';
import {getUsername} from '../libs/utils';
const observer = new MutationObserver(([{addedNodes}]) => {
// Remove events from dashboard
for (const item of select.all('#dashboard .news .watch_started, #d... | (): Promise<void> {
observer.observe((await elementReady('#dashboard .news'))!, {childList: true});
}
features.add({
id: __featureName__,
description: 'Hides "starred" events for your own repos on the newsfeed.',
screenshot: false,
include: [
features.isDashboard
],
init
});
| init | identifier_name |
hide-own-stars.tsx | import select from 'select-dom';
import elementReady from 'element-ready';
import features from '../libs/features';
import {getUsername} from '../libs/utils';
const observer = new MutationObserver(([{addedNodes}]) => {
// Remove events from dashboard
for (const item of select.all('#dashboard .news .watch_started, #d... |
features.add({
id: __featureName__,
description: 'Hides "starred" events for your own repos on the newsfeed.',
screenshot: false,
include: [
features.isDashboard
],
init
});
| {
observer.observe((await elementReady('#dashboard .news'))!, {childList: true});
} | identifier_body |
hide-own-stars.tsx | import select from 'select-dom';
import elementReady from 'element-ready';
import features from '../libs/features';
import {getUsername} from '../libs/utils';
const observer = new MutationObserver(([{addedNodes}]) => {
// Remove events from dashboard
for (const item of select.all('#dashboard .news .watch_started, #d... |
}
// Observe the new ajaxed-in containers
for (const node of addedNodes) {
if (node instanceof HTMLDivElement) {
observer.observe(node, {childList: true});
}
}
});
async function init(): Promise<void> {
observer.observe((await elementReady('#dashboard .news'))!, {childList: true});
}
features.add({
id:... | {
item.style.display = 'none';
} | conditional_block |
hide-own-stars.tsx | import select from 'select-dom';
import elementReady from 'element-ready';
import features from '../libs/features';
import {getUsername} from '../libs/utils';
const observer = new MutationObserver(([{addedNodes}]) => {
// Remove events from dashboard
for (const item of select.all('#dashboard .news .watch_started, #d... | for (const node of addedNodes) {
if (node instanceof HTMLDivElement) {
observer.observe(node, {childList: true});
}
}
});
async function init(): Promise<void> {
observer.observe((await elementReady('#dashboard .news'))!, {childList: true});
}
features.add({
id: __featureName__,
description: 'Hides "starre... | }
}
// Observe the new ajaxed-in containers | random_line_split |
list-page.component.spec.ts | // /* tslint:disable:no-unused-variable */
// import { async, ComponentFixture, TestBed } from '@angular/core/testing';
// import { RouterTestingModule } from '@angular/router/testing';
// import { MockBackend } from '@angular/http/testing';
// import { RequestOptions, BaseRequestOptions, Http } from '@angular/http';
/... | // import { ToolbarModule } from 'patternfly-ng';
// import { StoreModule } from '../../store/store.module';
// import { SyndesisCommonModule } from '../../common/common.module';
// import { PatternflyUIModule } from '../../common/ui-patternfly/ui-patternfly.module';
// import { ConnectionsListPage } from './list-page... | random_line_split | |
gather_moves.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | assignment_id,
assignment_span,
assignee_id,
mode);
}
// (keep in sync with move_error::report_cannot_move_out_of )
fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
... | mode: euv::MutateMode) {
move_data.add_assignment(bccx.tcx,
assignee_loan_path, | random_line_split |
gather_moves.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn gather_match_variant<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
move_data: &MoveData<'tcx>,
_move_error_collector: &MoveErrorCollector<'tcx>,
move_pat: &ast::Pat,
... | {
let kind = match move_reason {
euv::DirectRefMove | euv::PatBindingMove => MoveExpr,
euv::CaptureMove => Captured
};
let move_info = GatherMoveInfo {
id: move_expr_id,
kind: kind,
cmt: cmt,
span_path_opt: None,
};
gather_move(bccx, move_data, move_er... | identifier_body |
gather_moves.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
move_data: &MoveData<'tcx>,
move_error_collector: &MoveErrorCollector<'tcx>,
move_pat: &ast::Pat,
cmt: mc::cmt<'tcx>) {
le... | gather_move_from_pat | identifier_name |
SSAOPass.d.ts | import {
Camera,
Color,
DataTexture,
Material,
MeshNormalMaterial,
Scene,
ShaderMaterial,
Vector3,
WebGLRenderer,
WebGLRenderTarget
} from '../../../src/Three';
import { Pass } from './Pass';
export class SSAOPass extends Pass {
constructor( scene: Scene, camera: Camera, width?: number, height?: number );... | Blur: number;
Beauty: number;
Depth: number;
Normal: number;
};
dipose(): void;
generateSampleKernel(): Vector3[];
generateRandomKernelRotations(): void;
renderPass( renderer: WebGLRenderer, passMaterial: Material, renderTarget: WebGLRenderTarget, clearColor?: Color | string | number, clearAlpha?: number ... |
static OUTPUT: {
Default: number;
SSAO: number; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.