file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
SearchContainer.js | import React, { Component } from 'react';
import InfoSection from '../components/InfoSection';
import InfoSectionToggle from '../components/InfoSectionToggle';
class SearchContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
error: '',
showConte... |
render() {
return (
<div>
{this.renderInfoSection()}
<section>
<InfoSectionToggle onPressInfo={this.onPressInfo.bind(this)} />
<ul className="input-list style-4 clearfix">
{this.renderError()}
<li>
<label className="search" htmlFor="search">Search: </l... | {
return (
<InfoSection
revealContent={this.state.showContent}
content={this.state.content}
title={'Add Skill'}
/>
);
} | identifier_body |
SearchContainer.js | import React, { Component } from 'react';
import InfoSection from '../components/InfoSection';
import InfoSectionToggle from '../components/InfoSectionToggle';
class SearchContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
error: '',
showConte... | () {
return (
<div>
{this.renderInfoSection()}
<section>
<InfoSectionToggle onPressInfo={this.onPressInfo.bind(this)} />
<ul className="input-list style-4 clearfix">
{this.renderError()}
<li>
<label className="search" htmlFor="search">Search: </label>
... | render | identifier_name |
ofx_test.py | import os
import pytest
from . import ofx
from .source_test import check_source_example
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'ofx'))
examples = [
('test_vanguard_basic', 'vanguard.ofx'),
('test_vanguard_matching', 'vanguard.o... | ofx_ids = {
'Assets:Vanguard:401k': 1,
}
for (account, want) in [
('Assets:Vanguard:401k:PreTax:VGI1', 1),
('Assets:Vanguard:401k:PreTax', 1),
('Assets:Vanguard:401k:VG1', 1),
('Assets:Vanguard:401k', 1),
('Assets:Vanguard:Unknown', None),
('Assets:Vanguar... | identifier_body | |
ofx_test.py | import os
import pytest
from . import ofx
from .source_test import check_source_example
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'ofx'))
examples = [
('test_vanguard_basic', 'vanguard.ofx'),
('test_vanguard_matching', 'vanguard.o... | assert ofx.find_ofx_id_for_account(account, ofx_ids) == want, account | conditional_block | |
ofx_test.py | import os
import pytest
from . import ofx
from .source_test import check_source_example
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'ofx'))
examples = [
('test_vanguard_basic', 'vanguard.ofx'),
('test_vanguard_matching', 'vanguard.o... | ('test_td_ameritrade', 'td_ameritrade.ofx'),
('test_anzcc', 'anzcc.ofx'),
('test_multiple_accounts', 'multiple_accounts.ofx'),
('test_bank_medium', 'bank_medium.ofx'),
('test_investment_401k', 'investment_401k.ofx'),
('test_investment_buy_sell_income', 'investment_buy_sell_income.ofx'),
('te... | ('test_checking_emptyledgerbal', 'checking-emptyledgerbal.ofx'), | random_line_split |
ofx_test.py | import os
import pytest
from . import ofx
from .source_test import check_source_example
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'ofx'))
examples = [
('test_vanguard_basic', 'vanguard.ofx'),
('test_vanguard_matching', 'vanguard.o... | (name: str, ofx_filename: str):
check_source_example(
example_dir=os.path.join(testdata_dir, name),
source_spec={
'module': 'beancount_import.source.ofx',
'ofx_filenames': [os.path.join(testdata_dir, ofx_filename)],
},
replacements=[(testdata_dir, '<testdata>'... | test_source | identifier_name |
RolesDialog.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | dlg.ShowModal()
dlg.Destroy()
return
def onDelete(self,evt):
try:
self.deleteObject('No role','Delete role',self.dbProxy.deleteRole)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Delete role',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Des... | self.updateObject(selectedObjt,updateParameters)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Edit role',wx.OK | wx.ICON_ERROR) | random_line_split |
RolesDialog.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
def onDelete(self,evt):
try:
self.deleteObject('No role','Delete role',self.dbProxy.deleteRole)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Delete role',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
| selectedObjt = self.objts[self.selectedLabel]
try:
updateParameters = DialogClassParameters(ROLE_ID,'Edit role',RoleDialog,ROLE_BUTTONCOMMIT_ID,self.dbProxy.updateRole,False)
self.updateObject(selectedObjt,updateParameters)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorTe... | identifier_body |
RolesDialog.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | (self,parent):
DimensionBaseDialog.__init__(self,parent,ROLES_ID,'Roles',(800,300),'role.png')
idList = [ROLES_LISTROLES_ID,ROLES_BUTTONADD_ID,ROLES_BUTTONDELETE_ID]
columnList = ['Name','Short Code','Type']
self.buildControls(idList,columnList,self.dbProxy.getRoles,'role')
listCtrl = self.FindWindo... | __init__ | identifier_name |
translation.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="hr_HR">
<context> | </message>
<message>
<source>Empty</source>
<translation>Prazno</translation>
</message>
</context>
<context>
<name>extension/ezxmkinstaller</name>
<message>
<source>XML Publisher</source>
<translation>XML objavljivač</translation>
</message>
</context>
<context>
... | <name>design/standard/class/datatype</name>
<message>
<source>Template Location</source>
<translation>Lokacija predloška</translation> | random_line_split |
instanceof.ts | class A {}
class B extends A {}
var a: A;
var b: B;
var i: i32;
var I: i64;
var f: f32;
var F: f64;
assert( a instanceof A );
assert( b instanceof A );
assert(!(i instanceof A));
assert(!(I instanceof A));
assert(!(f instanceof A));
assert(!(F instanceof A));
// assert(!(a instanceof B)); // dynamic upcast, checke... | assert(!isI32(0.0));
assert(!isI32(<u32>0)); // signedness is relevant
assert(!isI32(<u16>0)); // byte size is relevant
var an: A | null = null;
assert(!(an instanceof A)); // TS: ==null is not an instance of A
assert( an instanceof A | null); // AS: ==null is an instance of A | null
an = changetype<A | nul... | return false;
}
}
assert( isI32(0)); | random_line_split |
instanceof.ts | class | {}
class B extends A {}
var a: A;
var b: B;
var i: i32;
var I: i64;
var f: f32;
var F: f64;
assert( a instanceof A );
assert( b instanceof A );
assert(!(i instanceof A));
assert(!(I instanceof A));
assert(!(f instanceof A));
assert(!(F instanceof A));
// assert(!(a instanceof B)); // dynamic upcast, checked in rt... | A | identifier_name |
instanceof.ts | class A {}
class B extends A {}
var a: A;
var b: B;
var i: i32;
var I: i64;
var f: f32;
var F: f64;
assert( a instanceof A );
assert( b instanceof A );
assert(!(i instanceof A));
assert(!(I instanceof A));
assert(!(f instanceof A));
assert(!(F instanceof A));
// assert(!(a instanceof B)); // dynamic upcast, checke... |
}
assert( isI32(0));
assert(!isI32(0.0));
assert(!isI32(<u32>0)); // signedness is relevant
assert(!isI32(<u16>0)); // byte size is relevant
var an: A | null = null;
assert(!(an instanceof A)); // TS: ==null is not an instance of A
assert( an instanceof A | null); // AS: ==null is an instance of A | null
... | {
return false;
} | conditional_block |
theme.ts | import { blue } from "@material-ui/core/colors";
import { createTheme } from "@material-ui/core";
import createPalette from "@material-ui/core/styles/createPalette";
const palette = createPalette({
primary: {
main: "#292",
light: "#3d3"
}
});
const theme = createTheme({
typography: {
fontSize: 24,
... | },
MuiTab: {
textColorInherit: { opacity: 1 },
root: {
textTransform: "none",
maxWidth: "none",
padding: 12,
transition: "background-color .2s",
"&$selected": { backgroundColor: palette.primary.main },
"&:hover": { backgroundColor: palette.primary.ligh... | display: "none"
} | random_line_split |
lib.rs | lock.try_unwrap() {
return data;
}
lock = self.cvar.wait(lock).unwrap();
}
}
}
/// A vector that can be mutated in-parallel via non-overlapping slices.
///
/// Get a `ParVec` and a vector of slices via `new()`, send the slices to other threads
/// and mutate them, ... | test_is_prime | identifier_name | |
lib.rs | to unwrap this box, replacing `data` with an empty vector if `slice_count == 0`
fn try_unwrap(&mut self) -> Option<Vec<T>> {
match self.slice_count {
0 => Some(mem::replace(&mut self.data, Vec::new())),
_ => None,
}
}
}
struct ParVecInner<T> {
inner: Mutex<VecBox<T>... | let slice = &parent[start..end];
start += slice_len;
slice as *const [T] as *mut [T]
}).collect()
}
/// A slice of `ParVec` that can be sent to another task for processing.
/// Automatically releases the slice on drop.
pub struct ParSlice<T: Send> {
inner: Arc<ParVecInner<T>>,
data... | (1 .. slice_count + 1).rev().map(|curr| {
let slice_len = (len - start) / curr;
let end = cmp::min(start + slice_len, len);
| random_line_split |
lib.rs | to unwrap this box, replacing `data` with an empty vector if `slice_count == 0`
fn try_unwrap(&mut self) -> Option<Vec<T>> {
match self.slice_count {
0 => Some(mem::replace(&mut self.data, Vec::new())),
_ => None,
}
}
}
struct ParVecInner<T> {
inner: Mutex<VecBox<T>... |
#[bench]
fn par_prime_factors_1000(b: &mut Bencher) {
let mut rng = thread_rng();
let pool = ThreadPool::new(TEST_SLICES);
b.iter(|| {
let mut vec: Vec<(u32, Vec<u32>)> = (1 .. TEST_MAX)
.map(|x| (x, Vec::new())).collect();
// Shuffle so each t... | {
let vec: Vec<u32> = (1 .. TEST_MAX).collect();
b.iter(|| {
let _: Vec<(u32, Vec<u32>)> = vec.iter()
.map(|&x| (x, get_prime_factors(x)))
.collect();
});
} | identifier_body |
test-async-wrap-disabled-propagate-parent.js | 'use strict';
require('../common');
const assert = require('assert');
const net = require('net');
const async_wrap = process.binding('async_wrap');
const providers = Object.keys(async_wrap.Providers);
const uidSymbol = Symbol('uid');
let cntr = 0;
let client;
function init(uid, type, parentUid, parentHandle) {
th... |
}
function noop() { }
async_wrap.setupHooks({ init });
async_wrap.enable();
const server = net.createServer(function(c) {
client = c;
// Allow init callback to run before closing.
setImmediate(() => {
c.end();
this.close();
});
}).listen(0, function() {
net.connect(this.address().port, noop);
});
... | {
cntr++;
// Cannot assert in init callback or will abort.
process.nextTick(() => {
assert.equal(providers[type], 'TCPWRAP');
assert.equal(parentUid, server._handle[uidSymbol],
'server uid doesn\'t match parent uid');
assert.equal(parentHandle, server._handle,
... | conditional_block |
test-async-wrap-disabled-propagate-parent.js | 'use strict';
require('../common');
const assert = require('assert');
const net = require('net');
const async_wrap = process.binding('async_wrap');
const providers = Object.keys(async_wrap.Providers);
const uidSymbol = Symbol('uid');
let cntr = 0;
let client;
function init(uid, type, parentUid, parentHandle) {
th... | const server = net.createServer(function(c) {
client = c;
// Allow init callback to run before closing.
setImmediate(() => {
c.end();
this.close();
});
}).listen(0, function() {
net.connect(this.address().port, noop);
});
async_wrap.disable();
process.on('exit', function() {
// init should have on... | random_line_split | |
test-async-wrap-disabled-propagate-parent.js | 'use strict';
require('../common');
const assert = require('assert');
const net = require('net');
const async_wrap = process.binding('async_wrap');
const providers = Object.keys(async_wrap.Providers);
const uidSymbol = Symbol('uid');
let cntr = 0;
let client;
function init(uid, type, parentUid, parentHandle) |
function noop() { }
async_wrap.setupHooks({ init });
async_wrap.enable();
const server = net.createServer(function(c) {
client = c;
// Allow init callback to run before closing.
setImmediate(() => {
c.end();
this.close();
});
}).listen(0, function() {
net.connect(this.address().port, noop);
});
a... | {
this[uidSymbol] = uid;
if (parentHandle) {
cntr++;
// Cannot assert in init callback or will abort.
process.nextTick(() => {
assert.equal(providers[type], 'TCPWRAP');
assert.equal(parentUid, server._handle[uidSymbol],
'server uid doesn\'t match parent uid');
asser... | identifier_body |
test-async-wrap-disabled-propagate-parent.js | 'use strict';
require('../common');
const assert = require('assert');
const net = require('net');
const async_wrap = process.binding('async_wrap');
const providers = Object.keys(async_wrap.Providers);
const uidSymbol = Symbol('uid');
let cntr = 0;
let client;
function init(uid, type, parentUid, parentHandle) {
th... | () { }
async_wrap.setupHooks({ init });
async_wrap.enable();
const server = net.createServer(function(c) {
client = c;
// Allow init callback to run before closing.
setImmediate(() => {
c.end();
this.close();
});
}).listen(0, function() {
net.connect(this.address().port, noop);
});
async_wrap.disab... | noop | identifier_name |
rpc.rs | ::ws::Server as WsServer;
pub use parity_rpc::informant::CpuPool;
pub const DAPPS_DOMAIN: &'static str = "web3.site";
#[derive(Debug, Clone, PartialEq)]
pub struct HttpConfiguration {
pub enabled: bool,
pub interface: String,
pub port: u16,
pub apis: ApiSet,
pub cors: Option<Vec<String>>,
pub hosts: Option<Vec<... | ,
apis: ApiSet::IpcContext,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WsConfiguration {
pub enabled: bool,
pub interface: String,
pub port: u16,
pub apis: ApiSet,
pub origins: Option<Vec<String>>,
pub hosts: Option<Vec<String>>,
pub signer_path: PathBuf,
pub support_token_api: bool,
pub ui_add... | {
let data_dir = ::dir::default_data_path();
parity_ipc_path(&data_dir, "$BASE/jsonrpc.ipc", 0)
} | conditional_block |
rpc.rs | ::ws::Server as WsServer;
pub use parity_rpc::informant::CpuPool;
pub const DAPPS_DOMAIN: &'static str = "web3.site";
#[derive(Debug, Clone, PartialEq)]
pub struct HttpConfiguration {
pub enabled: bool,
pub interface: String,
pub port: u16,
pub apis: ApiSet,
pub cors: Option<Vec<String>>,
pub hosts: Option<Vec<... | <D: rpc_apis::Dependencies> {
pub apis: Arc<D>,
pub remote: TokioRemote,
pub stats: Arc<RpcStats>,
pub pool: Option<CpuPool>,
}
pub fn new_ws<D: rpc_apis::Dependencies>(
conf: WsConfiguration,
deps: &Dependencies<D>,
) -> Result<Option<WsServer>, String> {
if !conf.enabled {
return Ok(None);
}
let domain =... | Dependencies | identifier_name |
rpc.rs | ::ws::Server as WsServer;
pub use parity_rpc::informant::CpuPool;
pub const DAPPS_DOMAIN: &'static str = "web3.site";
#[derive(Debug, Clone, PartialEq)]
pub struct HttpConfiguration {
pub enabled: bool,
pub interface: String,
pub port: u16,
pub apis: ApiSet,
pub cors: Option<Vec<String>>,
pub hosts: Option<Vec<... |
}
fn address(enabled: bool, bind_iface: &str, bind_port: u16, hosts: &Option<Vec<String>>) -> Option<rpc::Host> {
if !enabled {
return None;
}
match *hosts {
Some(ref hosts) if !hosts.is_empty() => Some(hosts[0].clone().into()),
_ => Some(format!("{}:{}", bind_iface, bind_port).into()),
}
}
pub struct Dep... | {
address(self.enabled, &self.interface, self.port, &self.hosts)
} | identifier_body |
rpc.rs | ::ws::Server as WsServer;
pub use parity_rpc::informant::CpuPool;
pub const DAPPS_DOMAIN: &'static str = "web3.site";
#[derive(Debug, Clone, PartialEq)]
pub struct HttpConfiguration {
pub enabled: bool,
pub interface: String,
pub port: u16,
pub apis: ApiSet,
pub cors: Option<Vec<String>>,
pub hosts: Option<Vec<... | }
}
pub fn new_ipc<D: rpc_apis::Dependencies>(
conf: IpcConfiguration,
dependencies: &Dependencies<D>
) -> Result<Option<IpcServer>, String> {
if !conf.enabled {
return Ok(None);
}
let handler = setup_apis(conf.apis, dependencies);
let remote = dependencies | Err(ref err) if err.kind() == io::ErrorKind::AddrInUse => Err(
format!("{} address {} is already in use, make sure that another instance of an Ethereum client is not running or change the address using the --{}-port and --{}-interface options.", id, url, options, options)
),
Err(e) => Err(format!("{} error: {:... | random_line_split |
main.js | $(function() {
var Y = YUI().use("profiler", function(Y){
var profile = [
{
"namespace": ["sakai", "api", "Security"],
"functions": ["saneHTML"]
},
{
"namespace": ["sakai", "api", "Widgets", "widgetLoader"],
... |
setTimeout(function() {
// get the report for all the registered function
var report = Y.Profiler.getFullReport();
console.log(report);
},5000);
});
});
}); | {
var ns = profile[i].namespace;
var fns = profile[i].functions;
// construct the namespace of the function properly
var nsobj = $("#ifr")[0].contentWindow[ns[0]];
for (var x=1, y=ns.length; x<y; x++) {
nsobj = nsobj[ns... | conditional_block |
main.js | $(function() {
var Y = YUI().use("profiler", function(Y){
var profile = [
{
"namespace": ["sakai", "api", "Security"],
"functions": ["saneHTML"]
},
{
"namespace": ["sakai", "api", "Widgets", "widgetLoader"],
... | }
setTimeout(function() {
// get the report for all the registered function
var report = Y.Profiler.getFullReport();
console.log(report);
},5000);
});
});
}); | Y.Profiler.registerFunction(fns[k], nsobj);
allFns.push(fns[k]);
} | random_line_split |
assistStorageEntry.js | Path = options.rootPath || '';
self.path = '';
if (self.parent !== null) {
self.path = self.parent.path;
if (self.parent.path !== '/' && !/\/$/.test(self.path)) {
self.path += '/';
}
}
self.path += self.definition.name;
self.abfsPath = (/^\//.test(self.path) ? 'abfs:/' : '... | {
const deferred = $.Deferred();
const typeMatch = path.match(/^([^:]+):\/(\/.*)\/?/i);
type = typeMatch ? typeMatch[1] : type || 'hdfs';
type = type.replace(/s3.*/i, 's3');
type = type.replace(/adl.*/i, 'adls');
type = type.replace(/abfs.*/i, 'abfs');
// TODO: connector.id for browser conn... | identifier_body | |
assistStorageEntry.js | 100;
const TYPE_SPECIFICS = {
adls: {
apiHelperFetchFunction: 'fetchAdlsPath',
dblClickPubSubId: 'assist.dblClickAdlsItem'
},
abfs: {
apiHelperFetchFunction: 'fetchAbfsPath',
dblClickPubSubId: 'assist.dblClickAbfsItem'
},
hdfs: {
apiHelperFetchFunction: 'fetchHdfsPath',
dblClickPubSub... | (entry, event, positionAdjustment) {
const $source = $(event.target);
const offset = $source.offset();
entry.contextPopoverVisible(true);
if (positionAdjustment) {
offset.left += positionAdjustment.left;
offset.top += positionAdjustment.top;
}
huePubSub.publish('context.popover.sho... | showContextPopover | identifier_name |
assistStorageEntry.js | 100;
const TYPE_SPECIFICS = {
adls: {
apiHelperFetchFunction: 'fetchAdlsPath',
dblClickPubSubId: 'assist.dblClickAdlsItem'
},
abfs: {
apiHelperFetchFunction: 'fetchAbfsPath',
dblClickPubSubId: 'assist.dblClickAbfsItem'
},
hdfs: {
apiHelperFetchFunction: 'fetchHdfsPath',
dblClickPubSub... | let entry = self;
while (entry) {
if (!entry.parent && entry.definition.name) {
const rootParts = entry.definition.name.split('/').filter(Boolean);
rootParts.reverse();
parts = parts.concat(rootParts);
} else if (entry.definition.name) {
parts.push(entry.definition.na... |
getHierarchy() {
const self = this;
let parts = []; | random_line_split |
assistStorageEntry.js | 100;
const TYPE_SPECIFICS = {
adls: {
apiHelperFetchFunction: 'fetchAdlsPath',
dblClickPubSubId: 'assist.dblClickAdlsItem'
},
abfs: {
apiHelperFetchFunction: 'fetchAbfsPath',
dblClickPubSubId: 'assist.dblClickAbfsItem'
},
hdfs: {
apiHelperFetchFunction: 'fetchHdfsPath',
dblClickPubSub... | else {
callback(self);
}
};
if (!self.loaded) {
self.loadEntries(findNextAndLoadDeep);
} else {
findNextAndLoadDeep();
}
}
getHierarchy() {
const self = this;
let parts = [];
let entry = self;
while (entry) {
if (!entry.parent && entry.definition.na... | {
loadedPages++;
self.fetchMore(findNextAndLoadDeep, () => {
callback(self);
});
} | conditional_block |
id.js | $.extend(window.lang_id, {
"Title": "Apakah Anda Melainkan ..",
"installApp": "Gunakan Aplikasi untuk membagikan jajak pendapat ini!",
"installAppComments": "Download gratis.",
"haveApp": "Aku sudah App!",
"SecondPageButton": "Bermain",
"Welcome": "Halo selamat datang!",
"rules": "1. Klik link aplikasi untuk memuat vot... | "notPublicUsers": "Tidak ada nama pemilih",
"missingAjaxKey": "Batas waktu meminta kunci polling, silakan cek koneksi internet anda.",
"more": "lebih",
"min1Option": "Letakkan setidaknya 1 pilihan",
"min2Options": "Pilihan tidak boleh kosong",
"duplicatedOptions": "Pilihan duplikat!",
"myName": "Masukkan nama panggilan... | "hidePolls": "Menyembunyikan jajak pendapat", | random_line_split |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
... | else if self.end >= self.position {
let (start, end) = self.memory.split_at_mut(self.end);
reader.poll_read_vectored(
cx,
&mut [
IoSliceMut::new(&mut *end),
IoSliceMut::new(&mut start[..self.position]),
][..... | {
Poll::Ready(Ok(0))
} | conditional_block |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
... |
pub(crate) fn rollback(&mut self, checkpoint: Checkpoint) {
if checkpoint.end == self.end {
return;
}
if checkpoint.backwards {
if self.end > checkpoint.end {
self.available_data -= self.end - checkpoint.end;
} else {
self... | {
Checkpoint {
end: self.end,
backwards: true,
}
} | identifier_body |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct Buffer {
... | (&mut self) -> io::Result<()> {
Ok(())
}
}
impl BackToTheBuffer for &mut Buffer {
fn reserve_write_use<
Tmp,
Gen: Fn(WriteContext<Self>) -> Result<(WriteContext<Self>, Tmp), GenError>,
Before: Fn(WriteContext<Self>, Tmp) -> GenResult<Self>,
>(
s: WriteContext<Self>,
... | flush | identifier_name |
buffer.rs | use crate::parsing::ParsingContext;
use amq_protocol::frame::{BackToTheBuffer, GenError, GenResult, WriteContext};
use futures_io::{AsyncRead, AsyncWrite};
use std::{
cmp,
io::{self, IoSlice, IoSliceMut},
pin::Pin,
task::{Context, Poll}, | pub(crate) struct Buffer {
memory: Vec<u8>,
capacity: usize,
position: usize,
end: usize,
available_data: usize,
}
pub(crate) struct Checkpoint {
end: usize,
backwards: bool,
}
impl Buffer {
pub(crate) fn with_capacity(capacity: usize) -> Buffer {
Buffer {
memory: v... | };
#[derive(Debug, PartialEq, Clone)] | random_line_split |
RPCServer.py | #!/usr/bin/python -OO
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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, e... |
return etree.tostring(ret, pretty_print=True)
def approveJob(jobUUID, chain, agent):
print "approving: ", jobUUID, chain, agent
if jobUUID in choicesAvailableForUnits:
choicesAvailableForUnits[jobUUID].proceedWithChoice(chain, agent)
return "approving: ", jobUUID, chain
def gearmanApproveJob... | ret.append(choice.xmlify()) | conditional_block |
RPCServer.py | #!/usr/bin/python -OO
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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, e... | (gearman_worker, gearman_job):
try:
#print "DEBUG - getting list of jobs"
#execute = gearman_job.task
ret = cPickle.dumps(getJobsAwaitingApproval())
#print ret
if not ret:
ret = ""
return ret
#catch OS errors
except Exception as inst:
print... | gearmanGetJobsAwaitingApproval | identifier_name |
RPCServer.py | #!/usr/bin/python -OO
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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, e... |
def getJobsAwaitingApproval():
ret = etree.Element("choicesAvailableForUnits")
dbStatus = verifyDatabaseIsNotLocked()
if dbStatus:
#print etree.tostring(dbStatus)
return etree.tostring(dbStatus)
for UUID, choice in choicesAvailableForUnits.items():
ret.append(choice.xmlify())
... | timeBeforeReturningErrorLockedDB = 4
timeToSleep = 0.1
numberOfRuns = 0 #count of number of runs in loop
while not databaseInterface.sqlLock.acquire(False):
time.sleep(timeToSleep)
numberOfRuns += 1
if numberOfRuns * timeToSleep > timeBeforeReturningErrorLockedDB:
return ... | identifier_body |
RPCServer.py | #!/usr/bin/python -OO
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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, e... | import gearman
import cPickle
import time
import traceback
from socket import gethostname
sys.path.append("/usr/lib/archivematica/archivematicaCommon")
from custom_handlers import GroupWriteRotatingFileHandler
import databaseInterface
def rpcError(code="", details=""):
ret = etree.Element("Error")
etree.SubEle... | from linkTaskManagerChoice import choicesAvailableForUnits
import logging
import lxml.etree as etree | random_line_split |
feed.js | "use strict";
Object.defineProperty(exports, "__esModule", { | value: true
});
var feed = exports.feed = { "viewBox": "0 0 16 16", "children": [{ "name": "path", "attribs": { "fill": "#000000", "d": "M6 8c0-1.105 0.895-2 2-2s2 0.895 2 2c0 1.105-0.895 2-2 2s-2-0.895-2-2zM10.38 3.602c1.56 0.846 2.62 2.498 2.62 4.398s-1.059 3.552-2.62 4.398c0.689-1.096 1.12-2.66 1.12-4.398s-0.431-3... | random_line_split | |
elfinder.ar.js | ' : ' موجود مسبقاً "$1"',
'errInvName' : 'الاسم مرفوض',
'errFolderNotFound' : 'المجلد غير موجود',
'errFileNotFound' : 'الملف غير موجود',
'errTrgFolderNotFound' : 'الملف الهدف "$1" غير موجود ',
'errPopup' : 'يمنعني المتصفح من إنشاء نافذة منبثقة , الرجاء تعديل الخي... | /******************************* commands names ********************************/
'cmdarchive' : 'أنشئ مجلد مضغوط',
'cmdback' : 'الخلف',
'cmdcopy' : 'نسخ',
'cmdcut' : 'قص',
'cmddownload' : 'تحميل',
'cmdduplicate' : 'تكرار',
'cmdedit' : 'تعديل الملف',
'cmdextract' : '... | 'errArcMaxSize' : 'Archive files exceeds maximum allowed size.',
| random_line_split |
elfinder.ar.js | 'errConf' : 'خطأ في الإعدادات الخاصة بالخادم الخلفي ',
'errJSON' : 'الميزة PHP JSON module غير موجودة ',
'errNoVolumes' : 'لا يمكن القراءة من أي من الوسائط الموجودة ',
'errCmdParams' : 'البيانات المرسلة للأمر غير مقبولة "$1".',
'errDataNotJSON' : 'المعلومات... | {
elFinder.prototype.i18.ar = {
translator : 'Tawfek Daghistani <tawfekov@gmail.com>',
language : 'العربية',
direction : 'rtl',
messages : {
/********************************** errors **********************************/
'error' : 'خطأ',
'errUnknown' : 'خطأ غير معرو... | conditional_block | |
_project_cfg_importer.py | """
Project Configuration Importer
Handles the importing the project configuration from a separate location
and validates the version against the specified expected version.
NOTE: If you update this file or any others in scripts and require a
NEW variable in project_cfg, then you need to UPDATE THE EXPECTED_CFG... | (project_cfg_module):
is_correct_version = False
if project_cfg_module.__CFG_VERSION__ == EXPECTED_CFG_VERSION:
is_correct_version = True
else:
raise Exception("\n\n================================= ERROR ========================================"
"\nIncorrect project ... | _verify_correct_version | identifier_name |
_project_cfg_importer.py | """
Project Configuration Importer
Handles the importing the project configuration from a separate location
and validates the version against the specified expected version.
NOTE: If you update this file or any others in scripts and require a
NEW variable in project_cfg, then you need to UPDATE THE EXPECTED_CFG... | is_correct_version = False
if project_cfg_module.__CFG_VERSION__ == EXPECTED_CFG_VERSION:
is_correct_version = True
else:
raise Exception("\n\n================================= ERROR ========================================"
"\nIncorrect project configuration version: " +... | identifier_body | |
_project_cfg_importer.py | """
Project Configuration Importer
Handles the importing the project configuration from a separate location
and validates the version against the specified expected version.
NOTE: If you update this file or any others in scripts and require a
NEW variable in project_cfg, then you need to UPDATE THE EXPECTED_CFG... | """
sys.path.append(PROJECT_CFG_DIR)
try:
project_cfg_module = importlib.import_module(PROJECT_CFG_NAME)
except:
raise FileNotFoundError("\n\n================================= ERROR ========================================"
"\nUnable to import project conf... | def get_project_cfg():
"""
Returns the project configuration module | random_line_split |
_project_cfg_importer.py | """
Project Configuration Importer
Handles the importing the project configuration from a separate location
and validates the version against the specified expected version.
NOTE: If you update this file or any others in scripts and require a
NEW variable in project_cfg, then you need to UPDATE THE EXPECTED_CFG... |
return is_correct_version
| raise Exception("\n\n================================= ERROR ========================================"
"\nIncorrect project configuration version: " + str(project_cfg_module.__CFG_VERSION__) +
"\n Development environment expected: " + str(EXPECTED_CFG_VERSION) +
... | conditional_block |
ogbg_molpcba.py | # coding=utf-8
# Copyright 2022 The init2winit 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 la... | count = 0
graphs_shards = []
labels_shards = []
weights_shards = []
def get_ogbg_molpcba(shuffle_rng, batch_size, eval_batch_size, hps=None):
"""Data generators for ogbg-molpcba."""
shuffle_buffer_size = 2**15
shuffle_rng_train, shuffle_rng_eval_train = jax.random.split(shuffle_rng)
t... | count += 1
# Separate the labels from the graph
labels = batched_graph.globals
graph = batched_graph._replace(globals={})
replaced_labels, weights = _get_weights_by_nan_and_padding(
labels, jraph.get_graph_padding_mask(graph))
graphs_shards.append(graph)
labels_shards.append(replaced_... | conditional_block |
ogbg_molpcba.py | # coding=utf-8
# Copyright 2022 The init2winit 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 la... |
return Dataset(train_iterator_fn, eval_train_epoch, valid_epoch, test_epoch)
| return itertools.islice(
_get_batch_iterator(
iter(test_ds), eval_batch_size, hps.max_nodes_multiplier,
hps.max_edges_multiplier), num_batches) | identifier_body |
ogbg_molpcba.py | # coding=utf-8
# Copyright 2022 The init2winit 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 la... | (shuffle_rng, batch_size, eval_batch_size, hps=None):
"""Data generators for ogbg-molpcba."""
shuffle_buffer_size = 2**15
shuffle_rng_train, shuffle_rng_eval_train = jax.random.split(shuffle_rng)
train_ds = _load_dataset(
'train',
should_shuffle=True,
shuffle_seed=shuffle_rng_train,
shuf... | get_ogbg_molpcba | identifier_name |
ogbg_molpcba.py | # coding=utf-8
# Copyright 2022 The init2winit 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 la... | n_node=num_nodes,
n_edge=np.array([len(edge_index) * 2]),
nodes=node_feat,
edges=np.concatenate([edge_feat, edge_feat]),
# Make the edges bidirectional
senders=np.concatenate([senders, receivers]),
receivers=np.concatenate([receivers, senders]),
# Keep the labels with the... |
senders = edge_index[:, 0]
receivers = edge_index[:, 1]
return jraph.GraphsTuple( | random_line_split |
talents.ts | import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import Constants from '../constants';
import { ITalent } from '../models';
@Injectable()
export class TalentsService {
private API... |
});
}
if (payload.order) {
Object.keys(payload.order).map((name) => {
params.set(`order[${name}]`, payload.order[name]);
});
}
if (!params.get('order[name]')) {
params.set('order[name]', 'asc');
}
return this.http.get(this.API_PATH, { search: params, headers }... | {
payload.filter['talents_ids'].forEach((item) => {
params.append('filter[talents_ids][]', item);
});
} | conditional_block |
talents.ts | import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import Constants from '../constants';
import { ITalent } from '../models';
@Injectable()
export class TalentsService {
private API... | }
if (payload.order) {
Object.keys(payload.order).map((name) => {
params.set(`order[${name}]`, payload.order[name]);
});
}
if (!params.get('order[name]')) {
params.set('order[name]', 'asc');
}
return this.http.get(this.API_PATH, { search: params, headers })
.ma... | {
const headers = new Headers({ 'Content-Type': 'application/json', 'X-Auth-Secret': token });
const params: URLSearchParams = new URLSearchParams();
if (payload.pagination) {
params.set('per', payload.pagination.per);
params.set('page', payload.pagination.page);
}
if (payload.filter)... | identifier_body |
talents.ts | import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import Constants from '../constants';
import { ITalent } from '../models';
@Injectable()
export class | {
private API_PATH: string = `${Constants.API_URL}/talents`;
constructor(private http: Http) { }
public getTalents(payload, token): Observable<ITalent[]> {
const headers = new Headers({ 'Content-Type': 'application/json', 'X-Auth-Secret': token });
const params: URLSearchParams = new URLSearchParams()... | TalentsService | identifier_name |
talents.ts | import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import Constants from '../constants';
import { ITalent } from '../models';
@Injectable()
export class TalentsService {
private API... | Object.keys(payload.order).map((name) => {
params.set(`order[${name}]`, payload.order[name]);
});
}
if (!params.get('order[name]')) {
params.set('order[name]', 'asc');
}
return this.http.get(this.API_PATH, { search: params, headers })
.map((res) => res.json());
}
p... |
if (payload.order) { | random_line_split |
eggie.py | #!/usr/bin/env python
#Copyright (c) <2015>, <Jaakko Leppakangas>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this
#... | ():
app = QtGui.QApplication(sys.argv)
window=PreprocessDialog()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
| main | identifier_name |
eggie.py | #!/usr/bin/env python
#Copyright (c) <2015>, <Jaakko Leppakangas>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this
#... | main() | conditional_block | |
eggie.py | #!/usr/bin/env python
#Copyright (c) <2015>, <Jaakko Leppakangas>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this | # this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCH... | # list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright notice, | random_line_split |
eggie.py | #!/usr/bin/env python
#Copyright (c) <2015>, <Jaakko Leppakangas>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this
#... |
if __name__ == '__main__':
main()
| app = QtGui.QApplication(sys.argv)
window=PreprocessDialog()
window.show()
sys.exit(app.exec_()) | identifier_body |
js_Fc4I144XPrPKyUpaWv36lNESuazCkfla6EpZyDPBOQk.js | or false.
*/
compare: function (reference, value) {
if (reference.constructor.name in states.Dependent.comparisons) {
// Use a custom compare function for certain reference value types.
return states.Dependent.comparisons[reference.constructor.name](reference, value);
}
else {
// Do ... | invert | identifier_name | |
js_Fc4I144XPrPKyUpaWv36lNESuazCkfla6EpZyDPBOQk.js | comparison otherwise.
return compare(reference, value);
}
},
/**
* Update the value of a dependee's state.
*
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
* @param value
* The new value for... | {
return (a === b) ? (a === undefined ? a : true) : (a === undefined || b === undefined);
} | identifier_body | |
js_Fc4I144XPrPKyUpaWv36lNESuazCkfla6EpZyDPBOQk.js | 0) ? '' : dots + '.';
$title.text(text + dots);
}, 500);
});
};
/**
* Switch active tab immediately.
*/
Drupal.overlayChild.behaviors.tabs = function (context, settings) {
var $tabsLinks = $('#overlay-tabs > li > a');
$('#overlay-tabs > li > a').bind('click.drupal-overlay', function () {
var act... | {
this.values[selector][state.pristine] = value;
this.reevaluate();
} | conditional_block | |
js_Fc4I144XPrPKyUpaWv36lNESuazCkfla6EpZyDPBOQk.js | .indexOf('?') > -1 ? '&' : '?') + 'render=overlay';
$(this).attr('action', action);
}
// Submit external forms into a new window.
else {
$(this).attr('target', '_new');
}
});
};
/**
* Replace the overlay title with a message while loading another page.
*/
Drupal.overlayChild.behaviors.l... | var states = Drupal.states = {
// An array of functions that should be postponed.
postponed: []
};
/**
* Attaches the states.
*/
Drupal.behaviors.states = {
attach: function (context, settings) {
for (var selector in settings.states) {
for (var state in settings.states[selector]) {
new states... | * without having to always declare "Drupal.states".
*/ | random_line_split |
AIReviewStream.tsx | /*
* Copyright (C) 2012-2022 Online-Go.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
* License, or (at your option) any later version.
*
* This pr... |
function onConnect() {
ai_socket.send("ai-review-connect", { uuid, game_id, ai_review_id });
watch_jwt();
}
function onMessage(data: any) {
props.callback(data);
}
return () => {
if (ai_socket.connected) {
ai_soc... | {
data.unwatch("config.user_jwt", onJwtChange);
} | identifier_body |
AIReviewStream.tsx | /*
* Copyright (C) 2012-2022 Online-Go.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
* License, or (at your option) any later version.
*
* This pr... | () {
const user = data.get("config.user");
const user_jwt = data.get("config.user_jwt");
if (!user.anonymous && user_jwt) {
ai_socket.send("authenticate", { jwt: user_jwt });
}
}
function watch_jwt() {
data.watch("config.user_j... | onJwtChange | identifier_name |
AIReviewStream.tsx | /*
* Copyright (C) 2012-2022 Online-Go.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
* License, or (at your option) any later version.
*
* This pr... | const cur_move_string = cur_move.getMoveStringToThisPoint();
const variation = cur_move_string.slice(trunk_move_string.length);
const key = `${uuid}-${game_id}-${ai_review_id}-${trunk_move.move_number}-${variation}`;
if (key in analysis_requests_made) {
return;
}
analysis_requests_made[... | );
return;
}
const trunk_move_string = trunk_move.getMoveStringToThisPoint(); | random_line_split |
AIReviewStream.tsx | /*
* Copyright (C) 2012-2022 Online-Go.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
* License, or (at your option) any later version.
*
* This pr... |
function onJwtChange() {
const user = data.get("config.user");
const user_jwt = data.get("config.user_jwt");
if (!user.anonymous && user_jwt) {
ai_socket.send("authenticate", { jwt: user_jwt });
}
}
function watch_jwt() {
... | {
ai_socket.on("connect", onConnect);
ai_socket.on(uuid, onMessage);
if (ai_socket.connected) {
onConnect();
}
} | conditional_block |
test_backend.py | '--hash-password', password])
print(hash_pw)
hash_pw = hash_pw.decode('ascii').strip('\n')
assert passlib.hash.sha512_crypt.verify(password, hash_pw), 'Hash does not match password'
def test_set_superuser_password(tmpdir):
"""Test that --set-superuser-hash works"""
with tmpdir.as_cwd():
... |
def test_do_aws_configure(tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', | random_line_split | |
test_backend.py | '--hash-password', password])
print(hash_pw)
hash_pw = hash_pw.decode('ascii').strip('\n')
assert passlib.hash.sha512_crypt.verify(password, hash_pw), 'Hash does not match password'
def test_set_superuser_password(tmpdir):
"""Test that --set-superuser-hash works"""
with tmpdir.as_cwd():
... | (tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
# Create a temp config
genconf_dir = tmpdir.join('genconf')
genconf_dir.ensure(dir=True)
temp_config_path = str(genconf_dir.join('config.yaml'))
# Initialize with defautls
make_default_config_if_needed(temp_conf... | test_do_validate_config | identifier_name |
test_backend.py | '--hash-password', password])
print(hash_pw)
hash_pw = hash_pw.decode('ascii').strip('\n')
assert passlib.hash.sha512_crypt.verify(password, hash_pw), 'Hash does not match password'
def test_set_superuser_password(tmpdir):
"""Test that --set-superuser-hash works"""
with tmpdir.as_cwd():
... | assert messages == expected_bad_messages
def test_do_validate_config(tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
# Create a temp config
genconf_dir = tmpdir.join('genconf')
genconf_dir.ensure(dir=True)
temp_config_path = str(genconf_dir.join('config.yaml'))
... | workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
bad_post_data = {
"agent_list": "foo",
"master_list": ["foo"],
}
expected_bad_messages = {
"agent_list": "Must be a JSON formatted list, but couldn't be p... | identifier_body |
test_backend.py |
return release.load_config('dcos-release.config.yaml')
@pytest.fixture(scope='module')
def config_testing(config):
if 'testing' not in config:
pytest.skip("Skipped because there is no `testing` configuration in dcos-release.config.yaml")
return config['testing']
@pytest.fixture(scope='module')
... | pytest.skip("Skipping because there is no configuration in dcos-release.config.yaml") | conditional_block | |
ImageEnhance.py | #
# The Python Imaging Library.
# $Id$
#
# image enhancement classes
#
# For a background, see "Image Processing By Interpolation and
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
# at http://www.sgi.com/grafica/interp/index.html
#
# History:
# 1996-03-23 fl Created
# 2009-06-16 fl Fixed mean calcu... | (_Enhance):
"""Adjust image sharpness.
This class can be used to adjust the sharpness of an image. An
enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
original image, and a factor of 2.0 gives a sharpened image.
"""
def __init__(self, image):
self.image = image... | Sharpness | identifier_name |
ImageEnhance.py | #
# The Python Imaging Library.
# $Id$
#
# image enhancement classes
#
# For a background, see "Image Processing By Interpolation and
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
# at http://www.sgi.com/grafica/interp/index.html
#
# History:
# 1996-03-23 fl Created
# 2009-06-16 fl Fixed mean calcu... | self.image = image
self.degenerate = image.filter(ImageFilter.SMOOTH) | identifier_body | |
ImageEnhance.py | #
# The Python Imaging Library.
# $Id$
#
# image enhancement classes
#
# For a background, see "Image Processing By Interpolation and
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
# at http://www.sgi.com/grafica/interp/index.html
#
# History:
# 1996-03-23 fl Created
# 2009-06-16 fl Fixed mean calcu... |
class Brightness(_Enhance):
"""Adjust image brightness.
This class can be used to control the brighntess of an image. An
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
original image.
"""
def __init__(self, image):
self.image = image
self.degenerate =... | random_line_split | |
rbawz2.py | #!/usr/bin/env python
#
# Computation of the rate-distortion function for source coding with side
# information at the decoder using the Blahut-Arimoto algorithm.
#
# Formulation similar to R.E. Blahut "Computation of Channel Capacity and
# Rate-Distortion Functions," IEEE Transactions on Information Theory, 18,
# no. ... |
if __name__=="__main__":
if len(argv)>1:
main(argv[1])
else:
main()
| if isfile(inputfile):
q=readinputfile(inputfile)
else:
nx=2
ny=2
q=array([[0.3,0.2],[0.24,0.26]],dtype='longdouble')
blahut_arimoto(q) | identifier_body |
rbawz2.py | #!/usr/bin/env python
#
# Computation of the rate-distortion function for source coding with side
# information at the decoder using the Blahut-Arimoto algorithm.
#
# Formulation similar to R.E. Blahut "Computation of Channel Capacity and
# Rate-Distortion Functions," IEEE Transactions on Information Theory, 18,
# no. ... | (inputfile):
a=[ line.split() for line in file(inputfile) ]
nx=len(a) # Number of lines
ny=len(a[0]) # Number of columns
q=zeros((nx,ny),dtype='longdouble')
for i in range(nx):
for j in range(ny):
q[i][j]=a[i][j]
return(q)
def main(inputfile="q.txt"):
if isfile(inputfile)... | readinputfile | identifier_name |
rbawz2.py | #!/usr/bin/env python
#
# Computation of the rate-distortion function for source coding with side
# information at the decoder using the Blahut-Arimoto algorithm.
#
# Formulation similar to R.E. Blahut "Computation of Channel Capacity and
# Rate-Distortion Functions," IEEE Transactions on Information Theory, 18,
# no. ... | def blahut_arimoto(q):
nx,ny=shape(q)
qx=[]
for i in range(nx):
qx.append(longdouble(sum(q[i,:])))
qy=[]
for j in range(ny):
qy.append(longdouble(sum(q[:,j])))
nz=nx
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# The array t contains all the possible codes that map Y into Z
nt=nx+1
t,nt... | random_line_split | |
rbawz2.py | #!/usr/bin/env python
#
# Computation of the rate-distortion function for source coding with side
# information at the decoder using the Blahut-Arimoto algorithm.
#
# Formulation similar to R.E. Blahut "Computation of Channel Capacity and
# Rate-Distortion Functions," IEEE Transactions on Information Theory, 18,
# no. ... | if len(argv)>1:
main(argv[1])
else:
main() | conditional_block | |
URITemplate.js | ',',
named: false,
empty_name_separator: false,
encode : 'encodeReserved'
},
// Fragment identifiers prefixed by '#'
'#' : {
prefix: '#',
separator: ',',
named: false,
empty_name_separator: false,
encode : 'encodeReserved'
},
// Name labels or extensi... |
if (d.type === 2) {
// without explode-modifier, keys of objects are returned comma-separated
result += _name + ',';
}
result += _value;
} else {
// only add the = if it is either default (?&) or there actually is a value (;)
result += _name + (empty_... | {
// first element, so prepend variable name
result += URI[encode](name) + (empty_name_separator || _value ? '=' : '');
} | conditional_block |
URITemplate.js | ',',
named: false,
empty_name_separator: false,
encode : 'encodeReserved'
},
// Fragment identifiers prefixed by '#'
'#' : {
prefix: '#',
separator: ',',
named: false,
empty_name_separator: false,
encode : 'encodeReserved'
},
// Name labels or extensi... | // only add the = if it is either default (?&) or there actually is a value (;)
result += _name + (empty_name_separator || _value ? '=' : '') + _value;
}
}
return result;
};
// expand an unnamed variable
URITemplate.expandUnnamed = function(d, options, explode, separator, length) {
... | }
result += _value;
} else { | random_line_split |
URITemplate.js | (expression) {
// serve from cache where possible
if (URITemplate._cache[expression]) {
return URITemplate._cache[expression];
}
// Allow instantiation without the 'new' keyword
if (!(this instanceof URITemplate)) {
return new URITemplate(expression);
}
this.expression = expres... | URITemplate | identifier_name | |
URITemplate.js |
var p = URITemplate.prototype;
// list of operators and their defined options
var operators = {
// Simple string expansion
'' : {
prefix: '',
separator: ',',
named: false,
empty_name_separator: false,
encode : 'encode'
},
// Reserved character strings
'+' : {
... | {
this.data = data;
this.cache = {};
} | identifier_body | |
canvas_msg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use canvas_paint_task::{FillOrStrokeStyle, LineCapStyle, LineJoinStyle, CompositionOrBlending};
use geom::matrix2d... | {
Canvas2d(Canvas2dMsg),
Common(CanvasCommonMsg),
WebGL(CanvasWebGLMsg),
}
#[derive(Clone)]
pub enum Canvas2dMsg {
Arc(Point2D<f32>, f32, f32, f32, bool),
ArcTo(Point2D<f32>, Point2D<f32>, f32),
DrawImage(Vec<u8>, Size2D<f64>, Rect<f64>, Rect<f64>, bool),
DrawImageSelf(Size2D<f64>, Rect<f6... | CanvasMsg | identifier_name |
canvas_msg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use canvas_paint_task::{FillOrStrokeStyle, LineCapStyle, LineJoinStyle, CompositionOrBlending};
use geom::matrix2d... | LineTo(Point2D<f32>),
MoveTo(Point2D<f32>),
PutImageData(Vec<u8>, Rect<f64>, Option<Rect<f64>>),
QuadraticCurveTo(Point2D<f32>, Point2D<f32>),
Rect(Rect<f32>),
RestoreContext,
SaveContext,
StrokeRect(Rect<f32>),
Stroke,
SetFillStyle(FillOrStrokeStyle),
SetStrokeStyle(FillOrSt... | Clip,
ClosePath,
Fill,
FillRect(Rect<f32>),
GetImageData(Rect<f64>, Size2D<f64>, Sender<Vec<u8>>), | random_line_split |
ShareSharp.js | import React from 'react'; | export default createSvgIcon(
<path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.0... | import createSvgIcon from './utils/createSvgIcon';
| random_line_split |
runner.rs | 4 and v6.
let bind_addr = match peer_addr {
std::net::SocketAddr::V4(_) => "0.0.0.0:0",
std::net::SocketAddr::V6(_) => "[::]:0",
};
// Create the UDP socket backing the QUIC connection, and register it with
// the event loop.
let socket = std::net::UdpSocket::bind(bind_addr).unwrap(... | },
}
}
}
| random_line_split | |
runner.rs | ::new().fill(&mut scid[..]).unwrap();
let scid = quiche::ConnectionId::from_ref(&scid);
// Create a QUIC connection and initiate handshake.
let url = &test.endpoint();
let mut conn =
quiche::connect(url.domain(), &scid, peer_addr, &mut config).unwrap();
if let Some(session_file) = &sessi... | {
hdrs.iter()
.map(|h| {
(
String::from_utf8(h.name().into()).unwrap(),
String::from_utf8(h.value().into()).unwrap(),
)
})
.collect()
} | identifier_body | |
runner.rs | (
test: &mut crate::Http3Test, peer_addr: std::net::SocketAddr,
verify_peer: bool, idle_timeout: u64, max_data: u64, early_data: bool,
session_file: Option<String>,
) -> Result<(), Http3TestError> {
const MAX_DATAGRAM_SIZE: usize = 1350;
let mut buf = [0; 65535];
let mut out = [0; MAX_DATAGRAM_... | run | identifier_name | |
unet.py | # The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... |
def tearDown(self):
for i in self.l:
i.rawserver.stop_listening_udp(i.socket)
i.socket.close()
#self.kfiles()
def kfiles(self):
for i in range(self.startport, self.startport+self.num):
try:
os.unlink('kh%s.db' % i)
... | self.r.listen_once(1) | conditional_block |
unet.py | # The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... | import sys, os
from krpc import KRPC
KRPC.noisy = 1
class Network:
def __init__(self, size=0, startport=5555, localip='127.0.0.1'):
self.num = size
self.startport = startport
self.localip = localip
def _done(self, val):
self.done = 1
def simpleSetUp(self):
... | from random import randrange
from threading import Event | random_line_split |
unet.py | # The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... | :
def __init__(self, size=0, startport=5555, localip='127.0.0.1'):
self.num = size
self.startport = startport
self.localip = localip
def _done(self, val):
self.done = 1
def simpleSetUp(self):
#self.kfiles()
d = dict([(x[0],x[1]) for x in common_optio... | Network | identifier_name |
unet.py | # The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... |
def simpleSetUp(self):
#self.kfiles()
d = dict([(x[0],x[1]) for x in common_options + rare_options])
self.r = RawServer(Event(), d)
self.l = []
for i in range(self.num):
self.l.append(UTKhashmir('', self.startport + i, 'kh%s.db' % (self.startport + i), s... | self.done = 1 | identifier_body |
patchDiff.js | import * as R from 'ramda';
import { getPatchPath } from 'xod-project';
import { isAmong } from 'xod-func-tools';
import { def } from './types';
import { CHANGE_TYPES } from './constants'; |
const createPatchChange = def(
'createPatchChange :: AnyChangeType -> Patch -> AnyPatchChange',
(changeType, patch) =>
R.compose(
R.when(
() =>
changeType === CHANGE_TYPES.ADDED ||
changeType === CHANGE_TYPES.MODIFIED,
R.assoc('data', patch)
),
R.applySpec(... |
const isEqualPatchPaths = def(
'isEqualPatchPaths :: Patch -> Patch -> Boolean',
R.useWith(R.equals, [getPatchPath, getPatchPath])
); | random_line_split |
require.js | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
(function (require, exports) {
/**
* @module
*/
/*whatsupdoc*/
var Q = require("q");
var has = Object.prototype.hasOwnProperty;
var update = function (_object, object) {
for (var key in object) {
if (has.call(object, key)) {
_o... | "supportDefine": supportDefine
});
return _require(id, undefined, {
"scope": scope
});
});
};
require.loader = loader;
return require;
};
exports.resolve = resolve;
function resolve(id, baseId) {
id = String(id);
var ids ... | random_line_split | |
require.js | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
(function (require, exports) {
/**
* @module
*/
/*whatsupdoc*/
var Q = require("q");
var has = Object.prototype.hasOwnProperty;
var update = function (_object, object) {
for (var key in object) {
if (has.call(object, key)) {
_o... | (id, baseId) {
id = String(id);
var ids = id.split("/");
// assert ids.length >= 1 since "".split("") == [""]
var first = ids[0];
if (first === ".." || first === ".") {
var baseIds = baseId.split("/");
baseIds.pop();
ids.unshift.apply(ids, baseIds);
}
var parts = [];
... | resolve | identifier_name |
require.js | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
(function (require, exports) {
/**
* @module
*/
/*whatsupdoc*/
var Q = require("q");
var has = Object.prototype.hasOwnProperty;
var update = function (_object, object) {
for (var key in object) {
if (has.call(object, key)) {
_o... | return parts.join("/");
}
}).apply({},
typeof exports !== "undefined" ? [
require,
exports
] : [
(function (global) {
return function (id) {
return global["/" + id];
}
})(this),
this["/require"] = {}
]
);
| {
id = String(id);
var ids = id.split("/");
// assert ids.length >= 1 since "".split("") == [""]
var first = ids[0];
if (first === ".." || first === ".") {
var baseIds = baseId.split("/");
baseIds.pop();
ids.unshift.apply(ids, baseIds);
}
var parts = [];
while (id... | identifier_body |
require.js | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
(function (require, exports) {
/**
* @module
*/
/*whatsupdoc*/
var Q = require("q");
var has = Object.prototype.hasOwnProperty;
var update = function (_object, object) {
for (var key in object) {
if (has.call(object, key)) {
_o... |
return module.exports;
};
// curries require for a module, so its baseId can be assumed
var Require = function (baseId) {
var _require = function (id) { return require(id, baseId); };
_require.async = function (id) { return require.async(id, baseId) };
_require.loader = loa... | {
throw new Error("require: Can't load " + enquote(id));
} | conditional_block |
fasta.rs | .map(|name| {
Sequence {
name: name.clone(),
len: self.inner.get(name).unwrap().len,
}
})
.collect()
}
}
/// A FASTA reader with an index as created by SAMtools (.fai).
pub struct IndexedReader<R: io::Read + io::Seek>... | const FASTA_FILE_NO_TRAILING_LF : &'static [u8] = b">id desc
GTAGGCTGAAAA | random_line_split | |
fasta.rs | : io::Read>(fai: R) -> csv::Result<Self> {
let mut inner = collections::HashMap::new();
let mut seqs = vec![];
let mut fai_reader = csv::Reader::from_reader(fai).delimiter(b'\t').has_headers(false);
for row in fai_reader.decode() {
let (name, record): (String, IndexRecord) = ... | asta: R, index: Index) -> Self {
IndexedReader {
reader: io::BufReader::new(fasta),
index: index,
}
}
/// For a given seqname, read the whole sequence into the given vector.
pub fn read_all(&mut self, seqname: &str, seq: &mut Text) -> io::Result<()> {
match s... | th_index(f | identifier_name |
fasta.rs | : io::Read>(fai: R) -> csv::Result<Self> {
let mut inner = collections::HashMap::new();
let mut seqs = vec![];
let mut fai_reader = csv::Reader::from_reader(fai).delimiter(b'\t').has_headers(false);
for row in fai_reader.decode() {
let (name, record): (String, IndexRecord) = ... | /// Return the id of the record.
pub fn id(&self) -> Option<&str> {
self.header[1..].trim_right().splitn(2, ' ').next()
}
/// Return descriptions if present.
pub fn desc(&self) -> Option<&str> {
self.header[1..].trim_right().splitn(2, ' ').skip(1).next()
}
/// Return the se... | if self.id().is_none() {
return Err("Expecting id for FastQ record.");
}
if !self.seq.is_ascii() {
return Err("Non-ascii character found in sequence.");
}
Ok(())
}
| identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.