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 |
|---|---|---|---|---|
test-amp-vk.js | /**
* Copyright 2017 The AMP HTML Authors. 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 require... | (dataParams, layout) {
const element = doc.createElement('amp-vk');
for (const param in dataParams) {
element.setAttribute(`data-${param}`, dataParams[param]);
}
element.setAttribute('width', 500);
element.setAttribute('height', 300);
if (layout) {
element.setAttribute('layout', l... | createAmpVkElement | identifier_name |
test-amp-vk.js | /**
* Copyright 2017 The AMP HTML Authors. 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 require... |
doc.body.appendChild(element);
return element.build().then(() => {
const resource = Resource.forElement(element);
resource.measure();
return element.layoutCallback();
}).then(() => element);
}
it('requires data-embedtype', () => {
const params = Object.assign({}, POST_PARAMS);
... | {
element.setAttribute('layout', layout);
} | conditional_block |
test-amp-vk.js | /**
* Copyright 2017 The AMP HTML Authors. 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 require... |
it('requires data-embedtype', () => {
const params = Object.assign({}, POST_PARAMS);
delete params['embedtype'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-embedtype attribute is required for/);
});
it('removes iframe after unlayoutCallback', () => {
... | {
const element = doc.createElement('amp-vk');
for (const param in dataParams) {
element.setAttribute(`data-${param}`, dataParams[param]);
}
element.setAttribute('width', 500);
element.setAttribute('height', 300);
if (layout) {
element.setAttribute('layout', layout);
}
do... | identifier_body |
Account.js | module.exports = function(config, mongoose, nodemailer) {
var crypto = require('crypto');
var Status = new mongoose.Schema({
name: {
first: { type: String },
last: { type: String }
},
status: { type: String }
});
var Contact = new mongoose.Schema(... | return console.log('Account was created');
};
var changePassword = function(accountId, newpassword) {
var shaSum = crypto.createHash('sha256');
shaSum.update(newpassword);
var hashedPassword = shaSum.digest('hex');
Account.update({_id:accountId},
{
... | } | random_line_split |
Account.js | module.exports = function(config, mongoose, nodemailer) {
var crypto = require('crypto');
var Status = new mongoose.Schema({
name: {
first: { type: String },
last: { type: String }
},
status: { type: String }
});
var Contact = new mongoose.Schema(... |
return console.log('Account was created');
};
var changePassword = function(accountId, newpassword) {
var shaSum = crypto.createHash('sha256');
shaSum.update(newpassword);
var hashedPassword = shaSum.digest('hex');
Account.update({_id:accountId},
{
... | {
return console.log(err);
} | conditional_block |
TestClass4.ts | import { ReducerOf } from '../../src/ReducerOf'
import { State } from '../helpers/State'
import { HandlerOf } from '../../src/HandlerOf'
import * as Constants from './constants'
import { Action, Store } from 'redux'
import { ActionsObservable } from 'redux-observable'
import 'rxjs/add/operator/map'
export const ACTION... |
} | {
return action$.map(action => { return { type: ACTION_TYPE1_FROM_BAR2 } })
} | identifier_body |
TestClass4.ts | import { ReducerOf } from '../../src/ReducerOf'
import { State } from '../helpers/State'
import { HandlerOf } from '../../src/HandlerOf'
import * as Constants from './constants'
import { Action, Store } from 'redux'
import { ActionsObservable } from 'redux-observable'
import 'rxjs/add/operator/map'
export const ACTION... | (state: Array<string> = [], action: Action) {
return [...state, 'foo1']
}
foo2(state: Array<string> = [], action: Action) {
return [...state, 'foo2']
}
@ReducerOf([Constants.ACTION_TYPE1])
foo3(state: Array<string> = [], action: Action) {
return [...state, 'foo3']
}
... | foo1 | identifier_name |
TestClass4.ts | import { ReducerOf } from '../../src/ReducerOf'
import { State } from '../helpers/State'
import { HandlerOf } from '../../src/HandlerOf'
import * as Constants from './constants'
import { Action, Store } from 'redux'
import { ActionsObservable } from 'redux-observable'
import 'rxjs/add/operator/map'
export const ACTION... |
} | return action$.map(action => { return { type: ACTION_TYPE1_FROM_BAR2 } })
}
| random_line_split |
constants.py | # Copyright (c) 2012 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | # ovs_cleanup script is used.
SKIP_CLEANUP = 'skip_cleanup' |
# Used in ovs port 'external_ids' in order mark it for no cleanup when | random_line_split |
findMainFile.js | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
'use strict';
const glob = require('glob');
const path = require('path');
/**
* Find the main file for the C# project
*
* @param {String} folder Name of the folder where to seek
* @return {String}
*/
module.ex... |
return mainFilePath && mainFilePath.length > 0 ? path.join(folder, mainFilePath[0]) : null;
};
| {
mainFilePath = glob.sync('MainPage.cs', {
cwd: folder,
ignore: ['node_modules/**', '**/build/**', 'Examples/**', 'examples/**'],
});
} | conditional_block |
findMainFile.js | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
'use strict';
const glob = require('glob');
const path = require('path');
/**
* Find the main file for the C# project
*
* @param {String} folder Name of the folder where to seek
* @return {String}
*/
module.ex... | ignore: ['node_modules/**', '**/build/**', 'Examples/**', 'examples/**'],
});
}
return mainFilePath && mainFilePath.length > 0 ? path.join(folder, mainFilePath[0]) : null;
}; |
if (mainFilePath.length === 0) {
mainFilePath = glob.sync('MainPage.cs', {
cwd: folder, | random_line_split |
Flickr.js | /* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2009 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/d... | /* ***********************************************
* LIST OF PHOTOS
* ********************************************* */
var list = new qx.ui.form.List();
list.setWidth(700);
list.setHeight(110);
list.setOrientation("horizontal");
this.getRoot().add(list, {left: 30, right... | store.bind("state", status, "value");
| random_line_split |
Flickr.js | /* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2009 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/d... |
},
__generateUrl: function(tag) {
if (!tag) {
return;
}
var url = "http://api.flickr.com/services/rest/?tags=" + tag;
url += "&method=flickr.photos.search&api_key=63a8042eead205f7e0040f488c02afd9&format=json";
return url;
}
}
});
| {
this.setUrl(this.__generateUrl(tag));
} | conditional_block |
fontfamilycelleditor.js | /**
*
*/
;
(function ($, window, document, undefined) {
var pluginName = "fontFamilyCellEditor";
var defaults = {
parent: "",
msg: "",
};
var MbSelectCellEditor = function (element, options) {
this.element = element;
this.options = $.extend({
parent: "",
... | {
selection.focus();
return false;
}
})
};
MbSelectCellEditor.prototype.changeValue = function (tag, entity, prop,
oldvalue, isnull, owner) {
var newvalue = $(tag).children("select").val();
... | selection.remove();
} else | conditional_block |
fontfamilycelleditor.js | /**
*
*/
;
(function ($, window, document, undefined) {
var pluginName = "fontFamilyCellEditor";
var defaults = {
parent: "",
msg: "",
};
var MbSelectCellEditor = function (element, options) {
this.element = element;
this.options = $.extend({
parent: "",
... |
})(jQuery, window, document); | $.data(this, pluginName)[options]();
}
});
}; | random_line_split |
remote.rs | use std::cell::{RefCell, Ref, Cell};
use std::io::SeekFrom;
use std::io::prelude::*;
use std::mem;
use std::path::Path;
use curl::easy::{Easy, List};
use git2;
use hex::ToHex;
use serde_json;
use url::Url;
use core::{PackageId, SourceId};
use ops;
use sources::git;
use sources::registry::{RegistryData, RegistryConfig... | (&self) -> CargoResult<&git2::Repository> {
self.repo.get_or_try_init(|| {
let path = self.index_path.clone().into_path_unlocked();
// Fast path without a lock
if let Ok(repo) = git2::Repository::open(&path) {
return Ok(repo)
}
// Ok,... | repo | identifier_name |
remote.rs | use std::cell::{RefCell, Ref, Cell};
use std::io::SeekFrom;
use std::io::prelude::*;
use std::mem;
use std::path::Path;
use curl::easy::{Easy, List};
use git2;
use hex::ToHex;
use serde_json;
use url::Url;
use core::{PackageId, SourceId};
use ops;
use sources::git;
use sources::registry::{RegistryData, RegistryConfig... |
fn download(&mut self, pkg: &PackageId, checksum: &str)
-> CargoResult<FileLock> {
let filename = format!("{}-{}.crate", pkg.name(), pkg.version());
let path = Path::new(&filename);
// Attempt to open an read-only copy first to avoid an exclusive write
// lock and ... | {
// Ensure that we'll actually be able to acquire an HTTP handle later on
// once we start trying to download crates. This will weed out any
// problems with `.cargo/config` configuration related to HTTP.
//
// This way if there's a problem the error gets printed before we even
... | identifier_body |
remote.rs | use std::cell::{RefCell, Ref, Cell};
use std::io::SeekFrom;
use std::io::prelude::*;
use std::mem;
use std::path::Path;
use curl::easy::{Easy, List};
use git2;
use hex::ToHex;
use serde_json;
use url::Url;
use core::{PackageId, SourceId};
use ops;
use sources::git;
use sources::registry::{RegistryData, RegistryConfig... |
let repo = self.repo()?;
let _lock = self.index_path.open_rw(Path::new(INDEX_LOCK),
self.config,
"the registry index")?;
self.config.shell().status("Updating",
format!("registry `{}`", self.sour... | ops::http_handle(self.config)?; | random_line_split |
remote.rs | use std::cell::{RefCell, Ref, Cell};
use std::io::SeekFrom;
use std::io::prelude::*;
use std::mem;
use std::path::Path;
use curl::easy::{Easy, List};
use git2;
use hex::ToHex;
use serde_json;
use url::Url;
use core::{PackageId, SourceId};
use ops;
use sources::git;
use sources::registry::{RegistryData, RegistryConfig... |
}
}
if needs_fetch {
// git fetch origin master
let url = self.source_id.url().to_string();
let refspec = "refs/heads/master:refs/remotes/origin/master";
git::fetch(&repo, &url, refspec, self.config).chain_err(|| {
format!("fa... | {
debug!("fast path failed, falling back to a git fetch");
} | conditional_block |
covidien_common.js | var filter_specialChars = "^[a-zA-Z0-9-_@\. ]+$";
var filter_specialChars_date = "^[0-9\/ ]+$";
$(document).ready(function(){
// For Menu Highlight - Covidien Brackets
var identifier = window.location.pathname;
var split = identifier.split("/");
var vTitle = $(this).attr('title').split("|");
function | ($ustring){
return $.inArray($ustring, split)> -1;
}
if (vTitle[0]=="User Settings ") {
//anch_user_settings
$('#anch_user_settings').after("<span class='T10C11'> ]</span>");
$('#anch_user_settings').before("<span class='T10C11'>[ </span>");
}
else if (check_url('node') && check_url('edit') && vTi... | check_url | identifier_name |
covidien_common.js | var filter_specialChars = "^[a-zA-Z0-9-_@\. ]+$";
var filter_specialChars_date = "^[0-9\/ ]+$";
$(document).ready(function(){
// For Menu Highlight - Covidien Brackets
var identifier = window.location.pathname;
var split = identifier.split("/");
var vTitle = $(this).attr('title').split("|");
function check_ur... |
$('#anch_devices').attr('class','active');
$('#anch_devices').after("<span class='T10C2'> ]</span>");
$('#anch_devices').before("<span class='T10C2'>[ </span>");
}
else if (check_url('reports') || check_url('report') ) {
//anch_devices
$('#anch_reports').attr('class','active');
$('#anch_reports'... | { $('#content-part').attr('style','border:0'); } | conditional_block |
covidien_common.js | var filter_specialChars = "^[a-zA-Z0-9-_@\. ]+$";
var filter_specialChars_date = "^[0-9\/ ]+$";
$(document).ready(function(){
// For Menu Highlight - Covidien Brackets
var identifier = window.location.pathname;
var split = identifier.split("/");
var vTitle = $(this).attr('title').split("|");
function check_ur... |
if (vTitle[0]=="User Settings ") {
//anch_user_settings
$('#anch_user_settings').after("<span class='T10C11'> ]</span>");
$('#anch_user_settings').before("<span class='T10C11'>[ </span>");
}
else if (check_url('node') && check_url('edit') && vTitle[0]!="User Settings ") {
//For edit catalogs
$(... | {
return $.inArray($ustring, split)> -1;
} | identifier_body |
covidien_common.js | var filter_specialChars = "^[a-zA-Z0-9-_@\. ]+$";
var filter_specialChars_date = "^[0-9\/ ]+$";
$(document).ready(function(){
// For Menu Highlight - Covidien Brackets
var identifier = window.location.pathname;
var split = identifier.split("/");
var vTitle = $(this).attr('title').split("|");
function check_ur... | $('#anch_system_admin').before("<span class='T10C2'>[ </span>");
}
else if (check_url('covidien') && check_url('home')) {
//anch_home
$('#content-part').attr('style','border:0');
$('#anch_home').attr('class','active');
$('#anch_home').after("<span class='T10C2'> ]</span>");
$('#anch_home').befor... | }
else if (check_url('node') && check_url('edit') && vTitle[0]!="User Settings ") {
//For edit catalogs
$('#anch_system_admin').attr('class','active');
$('#anch_system_admin').after("<span class='T10C2'> ]</span>"); | random_line_split |
test-define-put.js | var assert = require('chai').assert;
var user = require('../util/models/user');
var util = require('./rest-builder-util');
var putObj = {
key: 'value'
};
var putData = {
q: putObj
};
describe('RestBuilder', function() {
describe('definePut', function() {
util.setUp(); | describe('no processors', function() {
it('should call db.del', function(done) {
this.rb.definePut('users', user, [], []);
this.client.put('/users/1', putData, function(err, req, res) {
assert.ifError(err);
util.mockDB.update.assertCalledOnceWithArgsIncluding(
[... | random_line_split | |
linedlg.py | # Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 1999, 2001, 2002 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2... |
return gc, bitmap, images
_arrow_width = 31
_arrow_height = 25
_mirror = Trafo(-1, 0, 0, 1, 0, 0)
def draw_arrow_bitmap(gc, arrow, which = 2):
gc.gc.foreground = 0
gc.gc.FillRectangle(0, 0, _arrow_width + 1, _arrow_height + 1)
gc.gc.foreground = 1
y = _arrow_height / 2
if which == 1:
... | draw_dash_bitmap(gc, dash)
image = create_bitmap_image(tk, 'dash_' + `len(images)`, bitmap)
images.append((image, dash)) | conditional_block |
linedlg.py | # Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 1999, 2001, 2002 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2... | (tk, tkwin, arrows):
arrows = [None] + arrows
bitmap = tkwin.CreatePixmap(_arrow_width, _arrow_height, 1)
gc = SimpleGC()
gc.init_gc(bitmap, foreground = 1, background = 0, line_width = 3)
gc.Translate(_arrow_width / 2, _arrow_height / 2)
gc.Scale(2)
images1 = []
for arrow in arrows:
... | create_arrow_images | identifier_name |
linedlg.py | # Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 1999, 2001, 2002 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2... |
def Update(self):
if self.document.HasSelection():
properties = self.document.CurrentProperties()
self.init_from_style(properties)
def do_apply(self):
kw = {}
if not self.var_color_none.get():
color = self.color_but.Color()
kw["line_patt... | self.Update() | identifier_body |
linedlg.py | # Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 1999, 2001, 2002 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2... | self.init_from_style(obj.Properties()) | random_line_split | |
main.js | ;
(function() {
var app = angular.module('dashboardApp', [
'ngRoute',
'dashboard'
]);
var dashboard = angular.module('dashboard', []);
dashboard.run(function($rootScope, invocationUtils, stringUtils, api, urls) {
$rootScope.invocationUtils = invocationUtils;
$rootScope... | templateUrl: 'app/views/FunctionsHome.html',
controller: 'FunctionsHomeController'
}).
when('/functions/definitions/:functionId', {
templateUrl: 'app/views/Function.html',
controller: 'FunctionController'
... | templateUrl: 'app/views/TriggeredJobRun.html',
controller: 'TriggeredJobRunController'
}).
when('/functions', { | random_line_split |
inline-closure.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
// END RUST SOURCE
// START rustc.foo.Inline.after.mir
// ...
// bb0: {
// ...
// _3 = [closure@NodeId(39)];
// ...
// _4 = &_3;
// ...
// _6 = _2;
// ...
// _7 = _2;
// _5 = (move _6, move _7);
// _8 = move (_5.0: i32);
// _9 = move (_5.1: i32);
// _0 = _8;
// ...
... | {
let x = |_t, _q| _t;
x(q, q)
} | identifier_body |
inline-closure.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
println!("{}", foo(0, 14));
}
fn foo<T: Copy>(_t: T, q: i32) -> i32 {
let x = |_t, _q| _t;
x(q, q)
}
// END RUST SOURCE
// START rustc.foo.Inline.after.mir
// ...
// bb0: {
// ...
// _3 = [closure@NodeId(39)];
// ...
// _4 = &_3;
// ...
// _6 = _2;
// ...
// _7 = _2;
/... | main | identifier_name |
inline-closure.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | x(q, q)
}
// END RUST SOURCE
// START rustc.foo.Inline.after.mir
// ...
// bb0: {
// ...
// _3 = [closure@NodeId(39)];
// ...
// _4 = &_3;
// ...
// _6 = _2;
// ...
// _7 = _2;
// _5 = (move _6, move _7);
// _8 = move (_5.0: i32);
// _9 = move (_5.1: i32);
// _0 = _8... | random_line_split | |
setup.py | #!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def | ():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list
packages = find_packages(exclude=['tests*'])
with codecs.o... | requirements | identifier_name |
setup.py | #!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def requirements():
|
packages = find_packages(exclude=['tests*'])
with codecs.open('README.rst', 'r', 'utf-8') as fd:
fn = os.path.join('telegram', 'version.py')
with open(fn) as fh:
code = compile(fh.read(), fn, 'exec')
exec(code)
setup(name='python-telegram-bot',
version=__version__,
a... | """Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list | identifier_body |
setup.py | #!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def requirements():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
... | code = compile(fh.read(), fn, 'exec')
exec(code)
setup(name='python-telegram-bot',
version=__version__,
author='Leandro Toledo',
author_email='devs@python-telegram-bot.org',
license='LGPLv3',
url='https://python-telegram-bot.org/',
keyword... | with codecs.open('README.rst', 'r', 'utf-8') as fd:
fn = os.path.join('telegram', 'version.py')
with open(fn) as fh: | random_line_split |
setup.py | #!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def requirements():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
... |
return requirements_list
packages = find_packages(exclude=['tests*'])
with codecs.open('README.rst', 'r', 'utf-8') as fd:
fn = os.path.join('telegram', 'version.py')
with open(fn) as fh:
code = compile(fh.read(), fn, 'exec')
exec(code)
setup(name='python-telegram-bot',
ve... | requirements_list.append(install.strip()) | conditional_block |
lib.rs | #![crate_name="otp"]
#![crate_type="lib"]
use std::time::{SystemTime, SystemTimeError};
use std::convert::TryInto;
use data_encoding::{BASE32_NOPAD, DecodeError};
use err_derive::Error;
use ring::hmac;
#[derive(Debug, Error)]
pub enum Error {
#[error(display="invalid time provided")]
InvalidTimeError(#[error(... |
/// Performs the [HMAC-based One-time Password Algorithm](http://en.wikipedia.org/wiki/HMAC-based_One-time_Password_Algorithm)
/// (HOTP) given an RFC4648 base32 encoded secret, and an integer counter.
pub fn make_hotp(secret: &str, counter: u64) -> Result<u32, Error> {
let decoded = decode_secret(secret)?;
e... | {
let offset = match digest.last() {
Some(x) => *x & 0xf,
None => return Err(Error::InvalidDigest(Vec::from(digest)))
} as usize;
let code_bytes: [u8; 4] = match digest[offset..offset+4].try_into() {
Ok(x) => x,
Err(_) => return Err(Error::InvalidDigest(Vec::from(digest)))
... | identifier_body |
lib.rs | #![crate_name="otp"]
#![crate_type="lib"]
use std::time::{SystemTime, SystemTimeError};
use std::convert::TryInto;
use data_encoding::{BASE32_NOPAD, DecodeError};
use err_derive::Error;
use ring::hmac;
#[derive(Debug, Error)]
pub enum Error {
#[error(display="invalid time provided")]
InvalidTimeError(#[error(... | (secret: &str, time_step: u64, skew: i64, time: u64) -> Result<u32, Error> {
let counter = ((time as i64 + skew) as u64) / time_step;
make_hotp(secret, counter)
}
/// Performs the [Time-based One-time Password Algorithm](http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm)
/// (TOTP) given an R... | make_totp_helper | identifier_name |
lib.rs | #![crate_name="otp"]
#![crate_type="lib"]
use std::time::{SystemTime, SystemTimeError};
use std::convert::TryInto;
use data_encoding::{BASE32_NOPAD, DecodeError};
use err_derive::Error;
use ring::hmac;
#[derive(Debug, Error)]
pub enum Error {
#[error(display="invalid time provided")]
InvalidTimeError(#[error(... | assert_eq!(make_totp_helper("BASE32SECRET3232", 1, -2, 1403).unwrap(), 316439);
}
} | assert_eq!(make_totp_helper("BASE32SECRET3232", 3600, 0, 7).unwrap(), 260182);
assert_eq!(make_totp_helper("BASE32SECRET3232", 30, 0, 35).unwrap(), 55283); | random_line_split |
GenericMeetingPanel.tsx | import sleep from 'ringcentral-integration/lib/sleep';
import React, { useState } from 'react';
import SpinnerOverlay from '../SpinnerOverlay';
import MeetingConfigs from '../MeetingConfigs';
import isSafari from '../../lib/isSafari';
import { VideoConfig, Topic } from '../VideoPanel/VideoConfig';
import { GenericMee... | ,
disabled: false,
showWhen: true,
showDuration: true,
showRecurringMeeting: true,
openNewWindow: true,
meetingOptionToggle: false,
passwordPlaceholderEnable: false,
audioOptionToggle: false,
onOK: undefined,
scheduleButton: undefined,
showSaveAsDefault: true,
showCustom: false,
showLaunchMeet... | {} | identifier_body |
GenericMeetingPanel.tsx | import sleep from 'ringcentral-integration/lib/sleep';
import React, { useState } from 'react';
import SpinnerOverlay from '../SpinnerOverlay';
import MeetingConfigs from '../MeetingConfigs';
import isSafari from '../../lib/isSafari';
import { VideoConfig, Topic } from '../VideoPanel/VideoConfig';
import { GenericMee... |
const {
meeting,
disabled,
currentLocale,
scheduleButton: ScheduleButton,
recipientsSection,
showWhen,
showDuration,
showRecurringMeeting,
openNewWindow,
meetingOptionToggle,
passwordPlaceholderEnable,
audioOptionToggle,
onOK,
init,
showSaveAsDefault,
... | {
return CustomPanel as JSX.Element;
} | conditional_block |
GenericMeetingPanel.tsx | import sleep from 'ringcentral-integration/lib/sleep';
import React, { useState } from 'react';
import SpinnerOverlay from '../SpinnerOverlay';
import MeetingConfigs from '../MeetingConfigs';
import isSafari from '../../lib/isSafari';
import { VideoConfig, Topic } from '../VideoPanel/VideoConfig';
import { GenericMee... | timePickerSize,
showLaunchMeetingBtn,
launchMeeting,
scheduleButtonLabel,
appCode,
schedule,
brandName,
personalMeetingId,
} = props;
if (!isRCM && !isRCV) {
return <SpinnerOverlay />;
}
// TODO: fix lint issue here
// eslint-disable-next-line react-hooks/rules-of-hooks
... | validatePasswordSettings,
isRCM,
isRCV,
datePickerSize, | random_line_split |
GenericMeetingPanel.tsx | import sleep from 'ringcentral-integration/lib/sleep';
import React, { useState } from 'react';
import SpinnerOverlay from '../SpinnerOverlay';
import MeetingConfigs from '../MeetingConfigs';
import isSafari from '../../lib/isSafari';
import { VideoConfig, Topic } from '../VideoPanel/VideoConfig';
import { GenericMee... | () {},
disabled: false,
showWhen: true,
showDuration: true,
showRecurringMeeting: true,
openNewWindow: true,
meetingOptionToggle: false,
passwordPlaceholderEnable: false,
audioOptionToggle: false,
onOK: undefined,
scheduleButton: undefined,
showSaveAsDefault: true,
showCustom: false,
showLaunc... | launchMeeting | identifier_name |
account_tax_registry.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Agile Business Group
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the L... | class AccountTaxRegistry(models.Model):
_name = 'account.tax.registry'
name = fields.Char('Name', required=True)
company_id = fields.Many2one(
'res.company', 'Company', required=True,
default=lambda self: self.env['res.company']._company_default_get(
'account.tax.registry'))
... | from openerp import models, fields
| random_line_split |
account_tax_registry.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Agile Business Group
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the L... | _name = 'account.tax.registry'
name = fields.Char('Name', required=True)
company_id = fields.Many2one(
'res.company', 'Company', required=True,
default=lambda self: self.env['res.company']._company_default_get(
'account.tax.registry'))
journal_ids = fields.One2many(
'acco... | identifier_body | |
account_tax_registry.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Agile Business Group
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the L... | (models.Model):
_name = 'account.tax.registry'
name = fields.Char('Name', required=True)
company_id = fields.Many2one(
'res.company', 'Company', required=True,
default=lambda self: self.env['res.company']._company_default_get(
'account.tax.registry'))
journal_ids = fields.One... | AccountTaxRegistry | identifier_name |
models.py | from django.db import models
from django.db import models
from django.utils.translation import ugettext as _
# from django.core.urlresolvers import reverse_lazy, reverse
from django.conf import settings
from projects.models import Project, Customer
class Report (models.Model):
HIGHLIGHT = 'HL'
LOWLIGHT =... |
class CustomerReport (Report):
target = models.ForeignKey (Customer, related_name='reports')
class Meta:
verbose_name = _('Customer report')
verbose_name_plural = _('Customer reports')
| verbose_name = _('Project report')
verbose_name_plural = _('Project reports') | identifier_body |
models.py | from django.db import models
from django.db import models
from django.utils.translation import ugettext as _
# from django.core.urlresolvers import reverse_lazy, reverse
from django.conf import settings
from projects.models import Project, Customer
class Report (models.Model):
HIGHLIGHT = 'HL'
LOWLIGHT =... | (self):
return self.title
#return str(self.project) + (self.title if len(self.title) < 30 else (self.title[:27]+'...'))
return mark_safe("<b>%s</b>: %s" % (self.project, self.title))
# def get_absolute_url (self):
# return reverse('reporting-detail', args=[str(self.id)])
class Pro... | __str__ | identifier_name |
models.py | from django.db import models
from django.db import models
from django.utils.translation import ugettext as _
# from django.core.urlresolvers import reverse_lazy, reverse
from django.conf import settings
from projects.models import Project, Customer
class Report (models.Model):
HIGHLIGHT = 'HL'
LOWLIGHT =... | return mark_safe("<b>%s</b>: %s" % (self.project, self.title))
# def get_absolute_url (self):
# return reverse('reporting-detail', args=[str(self.id)])
class ProjectReport (Report):
target = models.ForeignKey (Project, related_name='reports')
class Meta:
verbose_name = _('Project... | #return str(self.project) + (self.title if len(self.title) < 30 else (self.title[:27]+'...'))
| random_line_split |
allocation.py | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... | self.dealloc(start, size)
return result
def dealloc(self, start, size):
"""Free a region of the buffer.
:Parameters:
`start` : int
Starting index of the region.
`size` : int
Size of the region.
"""
assert size... | random_line_split | |
allocation.py | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... |
free_end = self.capacity - (self.starts[-1] + self.sizes[-1])
return self.get_fragmented_free_size() + free_end
def get_usage(self):
"""Return fraction of capacity currently allocated.
:rtype: float
"""
return 1. - self.get_free_size() / float(self.capacity)
... | return self.capacity | conditional_block |
allocation.py | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... | (Exception):
"""The buffer is not large enough to fulfil an allocation.
Raised by `Allocator` methods when the operation failed due to lack of
buffer space. The buffer should be increased to at least
requested_capacity and then the operation retried (guaranteed to
pass second time).
"""
... | AllocatorMemoryException | identifier_name |
allocation.py | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... |
def __str__(self):
return 'allocs=' + repr(list(zip(self.starts, self.sizes)))
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, str(self))
| return not self.starts | identifier_body |
test_mlresult.py | import os
import unittest
import numpy as np
from tfsnippet.examples.utils import MLResults
from tfsnippet.utils import TemporaryDirectory
def head_of_file(path, n):
with open(path, 'rb') as f:
return f.read(n)
class MLResultTestCase(unittest.TestCase):
def test_imwrite(self):
| with TemporaryDirectory() as tmpdir:
results = MLResults(tmpdir)
im = np.zeros([32, 32], dtype=np.uint8)
im[16:, ...] = 255
results.save_image('test.bmp', im)
file_path = os.path.join(tmpdir, 'test.bmp')
self.assertTrue(os.path.isfile(file_path))
... | identifier_body | |
test_mlresult.py | import os
import unittest
import numpy as np
from tfsnippet.examples.utils import MLResults
from tfsnippet.utils import TemporaryDirectory | with open(path, 'rb') as f:
return f.read(n)
class MLResultTestCase(unittest.TestCase):
def test_imwrite(self):
with TemporaryDirectory() as tmpdir:
results = MLResults(tmpdir)
im = np.zeros([32, 32], dtype=np.uint8)
im[16:, ...] = 255
results.... |
def head_of_file(path, n): | random_line_split |
test_mlresult.py | import os
import unittest
import numpy as np
from tfsnippet.examples.utils import MLResults
from tfsnippet.utils import TemporaryDirectory
def head_of_file(path, n):
with open(path, 'rb') as f:
return f.read(n)
class MLResultTestCase(unittest.TestCase):
def | (self):
with TemporaryDirectory() as tmpdir:
results = MLResults(tmpdir)
im = np.zeros([32, 32], dtype=np.uint8)
im[16:, ...] = 255
results.save_image('test.bmp', im)
file_path = os.path.join(tmpdir, 'test.bmp')
self.assertTrue(os.path.isf... | test_imwrite | identifier_name |
test_sequence.py | import os
import re
from nose.tools import raises
import seqpoet
class TestSequence:
def setup(self):
self.seq1 = 'ACATacacagaATAgagaCacata'
self.illegal = 'agagcatgcacthisisnotcorrect'
def test_sequence_length(self):
s = seqpoet.Sequence(self.seq1)
assert len(s) == len(self... | s = seqpoet.Sequence(self.illegal) | identifier_body | |
test_sequence.py | import os
import re
from nose.tools import raises
import seqpoet
class TestSequence:
def setup(self):
self.seq1 = 'ACATacacagaATAgagaCacata'
self.illegal = 'agagcatgcacthisisnotcorrect'
def test_sequence_length(self):
s = seqpoet.Sequence(self.seq1)
assert len(s) == len(self... | assert str(s) == self.seq1.lower()
def test_repr(self):
s = seqpoet.Sequence(self.seq1)
assert repr(s) == '<Sequence: acata...>'
assert repr(s.revcomp()) == '<Sequence: tatgt...>'
def test_indexing(self):
s = seqpoet.Sequence(self.seq1)
assert s[4] == 'a'
... | s = seqpoet.Sequence(self.seq1) | random_line_split |
test_sequence.py | import os
import re
from nose.tools import raises
import seqpoet
class TestSequence:
def setup(self):
self.seq1 = 'ACATacacagaATAgagaCacata'
self.illegal = 'agagcatgcacthisisnotcorrect'
def test_sequence_length(self):
s = seqpoet.Sequence(self.seq1)
assert len(s) == len(self... | (self):
s = seqpoet.Sequence(self.seq1)
assert str(s) == self.seq1.lower()
def test_repr(self):
s = seqpoet.Sequence(self.seq1)
assert repr(s) == '<Sequence: acata...>'
assert repr(s.revcomp()) == '<Sequence: tatgt...>'
def test_indexing(self):
s = seqpoet.Seque... | test_str | identifier_name |
Result.ts | import { Cache, StateObject } from "../../collections/stateful";
import { exists } from "../../util/object";
import { parseXSD, XSDSchema } from "../../util/SAXParser";
import { DFULogicalFile } from "../services/WsDFU";
import { ECLResult, ECLSchemas, Service, WUResultRequest, WUResultResponse } from "../services/WsWo... | (): number { return this.get("Total"); }
get ECLSchemas(): ECLSchemas { return this.get("ECLSchemas"); }
get NodeGroup(): string { return this.get("NodeGroup"); }
get ResultViews(): any[] { return this.get("ResultViews"); }
constructor(connection: Service | string, wuid: string, eclResult: ECLResult, r... | Total | identifier_name |
Result.ts | import { Cache, StateObject } from "../../collections/stateful";
import { exists } from "../../util/object";
import { parseXSD, XSDSchema } from "../../util/SAXParser";
import { DFULogicalFile } from "../services/WsDFU";
import { ECLResult, ECLSchemas, Service, WUResultRequest, WUResultResponse } from "../services/WsWo... |
get NodeGroup(): string { return this.get("NodeGroup"); }
get ResultViews(): any[] { return this.get("ResultViews"); }
constructor(connection: Service | string, wuid: string, eclResult: ECLResult, resultViews: any[]) {
super();
if (connection instanceof Service) {
this.connecti... | { return this.get("ECLSchemas"); } | identifier_body |
Result.ts | import { Cache, StateObject } from "../../collections/stateful";
import { exists } from "../../util/object";
import { parseXSD, XSDSchema } from "../../util/SAXParser";
import { DFULogicalFile } from "../services/WsDFU";
import { ECLResult, ECLSchemas, Service, WUResultRequest, WUResultResponse } from "../services/WsWo... |
return this.WUResult().then((response) => {
if (exists("Result.XmlSchema.xml", response)) {
this.xsdSchema = parseXSD(response.Result.XmlSchema.xml);
return this.xsdSchema;
}
return this;
});
}
fetchResult(): Promise<any[]> {
... | {
return Promise.resolve(this.xsdSchema);
} | conditional_block |
Result.ts | import { Cache, StateObject } from "../../collections/stateful";
import { exists } from "../../util/object";
import { parseXSD, XSDSchema } from "../../util/SAXParser";
import { DFULogicalFile } from "../services/WsDFU";
import { ECLResult, ECLSchemas, Service, WUResultRequest, WUResultResponse } from "../services/WsWo... | }
isComplete() {
return this.Total !== -1;
}
fetchXMLSchema(): Promise<XSDSchema> {
if (this.xsdSchema) {
return Promise.resolve(this.xsdSchema);
}
return this.WUResult().then((response) => {
if (exists("Result.XmlSchema.xml", response)) {
... | ResultViews: resultViews,
...eclResult
}); | random_line_split |
util.rs | // Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modifi... | let mut parts = [0u8; 6];
let splits = s.split(':');
let mut i = 0;
for split in splits {
if i == 6 {
return Err(ParseMacAddrErr::TooManyComponents);
}
match u8::from_str_radix(split, 16) {
Ok(b) if split.len() != 0 => p... | random_line_split | |
util.rs | // Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modifi... | (a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> MacAddr {
MacAddr(a, b, c, d, e, f)
}
}
impl PrimitiveValues for MacAddr {
type T = (u8, u8, u8, u8, u8, u8);
fn to_primitive_values(&self) -> (u8, u8, u8, u8, u8, u8) {
(self.0, self.1, self.2, self.3, self.4, self.5)
}
}
impl fmt::Display... | new | identifier_name |
util.rs | // Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modifi... | else {
let addr = internal::sockaddr_to_addr(mem::transmute(sa),
mem::size_of::<libc::sockaddr_storage>());
match addr {
Ok(sa) => (None, Some(sa.ip())),
Err(_) => (None, None),
}
}
}
}
#... | {
let sll: *const libc::sockaddr_ll = mem::transmute(sa);
let mac = MacAddr((*sll).sll_addr[0],
(*sll).sll_addr[1],
(*sll).sll_addr[2],
(*sll).sll_addr[3],
(*sll).sll_addr[4],
... | conditional_block |
util.rs | // Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modifi... |
}
impl fmt::Display for MacAddr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt,
"{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
self.0,
self.1,
self.2,
self.3,
self.4,
self.5)
}
}
impl fmt... | {
(self.0, self.1, self.2, self.3, self.4, self.5)
} | identifier_body |
context.py | """
JSON-LD contexts.
"""
from .namespaces import ns_mgr, D
base = {
"@base": str(D),
"a": "@type",
"uri": "@id",
"label": "rdfs:label",
}
#set namespaces from the ns_mgr |
#BCITE publications
publication = {
"title": "rdfs:label",
"authors": "bcite:authorList",
'pmid': 'bcite:pmid',
'doi': 'bcite:doi',
"pmcid": "bcite:pmcid",
"issue": "bcite:issue",
"volume": "bcite:volume",
"issn": "bcite:issn",
"eissn": "bcite:eissn",
"book": "bcite:book",
"... | for prefix, iri in ns_mgr.namespaces():
base[prefix] = iri.toPython() | random_line_split |
context.py | """
JSON-LD contexts.
"""
from .namespaces import ns_mgr, D
base = {
"@base": str(D),
"a": "@type",
"uri": "@id",
"label": "rdfs:label",
}
#set namespaces from the ns_mgr
for prefix, iri in ns_mgr.namespaces():
|
#BCITE publications
publication = {
"title": "rdfs:label",
"authors": "bcite:authorList",
'pmid': 'bcite:pmid',
'doi': 'bcite:doi',
"pmcid": "bcite:pmcid",
"issue": "bcite:issue",
"volume": "bcite:volume",
"issn": "bcite:issn",
"eissn": "bcite:eissn",
"book": "bcite:book",
... | base[prefix] = iri.toPython() | conditional_block |
test_pnutils.py | # Copyright (C) 2012 Alex Nitz, Josh Willis
#
# This program 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 version.
#
# This program is distr... | if __name__ == '__main__':
results = unittest.TextTestRunner(verbosity=2).run(suite)
simple_exit(results) | suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestUtils))
| random_line_split |
test_pnutils.py | # Copyright (C) 2012 Alex Nitz, Josh Willis
#
# This program 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 version.
#
# This program is distr... | (self):
result = mass1_mass2_to_tau0_tau3(3.0,5.0,15.0)
answer = (63.039052988077955, 2.353532999897545)
self.assertAlmostEqual(result[0]/answer[0],1,places=6)
self.assertAlmostEqual(result[1]/answer[1],1,places=6)
def test_tau0_tau3_to_mtotal_eta(self):
result = tau0_tau3_t... | test_mass1_mass2_to_tau0_tau3 | identifier_name |
test_pnutils.py | # Copyright (C) 2012 Alex Nitz, Josh Willis
#
# This program 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 version.
#
# This program is distr... |
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestUtils))
if __name__ == '__main__':
results = unittest.TextTestRunner(verbosity=2).run(suite)
simple_exit(results)
| result = mass1_mass2_spin1z_spin2z_to_beta_sigma_gamma(1.4, 1.4,
0., 0.)
for i in range(3):
self.assertAlmostEqual(result[i], 0, places=6)
# with spin
result = mass1_mass2_spin1z_spin2z_to_beta_sigma_gamma(10., 1.4,
... | identifier_body |
test_pnutils.py | # Copyright (C) 2012 Alex Nitz, Josh Willis
#
# This program 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 version.
#
# This program is distr... |
# with spin
result = mass1_mass2_spin1z_spin2z_to_beta_sigma_gamma(10., 1.4,
0.9, 0.1)
answer = [7.208723197, 3.251802285, 243.2697314]
for r, a in zip(result, answer):
self.assertAlmostEqual(r / a, 1, places=6)
... | self.assertAlmostEqual(result[i], 0, places=6) | conditional_block |
forget_room.rs | //! `POST /_matrix/client/*/rooms/{roomId}/forget`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidforget
use ruma_common::{api::ruma_api, RoomId};
ruma_api! {
metadata: {
description: "Forget a roo... | () -> Self {
Self {}
}
}
}
| new | identifier_name |
forget_room.rs | //! `POST /_matrix/client/*/rooms/{roomId}/forget`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidforget
use ruma_common::{api::ruma_api, RoomId};
ruma_api! {
metadata: {
description: "Forget a roo... |
}
}
| {
Self {}
} | identifier_body |
forget_room.rs | //! `POST /_matrix/client/*/rooms/{roomId}/forget`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidforget
use ruma_common::{api::ruma_api, RoomId};
ruma_api! {
metadata: {
description: "Forget a roo... | } | random_line_split | |
mod.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::test_utils::*;
use super::super::*;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::u32;
mod br8_16;
mod br8_32;
mod br8_64;
mod call_16;
mod call_32;
mod call_64;
mod ip_rel_64;
mod jcc_16;
mod jc... | (bitness: u32, rip: u64, data: &[u8], options: u32) -> Vec<Instruction> {
let mut decoder = create_decoder(bitness, data, options).0;
decoder.set_ip(rip);
decoder.into_iter().collect()
}
fn sort(mut vec: Vec<RelocInfo>) -> Vec<RelocInfo> {
vec.sort_unstable_by(|a, b| {
let c = a.address.cmp(&b.address);
if c !... | decode | identifier_name |
mod.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::test_utils::*;
use super::super::*;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::u32;
mod br8_16;
mod br8_32;
mod br8_64;
mod call_16;
mod call_32;
mod call_64;
mod ip_rel_64;
mod jcc_16;
mod jc... | }
}
assert_eq!(constant_offsets, expected_constant_offsets);
} | decoder.set_ip(new_rip.wrapping_add(offset as u64));
decoder.decode_out(&mut instr);
expected_constant_offsets.push(decoder.get_constant_offsets(&instr)); | random_line_split |
mod.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::test_utils::*;
use super::super::*;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::u32;
mod br8_16;
mod br8_32;
mod br8_64;
mod call_16;
mod call_32;
mod call_64;
mod ip_rel_64;
mod jcc_16;
mod jc... |
#[allow(clippy::too_many_arguments)]
fn encode_test(
bitness: u32, orig_rip: u64, original_data: &[u8], new_rip: u64, new_data: &[u8], mut options: u32, decoder_options: u32,
expected_instruction_offsets: &[u32], expected_reloc_infos: &[RelocInfo],
) {
let orig_instrs = decode(bitness, orig_rip, original_data, dec... | {
vec.sort_unstable_by(|a, b| {
let c = a.address.cmp(&b.address);
if c != Ordering::Equal {
c
} else {
a.kind.cmp(&b.kind)
}
});
vec
} | identifier_body |
mod.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::test_utils::*;
use super::super::*;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::u32;
mod br8_16;
mod br8_32;
mod br8_64;
mod call_16;
mod call_32;
mod call_64;
mod ip_rel_64;
mod jcc_16;
mod jc... | else {
a.kind.cmp(&b.kind)
}
});
vec
}
#[allow(clippy::too_many_arguments)]
fn encode_test(
bitness: u32, orig_rip: u64, original_data: &[u8], new_rip: u64, new_data: &[u8], mut options: u32, decoder_options: u32,
expected_instruction_offsets: &[u32], expected_reloc_infos: &[RelocInfo],
) {
let orig_instrs ... | {
c
} | conditional_block |
subscription_manifest.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <ajkofink@gmail.com>
#
# This program 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) ... | ():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
... | main | identifier_name |
subscription_manifest.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <ajkofink@gmail.com>
#
# This program 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) ... | files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
... | random_line_split | |
subscription_manifest.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <ajkofink@gmail.com>
#
# This program 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) ... |
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
el... | module.fail_json(msg="Manifest is older than existing data.") | conditional_block |
subscription_manifest.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <ajkofink@gmail.com>
#
# This program 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) ... |
if __name__ == '__main__':
main()
| module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organ... | identifier_body |
scripts.js | exports.BattleScripts = {
init: function() {
for (var i in this.data.Pokedex) {
var template = this.getTemplate(i);
var newStats = {
hp: template.id === 'shedinja' ? 1 : this.clampIntRange(150 - template.baseStats.hp, 5, 145),
atk: this.clampIntRange(150 - template.baseStats.atk, 5, 145),
def: this... | }; | }
} | random_line_split |
tail_boom_flex.py | " tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash deriva... | (self, htail, hbending, wing):
mh = htail.mh
mw = wing.mw
Vh = htail.Vh
th = hbending.th
CLhmin = htail.CLhmin
CLwmax = wing.planform.CLmax
Sw = wing.planform.S
bw = wing.planform.b
lh = htail.lh
CM = wing.planform.CM
constraints =... | setup | identifier_name |
tail_boom_flex.py | " tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash deriva... | CM = wing.planform.CM
constraints = [
Fne >= 1 + mh*th,
sph1*(mw*Fne/mh/Vh) + deda <= 1,
sph2 <= Vh*CLhmin/CLwmax,
# (sph1 + sph2).mono_lower_bound({"sph1": .48, "sph2": .52}) >= (
# SMcorr + wing["C_M"]/wing["C_{L_{max}}"]),
d... | Sw = wing.planform.S
bw = wing.planform.b
lh = htail.lh | random_line_split |
tail_boom_flex.py | " tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash deriva... | mh = htail.mh
mw = wing.mw
Vh = htail.Vh
th = hbending.th
CLhmin = htail.CLhmin
CLwmax = wing.planform.CLmax
Sw = wing.planform.S
bw = wing.planform.b
lh = htail.lh
CM = wing.planform.CM
constraints = [
Fne >= 1 + mh*th,
... | identifier_body | |
test_link_shared_libraries.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.backend.native.targets.native_artifact import NativeArtifact
from pants.backend.native.tasks.cpp_compile import CppCompile
from pants.backend.native.tasks.link_shared... | (NativeTaskTestBase, NativeCompileTestMixin):
@classmethod
def task_type(cls):
return LinkSharedLibraries
def test_caching(self):
cpp = self.create_simple_cpp_library(ctypes_native_library=NativeArtifact(lib_name="test"))
cpp_compile_task_type = self.synthesize_task_subtype(CppComp... | LinkSharedLibrariesTest | identifier_name |
test_link_shared_libraries.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.backend.native.targets.native_artifact import NativeArtifact
from pants.backend.native.tasks.cpp_compile import CppCompile
from pants.backend.native.tasks.link_shared... | cpp = self.create_simple_cpp_library(ctypes_native_library=NativeArtifact(lib_name="test"))
cpp_compile_task_type = self.synthesize_task_subtype(CppCompile, "cpp_compile_scope")
context = self.prepare_context_for_compile(
target_roots=[cpp],
for_task_types=[cpp_compile_task_type... | identifier_body | |
test_link_shared_libraries.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.backend.native.targets.native_artifact import NativeArtifact
from pants.backend.native.tasks.cpp_compile import CppCompile
from pants.backend.native.tasks.link_shared... | context = self.prepare_context_for_compile(
target_roots=[cpp],
for_task_types=[cpp_compile_task_type],
options={"libc": {"enable_libc_search": True}},
)
cpp_compile = cpp_compile_task_type(
context, os.path.join(self.pants_workdir, "cpp_compile")... | random_line_split | |
ProcessDetector.test.ts | /*
* Copyright The OpenTelemetry 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... | sinon.restore();
});
it('should return empty resource', async () => {
const resource: Resource = await processDetector.detect();
assertEmptyResource(resource);
});
}); | afterEach(() => { | random_line_split |
AntlrParser.js | "use strict";
var antlr4 = require('antlr4/index');
var LambdaCalculusLexer = require("../antlr/generated/LambdaCalculusLexer");
var LambdaCalculusParser = require("../antlr/generated/LambdaCalculusParser");
var AstCreator = require("./ParseTreeListeningAstCreator").AstCreator;
var Immutable = require('immutable');
... | }(); | random_line_split | |
tileinfo.py | #!/usr/bin/env python
"""Print out a report about whats in a vectortile
Usage:
tileinfo.py [options] [SOURCE]
Options:
--srcformat=SRC_FORMAT Source file format: (tile | json)
--indent=INT|None JSON indentation level. Defaults to 4. Use 'None' to disable.
-h --help Show this screen.
--vers... |
def main():
"""
Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'.
"""
arguments = docopt(__doc__, version='tileinfo 0.1')
src_name = arguments['SOURCE']
src_format = arguments['--srcformat']
indent = arguments['--indent']
... | """
Compute min/max for all registered columns.
Parameters
----------
data : list
List of points from tile.
cols : list
List of columns from tile header.
Returns
-------
dict
{
column: {
min: value,
max: value
... | identifier_body |
tileinfo.py | #!/usr/bin/env python
"""Print out a report about whats in a vectortile
Usage:
tileinfo.py [options] [SOURCE]
Options:
--srcformat=SRC_FORMAT Source file format: (tile | json)
--indent=INT|None JSON indentation level. Defaults to 4. Use 'None' to disable.
-h --help Show this screen.
--vers... | Compute min/max for all registered columns.
Parameters
----------
data : list
List of points from tile.
cols : list
List of columns from tile header.
Returns
-------
dict
{
column: {
min: value,
max: value
... |
""" | random_line_split |
tileinfo.py | #!/usr/bin/env python
"""Print out a report about whats in a vectortile
Usage:
tileinfo.py [options] [SOURCE]
Options:
--srcformat=SRC_FORMAT Source file format: (tile | json)
--indent=INT|None JSON indentation level. Defaults to 4. Use 'None' to disable.
-h --help Show this screen.
--vers... |
return {n: {'min': min(v), 'max': max(v)} for n, v in stats.items()}
def main():
"""
Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'.
"""
arguments = docopt(__doc__, version='tileinfo 0.1')
src_name = arguments['SOURCE']
... | for c, v in point.items():
stats[c].append(v) | conditional_block |
tileinfo.py | #!/usr/bin/env python
"""Print out a report about whats in a vectortile
Usage:
tileinfo.py [options] [SOURCE]
Options:
--srcformat=SRC_FORMAT Source file format: (tile | json)
--indent=INT|None JSON indentation level. Defaults to 4. Use 'None' to disable.
-h --help Show this screen.
--vers... | ():
"""
Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'.
"""
arguments = docopt(__doc__, version='tileinfo 0.1')
src_name = arguments['SOURCE']
src_format = arguments['--srcformat']
indent = arguments['--indent']
if isin... | main | identifier_name |
urls.py | # Copyright 2015, A10 Networks
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | ) | # url(r'^deleteappliance$', views.DeleteApplianceView.as_view(), name='deleteappliance')
# url(r'^addimage$', views.AddImageView.as_view(), name="addimage") | random_line_split |
gru_cell.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 Timothy Dozat
#
# 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 ... | def __call__(self, inputs, state, scope=None):
""""""
with tf.variable_scope(scope or type(self).__name__):
cell_tm1, hidden_tm1 = tf.split(axis=1, num_or_size_splits=2, value=state)
with tf.variable_scope('Gates'):
linear = linalg.linear([inputs, hidden_tm1],
... | """"""
#============================================================= | random_line_split |
gru_cell.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 Timothy Dozat
#
# 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 ... | return self.output_size * 2 | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.