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 |
|---|---|---|---|---|
sync_batchnorm.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
return model
@classmethod
def get_execution_order(cls):
eo = super().get_execution_order()
eo["setup_experiment"].insert(0, "Sync Batchnorm begin")
eo["setup_experiment"].append("Sync Batchnorm end")
return eo
| model = nn.modules.SyncBatchNorm.convert_sync_batchnorm(module=model) | conditional_block |
sync_batchnorm.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | eo = super().get_execution_order()
eo["setup_experiment"].insert(0, "Sync Batchnorm begin")
eo["setup_experiment"].append("Sync Batchnorm end")
return eo
| """
This mixin converts the BatchNorm modules to SyncBatchNorm modules when utilizing
distributed training on GPUs.
Example config:
config=dict(
use_sync_batchnorm=True
)
"""
def create_model(self, config, device):
model = super().create_model(config, device)
... | identifier_body |
sync_batchnorm.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | use_sync_batchnorm = config.get("use_sync_batchnorm", True)
distributed = config.get("distributed", False)
if use_sync_batchnorm and distributed and next(model.parameters()).is_cuda:
# Convert batch norm to sync batch norms
model = nn.modules.SyncBatchNorm.convert_sync_ba... | use_sync_batchnorm=True
)
"""
def create_model(self, config, device):
model = super().create_model(config, device) | random_line_split |
sync_batchnorm.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | (cls):
eo = super().get_execution_order()
eo["setup_experiment"].insert(0, "Sync Batchnorm begin")
eo["setup_experiment"].append("Sync Batchnorm end")
return eo
| get_execution_order | identifier_name |
cs2quiz2.py | #PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) "apple" == "apple"
#b) 1 != 1
#c) 5 >= 6
#2) What does 'return' do?
#'Return' returns a value. It can be used after an calculation is
#executed. When the python interpreter solves a math problem, you can
#"return" the value back into the interpreter... |
def main():
print "Please type in three different numbers." #simple directions givens
num1 = float(raw_input("Number 1: ")) #raw input of user's desired numbers.
num2 = float(raw_input("Number 2: "))
num3 = float(raw_input("Number 3: "))
output(num1, num2, num3)
main() #main function to execute m... | if num1 > num2 and num1 > num3:
print """
The greatest number is {}
""".format(num1)
elif num2 > num1 and num2 > num3:
print """
The greatest number is {}
""".format(num2)
elif num3 > num1 and num3 > num2:
print """
The greatest number is {}
""".format(num3)
elif num1 == num2 == n... | identifier_body |
cs2quiz2.py | #PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) "apple" == "apple"
#b) 1 != 1
#c) 5 >= 6
#2) What does 'return' do?
#'Return' returns a value. It can be used after an calculation is
#executed. When the python interpreter solves a math problem, you can
#"return" the value back into the interpreter... | ():
print "Please type in three different numbers." #simple directions givens
num1 = float(raw_input("Number 1: ")) #raw input of user's desired numbers.
num2 = float(raw_input("Number 2: "))
num3 = float(raw_input("Number 3: "))
output(num1, num2, num3)
main() #main function to execute my script
... | main | identifier_name |
cs2quiz2.py | #PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) "apple" == "apple"
#b) 1 != 1
#c) 5 >= 6
#2) What does 'return' do?
#'Return' returns a value. It can be used after an calculation is
#executed. When the python interpreter solves a math problem, you can
#"return" the value back into the interpreter... |
def main():
print "Please type in three different numbers." #simple directions givens
num1 = float(raw_input("Number 1: ")) #raw input of user's desired numbers.
num2 = float(raw_input("Number 2: "))
num3 = float(raw_input("Number 3: "))
output(num1, num2, num3)
main() #main function to execute m... | print """
You did not follow directions.
""" | conditional_block |
cs2quiz2.py | #PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) "apple" == "apple"
#b) 1 != 1
#c) 5 >= 6
#2) What does 'return' do?
#'Return' returns a value. It can be used after an calculation is
#executed. When the python interpreter solves a math problem, you can
#"return" the value back into the interpreter... | #3) What are 2 ways indentation is important in python code?
#a) Indentation is important because it tells specific lines of code where it belongs in a certain function.
#b) And the correct indentation levels tells python when a specific function ends.
#PART 2: Reading
#Type the values for 9 of the 12 of the variables... | random_line_split | |
__init__.py | # cloudscope.simulation.workload
# Defines simulation processes that generate "work", e.g. accesses.
#
# Author: Benjamin Bengfort <bengfort@cs.umd.edu>
# Created: Wed Jul 27 10:21:57 2016 -0400
#
# Copyright (C) 2016 University of Maryland
# For license information, see LICENSE.txt
#
# ID: __init__.py [b9507c0] ben... |
# Otherwise construct a conflict generation workload.
users = kwargs.pop('users', settings.simulation.users)
workload = ConflictWorkloadAllocation(sim, **kwargs)
workload.allocate_many(users)
return workload
| return TracesWorkload(trace, sim) | conditional_block |
__init__.py | # cloudscope.simulation.workload
# Defines simulation processes that generate "work", e.g. accesses.
#
# Author: Benjamin Bengfort <bengfort@cs.umd.edu>
# Created: Wed Jul 27 10:21:57 2016 -0400
#
# Copyright (C) 2016 University of Maryland
# For license information, see LICENSE.txt
#
# ID: __init__.py [b9507c0] ben... | - Create a conflict/topology allocating workload for n users.
See the workload allocation objects for more information.
"""
# Create a manual trace if it's passed in
trace = kwargs.pop('trace', None)
if trace:
if settings.simulation.synchronous_access:
raise NotImplement... | - Load the accesses from a trace file | random_line_split |
__init__.py | # cloudscope.simulation.workload
# Defines simulation processes that generate "work", e.g. accesses.
#
# Author: Benjamin Bengfort <bengfort@cs.umd.edu>
# Created: Wed Jul 27 10:21:57 2016 -0400
#
# Copyright (C) 2016 University of Maryland
# For license information, see LICENSE.txt
#
# ID: __init__.py [b9507c0] ben... | (sim, **kwargs):
"""
Returns the correct workload for the simulation. There are currently two
possible workloads to return depending on the kwargs:
- Load the accesses from a trace file
- Create a conflict/topology allocating workload for n users.
See the workload allocation objects fo... | create | identifier_name |
__init__.py | # cloudscope.simulation.workload
# Defines simulation processes that generate "work", e.g. accesses.
#
# Author: Benjamin Bengfort <bengfort@cs.umd.edu>
# Created: Wed Jul 27 10:21:57 2016 -0400
#
# Copyright (C) 2016 University of Maryland
# For license information, see LICENSE.txt
#
# ID: __init__.py [b9507c0] ben... | users = kwargs.pop('users', settings.simulation.users)
workload = ConflictWorkloadAllocation(sim, **kwargs)
workload.allocate_many(users)
return workload
| """
Returns the correct workload for the simulation. There are currently two
possible workloads to return depending on the kwargs:
- Load the accesses from a trace file
- Create a conflict/topology allocating workload for n users.
See the workload allocation objects for more information.
... | identifier_body |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
... | // 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, | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | () {
do glfw::start {
do glfw::Monitor::get_primary().map |monitor| {
println!("{:s}:", monitor.get_name());
println!(" {:s}\n", monitor.get_video_mode().unwrap().to_str());
};
println("Available monitors\n\
------------------");
... | main | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
fn main() {
do glfw::start {
do glfw::Monitor::get_primary().map |monitor| {
println!("{:s}:", monitor.get_name());
println!(" {:s}\n", monitor.get_video_mode().unwrap().to_str());
};
println("Available monitors\n\
------------------... | {
std::rt::start_on_main_thread(argc, argv, main)
} | identifier_body |
arrow_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* 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... | () {
class Base {
f() {
assertTrue(this instanceof Sub);
}
}
class Sub extends Base {
f() {
(() => super.f())();
}
}
(new Sub()).f();
}
| testBug1907 | identifier_name |
arrow_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* 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... |
f(var_args) {
forEach(arguments, x => this.log(arguments[0]));
if (arguments.length > 1) {
forEach(arguments, x => this.log(arguments[1]));
}
}
}
var c = new C();
c.f(3, 4);
assertArrayEquals([3, 3, 4, 4], log);
}
function testBug1907() {
class Base {
f() {
asse... | {
log.push(x);
} | identifier_body |
arrow_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* 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... | var a = [1, 2, 3];
function map(arr, f) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(f(arr[i]));
}
return result;
}
assertArrayEquals([2, 3, 4], map(a, (x) => x + 1));
}
function testTemplate() {
var f = x => `x is ${x}`;
assertEquals('x is foo', f('foo'));
}
... | function testBasic() { | random_line_split |
arrow_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable... |
}
function testTwoArrowFunctionsInSameFunctionScope() {
var count = 0;
forEach([1, 2], x => count += x);
forEach([3, 4], x => count += x);
assertEquals(10, count);
}
function testTwoArrowFunctionsInSameBlockScope() {
while (true) {
var count = 0;
forEach([1, 2], x => count += x);
forEach([3, 4]... | {
f(arr[i]);
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of the osmxapi Python module.
#
# osmxapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | #.
#.
anydict[e] = anylist
#.
return anydict
#.
#.
if __name__ == '__main__':
from xapiquery import XapiQuery
xapi = OsmXapi(debug = True)
uniparken = XapiQuery (lats=56.1618032,
lonw=10.1891327,
... | anylist.append(dom.parseRelation(a)) | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of the osmxapi Python module.
#
# osmxapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | anydict[e] = anylist
#.
return anydict
#.
#.
if __name__ == '__main__':
from xapiquery import XapiQuery
xapi = OsmXapi(debug = True)
uniparken = XapiQuery (lats=56.1618032,
lonw=10.1891327,
latn=56.1719343,
... | Return any data for query"""
uri = self.base+"?*"+repr(query)
data = self.http.get(uri)
if raw: return data
data = xml.dom.minidom.parseString(data)
anydict = {}
for e in "node", "way", "relation":
d = data.getElementsByTagName("osm")[0].getElementsByTagName(e... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of the osmxapi Python module.
#
# osmxapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | #.
uri = self.base+"?node"+repr(query)
data = self.http.get(uri)
if raw: return data
if not data: return data
data = xml.dom.minidom.parseString(data)
data = data.getElementsByTagName("osm")[0].getElementsByTagName("node")
nodelist = []
for n in data... | urn None
| conditional_block |
__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of the osmxapi Python module.
#
# osmxapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | lf, query=None, raw=None):
"""Return relation data for query"""
uri = self.base+"?relation"+repr(query)
data = self.http.get(uri)
if raw: return data
data = xml.dom.minidom.parseString(data)
data = data.getElementsByTagName("osm")[0].getElementsByTagName("relation")
... | ationGet(se | identifier_name |
StateReviewTrendsPOC.py | __author__ = 'Akshay'
"""
File contains code to Mine reviews and stars from a state reviews.
This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map.
For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for e... |
if state not in state_business:
state_business[state] = 0
if len(state_business.keys()) == 50:
break
if category in categories:
print state
business_id = str(temp["business_id"])
city = str(temp["city... | continue | conditional_block |
StateReviewTrendsPOC.py | __author__ = 'Akshay'
"""
File contains code to Mine reviews and stars from a state reviews.
This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map.
For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for e... | state_3_star_dict[state] = 0
if state not in state_2_star_dict:
state_2_star_dict[state] = 0
if state not in state_1_star_dict:
state_1_star_dict[state] = 0
if star_rating == 5:
state_5_star_dict[state] += 1
... | count = 0
with open('Data\state_stars_date_business.txt') as fp:
for line in fp.readlines():
count += 1
tup = (line.split("\t")[0], line.split("\t")[1], line.split("\t")[2], line.split("\t")[3],
line.split("\t")[4], line.split("\t")[5])
state = tup[1]
... | identifier_body |
StateReviewTrendsPOC.py | __author__ = 'Akshay'
"""
File contains code to Mine reviews and stars from a state reviews.
This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map.
For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for e... | ():
count = 0
with open('Data\state_stars_date_business.txt') as fp:
for line in fp.readlines():
count += 1
tup = (line.split("\t")[0], line.split("\t")[1], line.split("\t")[2], line.split("\t")[3],
line.split("\t")[4], line.split("\t")[5])
state =... | state_review_trends | identifier_name |
StateReviewTrendsPOC.py | __author__ = 'Akshay'
"""
File contains code to Mine reviews and stars from a state reviews.
This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map.
For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for e... | if state not in state_3_star_dict:
state_3_star_dict[state] = 0
if state not in state_2_star_dict:
state_2_star_dict[state] = 0
if state not in state_1_star_dict:
state_1_star_dict[state] = 0
if star_rating == 5:
... | state_5_star_dict[state] = 0
if state not in state_4_star_dict:
state_4_star_dict[state] = 0
| random_line_split |
byte_buf.rs | //! Helper types for tests
use serde::de::{self, Deserialize, Deserializer, Error};
use std::fmt;
/// Wrapper around `Vec<u8>` that deserialized using `deserialize_byte_buf`
/// instead of vector's generic `deserialize_seq`
#[derive(Debug, PartialEq)]
pub struct ByteBuf(pub Vec<u8>);
impl<'de> Deserialize<'de> for B... | where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = Bytes<'de>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("borrowed bytes")
}
fn visit_bor... | impl<'de> Deserialize<'de> for Bytes<'de> {
fn deserialize<D>(d: D) -> Result<Self, D::Error> | random_line_split |
byte_buf.rs | //! Helper types for tests
use serde::de::{self, Deserialize, Deserializer, Error};
use std::fmt;
/// Wrapper around `Vec<u8>` that deserialized using `deserialize_byte_buf`
/// instead of vector's generic `deserialize_seq`
#[derive(Debug, PartialEq)]
pub struct ByteBuf(pub Vec<u8>);
impl<'de> Deserialize<'de> for B... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("borrowed bytes")
}
fn visit_borrowed_bytes<E: Error>(self, v: &'de [u8]) -> Result<Self::Value, E> {
Ok(Bytes(v))
}
}
Ok(d.deserialize_bytes(Visitor)?)
}
}
| expecting | identifier_name |
effects.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Animated types for CSS values related to effects.
use crate::values::animated::color::Color;
use crate::valu... |
/// An animated value for a single `filter`.
#[cfg(feature = "gecko")]
pub type Filter = GenericFilter<Angle, Number, Length, SimpleShadow, ComputedUrl>;
/// An animated value for a single `filter`.
#[cfg(not(feature = "gecko"))]
pub type Filter = GenericFilter<Angle, Number, Length, Impossible, Impossible>;
/// An ... | use crate::values::Impossible;
/// An animated value for a single `box-shadow`.
pub type BoxShadow = GenericBoxShadow<Color, Length, Length, Length>; | random_line_split |
traversal.rs | where N: LayoutNode + TNode,
N::ConcreteElement: TElement
{
type SharedContext = SharedLayoutContext;
#[allow(unsafe_code)]
fn new<'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self {
// FIXME(bholley): This transmutation from &'a to &'lc is very unfortunate, but I haven't
... | if self.should_process() { | random_line_split | |
traversal.rs | script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutNode};
use servo_config::opts;
use std::mem;
use style::atomic_refcell::AtomicRefCell;
use style::context::{LocalStyleContext, SharedStyleContext, StyleContext};
use style::data::ElementData;
use style::dom::{TElement, TNode};
use style::selector_pa... | <'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self {
// FIXME(bholley): This transmutation from &'a to &'lc is very unfortunate, but I haven't
// found a way to avoid it despite spending several days on it (and consulting Manishearth,
// brson, and nmatsakis).
//
// ... | new | identifier_name |
traversal.rs | _layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutNode};
use servo_config::opts;
use std::mem;
use style::atomic_refcell::AtomicRefCell;
use style::context::{LocalStyleContext, SharedStyleContext, StyleContext};
use style::data::ElementData;
use style::dom::{TElement, TNode};
use style::selector_parser::R... |
}
/// The bubble-inline-sizes traversal, the first part of layout computation. This computes
/// preferred and intrinsic inline-sizes and bubbles them up the tree.
pub struct BubbleISizes<'a> {
pub layout_context: &'a LayoutContext<'a>,
}
impl<'a> PostorderFlowTraversal for BubbleISizes<'a> {
#[inline]
f... | {
el.mutate_data().unwrap().persist();
unsafe { el.unset_dirty_descendants(); }
remove_from_bloom_filter(context, root, el);
} | conditional_block |
libK0_Password.js | var vgPwd = {
aleph_t : '',
ok : 0,
filas : new Array(),
laFila :'',
cabecera : '',
usuario : '',
users : '',
proys : '',
roles : '',
mkUsrPwd : 't4UserPwd.cgi',
cambiaPwd : 't4CambiaPwd.cgi',
}
function ecoGetFilaUsr(resp){
var filas = new Array();
va... |
else {alert('DATOS_INCORRECTOS'); }
hideModal();
return false;
}
function cambiaPassword(){
var usr = vgPwd.usuario.get('usr');
var frm = creaFormCambiaPwd(usr);
var modal = new retoModal(frm);
}
function editPwdUser(){
var frm = $('frmAltaUser');
var str = frm.serialize(true);
var hFila... | {
ajaxCambiaPwd (user,pwd0,pwd1,ecoCambiaPassword); // cambia la entrada encriptada en el FS (retoUsrsPwds.txt) !!!!
} | conditional_block |
libK0_Password.js | var vgPwd = {
aleph_t : '',
ok : 0,
filas : new Array(),
laFila :'',
cabecera : '',
usuario : '',
users : '',
proys : '',
roles : '',
mkUsrPwd : 't4UserPwd.cgi',
cambiaPwd : 't4CambiaPwd.cgi',
}
function ecoGetFilaUsr(resp){
var filas = new Array();
va... | (){
var frm = $('frmCambiaPwd');
var str = frm.serialize(true);
var hash = $H(str);
var user = hash.get('usr');
var pwd0 = hash.get('pwd0');
var pwd1 = hash.get('pwd1');
var pwd2 = hash.get('pwd2');
console.log(user+':'+pwd0+':'+pwd1+':'+pwd2)
if (user && pwd0 && pwd1 && pwd2 && (pwd1 == pwd2) && (p... | cambiaPassword1 | identifier_name |
libK0_Password.js | var vgPwd = {
aleph_t : '',
ok : 0,
filas : new Array(),
laFila :'',
cabecera : '',
usuario : '',
users : '',
proys : '',
roles : '',
mkUsrPwd : 't4UserPwd.cgi',
cambiaPwd : 't4CambiaPwd.cgi',
}
function ecoGetFilaUsr(resp){
var filas = new Array();
va... |
function cierraSesion(){
window.location = "login.html";
}
//------------------------------------------------------------------- Crea Usuario/Password
function ajaxCambiaPwd (usr,pwd0,pwd1,eco){
var params = '';
params += 'id='+vgComun.idSesion;
params += '&usr='+usr;
params += '&pwd0='+pwd0;
... | $('nomUsr').update(nom);
}
| random_line_split |
libK0_Password.js | var vgPwd = {
aleph_t : '',
ok : 0,
filas : new Array(),
laFila :'',
cabecera : '',
usuario : '',
users : '',
proys : '',
roles : '',
mkUsrPwd : 't4UserPwd.cgi',
cambiaPwd : 't4CambiaPwd.cgi',
}
function ecoGetFilaUsr(resp){
var filas = new Array();
va... |
function cambiaPassword(){
var usr = vgPwd.usuario.get('usr');
var frm = creaFormCambiaPwd(usr);
var modal = new retoModal(frm);
}
function editPwdUser(){
var frm = $('frmAltaUser');
var str = frm.serialize(true);
var hFila = $H(str);
var usr = hFila.get('usr');
var frm = creaFormCambiaPwd(usr);... | {
var frm = $('frmCambiaPwd');
var str = frm.serialize(true);
var hash = $H(str);
var user = hash.get('usr');
var pwd0 = hash.get('pwd0');
var pwd1 = hash.get('pwd1');
var pwd2 = hash.get('pwd2');
console.log(user+':'+pwd0+':'+pwd1+':'+pwd2)
if (user && pwd0 && pwd1 && pwd2 && (pwd1 == pwd2) && (pwd... | identifier_body |
spec-main.js | via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
*/
... | else {
require.config({
waitSeconds: 30,
baseUrl: getQueryParameter('baseUrl') || '../Source',
paths: {
'Specs': '../Specs',
'Source' : '.'
}
});
}
require(toRequire, function(
Cesium,
paths... | {
require.config({
waitSeconds: 30,
baseUrl: getQueryParameter('baseUrl') || '../Build/Cesium',
paths: {
'Stubs': '../Stubs',
'Specs': '../../Specs',
'Source' : '../../Source'
},
shim: {
'... | conditional_block |
spec-main.js | via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
*/
... |
var built = getQueryParameter('built');
var release = getQueryParameter('release');
var toRequire = ['Cesium'];
if (built) {
require.config({
waitSeconds: 30,
baseUrl: getQueryParameter('baseUrl') || '../Build/Cesium',
paths: {
'Stubs': '..... | {
var match = new RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
} | identifier_body |
spec-main.js | baseUrl: getQueryParameter('baseUrl') || '../Build/Cesium',
paths: {
'Stubs': '../Stubs',
'Specs': '../../Specs',
'Source' : '../../Source'
},
shim: {
'Cesium': {
exports: 'Cesium'
... | * ## Execution
*
* Load the modules via AMD, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. | random_line_split | |
spec-main.js | Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-g... | (name) {
var match = new RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var built = getQueryParameter('built');
var release = getQueryParameter('release');
var toRequire = ['Cesium'];
if (built) ... | getQueryParameter | identifier_name |
test_containers_smartstate_analysis.py | import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui impor... |
random_image_instance.perform_smartstate_analysis(wait_for_finish=True)
view = navigate_to(random_image_instance, 'Details')
for tbl, attr, verifier in test_item.tested_attr:
table = getattr(view.entities, tbl)
table_data = {k.lower(): v for k, v in table.read().items()}
if not s... | random_line_split | |
test_containers_smartstate_analysis.py | import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui impor... |
original_scan = random_image_instance.last_scan_attempt_on
random_image_instance.scan()
task = provider.appliance.collections.tasks.instantiate(
name=f"Container Image Analysis: '{random_image_instance.name}'", tab='AllTasks')
task.wait_for_finished()
soft_assert(original_scan != rando... | random_image_instance.unassign_policy_profiles('OpenSCAP profile') | conditional_block |
test_containers_smartstate_analysis.py | import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui impor... |
def get_table_attr(instance, table_name, attr):
# Trying to read the table <table_name> attribute <attr>
view = navigate_to(instance, 'Details', force=True)
table = getattr(view.entities, table_name, None)
if table:
return table.read().get(attr)
@pytest.mark.parametrize(('test_item'), TEST_... | """
Polarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
random_image_instance.assign_policy_profiles('OpenSCAP profile')
random_image_instance.check_compliance() | identifier_body |
test_containers_smartstate_analysis.py | import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui impor... | (provider, test_item, soft_assert,
delete_all_container_tasks,
random_image_instance):
"""
Polarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
... | test_containers_smartstate_analysis | identifier_name |
nodejs-imap.js | var forge = require('../js/forge');
var net = require('net');
var socket = new net.Socket();
var client = forge.tls.createConnection({
server: false,
verify: function(connection, verified, depth, certs) {
// skip verification for testing
return true;
},
connected: function(connection) {
console.lo... |
// connect to gmail's imap server
socket.connect(993, 'imap.gmail.com'); | client.process(data.toString('binary'));
});
socket.on('end', function() {
console.log('[socket] disconnected');
}); | random_line_split |
BORepository.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
namespace trainingtesting {
export namespace bo {
/** 业务仓库 */... | * @param saver 保存者
*/
saveCustomer(saver: ibas.ISaveCaller<bo.ICustomer>): void;
/**
* 查询 销售订单
* @param fetcher 查询者
*/
fetchSalesOrder(fetcher: ibas.IFetchCaller<bo.ISalesOrder>): void;
/**
... | random_line_split | |
beanbot.py | #!/usr/bin/env python
#
# Simple IRC Bot to announce messages
#
# Code originally based on example bot and irc-bot class from
# Joel Rosdahl <joel@rosdahl.net>, author of included python-irclib.
#
"""An IRC bot to announce messages on a channel.
This is an example bot that uses the SingleServerIRCBot class from
ircb... | import ConfigParser
c = ConfigParser.ConfigParser()
c.read(configfile)
cfgsect = botname
ircaddr = parse_host_port(c.get(cfgsect, 'host'), 6667)
channel = c.get(cfgsect, 'channel')
nickname = c.get(cfgsect, 'nickname')
try:
nickpass = c.get(cfgsect, 'nickpass')
except ConfigParser.NoOptionError:
... | import getopt
try:
opts, args = getopt.gnu_getopt(sys.argv, 'd', ('debug',))
except getopt.GetoptError:
usage()
debug = False
for opt, val in opts:
if opt in ('-d', '--debug'):
debug = True
if len(args) not in (1, 2):
usage()
if len(args) > 1:
configfile = args[1]
else:
c... | identifier_body |
beanbot.py | #!/usr/bin/env python
#
# Simple IRC Bot to announce messages
#
# Code originally based on example bot and irc-bot class from
# Joel Rosdahl <joel@rosdahl.net>, author of included python-irclib.
#
"""An IRC bot to announce messages on a channel.
This is an example bot that uses the SingleServerIRCBot class from
ircb... | if len(a) > 1 and irc_lower(a[0]) == irc_lower(c.get_nickname()):
self.do_command(e, string.strip(a[1]))
def say_public(self, text):
"Print TEXT into public channel, for all to see."
self.queue.send(text, self.channel)
def say_private(self, nick, text):
"Send private message of TEXT to NICK.... | def on_pubmsg(self, c, e):
a = string.split(e.arguments()[0], ":", 1) | random_line_split |
beanbot.py | #!/usr/bin/env python
#
# Simple IRC Bot to announce messages
#
# Code originally based on example bot and irc-bot class from
# Joel Rosdahl <joel@rosdahl.net>, author of included python-irclib.
#
"""An IRC bot to announce messages on a channel.
This is an example bot that uses the SingleServerIRCBot class from
ircb... | (self, nick, text):
"Send private message of TEXT to NICK."
self.queue.send(text,nick)
def reply(self, e, text):
"Send TEXT to public channel or as private msg, in reply to event E."
if e.eventtype() == "pubmsg":
self.say_public("%s: %s" % (nm_to_n(e.source()), text))
else:
self.say_p... | say_private | identifier_name |
beanbot.py | #!/usr/bin/env python
#
# Simple IRC Bot to announce messages
#
# Code originally based on example bot and irc-bot class from
# Joel Rosdahl <joel@rosdahl.net>, author of included python-irclib.
#
"""An IRC bot to announce messages on a channel.
This is an example bot that uses the SingleServerIRCBot class from
ircb... |
if len(args) not in (1, 2):
usage()
if len(args) > 1:
configfile = args[1]
else:
configfile = '%s.conf' % botname
import ConfigParser
c = ConfigParser.ConfigParser()
c.read(configfile)
cfgsect = botname
ircaddr = parse_host_port(c.get(cfgsect, 'host'), 6667)
channel = c.get(cfgsect, 'c... | if opt in ('-d', '--debug'):
debug = True | conditional_block |
consumption.js | /**
* Submit form data
*/
function submitFormDataConsumption(reinsert) {
$('#popup_reinsert').val(reinsert ? 'T' : 'F');
submitData('#popup_modform');
}
/**
* Submit form data
* param integer id the meter id
*/
function submitFormDataDoneConsumption(ids, reinsert) {
reloadTab(undefine... |
/**
* Switch the insert year
*/
function insertYearChange() {
var days = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var currType = $('#popup_insert_type').val();
var currYear = $('#popup_insert_year').val();
var m, d;
// Monthly dates
for (var i = 1; i <= 12; i++) {
... | {
var types = ['free', 'month', 'year'];
var currType = $('#popup_insert_type').val();
$('.year_data').toggle(currType != 'free'); // Show/hide the year selection
$.each(types, function () {
$('#kind_' + this).toggle(currType == this);
});
} | identifier_body |
consumption.js | /**
* Submit form data
*/
function submitFormDataConsumption(reinsert) {
$('#popup_reinsert').val(reinsert ? 'T' : 'F');
submitData('#popup_modform');
}
/**
* Submit form data
* param integer id the meter id
*/
function submitFormDataDoneConsumption(ids, reinsert) {
reloadTab(undefine... |
// Yearly dates
$('#popup_co_start_date_year').val('01' + date_separator + '01' + date_separator + currYear);
$('#popup_co_end_date_year').val('31' + date_separator + '12' + date_separator + currYear);
}
function calcEnergyCostValue(qtySelector, priceSelector) {
var qty = locale2float($(qtySe... | {
m = (i < 10 ? '0' : '') + i;
if (i == 2)
d = ((currYear % 4 == 0) && (currYear % 1000 != 0)) ? 29 : 28;
else
d = days[i - 1];
d = (d < 10 ? '0' : '') + d;
$('#popup_co_start_date_month_' + i).val('01' + date_separator + m + date_separator + currYe... | conditional_block |
consumption.js | /**
* Submit form data
*/
function submitFormDataConsumption(reinsert) {
$('#popup_reinsert').val(reinsert ? 'T' : 'F');
submitData('#popup_modform');
}
/**
* Submit form data
* param integer id the meter id
*/
function submitFormDataDoneConsumption(ids, reinsert) {
reloadTab(undefine... | var qty = locale2float($(qtySelector).val());
var price = locale2float($(priceSelector).val());
if (qty == '' || price == '') {
return '';
}
return float2locale(roundNumber(price / qty, 2));
}
function calcValue() {
var currType = $('#popup_insert_type').val();
if (currTyp... | $('#popup_co_end_date_year').val('31' + date_separator + '12' + date_separator + currYear);
}
function calcEnergyCostValue(qtySelector, priceSelector) {
| random_line_split |
consumption.js | /**
* Submit form data
*/
function submitFormDataConsumption(reinsert) {
$('#popup_reinsert').val(reinsert ? 'T' : 'F');
submitData('#popup_modform');
}
/**
* Submit form data
* param integer id the meter id
*/
function submitFormDataDoneConsumption(ids, reinsert) {
reloadTab(undefine... | () {
var currType = $('#popup_insert_type').val();
if (currType == 'month') {
for (var i = 1; i <= 12; i++) {
$('#popup_co_energy_costs_month_' + i).val(calcEnergyCostValue('#popup_co_value_month_' + i, '#popup_co_bill_month_' + i));
}
} else if (currType == 'year') {
... | calcValue | identifier_name |
Headline_facet.graphql.ts | /* tslint:disable */
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type Headline_facet = {
readonly name?: string | null;
readonly " $refType": "Headline_facet";
};
export type Headline_facet$data = Headline_facet;
export type Headline_facet$key = {
re... | const node: ReaderFragment = (function(){
var v0 = [
{
"kind": "ScalarField",
"alias": null,
"name": "name",
"args": null,
"storageKey": null
}
];
return {
"kind": "Fragment",
"name": "Headline_facet",
"type": "ArtworkFilterFacet",
"metadata": null,
"argumentDefinitions": [],
"select... | random_line_split | |
angular-locale_os.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n... | }
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0440\u0430\u0437\u043c\u04d5",
"\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0444\u04d5\u0441\u0442\u04d5"
],
"DAY": [
"\u0445\u0443\u044b\u0446\... | random_line_split | |
angular-locale_os.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n... |
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0440\u0430\u0437\u043c\u04d5",
"\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0444\u04d5\u0441\u0442\u04d5"
],
"DAY": [
"\u0445\u0443\u044b\u0446\u... | {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
} | identifier_body |
angular-locale_os.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function | (n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u04d5\u043c\u0431\u0438\u... | getVF | identifier_name |
angular-locale_os.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n... | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
model.py | ");
# 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,
#... | # return eHata value without adjustment.
print 'EHata only for d=%f' % d
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
return ehata.ExtendedHata_PropagationLoss(f, h1, h2, land_cat, profile)
if d >= 80000.0:
print 'EHata for distance %f > 80km' % d
# Derive profile_80km
... | return fspl_loss + (1.0 + math.log10(d/1000.0))*(ehata_loss - fspl_loss)
if d > 1000.0 and d < 80000.0: | random_line_split |
model.py | # 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,
# ... | (f, d, h1, h2):
r = math.sqrt(d*d + (h1-h2)*(h1-h2))
return 20*math.log10(r) + 20*math.log10(f) - 27.56
class PropagationLossModel:
def __init__(self, itu_dir, ned_dir, nlcd_dir):
self.climIndx = tropoClim.ClimateIndexer(itu_dir)
self.refractivityIndx = refractivity.RefractivityIndexer(itu_dir)
self.... | FreeSpacePathLoss | identifier_name |
model.py | ");
# 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,
#... | return itm_loss
# Run directly, takes args of "lat1, lng1, h1, lat2, lng2, h2, f" and prints the
# (median) propagation loss in dB.
if __name__ == '__main__':
dir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.dirname(os.path.dirname(dir))
ituDir = os.path.join(os.path.join(rootDir, 'data... | if land_cat == '':
code = self.nlcdIndx.NlcdCode(lat2, lng2)
if code == 11:
code = self.nlcdIndx.NlcdCode(lat1, lng1)
land_cat = land_use.NlcdLandCategory(code)
print 'Using land_cat =', land_cat
# Calculate effective heights of tx and rx:
profile = self.nedIndx.Profile(lat1, lng1, ... | identifier_body |
model.py | # 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,
# ... |
else:
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5)
ehata_loss = self.ExtendedHata_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, land_cat)
if ehata_loss > itm_loss:
return ehata_loss
return itm_loss
# Run directly, takes args of "l... | itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5)
print 'Returning itm_loss for rural > 200: ', itm_loss
return itm_loss | conditional_block |
builder.js | ++){
if(this.getCellNodeIndex(cell) == inCellIndex){
return cell;
}
}
}
},
findCellTarget: function(inSourceNode, inTopNode){
var n = inSourceNode;
while(n && (!this.isCellNode(n) || (dojox.grid.gridViewTag in n.offsetParent.parentNode && n.offsetParent.parentNode[dojox.grid.gridViewTag] != th... | }
// Mozilla 1.8 (FF 1.5) has a bug that makes offsetLeft = -parent border width
// when parent has border, overflow: hidden, and is positioned
// handle this problem here ... not a general solution!
x += (n.offsetLeft < 0 ? 0 : n.offsetLeft);
return true;
});
return x;
},
// event decoration
... | var n = dojox.grid.ascendDom(e.target, function(){
if(!n || n == e.cellNode){
return false; | random_line_split |
builder.js | ){
try{
var row = e.relatedTarget && this.findRowTarget(e.relatedTarget);
return !row && (e.rowIndex==-1) || row && (e.rowIndex==row.gridRowIndex);
}catch(x){
// e.relatedTarget on INPUT has permission problem in FF: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
return false;
}
},
dispatch... | {
this.grid.onMouseDown(e);
this.grid.onMouseOverRow(e);
} | conditional_block | |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | 'website': 'http://www.odoo-magento-connector.com',
'description': """
Magento Connector - Export Partners
===================================
Extension for **Magento Connector**, export the partners to Magento.
This module is considered as experimental, the creation of the partners
is not guaranted to work correct... | random_line_split | |
regress-465980-02.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
var push = Array.prototype.push;
var unshift = Array.prototype.unshift;
function testArrayPush(startLength, pushArgs, expectThrow, expectLength)
{
print("running testArrayPush(" +
startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectL... | {
return name + "(" + startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")";
} | identifier_body |
regress-465980-02.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | ()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
function describe(name, startLength, pushArgs, expectThrow, expectLength)
{
return name + "(" + startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")";
}
var push = ... | test | identifier_name |
regress-465980-02.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
if (!expectThrow)
{
throw "unexpected exception " + e + " for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
if (a.length !== expectLength)
{
throw "unexpected modified-array length for " +
des... | {
throw "unexpected exception type thrown: " + e + " for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
} | conditional_block |
regress-465980-02.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | //-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
function describe(name, startLength, pushArgs, expectT... | var expect = '';
| random_line_split |
migrate.js | import fs from 'fs';
import path from 'path';
import { isLocalId, winningRev } from 'pouchdb-utils';
import levelup from 'levelup';
import { obj as through } from 'through2';
import LevelWriteStream from "level-write-stream";
var stores = [
'document-store',
'by-sequence',
'attach-store',
'attach-binary-store'... |
done.push(storePath);
if (!(--todo)) {
done.forEach(function (item) {
leveldown.destroy(item, function () {
if (++todo === done.length) {
fs.rmdir(base, callback);
}
});
});
}
});
});
});
};
var ... | {
return callback(err);
} | conditional_block |
migrate.js | import fs from 'fs';
import path from 'path';
import { isLocalId, winningRev } from 'pouchdb-utils';
import levelup from 'levelup';
import { obj as through } from 'through2';
import LevelWriteStream from "level-write-stream";
var stores = [
'document-store',
'by-sequence',
'attach-store',
'attach-binary-store'... | (n) {
return ('0000000000000000' + n).slice(-16);
}
var UPDATE_SEQ_KEY = '_local_last_update_seq';
var DOC_COUNT_KEY = '_local_doc_count';
var UUID_KEY = '_local_uuid';
var toSublevel = function (name, db, callback) {
// local require to prevent crashing if leveldown isn't installed.
var leveldown = require("lev... | formatSeq | identifier_name |
migrate.js | import fs from 'fs';
import path from 'path';
import { isLocalId, winningRev } from 'pouchdb-utils';
import levelup from 'levelup';
import { obj as through } from 'through2';
import LevelWriteStream from "level-write-stream";
var stores = [
'document-store',
'by-sequence',
'attach-store',
'attach-binary-store'... | prefix: stores.bySeqStore,
type: 'del'
});
stores.bySeqStore.get(DOC_COUNT_KEY, function (err, value) {
if (value) {
// if no doc count key,
// just skip
// we can live with this
batches.push({
key: DOC_COUNT_KEY,
value: value,
pref... | valueEncoding: 'json'
});
batches.push({
key: UUID_KEY, | random_line_split |
migrate.js | import fs from 'fs';
import path from 'path';
import { isLocalId, winningRev } from 'pouchdb-utils';
import levelup from 'levelup';
import { obj as through } from 'through2';
import LevelWriteStream from "level-write-stream";
var stores = [
'document-store',
'by-sequence',
'attach-store',
'attach-binary-store'... |
var UPDATE_SEQ_KEY = '_local_last_update_seq';
var DOC_COUNT_KEY = '_local_doc_count';
var UUID_KEY = '_local_uuid';
var toSublevel = function (name, db, callback) {
// local require to prevent crashing if leveldown isn't installed.
var leveldown = require("leveldown");
var base = path.resolve(name);
functio... | {
return ('0000000000000000' + n).slice(-16);
} | identifier_body |
examples.state.ts | import { ActionReducerMap, createFeatureSelector } from '@ngrx/store';
import { AppState } from '../../core/core.module';
import { todosReducer } from './todos/todos.reducer';
import { TodosState } from './todos/todos.model';
import { stockMarketReducer } from './stock-market/stock-market.reducer';
import { StockMark... | export const reducers: ActionReducerMap<ExamplesState> = {
todos: todosReducer,
stocks: stockMarketReducer,
books: bookReducer,
form: formReducer
};
export interface ExamplesState {
todos: TodosState;
stocks: StockMarketState;
form: FormState;
books: BookState;
}
export interface State extends AppStat... |
export const FEATURE_NAME = 'examples';
export const selectExamples = createFeatureSelector<State, ExamplesState>(
FEATURE_NAME
); | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | """Create and customize interactive maps using the 'Leaflet' JavaScript
library and the 'htmlwidgets' package. These maps can be used directly from
the R console, from 'RStudio', in Shiny apps and R Markdown documents."""
homepage = "http://rstudio.github.io/leaflet/"
url = "https://cran.r-project... | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
# | # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Le... | # This file is part of Spack. | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (RPackage):
"""Create and customize interactive maps using the 'Leaflet' JavaScript
library and the 'htmlwidgets' package. These maps can be used directly from
the R console, from 'RStudio', in Shiny apps and R Markdown documents."""
homepage = "http://rstudio.github.io/leaflet/"
url = "https:... | RLeaflet | identifier_name |
854bb8a5b4870edd996b9fac68c2200dd8e9562f.js | var React = require("react");
var MessageForm = require("./MessageForm");
var MessagesList = require("./MessagesList");
var LoginForm = require("./Login/LoginForm");
var MessageActions = require("./Actions/MessageActions");
var Emitter = require("./Emitter");
var MessagesStore = require("./Stores/MessagesStore");
va... | module.exports = Chat; | random_line_split | |
854bb8a5b4870edd996b9fac68c2200dd8e9562f.js | var React = require("react");
var MessageForm = require("./MessageForm");
var MessagesList = require("./MessagesList");
var LoginForm = require("./Login/LoginForm");
var MessageActions = require("./Actions/MessageActions");
var Emitter = require("./Emitter");
var MessagesStore = require("./Stores/MessagesStore");
va... |
return React.createElement("div", null,
React.createElement(MessagesList, {messages: this.state.messages}),
React.createElement(MessageForm, null)
)
}
});
module.exports = Chat; | {
return React.createElement(LoginForm, null)
} | conditional_block |
DrawingRecorder.ts | ///<reference path="./IInputActionCallback.ts" />
///<reference path="./Point.ts" />
///<reference path="../Historical.ts" />
///<reference path="../user/Action.ts" />
import { Action } from "../user/Action";
import { Historical } from "../Historical";
import { InputProvider } from "./InputProvider";
import { Point } f... |
protected onPlaybackComplete()
{
}
private _layers;
} | }
} | random_line_split |
DrawingRecorder.ts | ///<reference path="./IInputActionCallback.ts" />
///<reference path="./Point.ts" />
///<reference path="../Historical.ts" />
///<reference path="../user/Action.ts" />
import { Action } from "../user/Action";
import { Historical } from "../Historical";
import { InputProvider } from "./InputProvider";
import { Point } f... |
public clear()
{
this.isRendering = false;
this.drawingPoints = new Array<Action<Point>>();
}
public startContinuousRendering()
{
this.record();
this.isRendering = true;
}
/**
* renders the drawing
*/
public renderDrawing()
{
if ... | {
this.isPlaying = true;
var node = this.drawingPoints[index];
var nextNode = this.drawingPoints[index + 1];
if (node && this.renderer)
{
this.renderer.render(node);
}
if (node && nextNode)
{
setTimeout(this.playback.bind(this), nex... | identifier_body |
DrawingRecorder.ts | ///<reference path="./IInputActionCallback.ts" />
///<reference path="./Point.ts" />
///<reference path="../Historical.ts" />
///<reference path="../user/Action.ts" />
import { Action } from "../user/Action";
import { Historical } from "../Historical";
import { InputProvider } from "./InputProvider";
import { Point } f... |
{
public constructor(provider: InputProvider)
{
this.drawingPoints = new Array<Action<Point>>();
provider.addInputActionListener(this.OnDraw.bind(this));
}
private drawingPoints: Array<Action<Point>>;
private isRecording: boolean;
private isPlaying: boolean;
private rendere... | DrawingRecorder | identifier_name |
DrawingRecorder.ts | ///<reference path="./IInputActionCallback.ts" />
///<reference path="./Point.ts" />
///<reference path="../Historical.ts" />
///<reference path="../user/Action.ts" />
import { Action } from "../user/Action";
import { Historical } from "../Historical";
import { InputProvider } from "./InputProvider";
import { Point } f... |
}
protected onPlaybackComplete()
{
}
private _layers;
} | {
var element = points[index];
this.drawingPoints.push(element);
if (this.isRendering)
{
this.renderer.render(element);
}
} | conditional_block |
index.node.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {TestUtils, CrashLog} from 'flipper-plugin';
import * as CrashReporterPlugin from '../index'; | test('test defaultPersistedState of CrashReporterPlugin', () => {
expect(
TestUtils.startDevicePlugin(CrashReporterPlugin).exportState(),
).toEqual({crashes: []});
});
test('test helper setdefaultPersistedState function', () => {
const crash: CrashLog = {
callstack: 'callstack',
reason: 'crash0',
... | random_line_split | |
cancel.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
return None
def _CancelJob(self, job_ref):
"""Cancels a job.
Args:
job_ref: resources.Resource, The reference to the job to cancel.
"""
apitools_client = self.context[commands.DATAFLOW_APITOOLS_CLIENT_KEY]
dataflow_messages = self.context[commands.DATAFLOW_MESSAGES_MODULE_KEY]
re... | self._CancelJob(job_ref) | conditional_block |
cancel.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (parser):
"""Register flags for this command."""
job_utils.ArgsForJobRefs(parser, nargs='+')
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: all the arguments that were provided to this command invocation.
Returns:
A pair of lists indica... | Args | identifier_name |
cancel.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | except exceptions.HttpError as unused_error:
log.err.Print('Failed to cancel job [{0}]'.format(job_ref.jobId))
| """Cancels a job.
Args:
job_ref: resources.Resource, The reference to the job to cancel.
"""
apitools_client = self.context[commands.DATAFLOW_APITOOLS_CLIENT_KEY]
dataflow_messages = self.context[commands.DATAFLOW_MESSAGES_MODULE_KEY]
request = dataflow_messages.DataflowProjectsJobsUpdateReq... | identifier_body |
cancel.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | log.err.Print('Failed to cancel job [{0}]'.format(job_ref.jobId)) | random_line_split | |
app.ts | import { Noise } from './noise';
export class App {
private state: AppState = AppState.Stopped;
private noise: Noise;
constructor() {
this.noise = new Noise();
}
bootstrap(): void {
this.bindEvents();
this.enterState(AppState.Stopped);
}
private bindEvents(): void {
const controlSta... | this.enterState(newState);
this.state = newState;
}
private enterState(state: AppState): void {
document.body.classList.add(CSSClassesByState.get(state));
setTimeout(() => document.body.classList.add('run'), 10);
if (state === AppState.Playing) {
this.noise.start();
}
}
private l... | random_line_split | |
app.ts | import { Noise } from './noise';
export class App {
private state: AppState = AppState.Stopped;
private noise: Noise;
constructor() |
bootstrap(): void {
this.bindEvents();
this.enterState(AppState.Stopped);
}
private bindEvents(): void {
const controlStart = document.querySelector('.control.start') as HTMLButtonElement;
controlStart.addEventListener('click', () => {
this.updateState(AppState.Starting);
});
con... | {
this.noise = new Noise();
} | identifier_body |
app.ts | import { Noise } from './noise';
export class App {
private state: AppState = AppState.Stopped;
private noise: Noise;
constructor() {
this.noise = new Noise();
}
bootstrap(): void {
this.bindEvents();
this.enterState(AppState.Stopped);
}
private bindEvents(): void {
const controlSta... |
}
}
const enum AppState {
Stopped,
Starting,
Playing,
Stopping,
}
const CSSClassesByState = new Map<AppState, string>([
[AppState.Stopped, 'stopped'],
[AppState.Starting, 'starting'],
[AppState.Playing, 'playing'],
[AppState.Stopping, 'stopping'],
]);
| {
this.noise.stop();
} | conditional_block |
app.ts | import { Noise } from './noise';
export class App {
private state: AppState = AppState.Stopped;
private noise: Noise;
constructor() {
this.noise = new Noise();
}
bootstrap(): void {
this.bindEvents();
this.enterState(AppState.Stopped);
}
private bindEvents(): void {
const controlSta... | (state: AppState): void {
document.body.classList.remove(CSSClassesByState.get(state));
document.body.classList.remove('run');
if (state === AppState.Playing) {
this.noise.stop();
}
}
}
const enum AppState {
Stopped,
Starting,
Playing,
Stopping,
}
const CSSClassesByState = new Map<App... | leaveState | identifier_name |
index.spec.ts | import { Subject } from "rxjs";
import { take, toArray } from "rxjs/operators";
import { v4 as uuid } from "uuid";
import {
createMainChannelFromSockets,
createSocket,
getUsername,
JupyterConnectionInfo,
verifiedConnect,
ZMQType
} from "../src";
import { EventEmitter } from "events";
import { Socket as _S... |
const socket = {
type: "hokey",
monitor: jest.fn(),
unmonitor: jest.fn(),
close: jest.fn(),
on: jest.fn(emitter.on.bind(emitter)),
emit: jest.fn(emitter.emit.bind(emitter)),
connect: jest.fn(() => {})
};
const p = verifiedConnect(
(socket as unknown) as _Soc... |
describe("verifiedConnect", () => {
test("verifiedConnect monitors the socket", async done => {
const emitter = new EventEmitter(); | random_line_split |
index.spec.ts | import { Subject } from "rxjs";
import { take, toArray } from "rxjs/operators";
import { v4 as uuid } from "uuid";
import {
createMainChannelFromSockets,
createSocket,
getUsername,
JupyterConnectionInfo,
verifiedConnect,
ZMQType
} from "../src";
import { EventEmitter } from "events";
import { Socket as _S... | extends _Socket {
send = jest.fn();
constructor() {
super("hokey");
this.send = jest.fn();
}
}
describe("createSocket", () => {
test("creates a JMP socket on the channel with identity", async done => {
const config = {
signature_scheme: "hmac-sha256",
key: "5ca1ab1e-c0da-aced-cafe-c0ff... | HokeySocket | identifier_name |
providerbootstrapper.py | bundle.
:rtype: bool or str
"""
if self._bypass_checks:
return False
cert = flags.CA_CERT_FILE
if cert is not None:
verify = cert
else:
verify = ca_bundle.where()
return verify
def _check_name_resolution(self):
"... | _check_api_certificate | identifier_name | |
providerbootstrapper.py | logger = logging.getLogger(__name__)
class UnsupportedProviderAPI(Exception):
"""
Raised when attempting to use a provider with an incompatible API.
"""
pass
class UnsupportedClientVersionError(Exception):
"""
Raised when attempting to use a provider with an older
client than supported.
... | res.raise_for_status()
except requests.exceptions.SSLError as exc:
self._err_msg = self.tr("Provider certificate could "
"not be verified")
raise
except Exception as exc:
# XXX careful!. The error might be also a SSL han... | """
Checks that https is working and that the provided certificate
checks out
"""
leap_assert(self._domain, "Cannot check HTTPS without a domain")
logger.debug("Checking https for %r" % (self._domain))
# We don't skip this check, since it's basic for the whole
# ... | identifier_body |
providerbootstrapper.py | logger = logging.getLogger(__name__)
class UnsupportedProviderAPI(Exception):
"""
Raised when attempting to use a provider with an incompatible API.
"""
pass
class UnsupportedClientVersionError(Exception):
"""
Raised when attempting to use a provider with an older
client than supported.
... | https_connection = None
down_provider_info = None
if self._signaler is not None:
name_resolution = self._signaler.prov_name_resolution
https_connection = self._signaler.prov_https_connection
down_provider_info = self._signaler.prov_download_provider_info
... |
self._domain = ProviderConfig.sanitize_path_component(domain)
self._download_if_needed = download_if_needed
name_resolution = None | random_line_split |
providerbootstrapper.py | logger = logging.getLogger(__name__)
class UnsupportedProviderAPI(Exception):
"""
Raised when attempting to use a provider with an incompatible API.
"""
pass
class UnsupportedClientVersionError(Exception):
"""
Raised when attempting to use a provider with an older
client than supported.
... |
else:
api_supported = ', '.join(provider.SUPPORTED_APIS)
error = ('Unsupported provider API version. '
'Supported versions are: {0}. '
'Found: {1}.').format(api_supported, api_version)
... | logger.debug("Provider definition has been modified") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.