file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
cadastro.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Events } from 'ionic-angular';
import { AppPreferences } from '@ionic-native/app-preferences';
import { Cliente } from '../../models/cliente';
import { EnderecoPage } from '../endereco/endereco';
import { Link } f... | return true;
}
}
| return false;
}
| conditional_block |
cadastro.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Events } from 'ionic-angular';
import { AppPreferences } from '@ionic-native/app-preferences';
import { Cliente } from '../../models/cliente';
import { EnderecoPage } from '../endereco/endereco';
import { Link } f... |
ionViewDidLoad() {
}
usuario_add() {
if (this.validaCampos()) {
this.http.post(this.link.api_url + 'clientes/add', {'Cliente': {'nome': this.nome, 'email': this.email, 'senha': this.senha}})
.map(res => res.json())
.subscribe(data => {
if (typeof data.message == "object... | {
this.link = new Link();
} | identifier_body |
cadastro.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Events } from 'ionic-angular';
import { AppPreferences } from '@ionic-native/app-preferences';
import { Cliente } from '../../models/cliente';
import { EnderecoPage } from '../endereco/endereco';
import { Link } f... | () {
if (this.validaCampos()) {
this.http.post(this.link.api_url + 'clientes/add', {'Cliente': {'nome': this.nome, 'email': this.email, 'senha': this.senha}})
.map(res => res.json())
.subscribe(data => {
if (typeof data.message == "object") {
this.cliente = data.message['... | usuario_add | identifier_name |
biscotti-auth.service.ts | import { Injectable } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpHeaderResponse,
HttpErrorResponse,
HttpEventType,
HttpResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/d... | {
public token = new BehaviorSubject<string>('');
constructor(
private http: HttpClient
) {
}
authorize(form: AuthRequest): Observable<string> {
return this
.http
.post('/biscotti/setup/authorize', form, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
... | BiscottiAuthService | identifier_name |
biscotti-auth.service.ts | import { Injectable } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpHeaderResponse,
HttpErrorResponse,
HttpEventType,
HttpResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/d... | ) {
}
authorize(form: AuthRequest): Observable<string> {
return this
.http
.post('/biscotti/setup/authorize', form, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
responseType: 'json',
observe: ... | export class BiscottiAuthService {
public token = new BehaviorSubject<string>('');
constructor(
private http: HttpClient | random_line_split |
AttachmentType_Dc.js | /**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
Ext.define("seava.ad.ui.extjs.dc.AttachmentType_Dc", {
extend: "e4e.dc.AbstractDc",
recordModel: seava.ad.ui.extjs.ds.AttachmentType_Ds
});
/* ... |
/* =========== controls =========== */
.addTextField({ name:"name", dataIndex:"name"})
.addBooleanField({ name:"active", dataIndex:"active"})
.addCombo({ xtype:"combo", name:"category", dataIndex:"category", store:[ "link", "upload"]})
/* =========== containers =========== */
.addPanel({ name:"main", ... | * Components definition
*/
_defineElements_: function() {
this._getBuilder_() | random_line_split |
admin.py | """ Django admin pages for student app """
from django import forms
from django.contrib.auth.models import User
from ratelimitbackend import admin
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from config_models.admin import Config... | return super(CourseEnrollmentAdmin, self).queryset(request).select_related('user')
class Meta(object):
model = CourseEnrollment
class UserProfileAdmin(admin.ModelAdmin):
""" Admin interface for UserProfile model. """
list_display = ('user', 'name',)
raw_id_fields = ('user',)
searc... | raw_id_fields = ('user',)
search_fields = ('course_id', 'mode', 'user__username',)
def queryset(self, request): | random_line_split |
admin.py | """ Django admin pages for student app """
from django import forms
from django.contrib.auth.models import User
from ratelimitbackend import admin
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from config_models.admin import Config... | (object):
model = CourseAccessRole
fields = '__all__'
email = forms.EmailField(required=True)
COURSE_ACCESS_ROLES = [(role_name, role_name) for role_name in REGISTERED_ACCESS_ROLES.keys()]
role = forms.ChoiceField(choices=COURSE_ACCESS_ROLES)
def clean_course_id(self):
"""
... | Meta | identifier_name |
admin.py | """ Django admin pages for student app """
from django import forms
from django.contrib.auth.models import User
from ratelimitbackend import admin
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from config_models.admin import Config... |
def clean_org(self):
"""If org and course-id exists then Check organization name
against the given course.
"""
if self.cleaned_data.get('course_id') and self.cleaned_data['org']:
org = self.cleaned_data['org']
org_name = self.cleaned_data.get('course_id').or... | """
Checking course-id format and course exists in module store.
This field can be null.
"""
if self.cleaned_data['course_id']:
course_id = self.cleaned_data['course_id']
try:
course_key = CourseKey.from_string(course_id)
except Invali... | identifier_body |
admin.py | """ Django admin pages for student app """
from django import forms
from django.contrib.auth.models import User
from ratelimitbackend import admin
from xmodule.modulestore.django import modulestore
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from config_models.admin import Config... |
class CourseAccessRoleAdmin(admin.ModelAdmin):
"""Admin panel for the Course Access Role. """
form = CourseAccessRoleForm
raw_id_fields = ("user",)
exclude = ("user",)
fieldsets = (
(None, {
'fields': ('email', 'course_id', 'org', 'role',)
}),
)
list_display ... | self.fields['email'].initial = self.instance.user.email | conditional_block |
freqs.rs | // Copyright 2012-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-MI... | 235, // 'u'
201, // 'v'
196, // 'w'
240, // 'x'
214, // 'y'
152, // 'z'
182, // '{'
205, // '|'
181, // '}'
127, // '~'
27, // '\x7f'
212, // '\x80'
211, // '\x81'
210, // '\x82'
213, // '\x83'
228, // '\x84'
197, // '\x85'
169, // '\x86'
159,... | 231, // 'p'
139, // 'q'
245, // 'r'
243, // 's'
251, // 't' | random_line_split |
tsxStatelessFunctionComponentOverload5.tsx | // @filename: file.tsx
// @jsx: preserve
// @module: amd
// @noLib: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react')
export interface ClickableProps {
children?: string;
className?: string;
}
export interface ButtonProps extends ClickableProps {
onClick: React.MouseEve... | (e: any){} }} children="hello" className />; // incorrect type for optional attribute
const b8 = <MainButton data-format />; // incorrect type for specified hyphanated name | onClick | identifier_name |
tsxStatelessFunctionComponentOverload5.tsx | // @filename: file.tsx
// @jsx: preserve
// @module: amd
// @noLib: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react')
export interface ClickableProps {
children?: string;
className?: string;
}
export interface ButtonProps extends ClickableProps {
onClick: React.MouseEve... |
return this._buildMainButton(props);
}
// Error
const b0 = <MainButton to='/some/path' onClick={(e)=>{}}>GO</MainButton>; // extra property;
const b1 = <MainButton onClick={(e: any)=> {}} {...obj0}>Hello world</MainButton>; // extra property;
const b2 = <MainButton {...{to: "10000"}} {...obj2} />; // ... | {
return this._buildMainLink(props);
} | conditional_block |
tsxStatelessFunctionComponentOverload5.tsx | // @filename: file.tsx
// @jsx: preserve
// @module: amd
// @noLib: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react')
export interface ClickableProps {
children?: string;
className?: string;
}
export interface ButtonProps extends ClickableProps {
onClick: React.MouseEve... | }} children="hello" className />; // incorrect type for optional attribute
const b8 = <MainButton data-format />; // incorrect type for specified hyphanated name | {} | identifier_body |
tsxStatelessFunctionComponentOverload5.tsx | // @filename: file.tsx
// @jsx: preserve
// @module: amd
// @noLib: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react')
| className?: string;
}
export interface ButtonProps extends ClickableProps {
onClick: React.MouseEventHandler<any>;
}
export interface LinkProps extends ClickableProps {
to: string;
}
export interface HyphenProps extends ClickableProps {
"data-format": string;
}
let obj0 = {
to: "... | export interface ClickableProps {
children?: string;
| random_line_split |
unzipWith.ts | /**
* Reverse the zip process, and reconstruct the original
* arrays as nested arrays. Pass in iterator to control
* how the final array is composed.
*
* implemented as a wrapper over the zipWith() function.
*
* NOTE: Once an iterator is specified, the function will mostly
* produce a single dimension array, as... | {
// must do some of the checking here as calling
// zipWith(...arrays) is assuming arrays is of array type
// and it will throw if data type is wrong.
if (!arrays || arrays.length <= 0) return [];
if (!Array.isArray(arrays)) return [];
// check the passed in parameter,
// if it consists of at least one ... | identifier_body | |
unzipWith.ts | /**
* Reverse the zip process, and reconstruct the original
* arrays as nested arrays. Pass in iterator to control
* how the final array is composed.
*
* implemented as a wrapper over the zipWith() function.
*
* NOTE: Once an iterator is specified, the function will mostly
* produce a single dimension array, as... |
return array;
});
}
| {
// loop thru every individual array and remove null or undefined
// at the tail end of the array as this is added by zip() due to
// non uniform size of array
let { length } = array;
do length--; while (length > 0 && array[length] == null);
array.length = length + 1;
} | conditional_block |
unzipWith.ts | /**
* Reverse the zip process, and reconstruct the original
* arrays as nested arrays. Pass in iterator to control
* how the final array is composed.
*
* implemented as a wrapper over the zipWith() function.
*
* NOTE: Once an iterator is specified, the function will mostly
* produce a single dimension array, as... | });
} | random_line_split | |
unzipWith.ts | /**
* Reverse the zip process, and reconstruct the original
* arrays as nested arrays. Pass in iterator to control
* how the final array is composed.
*
* implemented as a wrapper over the zipWith() function.
*
* NOTE: Once an iterator is specified, the function will mostly
* produce a single dimension array, as... | (arrays: any[], iterator?: FnAny): any[] {
// must do some of the checking here as calling
// zipWith(...arrays) is assuming arrays is of array type
// and it will throw if data type is wrong.
if (!arrays || arrays.length <= 0) return [];
if (!Array.isArray(arrays)) return [];
// check the passed in parame... | unzipWith | identifier_name |
map-bind.js | var map = L.map('clom_map');
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IjZjNmRjNzk3ZmE2MTcwOTEwMGY0MzU3YjUzOWFmNWZhIn0.Y8bhBaUMqFiPrDRW9hieoQ', {
maxZoom: 18,
id: 'mapbox.streets'
}).addTo(map);
function onLocationFound(e) {
var radius = e.accuracy / ... | function onLocationError(e) {
alert(e.message);
}
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({setView: true, maxZoom: 16}); |
L.circle(e.latlng, radius).addTo(map);
}
| random_line_split |
map-bind.js | var map = L.map('clom_map');
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IjZjNmRjNzk3ZmE2MTcwOTEwMGY0MzU3YjUzOWFmNWZhIn0.Y8bhBaUMqFiPrDRW9hieoQ', {
maxZoom: 18,
id: 'mapbox.streets'
}).addTo(map);
function | (e) {
var radius = e.accuracy / 2;
L.marker(e.latlng).addTo(map)
.bindPopup("You are within " + radius + " meters from this point").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
function onLocationError(e) {
alert(e.message);
}
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocati... | onLocationFound | identifier_name |
map-bind.js | var map = L.map('clom_map');
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IjZjNmRjNzk3ZmE2MTcwOTEwMGY0MzU3YjUzOWFmNWZhIn0.Y8bhBaUMqFiPrDRW9hieoQ', {
maxZoom: 18,
id: 'mapbox.streets'
}).addTo(map);
function onLocationFound(e) {
var radius = e.accuracy / ... |
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({setView: true, maxZoom: 16});
| {
alert(e.message);
} | identifier_body |
getFormValues.spec.js | import createGetFormValues from '../getFormValues';
import plain from '../../structure/plain';
import plainExpectations from '../../structure/plain/expectations';
import immutable from '../../structure/immutable';
import immutableExpectations from '../../structure/immutable/expectations';
import addExpectations from '.... |
describe(name, function () {
it('should return a function', function () {
expect(getFormValues('foo')).toBeA('function');
});
it('should get the form values from state', function () {
expect(getFormValues('foo')(fromJS({
form: {
foo: {
values: {
do... |
var fromJS = structure.fromJS;
var getIn = structure.getIn;
| random_line_split |
utils.py | #!/usr/bin/env python
#
"""oocgcm.core.utils
Define various generic utilities tools to be used in several submodules.
"""
import numpy as np
import xarray as xr
import dask.array as da
#
#=========================== General purpose ==================================
#
class _SliceGetter(object):
"""Class that re... | (self, index):
return index
returnslice = _SliceGetter()
#
#================= Applying numpy functions to dataarray =======================
#
def map_apply(func,scalararray):
"""Return a xarray dataarray with value func(scalararray.data)
Parameters
----------
func : function
Any func... | __getitem__ | identifier_name |
utils.py | #!/usr/bin/env python
#
"""oocgcm.core.utils
Define various generic utilities tools to be used in several submodules.
"""
import numpy as np
import xarray as xr
import dask.array as da
#
#=========================== General purpose ==================================
#
class _SliceGetter(object):
"""Class that re... |
Returns
-------
test : bool
boolean value of the test.
"""
if hasattr(xarr,'name'):
arrayname = xarr.name
else:
arrayname = 'array'
if not(is_xarray(xarr)):
raise TypeError(arrayname + 'is expected to be a xarray.DataArray')
if not(_chunks_are_compatible(x... | number of dimensions over which chunks should be compared. | random_line_split |
utils.py | #!/usr/bin/env python
#
"""oocgcm.core.utils
Define various generic utilities tools to be used in several submodules.
"""
import numpy as np
import xarray as xr
import dask.array as da
#
#=========================== General purpose ==================================
#
class _SliceGetter(object):
"""Class that re... | """Minimal exception for grid location incompatibility.
"""
def __init__(self):
Exception.__init__(self,"incompatible grid_location") | identifier_body | |
utils.py | #!/usr/bin/env python
#
"""oocgcm.core.utils
Define various generic utilities tools to be used in several submodules.
"""
import numpy as np
import xarray as xr
import dask.array as da
#
#=========================== General purpose ==================================
#
class _SliceGetter(object):
"""Class that re... |
for kwargs in extra_kwargs:
xarr.attrs[kwargs] = extra_kwargs[kwargs]
return xarr
def _grid_location_equals(xarr,grid_location=None):
"""Return True when the xarr grid_location attribute is grid_location
Parameters
----------
xarr : xarray.DataArray
xarray dataarray which att... | raise TypeError('except a xarray.DataArray') | conditional_block |
ph2.py | import json
import argparse
import numpy
import sys
import copy
from astropy.coordinates import SkyCoord
from astropy import units
import operator
class Program(object):
|
class Target(object):
def __init__(self, filename=None):
self.config = json.load(open(filename))
@property
def token(self):
return self.config["identifier"]["client_token"]
@property
def mag(self):
return self.config["moving_target"]["ephemeris_points"][0]["mag"]
@p... | def __init__(self, runid="16BP06", pi_login="gladman"):
self.config = {"runid": runid,
"pi_login": pi_login,
"program_configuration": {"mjdates": [],
"observing_blocks": [],
... | identifier_body |
ph2.py | import json
import argparse
import numpy
import sys
import copy
from astropy.coordinates import SkyCoord
from astropy import units
import operator
class Program(object):
def __init__(self, runid="16BP06", pi_login="gladman"):
self.config = {"runid": runid,
"pi_login": pi_login,
... | (self, target):
self.config["program_configuration"]["mjdates"].append(target)
def add_observing_block(self, observing_block):
self.config["program_configuration"]["observing_blocks"].append(observing_block)
def add_observing_group(self, observing_group):
self.config["program_configura... | add_target | identifier_name |
ph2.py | import json
import argparse
import numpy
import sys
import copy
from astropy.coordinates import SkyCoord
from astropy import units
import operator
class Program(object):
def __init__(self, runid="16BP06", pi_login="gladman"):
self.config = {"runid": runid,
"pi_login": pi_login,
... |
sf = lambda x, y: cmp(x.ra, y.ra)
order_tokens = sorted(ob_coordinate, cmp=sf, key=ob_coordinate.get)
total_itime = 0
ogs = {}
scheduled = {}
og_idx = 0
while len(scheduled) < len(ob_tokens):
og_idx += 1
og_token = "OG_{}_{}_{}".format(args.ogname, og_idx, 0)
sys.std... | ob.config["instrument_config_identifiers"] = [{"server_token": "I{}".format(idx)}]
program.add_observing_block(ob.config)
ob_tokens.append(ob_token)
mags[ob_token] = target.mag
ob_coordinate[ob_token] = target.coordinate | random_line_split |
ph2.py | import json
import argparse
import numpy
import sys
import copy
from astropy.coordinates import SkyCoord
from astropy import units
import operator
class Program(object):
def __init__(self, runid="16BP06", pi_login="gladman"):
self.config = {"runid": runid,
"pi_login": pi_login,
... |
print "Total I-Time: {} hrs".format(total_itime/3600.)
json.dump(program.config, open('program.json', 'w'), indent=4, sort_keys=True)
| og_idx += 1
og_token = "OG_{}_{}_{}".format(args.ogname, og_idx, 0)
sys.stdout.write("{}: ".format(og_token))
og = ObservingGroup(og_token)
og_coord = None
og_itime = 0
for ob_token in order_tokens:
if ob_token not in scheduled:
if og_coord is ... | conditional_block |
select.rs | use super::{parse_index_range, Index, Range};
use std::{
iter::{empty, FromIterator},
str::FromStr,
};
/// Represents a filter on a vector-like object
#[derive(Debug, PartialEq, Clone)]
pub enum Select<K> {
/// Select all elements
All,
/// Select a single element based on its index | /// Select an element by mapped key
Key(K),
}
pub trait SelectWithSize {
type Item;
fn select<O, K>(&mut self, selection: &Select<K>, len: usize) -> O
where
O: FromIterator<Self::Item>;
}
impl<I, T> SelectWithSize for I
where
I: DoubleEndedIterator<Item = T>,
{
type Item = T;
... | Index(Index),
/// Select a range of elements
Range(Range), | random_line_split |
select.rs | use super::{parse_index_range, Index, Range};
use std::{
iter::{empty, FromIterator},
str::FromStr,
};
/// Represents a filter on a vector-like object
#[derive(Debug, PartialEq, Clone)]
pub enum Select<K> {
/// Select all elements
All,
/// Select a single element based on its index
Index(Index)... | <O, K>(&mut self, s: &Select<K>, size: usize) -> O
where
O: FromIterator<Self::Item>,
{
match s {
Select::Key(_) => empty().collect(),
Select::All => self.collect(),
Select::Index(Index::Forward(idx)) => self.nth(*idx).into_iter().collect(),
Select... | select | identifier_name |
select.rs | use super::{parse_index_range, Index, Range};
use std::{
iter::{empty, FromIterator},
str::FromStr,
};
/// Represents a filter on a vector-like object
#[derive(Debug, PartialEq, Clone)]
pub enum Select<K> {
/// Select all elements
All,
/// Select a single element based on its index
Index(Index)... |
}
impl<K: FromStr> FromStr for Select<K> {
type Err = ();
fn from_str(data: &str) -> Result<Self, ()> {
if data == ".." {
Ok(Select::All)
} else if let Ok(index) = data.parse::<isize>() {
Ok(Select::Index(Index::new(index)))
} else if let Some(range) = parse_in... | {
match s {
Select::Key(_) => empty().collect(),
Select::All => self.collect(),
Select::Index(Index::Forward(idx)) => self.nth(*idx).into_iter().collect(),
Select::Index(Index::Backward(idx)) => self.rev().nth(*idx).into_iter().collect(),
Select::Range... | identifier_body |
t2t_trainer_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... |
"""Tests for t2t_trainer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensor2tensor.bin import t2t_trainer
from tensor2tensor.utils import trainer_lib_test
import tensorflow as tf
FLAGS = tf.flags.FLAGS
class TrainerTest(tf.test.TestCase):
... | # See the License for the specific language governing permissions and
# limitations under the License. | random_line_split |
t2t_trainer_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... |
if __name__ == "__main__":
tf.test.main()
| FLAGS.problem = "tiny_algo"
FLAGS.model = "transformer"
FLAGS.hparams_set = "transformer_tiny"
FLAGS.train_steps = 1
FLAGS.eval_steps = 1
FLAGS.output_dir = tf.test.get_temp_dir()
FLAGS.data_dir = tf.test.get_temp_dir()
t2t_trainer.main(None) | identifier_body |
t2t_trainer_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | tf.test.main() | conditional_block | |
t2t_trainer_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | (tf.test.TestCase):
@classmethod
def setUpClass(cls):
trainer_lib_test.TrainerLibTest.setUpClass()
def testTrain(self):
FLAGS.problem = "tiny_algo"
FLAGS.model = "transformer"
FLAGS.hparams_set = "transformer_tiny"
FLAGS.train_steps = 1
FLAGS.eval_steps = 1
FLAGS.output_dir = tf.test... | TrainerTest | identifier_name |
Point.js | function Point(x, y) {
this.x = x;
this.y = y;
}
function | (x, y) { return new Point(x, y); } // shorthand
Point.ORIGIN = P(0, 0);
Point.DIRECTIONS = [P(0, 1), P(1, 0), P(-1, 0), P(0, -1)];
Point.prototype.plus = function(point) {
return P(this.x + point.x, this.y + point.y);
};
Point.prototype.minus = function(point) {
return P(this.x - point.x, this.y - point.y);
... | P | identifier_name |
Point.js | function Point(x, y) |
function P(x, y) { return new Point(x, y); } // shorthand
Point.ORIGIN = P(0, 0);
Point.DIRECTIONS = [P(0, 1), P(1, 0), P(-1, 0), P(0, -1)];
Point.prototype.plus = function(point) {
return P(this.x + point.x, this.y + point.y);
};
Point.prototype.minus = function(point) {
return P(this.x - point.x, this.y ... | {
this.x = x;
this.y = y;
} | identifier_body |
Point.js | function Point(x, y) {
this.x = x;
this.y = y;
}
function P(x, y) { return new Point(x, y); } // shorthand
Point.ORIGIN = P(0, 0);
Point.DIRECTIONS = [P(0, 1), P(1, 0), P(-1, 0), P(0, -1)];
Point.prototype.plus = function(point) { | };
Point.prototype.minus = function(point) {
return P(this.x - point.x, this.y - point.y);
};
Point.prototype.times = function(scalar) {
return P(this.x * scalar, this.y * scalar);
};
Point.prototype.norm1 = function() {
return Math.abs(this.x) + Math.abs(this.y);
};
Point.prototype.equals = function(po... | return P(this.x + point.x, this.y + point.y); | random_line_split |
view_compiler.d.ts | import { AnimationEntryCompileResult } from '../animation/animation_compiler';
import { CompileDirectiveMetadata, CompilePipeMetadata } from '../compile_metadata';
import { CompilerConfig } from '../config';
import * as o from '../output/output_ast';
import { TemplateAst } from '../template_parser/template_ast';
import... | {
statements: o.Statement[];
viewFactoryVar: string;
dependencies: Array<ViewFactoryDependency | ComponentFactoryDependency>;
constructor(statements: o.Statement[], viewFactoryVar: string, dependencies: Array<ViewFactoryDependency | ComponentFactoryDependency>);
}
export declare class ViewCompiler {
... | ViewCompileResult | identifier_name |
view_compiler.d.ts | import { AnimationEntryCompileResult } from '../animation/animation_compiler';
import { CompileDirectiveMetadata, CompilePipeMetadata } from '../compile_metadata';
import { CompilerConfig } from '../config';
import * as o from '../output/output_ast';
import { TemplateAst } from '../template_parser/template_ast';
import... | private _animationCompiler;
constructor(_genConfig: CompilerConfig);
compileComponent(component: CompileDirectiveMetadata, template: TemplateAst[], styles: o.Expression, pipes: CompilePipeMetadata[], compiledAnimations: AnimationEntryCompileResult[]): ViewCompileResult;
} | random_line_split | |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... | {
match action {
Action::ActionCancel { id } => {
let _ = remove_in_flight(in_flight, &id)
.await
.map(|tx| tx.send(Ok(serde_json::Value::Null)));
Ok(Ok(serde_json::Value::Null))
}
Action::ActionStart { id, action, args } => {
... | identifier_body | |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... | (
id: ActionId,
in_flight: SharedLocalActionsInFlight,
fut: impl Future<Output = Result<Value, String>> + Send + 'static,
) -> Result<Result<serde_json::value::Value, String>, ActionRunnerError> {
let rx = add_in_flight(Arc::clone(&in_flight), id.clone()).await;
spawn_plugin(fut, in_flight, id);
... | run_plugin | identifier_name |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... | /// Removes an action id from the in-flight list.
///
/// Returns the tx handle which can then be used to cancel the action if needed.
async fn remove_in_flight(
in_flight: SharedLocalActionsInFlight,
id: &ActionId,
) -> Option<oneshot::Sender<Result<Value, String>>> {
let mut in_flight = in_flight.lock().a... | }
| random_line_split |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... |
};
run_plugin(id, in_flight, plugin).await
}
}
}
| {
return Err(ActionRunnerError::RequiredError(error::RequiredError(
format!("Could not find action {} in local registry", action),
)))
} | conditional_block |
addComment.js | Template.addComment.events({
// press enter on input
'keyup #addcomment': function(event) {
if (event.which === 13) {
event.stopPropagation();
const comment = event.target.value;
if (comment) {
event.target.value = '';
const userName = Meteor.users.findOne().username;
... | }); | random_line_split | |
addComment.js | Template.addComment.events({
// press enter on input
'keyup #addcomment': function(event) {
if (event.which === 13) {
event.stopPropagation();
const comment = event.target.value;
if (comment) {
event.target.value = '';
const userName = Meteor.users.findOne().username;
... |
});
}
return false;
}
},
'click #submitcomment': function() {
const commentBox = document.querySelector('#addcomment');
if (commentBox.value) {
const comment = commentBox.value;
commentBox.value = '';
const userName = Meteor.users.findOne().username;
con... | {
alert(err);
} | conditional_block |
SiteMapClient.py | """ Client-side transfer class for monitoring system
"""
import time
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC import S_OK
class SiteMapClient:
###########################################################################
def __init__( self, getRPCClient = None ):
self.getRPCClient = getRPCCl... |
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
| """ Retrieves a single file and puts it in the output directory
"""
if self.lastDataRetrievalTime - time.time() < 300:
result = self.__getRPCClient().getSitesData()
if 'rpcStub' in result:
del( result[ 'rpcStub' ] )
if not result[ 'OK' ]:
return result
self.sitesData = re... | identifier_body |
SiteMapClient.py | """ Client-side transfer class for monitoring system
"""
import time
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC import S_OK
class SiteMapClient:
###########################################################################
def __init__( self, getRPCClient = None ):
self.getRPCClient = getRPCCl... |
if not result[ 'OK' ]:
return result
self.sitesData = result[ 'Value' ]
if self.sitesData:
self.lastDataRetrievalTime = time.time()
return S_OK( self.sitesData )
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
| del( result[ 'rpcStub' ] ) | conditional_block |
SiteMapClient.py | """ Client-side transfer class for monitoring system
"""
import time
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC import S_OK
class SiteMapClient:
###########################################################################
def | ( self, getRPCClient = None ):
self.getRPCClient = getRPCClient
self.lastDataRetrievalTime = 0
self.sitesData = {}
def __getRPCClient( self ):
if self.getRPCClient:
return self.getRPCClient( "Framework/SiteMap" )
return RPCClient( "Framework/SiteMap" )
############################... | __init__ | identifier_name |
SiteMapClient.py | """ Client-side transfer class for monitoring system
"""
import time
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC import S_OK
class SiteMapClient:
###########################################################################
def __init__( self, getRPCClient = None ):
self.getRPCClient = getRPCCl... | if not result[ 'OK' ]:
return result
self.sitesData = result[ 'Value' ]
if self.sitesData:
self.lastDataRetrievalTime = time.time()
return S_OK( self.sitesData )
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF# | if 'rpcStub' in result:
del( result[ 'rpcStub' ] ) | random_line_split |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... |
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
fn freqy_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
let ninfo = NeedleInfo::new(needle);
let mut prestate = PrefilterState::new();
find(&mut prestate, &ninfo, haystack, needle)
}
#[test]
fn freqy_fo... | {
let mut i = 0;
let (rare1i, rare2i) = ninfo.rarebytes.as_rare_usize();
let (rare1, rare2) = ninfo.rarebytes.as_rare_bytes(needle);
while prestate.is_effective() {
// Use a fast vectorized implementation to skip to the next
// occurrence of the rarest byte (heuristically chosen) in the
... | identifier_body |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... |
// We've done what we can. There might be a match here.
return Some(i - rare1i);
}
// The only way we get here is if we believe our skipping heuristic
// has become ineffective. We're allowed to return false positives,
// so return the position at which we advanced to, aligned to the
... | {
i += 1;
continue;
} | conditional_block |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... |
// Check that the functions below satisfy the Prefilter function type.
const _: PrefilterFnTy = find;
/// Look for a possible occurrence of needle. The position returned
/// corresponds to the beginning of the occurrence, if one exists.
///
/// Callers may assume that this never returns false negatives (i.e., it
/// ... |
use crate::memmem::{
prefilter::{PrefilterFnTy, PrefilterState},
NeedleInfo,
}; | random_line_split |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... | (
prestate: &mut PrefilterState,
ninfo: &NeedleInfo,
haystack: &[u8],
needle: &[u8],
) -> Option<usize> {
let mut i = 0;
let (rare1i, rare2i) = ninfo.rarebytes.as_rare_usize();
let (rare1, rare2) = ninfo.rarebytes.as_rare_bytes(needle);
while prestate.is_effective() {
// Use a fa... | find | identifier_name |
branch_implpermissions.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct Branc... | () -> BranchImplpermissions {
BranchImplpermissions {
create: None,
read: None,
start: None,
stop: None,
_class: None,
}
}
}
| new | identifier_name |
branch_implpermissions.rs | /*
* Swaggy Jenkins | * Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct BranchImplpermissions {
#... | * | random_line_split |
TextArea.tsx | import * as React from 'react';
interface TextAreaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
innerRef?: React.Ref<HTMLTextAreaElement>;
autoResize?: boolean;
minHeight?: string
}
export default function TextArea(p: TextAreaProps) {
function handleResize(ta: HTMLTextAreaElemen... |
const handleRef = React.useCallback((a: HTMLTextAreaElement | null) => {
a && handleResize(a);
innerRef && (typeof innerRef == "function" ? innerRef(a) : (innerRef as any).current = a);
}, [innerRef, minHeight]);
return (
<textarea onInput={autoResize ? (e => handleResize(e.currentTarget)) : ... |
const { autoResize, innerRef, minHeight, ...props } = p;
| random_line_split |
TextArea.tsx | import * as React from 'react';
interface TextAreaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
innerRef?: React.Ref<HTMLTextAreaElement>;
autoResize?: boolean;
minHeight?: string
}
export default function TextArea(p: TextAreaProps) |
TextArea.defaultProps = { autoResize: true, minHeight: "50px" };
| {
function handleResize(ta: HTMLTextAreaElement) {
ta.style.height = "0";
ta.style.height = ta.scrollHeight + 'px';
ta.style.minHeight = p.minHeight!;
ta.scrollTop = ta.scrollHeight;
}
const { autoResize, innerRef, minHeight, ...props } = p;
const handleRef = React.useCallback((a: ... | identifier_body |
TextArea.tsx | import * as React from 'react';
interface TextAreaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
innerRef?: React.Ref<HTMLTextAreaElement>;
autoResize?: boolean;
minHeight?: string
}
export default function TextArea(p: TextAreaProps) {
function | (ta: HTMLTextAreaElement) {
ta.style.height = "0";
ta.style.height = ta.scrollHeight + 'px';
ta.style.minHeight = p.minHeight!;
ta.scrollTop = ta.scrollHeight;
}
const { autoResize, innerRef, minHeight, ...props } = p;
const handleRef = React.useCallback((a: HTMLTextAreaElement | null) ... | handleResize | identifier_name |
_health.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... | getSubSystemName(name): string {
if (name) {
const split = name.split('.');
split.splice(0, 1);
const remainder = split.join('.');
return remainder ? ' - ' + remainder : '';
}
}
/* private methods */
private addHealthObject(result, isLeaf,... | }
| random_line_split |
_health.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... |
}
}
}
// Add the details
if (hasDetails) {
healthData.details = details;
}
// Only add nodes if they provide additional information
if (isLeaf || hasDetails || healthData.error) {
result.push(healthData);
}
... | {
details[key] = value;
hasDetails = true;
} | conditional_block |
_health.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... |
/* private methods */
private addHealthObject(result, isLeaf, healthObject, name): any {
const healthData: any = {
name
};
const details = {};
let hasDetails = false;
for (const key in healthObject) {
if (healthObject.hasOwnProperty(key)) {
... | {
if (name) {
const split = name.split('.');
split.splice(0, 1);
const remainder = split.join('.');
return remainder ? ' - ' + remainder : '';
}
} | identifier_body |
_health.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... | (name): string {
if (name) {
const split = name.split('.');
split.splice(0, 1);
const remainder = split.join('.');
return remainder ? ' - ' + remainder : '';
}
}
/* private methods */
private addHealthObject(result, isLeaf, healthObject, name)... | getSubSystemName | identifier_name |
log.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
js.set_integer("errors", tx.errors as u64);
let jsa = Json::array();
for payload in tx.payload_types.iter() {
jsa.array_append_string(&format!("{:?}", payload));
}
js.set("payload", jsa);
let jsa = Json::array();
for notify in tx.notify_types.iter() {
jsa.array_append_string... | {
js.set_string("role", &"responder");
js.set_string("alg_enc", &format!("{:?}", state.alg_enc));
js.set_string("alg_auth", &format!("{:?}", state.alg_auth));
js.set_string("alg_prf", &format!("{:?}", state.alg_prf));
js.set_string("alg_dh", &format!("{:?}", state.alg_dh));
... | conditional_block |
log.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | } | return js.unwrap(); | random_line_split |
log.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
let js = Json::object();
js.set_integer("version_major", tx.hdr.maj_ver as u64);
js.set_integer("version_minor", tx.hdr.min_ver as u64);
js.set_integer("exchange_type", tx.hdr.exch_type.0 as u64);
js.set_integer("message_id", tx.hdr.msg_id as u64);
js.set_string("init_spi", &format!("{:016x}",... | identifier_body | |
log.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | (state: &mut IKEV2State, tx: &mut IKEV2Transaction) -> *mut JsonT
{
let js = Json::object();
js.set_integer("version_major", tx.hdr.maj_ver as u64);
js.set_integer("version_minor", tx.hdr.min_ver as u64);
js.set_integer("exchange_type", tx.hdr.exch_type.0 as u64);
js.set_integer("message_id", tx.hdr... | rs_ikev2_log_json_response | identifier_name |
twilio-mnc-mcc-getter.py | import logging
import os
from twilio.rest import Client
class TwilioClient(object):
def __init__(self):
self.logger = logging.getLogger("botosan.logger")
self.account_sid = os.environ["TWILIO_SID"]
self.account_token = os.environ["TWILIO_TOKEN"] | :param phone_number: The phone number, containing the +CC Number, ex: +12345678901 for the US.
:return: a tuple containing the mcc and mnc
"""
number = self.client.lookups.phone_numbers(phone_number).fetch(type="carrier")
self.logger.info(number.carrier['mobile_country_code'])
... | self.client = Client(self.account_sid, self.account_token)
def get_mcc_and_mnc(self, phone_number):
"""
Gets the Mobile Country Code and Mobile Network code for a given Twilio Number | random_line_split |
twilio-mnc-mcc-getter.py | import logging
import os
from twilio.rest import Client
class TwilioClient(object):
def __init__(self):
self.logger = logging.getLogger("botosan.logger")
self.account_sid = os.environ["TWILIO_SID"]
self.account_token = os.environ["TWILIO_TOKEN"]
self.client = Client(self.account_si... |
return phone_numbers
| phone_numbers.append(number.phone_number) | conditional_block |
twilio-mnc-mcc-getter.py | import logging
import os
from twilio.rest import Client
class TwilioClient(object):
def __init__(self):
self.logger = logging.getLogger("botosan.logger")
self.account_sid = os.environ["TWILIO_SID"]
self.account_token = os.environ["TWILIO_TOKEN"]
self.client = Client(self.account_si... | (self, phone_number):
"""
Gets the Mobile Country Code and Mobile Network code for a given Twilio Number
:param phone_number: The phone number, containing the +CC Number, ex: +12345678901 for the US.
:return: a tuple containing the mcc and mnc
"""
number = self.client.loo... | get_mcc_and_mnc | identifier_name |
twilio-mnc-mcc-getter.py | import logging
import os
from twilio.rest import Client
class TwilioClient(object):
def __init__(self):
self.logger = logging.getLogger("botosan.logger")
self.account_sid = os.environ["TWILIO_SID"]
self.account_token = os.environ["TWILIO_TOKEN"]
self.client = Client(self.account_si... |
def get_available_numbers(self):
numbers = self.client.available_phone_numbers("GB").local.list(exclude_local_address_required=True)
print(numbers.count())
phone_numbers = []
for number in numbers:
phone_numbers.append(number.phone_number)
return phone_numbers
| """
Gets the Mobile Country Code and Mobile Network code for a given Twilio Number
:param phone_number: The phone number, containing the +CC Number, ex: +12345678901 for the US.
:return: a tuple containing the mcc and mnc
"""
number = self.client.lookups.phone_numbers(phone_numbe... | identifier_body |
vtkExporter.py | from yade import export,polyhedra_utils
mat = PolyhedraMat()
O.bodies.append([
sphere((0,0,0),1),
sphere((0,3,0),1),
sphere((0,2,4),2),
sphere((0,5,2),1.5),
facet([Vector3(0,-3,-1),Vector3(0,-2,5),Vector3(5,4,0)]),
facet([Vector3(0,-3,-1),Vector3(0,-2,5),Vector3(-5,4,0)]),
polyhedra_utils.polyhedra(mat,(1,2,3),... | O.step()
vtkExporter = export.VTKExporter('vtkExporterTesting')
vtkExporter.exportSpheres(what=[('dist','b.state.pos.norm()')])
vtkExporter.exportFacets(what=[('pos','b.state.pos')])
vtkExporter.exportInteractions(what=[('kn','i.phys.kn')])
vtkExporter.exportPolyhedra(what=[('n','b.id')]) | random_line_split | |
lib.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Types for loading and managing AWS access credentials for API requests.
extern crate chrono;
extern crate reqwest;
extern crate regex;
extern... | (provider: P) -> Result<AutoRefreshingProviderSync<P>, CredentialsError> {
let creds = try!(provider.credentials());
Ok(BaseAutoRefreshingProvider {
credentials_provider: provider,
cached_credentials: Mutex::new(creds)
})
}
}
impl <P: ProvideAwsCredentials> ProvideAw... | with_mutex | identifier_name |
lib.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Types for loading and managing AWS access credentials for API requests.
extern crate chrono;
extern crate reqwest;
extern crate regex;
extern... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credential_chain_explicit_profile_provider() {
let profile_provider = ProfileProvider::with_configuration(
"tests/sample-data/multiple_profile_credentials",
"foo",
);
let chain = ChainProvider::with_profile... | {
match json_object.get(key) {
Some(v) => Ok(v.as_str().expect(&format!("{} value was not a string", key)).to_owned()),
None => Err(CredentialsError::new(format!("Couldn't find {} in response.", key))),
}
} | identifier_body |
lib.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Types for loading and managing AWS access credentials for API requests.
extern crate chrono;
extern crate reqwest;
extern crate regex;
extern... | &self.token
}
/// Determine whether or not the credentials are expired.
fn credentials_are_expired(&self) -> bool {
// This is a rough hack to hopefully avoid someone requesting creds then sitting on them
// before issuing the request:
self.expires_at < UTC::now() + Duration... |
/// Get a reference to the access token.
pub fn token(&self) -> &Option<String> { | random_line_split |
testmethods.py | import zmq
class JRPC:
def __init__(self):
self.id = 0
def make_noti(self, method, params=None):
noti = {"jsonrpc":"2.0", "method":method}
if params is not None:
noti["params"] = params
return noti
def make_req(self, method, params=None):
req = self.make_noti(method, params)
req["id"] = self.id
s... | req = jrpc.make_noti("foreach", a)
zsock.send_json(req)
rep = zsock.recv()
assert not rep | req = jrpc.make_noti("foreach", d)
zsock.send_json(req)
rep = zsock.recv()
assert not rep
| random_line_split |
testmethods.py | import zmq
class JRPC:
def __init__(self):
|
def make_noti(self, method, params=None):
noti = {"jsonrpc":"2.0", "method":method}
if params is not None:
noti["params"] = params
return noti
def make_req(self, method, params=None):
req = self.make_noti(method, params)
req["id"] = self.id
self.id += 1
return req
zctx = zmq.Context.instance()
zs... | self.id = 0 | identifier_body |
testmethods.py | import zmq
class JRPC:
def __init__(self):
self.id = 0
def make_noti(self, method, params=None):
noti = {"jsonrpc":"2.0", "method":method}
if params is not None:
noti["params"] = params
return noti
def make_req(self, method, params=None):
req = self.make_noti(method, params)
req["id"] = self.id
s... |
zsock.send_json(batchreq)
batchrep = zsock.recv_json()
for k in range(10):
assert(batchrep[k]['result']==sum(range(1+k)))
a = range(3)
o = {1:1, 2:2, 3:3}
d = { "one": "un", "two": 2, "three": 3.0, "four": True, "five": False, "six": None, "seven":a, "eight":o }
req = jrpc.make_noti("iterate", d)
zsock.send_json(re... | batchreq.append(jrpc.make_req("sum", range(1+k))) | conditional_block |
testmethods.py | import zmq
class JRPC:
def | (self):
self.id = 0
def make_noti(self, method, params=None):
noti = {"jsonrpc":"2.0", "method":method}
if params is not None:
noti["params"] = params
return noti
def make_req(self, method, params=None):
req = self.make_noti(method, params)
req["id"] = self.id
self.id += 1
return req
zctx = zmq.... | __init__ | identifier_name |
product.gears.js | var script = new Script();
function Product () {
this.showProductResult = function (){
var that = this;
$("#excelDataTable").find("tbody").remove(); | method: "POST",
url: "/product/result",
data: data,
complete: function(data){
if(data.status !== 500){
data = data.responseJSON;
data = JSON.parse(data);
console.log(data);
scr... | var data = {
ProductCount: $('#ProductCount').val(),
ProductCountry: $('#ProductCountry').val()
};
$.ajax({ | random_line_split |
product.gears.js | var script = new Script();
function | () {
this.showProductResult = function (){
var that = this;
$("#excelDataTable").find("tbody").remove();
var data = {
ProductCount: $('#ProductCount').val(),
ProductCountry: $('#ProductCountry').val()
};
$.ajax({
method: "POST",
... | Product | identifier_name |
product.gears.js | var script = new Script();
function Product () | {
this.showProductResult = function (){
var that = this;
$("#excelDataTable").find("tbody").remove();
var data = {
ProductCount: $('#ProductCount').val(),
ProductCountry: $('#ProductCountry').val()
};
$.ajax({
method: "POST",
ur... | identifier_body | |
product.gears.js | var script = new Script();
function Product () {
this.showProductResult = function (){
var that = this;
$("#excelDataTable").find("tbody").remove();
var data = {
ProductCount: $('#ProductCount').val(),
ProductCountry: $('#ProductCountry').val()
};
$.aj... | });
}
this.showAllProductCountry = function (){
var that = this;
$.ajax({
method: "GET",
url: "/product/country",
complete: function(data){
if(data.status !== 500){
data = data.responseJSON;
data = JSON.... | {
data = data.responseJSON;
data = JSON.parse(data);
var template = "{{#.}}" +
"<option>{{кількість одиниць виробу}}</option>" +
"{{/.}}";
var rendered = Mustache.render(template, data);
... | conditional_block |
cache_repair.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::input_arg::*;
use common::output_option::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: &str = concat!(
"cache_repair ",
include... |
}
impl<'a> OutputProgram<'a> for CacheRepair {
fn missing_output_arg() -> &'a str {
msg::MISSING_OUTPUT_ARG
}
}
impl<'a> MetadataWriter<'a> for CacheRepair {
fn file_not_found() -> &'a str {
msg::FILE_NOT_FOUND
}
}
//-----------------------------------------
test_accepts_help!(Cache... | {
"bad checksum in superblock"
} | identifier_body |
cache_repair.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::input_arg::*;
use common::output_option::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: &str = concat!(
"cache_repair ",
include... | impl<'a> OutputProgram<'a> for CacheRepair {
fn missing_output_arg() -> &'a str {
msg::MISSING_OUTPUT_ARG
}
}
impl<'a> MetadataWriter<'a> for CacheRepair {
fn file_not_found() -> &'a str {
msg::FILE_NOT_FOUND
}
}
//-----------------------------------------
test_accepts_help!(CacheRepa... | "bad checksum in superblock"
}
}
| random_line_split |
cache_repair.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::input_arg::*;
use common::output_option::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: &str = concat!(
"cache_repair ",
include... | () -> &'a str {
msg::FILE_NOT_FOUND
}
fn missing_input_arg() -> &'a str {
msg::MISSING_INPUT_ARG
}
fn corrupted_input() -> &'a str {
"bad checksum in superblock"
}
}
impl<'a> OutputProgram<'a> for CacheRepair {
fn missing_output_arg() -> &'a str {
msg::MISSING_... | file_not_found | identifier_name |
arena.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... |
}
#[cfg(test)]
mod test {
use super::{Arena, TypedArena};
use test::BenchHarness;
struct Point {
x: int,
y: int,
z: int,
}
#[test]
pub fn test_pod() {
let arena = TypedArena::new();
for _ in range(0, 1000000) {
arena.alloc(Point {
... | {
// Determine how much was filled.
let start = self.first.get_ref().start(self.tydesc) as uint;
let end = self.ptr as uint;
let diff = (end - start) / mem::size_of::<T>();
// Pass that to the `destroy` method.
unsafe {
let opt_tydesc = if intrinsics::needs_d... | identifier_body |
arena.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... |
// Walk down a chunk, running the destructors for any objects stored
// in it.
unsafe fn destroy_chunk(chunk: &Chunk) {
let mut idx = 0;
let buf = {
let data = chunk.data.borrow();
data.get().as_ptr()
};
let fill = chunk.fill.get();
while idx < fill {
let tydesc_data: *uint... | } | random_line_split |
arena.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... | () {
let arena = TypedArena::new();
for _ in range(0, 1000000) {
arena.alloc(Point {
x: 1,
y: 2,
z: 3,
});
}
}
#[bench]
pub fn bench_pod(bh: &mut BenchHarness) {
let arena = TypedArena::new();
bh... | test_pod | identifier_name |
arena.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... |
this.pod_head.fill.set(end);
//debug!("idx = {}, size = {}, align = {}, fill = {}",
// start, n_bytes, align, head.fill.get());
ptr::offset(this.pod_head.data.get().as_ptr(), start as int)
}
}
#[inline]
fn alloc_pod<'a, T>(&'a mut self, op: |... | {
return this.alloc_pod_grow(n_bytes, align);
} | conditional_block |
test__helpers.py | # Copyright 2014 Google Inc.
#
# 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, ... | from google.cloud.storage._helpers import _base64_md5hash
return _base64_md5hash(bytes_to_sign)
def test_it(self):
from io import BytesIO
BYTES_TO_SIGN = b'FOO'
BUFFER = BytesIO()
BUFFER.write(BYTES_TO_SIGN)
BUFFER.seek(0)
SIGNED_CONTENT = self._ca... |
def _call_fut(self, bytes_to_sign): | random_line_split |
test__helpers.py | # Copyright 2014 Google Inc.
#
# 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, ... | (object):
def _patch_property(self, name, value):
self._patched = (name, value)
do_re_mi = self._call_fut('solfege')
test = Test()
test.do_re_mi = 'Latido'
self.assertEqual(test._patched, ('solfege', 'Latido'))
class Test__base64_md5hash(unittest.TestCa... | Test | identifier_name |
test__helpers.py | # Copyright 2014 Google Inc.
#
# 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, ... |
test = Test(solfege='Latido')
self.assertEqual(test.do_re_mi, 'Latido')
def test_setter(self):
class Test(object):
def _patch_property(self, name, value):
self._patched = (name, value)
do_re_mi = self._call_fut('solfege')
test = Test()
... | def __init__(self, **kw):
self._properties = kw.copy()
do_re_mi = self._call_fut('solfege') | identifier_body |
db_logger.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Smile (<http://www.smile.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... |
@add_timing
def time_debug(self, msg):
self._logger.debug(msg, self._logger_args)
| self._logger.info(msg, self._logger_args) | identifier_body |
db_logger.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Smile (<http://www.smile.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | (self, msg):
self._logger.error(msg, self._logger_args)
@add_trace
def critical(self, msg):
self._logger.critical(msg, self._logger_args)
@add_trace
def exception(self, msg):
self._logger.exception(msg, self._logger_args)
@add_timing
def time_info(self, msg):
s... | error | identifier_name |
db_logger.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Smile (<http://www.smile.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... |
@add_trace
def critical(self, msg):
self._logger.critical(msg, self._logger_args)
@add_trace
def exception(self, msg):
self._logger.exception(msg, self._logger_args)
@add_timing
def time_info(self, msg):
self._logger.info(msg, self._logger_args)
@add_timing
de... | def error(self, msg):
self._logger.error(msg, self._logger_args) | random_line_split |
db_logger.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Smile (<http://www.smile.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... |
cr.execute("select nextval('smile_log_seq')")
res = cr.fetchone()
pid = res and res[0] or 0
finally:
cr.close()
self._logger_start = datetime.datetime.now()
self._logger_args = {'dbname': dbname, 'model_name': model_name, 'res_id': res_id, 'uid':... | cr.execute("create sequence smile_log_seq") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.