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 |
|---|---|---|---|---|
api.ts | "/: B": 0},
remainder: {"remainder: A": 0, "remainder: B": 0},
round: {"round: A": 0, "round: B": 0},
contains: {"contains: inner": " ", "contains: outer": ""},
count: {"count: A": []},
mean: {"mean: A": []},
split: {"split: split": " ", "split: string": ""},
concat: {"concat: A": "", "conc... | { return; } | conditional_block | |
api.ts | view: {key: "view",
dependents: pkDependents.concat(
["field"])},
source: {key: "source",
foreign: {view: "view"},
dependents: []},
field: {key: "field",
foreign: {view: "view"},
dependents: pkDependents,
},
"chunked sou... | {
if(arguments.length < 3) { throw new Error("Must specify type and query and changes for change."); }
// When useIds is set, retrieve will return undefined for an empty result
var read = retrieve(type, params, context, useIds) || [];
var write = read.map(function(item) {
return writeInto(item, ch... | identifier_body | |
api.ts | "grouped field": {},
"negated source": {},
"sorted field": {},
"select": {},
"variable" : {},
"binding": {},
"constant binding": {},
"view description": {},
"text input": {},
"mouse position": {},
"click": {},
"client event": {},
"location": {},
"session ... | toDiffs | identifier_name | |
api.ts | : true,
uiGridSize: 10,
initialValue: undefined,
queryEditorActive: undefined,
queryEditorInfo: undefined,
sort: {}
};
export type Diff = any[];
interface Context {[key:string]: Id}
interface Write<T> {type: string, content: T|T[], context?: Context|Context[], mode?: string, originalKeys?: st... | dest[key] = writeInto(dest[key] || {}, src[key]);
}
// If it's a primitive value, overwrite the current value. | random_line_split | |
setup.py | #!/usr/bin/env python
from distutils.core import setup, Extension
poppler_install_path = '/usr'
import multivio
setup(
name='multivio',
version=multivio.__version__, | description='Multivio server.',
long_description='''Multivio is a project...''',
license=multivio.__license__,
url='http://www.multivio.org',
ext_modules=[Extension('multivio/poppler/_mypoppler', ['multivio/poppler/mypoppler.i'],
swig_opts=['-c++', '-modern', '-I%s/include' % poppler_install... | random_line_split | |
OrganizationTreeController.ts | "use strict";
module ServiceRegister
{
export class OrganizationTreeController implements Affecto.Base.IController
{
public static $inject = ["$scope", "$routeParams", "$location", "organizationService", "busyIndicationService"];
public model: Tree;
public selectedOrganizationId: stri... | }
public createSubOrganization($event: any, node: any): void
{
$event.stopPropagation();
this.$location.path("/Organizations/" + node.id + "/Organizations");
}
public get canEdit(): boolean
{
return !this.isEditModeEnabled && this.mode... | this.$location.path("/Organizations/" + orgId);
}
| conditional_block |
OrganizationTreeController.ts | "use strict";
module ServiceRegister
{
export class OrganizationTreeController implements Affecto.Base.IController
{
public static $inject = ["$scope", "$routeParams", "$location", "organizationService", "busyIndicationService"];
public model: Tree;
public selectedOrganizationId: stri... |
public enableEditMode(): void
{
this.isEditModeEnabled = true;
}
public disableEditMode(): void
{
this.isEditModeEnabled = false;
}
private createTreeOptions(): void
{
this.treeOptions = {
templateUrl:... | {
return !this.isEditModeEnabled && this.model != null && this.model.value != null && this.model.value.length > 0;
} | random_line_split |
OrganizationTreeController.ts | "use strict";
module ServiceRegister
{
export class OrganizationTreeController implements Affecto.Base.IController
{
public static $inject = ["$scope", "$routeParams", "$location", "organizationService", "busyIndicationService"];
public model: Tree;
public selectedOrganizationId: stri... | public get canEdit(): boolean
{
return !this.isEditModeEnabled && this.model != null && this.model.value != null && this.model.value.length > 0;
}
public enableEditMode(): void
{
this.isEditModeEnabled = true;
}
public disableEditMode(): ... | $event.stopPropagation();
this.$location.path("/Organizations/" + node.id + "/Organizations");
}
| identifier_body |
OrganizationTreeController.ts | "use strict";
module ServiceRegister
{
export class OrganizationTreeController implements Affecto.Base.IController
{
public static $inject = ["$scope", "$routeParams", "$location", "organizationService", "busyIndicationService"];
public model: Tree;
public selectedOrganizationId: stri... | : void
{
this.isEditModeEnabled = true;
}
public disableEditMode(): void
{
this.isEditModeEnabled = false;
}
private createTreeOptions(): void
{
this.treeOptions = {
templateUrl: "organizationTreeTemplate.html"... | ableEditMode() | identifier_name |
files.ts | import moment from 'moment';
import sanitizeFilename from 'sanitize-filename';
export const defaultProps = {
prefix: 'logs',
extension: 'zip',
isUTC: true,
sanitize: true,
};
type Props = {
prefix?: string;
extension?: string;
// @ts-ignore ts-migrate(2709) FIXME: Cannot use namespace 'moment' as a type.... | return fileName;
};
export const isFileNameWithTimestamp = (prefix = 'logs', extension = 'zip') => (
fileName: string
) =>
fileName.match(
RegExp(
`(${prefix}-)([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{6}.0[0-9]{3}Z)(.${extension})`
)
);
export const getPathSlash = (path: string) =>
path.indexOf('/') > ... | let fileName = `${prefix}-${`${date.format('YYYY-MM-DDTHHmmss.0SSS')}${z}`}${
extension ? '.' : ''
}${extension}`;
if (sanitize) fileName = sanitizeFilename(fileName); | random_line_split |
threading.rs | use std::sync::mpsc::{Receiver as MpscReceiver, TryRecvError};
use std::thread::Builder as ThreadBuilder;
use super::connection::Connection;
use super::Status;
use ::internal::Timer;
use ::model::GuildId;
pub fn start(guild_id: GuildId, rx: MpscReceiver<Status>) |
fn runner(rx: &MpscReceiver<Status>) {
let mut sender = None;
let mut receiver = None;
let mut connection = None;
let mut timer = Timer::new(20);
'runner: loop {
loop {
match rx.try_recv() {
Ok(Status::Connect(info)) => {
connection = match ... | {
let name = format!("Serenity Voice (G{})", guild_id);
ThreadBuilder::new()
.name(name)
.spawn(move || runner(&rx))
.expect(&format!("[Voice] Error starting guild: {:?}", guild_id));
} | identifier_body |
threading.rs | use std::sync::mpsc::{Receiver as MpscReceiver, TryRecvError};
use std::thread::Builder as ThreadBuilder;
use super::connection::Connection;
use super::Status;
use ::internal::Timer;
use ::model::GuildId;
pub fn start(guild_id: GuildId, rx: MpscReceiver<Status>) {
let name = format!("Serenity Voice (G{})", guild_i... | let mut sender = None;
let mut receiver = None;
let mut connection = None;
let mut timer = Timer::new(20);
'runner: loop {
loop {
match rx.try_recv() {
Ok(Status::Connect(info)) => {
connection = match Connection::new(info) {
... | random_line_split | |
threading.rs | use std::sync::mpsc::{Receiver as MpscReceiver, TryRecvError};
use std::thread::Builder as ThreadBuilder;
use super::connection::Connection;
use super::Status;
use ::internal::Timer;
use ::model::GuildId;
pub fn | (guild_id: GuildId, rx: MpscReceiver<Status>) {
let name = format!("Serenity Voice (G{})", guild_id);
ThreadBuilder::new()
.name(name)
.spawn(move || runner(&rx))
.expect(&format!("[Voice] Error starting guild: {:?}", guild_id));
}
fn runner(rx: &MpscReceiver<Status>) {
let mut sen... | start | identifier_name |
countdown.js | /*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/
/* Change the items below to create you... |
else {
document.getElementById('count2').style.display = "none";
document.getElementById('dday').innerHTML = dday;
document.getElementById('dhour').innerHTML = dhour;
document.getElementById('dmin').innerHTML = dmin;
document.getElementById('dsec').innerHTML = dsec;
... | {
document.getElementById('count2').innerHTML = current;
document.getElementById('count2').style.display = "block";
document.getElementById('count2').style.width = "390px";
document.getElementById('dday').style.display = "none";
document.getElementById('dhour').style.display = "n... | conditional_block |
countdown.js | /*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/
/* Change the items below to create you... | document.getElementById('count2').innerHTML = current;
document.getElementById('count2').style.display = "block";
document.getElementById('count2').style.width = "390px";
document.getElementById('dday').style.display = "none";
document.getElementById('dhour').style.display = "non... | {
theyear = yr;themonth = m;theday = d;thehour = hr;theminute = min;
var today = new Date();
var todayy = today.getYear();
if (todayy < 1000) { todayy += 1900; }
var todaym = today.getMonth();
var todayd = today.getDate();
var todayh = today.getHours();
var todaymin = today.getMinutes();... | identifier_body |
countdown.js | /*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here! |
/* Change the items below to create your countdown target date and announcement once the target date and time are reached. */
var current = "It's Pony Time!"; //-->enter what you want the script to display when the target date and time are reached, limit to 20 characters
var year = 2015; //-->Enter the count d... | Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/ | random_line_split |
countdown.js | /*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/
/* Change the items below to create you... | (yr,m,d,hr,min){
theyear = yr;themonth = m;theday = d;thehour = hr;theminute = min;
var today = new Date();
var todayy = today.getYear();
if (todayy < 1000) { todayy += 1900; }
var todaym = today.getMonth();
var todayd = today.getDate();
var todayh = today.getHours();
var todaymin = toda... | countdown | identifier_name |
config.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// 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.
// Th... | () -> Self {
let toml = r#"
id_card=0
port = 40000
max_peer = 1
[[peers]]
id_card=0
ip = "127.0.0.1"
port = 40000
"#;
toml::decode_str(toml).unwrap()
}
}
#[cfg(test)]
mod test {
use super::NetConfig;
... | test_config | identifier_name |
config.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// 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.
// Th... |
}
#[cfg(test)]
mod test {
use super::NetConfig;
extern crate toml;
#[test]
fn basics() {
let toml = r#"
port = 40000
max_peer = 2
[[peers]]
ip = "127.0.0.1"
port = 40001
[[peers]]
ip = "127.0.0.1"
... | {
let toml = r#"
id_card=0
port = 40000
max_peer = 1
[[peers]]
id_card=0
ip = "127.0.0.1"
port = 40000
"#;
toml::decode_str(toml).unwrap()
} | identifier_body |
config.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// 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.
// Th... | id_card=0
port = 40000
max_peer = 1
[[peers]]
id_card=0
ip = "127.0.0.1"
port = 40000
"#;
toml::decode_str(toml).unwrap()
}
}
#[cfg(test)]
mod test {
use super::NetConfig;
extern crate toml;
#[test]
... | let toml = r#" | random_line_split |
wsgi.py | """
WSGI config for comic project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application) | from django.core.wsgi import get_wsgi_application | random_line_split |
cci_nested_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fail!();
}
#[inline]
pub fn new_int_alist<B:Copy>() -> alist<int, B> {
fn eq_int(&&a: int, &&b: int) -> bool { a == b }
return alist {eq_fn: eq_int, data: @mut ~[]};
}
#[inline]
pub fn new_int_alist_2<B:Copy>() -> alist<int, B> {
#[inline]
fn eq_int(&&a: int, &&b: int) -> bool { a == b }
... | { return entry.value; } | conditional_block |
cci_nested_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[inline]
pub fn new_int_alist<B:Copy>() -> alist<int, B> {
fn eq_int(&&a: int, &&b: int) -> bool { a == b }
return alist {eq_fn: eq_int, data: @mut ~[]};
}
#[inline]
pub fn new_int_alist_2<B:Copy>() -> alist<int, B> {
#[inline]
fn eq_int(&&a: int, &&b: int) -> bool { a == b }
return alist {eq_fn... | {
let eq_fn = lst.eq_fn;
for lst.data.each |entry| {
if eq_fn(entry.key, k) { return entry.value; }
}
fail!();
} | identifier_body |
cci_nested_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <A:Copy,B:Copy>(lst: alist<A,B>, k: A, v: B) {
lst.data.push(Entry{key:k, value:v});
}
pub fn alist_get<A:Copy,B:Copy>(lst: alist<A,B>, k: A) -> B {
let eq_fn = lst.eq_fn;
for lst.data.each |entry| {
if eq_fn(entry.key, k) { return entry.value; }
}
fail!();
}
#[inline]
pub fn new_int_alist... | alist_add | identifier_name |
cci_nested_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | #[legacy_modes];
pub struct Entry<A,B> {key: A, value: B}
pub struct alist<A,B> { eq_fn: @fn(A,A) -> bool, data: @mut ~[Entry<A,B>] }
pub fn alist_add<A:Copy,B:Copy>(lst: alist<A,B>, k: A, v: B) {
lst.data.push(Entry{key:k, value:v});
}
pub fn alist_get<A:Copy,B:Copy>(lst: alist<A,B>, k: A) -> B {
let eq_fn... | // 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, modified, or distributed
// except according to those terms.
| random_line_split |
run.py | Tprim, C, P
def learnAndPredict(Ti, C, TOList):
rng = np.random.RandomState(SEED)
learning_rate = learning_rate0
print np.mean(Ti[1000,:])
aminW = np.amin(Ti[:1000,:])
amaxW = np.amax(Ti[:1000,:])
Ti[:1000,:] = (Ti[:1000,:] - aminW) / (amaxW - aminW)
astdW = np.std(Ti[:1000,:]... | if jj%300000 == 0:
print jj/300000,
need = 1 - need
if need == 1:
pairNo = onesIter % Nones
ppp = onesIter / Nones
s,t = ONES[pairNo]
shift = rng.randint(0, ile - L)
onesIter += 1
if need == 0:
zer = rng.... | random_line_split | |
run.py | rr[pos] = val2 # to sum
pos+=1
nps = np.sum(rr)
_w = [_x for _x in rr if _x >= 0.2]
_wn = len(_w)
if nps < THREAD :
if nott > 0:
lenn.append(nott);
... | P=[]; lenn = []; nott = 0
_nps = []
_s = []
with open(path+sp) as ff:
for line in ff:
x,y = line.split(',')
P.append([float(x),float(y)])
print "opening"
with open(path+s) as f:
rlast = []; cnt = 0; arrayprev = []; Ti = []; ile = 0
for li... | identifier_body | |
run.py |
if cnt != 0:
pos = 0; r = []; rr2 = np.zeros(NN); rr = np.zeros(NN); rp = []
for x in line.split(','):
x_f = float(x)
rp.append(x_f)
for x in rp:
val2 = x - arrayprev[pos]
rr[p... | print str(cnt/1794), "% ", | conditional_block | |
run.py | Tprim, C, P
def | (Ti, C, TOList):
rng = np.random.RandomState(SEED)
learning_rate = learning_rate0
print np.mean(Ti[1000,:])
aminW = np.amin(Ti[:1000,:])
amaxW = np.amax(Ti[:1000,:])
Ti[:1000,:] = (Ti[:1000,:] - aminW) / (amaxW - aminW)
astdW = np.std(Ti[:1000,:])
ameanW = np.mean(Ti[:1000,:])
Ti[... | learnAndPredict | identifier_name |
issue-2311-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn foo<A:Copy>(b: A) -> foo<A> {
foo {
x: b
}
}
pub fn main() { }
| {
fail!();
} | identifier_body |
issue-2311-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn foo<A:Copy>(b: A) -> foo<A> {
foo {
x: b
}
}
pub fn main() { } | pub fn bar<B,C:clam<A>>(&self, c: C) -> B {
fail!();
} | random_line_split |
issue-2311-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
scatter-chart-util.ts | export default {
// compare(aData: any[][], dataIndex: number, fnCompare: (result: number) => boolean): any {
// let targetIndex = 0;
// for (let i = 1, len = aData.length; i < len; i++) {
// const result = aData[targetIndex][dataIndex] - aData[i][dataIndex];
// if (fnCompare... | // indexOf(aData: any[], value: any): number {
// for (let i = 0 ; i < aData.length ; i++) {
// if (aData[i] === value) {
// return i;
// }
// }
// return -1;
// },
// getBoundaryValue(oRange: { min: number, max: number}, value: number): number... | // return result < 0;
// }, | random_line_split |
extract_references.py | #!/usr/bin/env python
import os, sys, codecs, re
def usage():
print "Usage info for extract_references.py"
print " extract_references.py ref_sgml ref_prefix"
print
sys.exit()
def main():
if (len(sys.argv) < 3 or sys.argv[1] == "-h"):
usage()
sgml = codecs.open(sys.argv[1], "r", "utf-8")
pref... |
for ref_file in ref_files:
ref_file.close()
if __name__ == "__main__":
main()
| (cur_doc, cur_seg, cur_txt) = ref_sets[0][j]
for i in range(len(ref_sets)):
if (j >= len(ref_sets[i])):
continue
(doc, seg, txt) = ref_sets[i][j]
if (doc != cur_doc or seg != cur_seg):
print "[ERR] document, segment ids don't match up: "
print "\t" + doc + " vs. " + cur_doc... | conditional_block |
extract_references.py | #!/usr/bin/env python
import os, sys, codecs, re
def usage():
print "Usage info for extract_references.py"
print " extract_references.py ref_sgml ref_prefix"
print
sys.exit()
def main():
| cur_doc = doc_pattern.search(line).groups()[0]
if ("</refset " in line or
("<doc " in line and cur_doc in map(lambda x: x[0], cur_ref_set))):
ref_sets.append(cur_ref_set)
cur_ref_set = []
if ("<seg " in line):
cur_seg = seg_pattern.search(line).groups()[0]
cur_txt ... | if (len(sys.argv) < 3 or sys.argv[1] == "-h"):
usage()
sgml = codecs.open(sys.argv[1], "r", "utf-8")
prefix = sys.argv[2]
doc_pattern = re.compile('.* docid="([^"]*).*"')
seg_pattern = re.compile('.* id="([^"]*)".*')
ref_sets = []
cur_ref_set = []
cur_doc = ""
cur_seg = ""
cur_txt = ""
... | identifier_body |
extract_references.py | #!/usr/bin/env python
import os, sys, codecs, re
def usage():
print "Usage info for extract_references.py"
print " extract_references.py ref_sgml ref_prefix"
print
sys.exit()
def main():
if (len(sys.argv) < 3 or sys.argv[1] == "-h"):
usage()
sgml = codecs.open(sys.argv[1], "r", "utf-8")
pref... | cur_seg = seg_pattern.search(line).groups()[0]
cur_txt = re.sub("<[^>]*>", "", line_tc)
cur_ref_set.append((cur_doc, cur_seg, cur_txt))
ref_files = []
ref_count = len(ref_sets[0])
for i, ref_set in enumerate(ref_sets):
if (ref_count != len(ref_set)):
print "[ERR] reference lengths d... | random_line_split | |
extract_references.py | #!/usr/bin/env python
import os, sys, codecs, re
def | ():
print "Usage info for extract_references.py"
print " extract_references.py ref_sgml ref_prefix"
print
sys.exit()
def main():
if (len(sys.argv) < 3 or sys.argv[1] == "-h"):
usage()
sgml = codecs.open(sys.argv[1], "r", "utf-8")
prefix = sys.argv[2]
doc_pattern = re.compile('.* docid="([... | usage | identifier_name |
analyze_gsimg-newauth.py | # Copyright 2020 Google LLC
#
# 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://apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
if debug:
print('Top %d labels from Vision API: %s' % (top, rsp))
# push results to Sheet, get cells-saved count
fsize = k_ize(len(data))
row = [folder,
'=HYPERLINK("storage.cloud.google.com/%s/%s", "%s")' % (
bucket, gcsname, fname), mtype, ftime, fsize, rsp
]
... | return | conditional_block |
analyze_gsimg-newauth.py | # Copyright 2020 Google LLC
#
# 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://apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | (sheet, row):
'append row to a Google Sheet, return #cells added'
# call Sheets API to write row to Sheet (via its ID)
rsp = SHEETS.spreadsheets().values().append(
spreadsheetId=sheet, range='Sheet1',
valueInputOption='USER_ENTERED', body={'values': [row]}
).execute()
if rsp... | sheet_append_row | identifier_name |
analyze_gsimg-newauth.py | # Copyright 2020 Google LLC
#
# 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://apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
def gcs_blob_upload(fname, bucket, media, mimetype):
'upload an object to a Google Cloud Storage bucket'
# build blob metadata and upload via GCS API
body = {'name': fname, 'uploadType': 'multipart', 'contentType': mimetype}
return GCS.objects().insert(bucket=bucket, body=body,
media_bod... | 'download file from Drive and return file info & binary if found'
# search for file on Google Drive
rsp = DRIVE.files().list(q="name='%s'" % fname,
fields='files(id,name,mimeType,modifiedTime)'
).execute().get('files', [])
# download binary & return file info if found, else return None
... | identifier_body |
analyze_gsimg-newauth.py | # Copyright 2020 Google LLC
#
# 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://apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
# create API service endpoints
DRIVE = discovery.build('drive', 'v3', credentials=creds)
GCS = discovery.build('storage', 'v1', credentials=creds)
VISION = discovery.build('vision', 'v1', credentials=creds)
SHEETS = discovery.build('sheets', 'v4', credentials=creds)
def drive_get_img(fname):
'download fi... | 'client_secret.json', SCOPES)
creds = flow.run_local_server()
with open(TOKENS, 'w') as token:
token.write(creds.to_json()) | random_line_split |
kendo.columnmenu.js | 2.710 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please re... | '#}#'+
'#}#'+
'#if(showColumns){#'+
'<li class="k-item k-columns-item"><span class="k-link"><span class="k-sprite k-i-columns"></span>${messages.columns}</span><ul>'+
'#for (var col in columns) {#'+
... | '<li class="k-separator"></li>'+ | random_line_split |
kendo.columnmenu.js | .710 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please rev... |
});
}
},
_updateColumnsMenu: function() {
var columns = this._ownerColumns(),
allselector = map(columns, function(field) {
return "[" + kendo.attr("index") + "=" + field.index+ "]";
}).join(","),
... | {
that.owner.hideColumn(index);
} | conditional_block |
kendo.columnmenu.js | .710 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please rev... |
var ColumnMenu = Widget.extend({
init: function(element, options) {
var that = this,
link;
Widget.fn.init.call(that, element, options);
element = that.element;
options = that.options;
that.owner = options.owner;
tha... | {
if (!String.prototype.trim) {
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
} else {
text = text.trim();
}
return text.replace(/ /gi, "");
} | identifier_body |
kendo.columnmenu.js | .710 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please rev... | (text) {
if (!String.prototype.trim) {
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
} else {
text = text.trim();
}
return text.replace(/ /gi, "");
}
var ColumnMenu = Widget.extend({
init: function(element, options) {
... | trim | identifier_name |
viewpop.js | /*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.... | } else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel'... | {
$scope.status = "Error en la recepción de datos del servidor";
}
| conditional_block |
viewpop.js | /*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.... | }]); | random_line_split | |
app.js | var socket = require('express.io')();
var moment = require('moment');
var settings = require('./settings');
var schedule = require('node-schedule');
var geolib = require('geolib');
socket.http().io();
socket.io.route('init', function(req){
req.io.join(req.data);
req.io.join(req.data + ':ctrl');
var room =... | var milliseconds = Math.round(Math.pow(distance / settings.resolution, settings.throttle) * 1000);
var room = req.io.room(req.data.id + ':ctrl');
var job = new schedule.Job(function(){ room.broadcast('locate'); });
job.schedule(moment().add(milliseconds, 'milliseconds'));
});
module.exports = socket; |
//TODO: determine distance between self and nearest coordinate in feet.
var distance = 5200;
| random_line_split |
dataset-list.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { DataFormService } from '@geonature_common/form/data-form.service';
import { Router } from '@angular/router';
import { CruvedStoreService } from '../../services/cruved-store.service';
@Co... |
updateFilter(event) {
const val = event.target.value.toLowerCase();
// filter our data
this.datasets = this.temp.filter(function(d) {
return d.dataset_name.toLowerCase().indexOf(val) !== -1 || !val;
});
// Whenever the filter changes, always go back to the first page
this.table.offse... | {
this._router.navigate(['admin/dataset', id_dataset]);
} | identifier_body |
dataset-list.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { DataFormService } from '@geonature_common/form/data-form.service';
import { Router } from '@angular/router';
import { CruvedStoreService } from '../../services/cruved-store.service';
@Co... | });
// Whenever the filter changes, always go back to the first page
this.table.offset = 0;
}
} | // filter our data
this.datasets = this.temp.filter(function(d) {
return d.dataset_name.toLowerCase().indexOf(val) !== -1 || !val; | random_line_split |
dataset-list.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { DataFormService } from '@geonature_common/form/data-form.service';
import { Router } from '@angular/router';
import { CruvedStoreService } from '../../services/cruved-store.service';
@Co... | (id_dataset) {
this._router.navigate(['admin/dataset', id_dataset]);
}
updateFilter(event) {
const val = event.target.value.toLowerCase();
// filter our data
this.datasets = this.temp.filter(function(d) {
return d.dataset_name.toLowerCase().indexOf(val) !== -1 || !val;
});
// Whenev... | datasetEdit | identifier_name |
UserRepo.tsx | import React, { useContext } from 'react';
import { Box } from '@chakra-ui/react';
import { Branches, User as UserType } from '../restinpeace/fetchGithubApi';
import UILibContext, { UILib } from '../components/UILibContext';
export type DoMergePR = (num: number) => Promise<unknown>;
| readonly branches: Branches;
};
};
const UserRepo: React.FunctionComponent<UserRepoProps> = ({ user, repo, doMergePR }) => {
const { Repo, User, BranchTable } = useContext<UILib>(UILibContext);
return (
<React.Fragment>
{!user && <p>User not found.</p>}
{repo && <Re... | export type UserRepoProps = {
readonly doMergePR?: DoMergePR;
readonly user?: UserType;
readonly repo?: {
readonly name: string; | random_line_split |
base.py | # Copyright 2017 OP5 AB
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... | self.useFixture(ConfigFixture(CONF))
self.useFixture(EmptyPolicyFixture())
@staticmethod
def conf_override(**kw):
"""Override flag variables for a test."""
group = kw.pop('group', None)
for k, v in kw.items():
CONF.set_override(k, v, group)
class EmptyPolic... | class BaseTestCase(base.BaseTestCase):
def setUp(self):
super(BaseTestCase, self).setUp() | random_line_split |
base.py | # Copyright 2017 OP5 AB
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... |
class EmptyPolicyFixture(fixtures.Fixture):
"""Override the policy with an empty policy file.
This overrides the policy with a completely fake and synthetic
policy file.
"""
def setUp(self):
super(EmptyPolicyFixture, self).setUp()
self._prepare_policy()
policy_engine.POL... | CONF.set_override(k, v, group) | conditional_block |
base.py | # Copyright 2017 OP5 AB
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... |
class ConfigFixture(config_fixture.Config):
def setUp(self):
super(ConfigFixture, self).setUp()
CONF(args=[],
prog='api',
project='monasca',
version=0,
description='Testing monasca-api.common')
policy_opts.set_defaults(CONF)
class Bas... | def list_rules(self):
return [] | identifier_body |
base.py | # Copyright 2017 OP5 AB
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... | (config_fixture.Config):
def setUp(self):
super(ConfigFixture, self).setUp()
CONF(args=[],
prog='api',
project='monasca',
version=0,
description='Testing monasca-api.common')
policy_opts.set_defaults(CONF)
class BaseTestCase(base.BaseTes... | ConfigFixture | identifier_name |
cstool.rs | self {
Ok(t) => t,
Err(e) => {
eprintln!("error: {}", e);
exit(1);
}
}
}
}
/// Print register names
fn reg_names(cs: &Capstone, regs: &[RegId]) -> String {
let names: Vec<String> = regs.iter().map(|&x| cs.reg_name(x).unwrap()).collect... | i.op_str().unwrap_or("")
)
.is_ok();
if show_detail {
let detail = cs.insn_detail(i).expect("Failed to get insn detail");
let output: &[(&str, String)] = &[
("insn id:", format!("{:?}", i.id().0)),
("read regs:", reg_names(&cs... | {
info!("Got {} bytes", code.len());
let mut cs = Capstone::new_raw(arch, mode, extra_mode, endian).expect_exit();
if show_detail {
cs.set_detail(true).expect("Failed to set detail");
}
let stdout = io::stdout();
let mut handle = stdout.lock();
for i in cs.disasm_all(code, addr).e... | identifier_body |
cstool.rs | self {
Ok(t) => t,
Err(e) => {
eprintln!("error: {}", e);
exit(1);
}
}
}
}
/// Print register names
fn reg_names(cs: &Capstone, regs: &[RegId]) -> String {
let names: Vec<String> = regs.iter().map(|&x| cs.reg_name(x).unwrap()).collect... | () {
// Lowercase arches
let _arches: Vec<String> = Arch::variants()
.iter()
.map(|x| format!("{}", x).to_lowercase())
.collect();
let arches: Vec<&str> = _arches.iter().map(|x| x.as_str()).collect();
// Lowercase modes
let _modes: Vec<String> = Mode::variants()
.ite... | main | identifier_name |
cstool.rs | self {
Ok(t) => t,
Err(e) => {
eprintln!("error: {}", e);
exit(1);
}
}
}
}
/// Print register names
fn reg_names(cs: &Capstone, regs: &[RegId]) -> String {
let names: Vec<String> = regs.iter().map(|&x| cs.reg_name(x).unwrap()).collect... | .get_matches();
let direct_input_bytes: Vec<u8> = if let Some(file_path) = matches.value_of(FILE_ARG) {
let mut file = File::open(file_path).expect_exit();
let capacity = match file.metadata() {
Err(_) => DEFAULT_CAPACITY,
Ok(metadata) => metadata.len() as usize,
... | .arg(CODE_ARG)
.required(true),
) | random_line_split |
SMB_Core.py | # -*- coding: utf-8 -*-
# ============================================================================ #
# SMB_Core.py
#
# Copyright:
# Copyright (C) 2014 by Christopher R. Hertel
#
# $Id: SMB_Core.py; 2019-04-14 16:25:33 -0500; Christopher R. Hertel$
#
# -----------------------------... | ( msglen=0 ):
"""Return the number of padding octets needed for 8-octet alignment.
Input: msglen - The length of the bytestream that may need to be
padded. It is assumed that this bytestream starts
on an 8-octet boundary (otherwise, the results are
som... | SMB_Pad8 | identifier_name |
SMB_Core.py | # -*- coding: utf-8 -*-
# ============================================================================ #
# SMB_Core.py
#
# Copyright:
# Copyright (C) 2014 by Christopher R. Hertel
#
# $Id: SMB_Core.py; 2019-04-14 16:25:33 -0500; Christopher R. Hertel$
#
# -----------------------------... | # Wikipedia: NTFS
# https://en.wikipedia.org/wiki/NTFS
#
# Class Values:
# _EPOCH_DELTA_SECS - The number of seconds between the Windows Epoch
# and the Unix/POSIX/Linux/BSD/etc. Epoch.
_EPOCH_DELTA_SECS = 11644473600
@classmethod
def utcNow( cls ):
"""Return the c... | """FILETIME format time value handling.
FILETIME values are given in bozoseconds since the Windows Epoch. The
Windows Epoch is UTC midnight on 1-Jan-1601, and a bozosecond is equal
to 100 nanoseconds (or 1/10th of a microsecond, or 10^-7 seconds).
There is no "official" prefix for 10^-7, so use of the term
... | identifier_body |
SMB_Core.py | # -*- coding: utf-8 -*-
# ============================================================================ #
# SMB_Core.py
#
# Copyright:
# Copyright (C) 2014 by Christopher R. Hertel
#
# $Id: SMB_Core.py; 2019-04-14 16:25:33 -0500; Christopher R. Hertel$
#
# -----------------------------... | # http://msdn.microsoft.com/en-us/library/cc246482.aspx
#
# ============================================================================ #
#
"""Carnaval Toolkit: Core components
Classes, functions, and other objects used throughout this SMB protocol
implementation. Fundamental stuff.
"""
# Imports ------... | #
# [MS-SMB2] Microsoft Corporation, "Server Message Block (SMB) Protocol
# Versions 2 and 3" | random_line_split |
main.rs | extern crate rusoto;
use std::{thread, time};
use rusoto::rds::{RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
fn | () {
let database_instance_name = "rusototester2";
let credentials = DefaultCredentialsProvider::new().unwrap();
// Security groups in the default VPC will need modification to let you access this from the internet:
let rds_client = RdsClient::new(default_tls_client().unwrap(), credentials, Region::Us... | main | identifier_name |
main.rs | extern crate rusoto;
use std::{thread, time};
use rusoto::rds::{RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
fn main() |
println!("Going to make the database instance.");
let db_creation_result = rds_client.create_db_instance(&create_db_instance_request).unwrap();
println!("Created! \n\n{:?}", db_creation_result);
// The endpoint isn't available until the DB is created, let's wait for it:
let describe_instances_requ... | {
let database_instance_name = "rusototester2";
let credentials = DefaultCredentialsProvider::new().unwrap();
// Security groups in the default VPC will need modification to let you access this from the internet:
let rds_client = RdsClient::new(default_tls_client().unwrap(), credentials, Region::UsEas... | identifier_body |
main.rs | extern crate rusoto;
use std::{thread, time};
use rusoto::rds::{RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
fn main() {
let database_instance_name = "rusototester2";
let credentials = DefaultCredentialsProv... | backup_retention_period: Some(0),
db_instance_identifier: database_instance_name.to_string(),
db_instance_class: "db.t2.micro".to_string(),
// name and login details should match `.env` in rusoto-rocket
master_user_password: Some("TotallySecurePassword501".to_string()),
m... | random_line_split | |
main.rs | extern crate rusoto;
use std::{thread, time};
use rusoto::rds::{RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
fn main() {
let database_instance_name = "rusototester2";
let credentials = DefaultCredentialsProv... | ,
None => {
println!("Waiting for db to be available...");
thread::sleep(ten_seconds);
continue;
},
};
}
let endpoint_address = endpoint.address.unwrap();
let endpoint_port = endpoint.port.unwrap();
println!("\n\nendpoint: ... | {
endpoint = endpoint_result.clone();
break;
} | conditional_block |
bit_score.py | """
"""
import os
import sys
import argparse
from roblib import bcolors, stream_blast_results
__author__ = 'Rob Edwards'
def self_bit_scores(blastf, verbose=False):
"""
Generate a dict of self:self bitscores
"""
ss = {}
for b in stream_blast_results(blastf, verbose):
if b.query == b.db:
... | if b.db not in pb:
pb[b.db] = {}
# we normalize by the bitscore of the two proteins if we can!
if b.query in ss and b.db in ss:
nb = b.bitscore / ((ss[b.query] + ss[b.db])/2)
else:
# if we can't do that, we cheat and normalize
# the bit s... | if b.query not in pb:
pb[b.query] = {} | random_line_split |
bit_score.py | """
"""
import os
import sys
import argparse
from roblib import bcolors, stream_blast_results
__author__ = 'Rob Edwards'
def self_bit_scores(blastf, verbose=False):
"""
Generate a dict of self:self bitscores
"""
ss = {}
for b in stream_blast_results(blastf, verbose):
if b.query == b.db:
... | if b.db not in pb:
pb[b.db] = {}
# we normalize by the bitscore of the two proteins if we can!
if b.query in ss and b.db in ss:
nb = b.bitscore / ((ss[b.query] + ss[b.db])/2)
else:
# if we can't do that, we cheat and normalize
# the bit s... | """
Make a pairwise average bit score that is
the bitscore / average of two proteins self/self bit
score
;param blastf: the blastfile
:param ss: the self-self bitscores
:param outf: the output file to write
:param verbose: more output
:return a dict of all vs. all normalized bit scores
... | identifier_body |
bit_score.py | """
"""
import os
import sys
import argparse
from roblib import bcolors, stream_blast_results
__author__ = 'Rob Edwards'
def self_bit_scores(blastf, verbose=False):
"""
Generate a dict of self:self bitscores
"""
ss = {}
for b in stream_blast_results(blastf, verbose):
if b.query == b.db:
... | (blastf, ss, outf, verbose=False):
"""
Make a pairwise average bit score that is
the bitscore / average of two proteins self/self bit
score
;param blastf: the blastfile
:param ss: the self-self bitscores
:param outf: the output file to write
:param verbose: more output
:return a dic... | pairwise_bit_scores | identifier_name |
bit_score.py | """
"""
import os
import sys
import argparse
from roblib import bcolors, stream_blast_results
__author__ = 'Rob Edwards'
def self_bit_scores(blastf, verbose=False):
"""
Generate a dict of self:self bitscores
"""
ss = {}
for b in stream_blast_results(blastf, verbose):
if b.query == b.db:
... |
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=' ')
parser.add_argument('-b', help='blast input file', required=True)
parser.add_argument('-o', help="output file base (we write both .tsv and .mat formats)", required=True)
parser.add_argument('-v', help='verbose output', act... | out.write(p)
for q in allkeys:
if p == q:
out.write("\t0")
elif q in pb[p]:
out.write(f"\t{1-pb[p][q]}")
else:
out.write("\t1")
out.write("\n") | conditional_block |
server.py | import gpib
class PARWriteError(Exception):
pass
class PARReadError(Exception):
pass
class PARCellWorking(Exception):
pass
class Poll: | COMMAND_ERROR = 2
CURVE_DONE = 4
OVERLOAD = 16
SWEEP_DONE = 32
SRQ = 64
OUTPUT_READY = 128
class PAR(object):
def __init__(self, addres):
self.dev = gpib.dev(*addres)
self.write('DD 13')
self.write('TYPE Succesfull init"')
def write(self, c... | COMMAND_DONE = 1 | random_line_split |
server.py | import gpib
class PARWriteError(Exception):
pass
class PARReadError(Exception):
pass
class PARCellWorking(Exception):
pass
class Poll:
COMMAND_DONE = 1
COMMAND_ERROR = 2
CURVE_DONE = 4
OVERLOAD = 16
SWEEP_DONE = 32
SRQ = 64
OUTPUT_READY = 128
class | (object):
def __init__(self, addres):
self.dev = gpib.dev(*addres)
self.write('DD 13')
self.write('TYPE Succesfull init"')
def write(self, cmd):
while True:
status = ord(gpib.serial_poll(self.dev))
#print '.',
if status & Poll.CO... | PAR | identifier_name |
server.py | import gpib
class PARWriteError(Exception):
pass
class PARReadError(Exception):
pass
class PARCellWorking(Exception):
pass
class Poll:
COMMAND_DONE = 1
COMMAND_ERROR = 2
CURVE_DONE = 4
OVERLOAD = 16
SWEEP_DONE = 32
SRQ = 64
OUTPUT_READY = 128
class PAR... | break
elif status & Poll.COMMAND_DONE != 0:
raise PARReadError("Nothing to read")
return gpib.read(self.dev, 1024)
def ask(self, cmd):
self.write(cmd)
return self.read()
def wait_for_relay(self):
cell_hw_switch = int(p.ask("CS... | def __init__(self, addres):
self.dev = gpib.dev(*addres)
self.write('DD 13')
self.write('TYPE Succesfull init"')
def write(self, cmd):
while True:
status = ord(gpib.serial_poll(self.dev))
#print '.',
if status & Poll.COMMAND_DONE != ... | identifier_body |
server.py | import gpib
class PARWriteError(Exception):
pass
class PARReadError(Exception):
pass
class PARCellWorking(Exception):
pass
class Poll:
COMMAND_DONE = 1
COMMAND_ERROR = 2
CURVE_DONE = 4
OVERLOAD = 16
SWEEP_DONE = 32
SRQ = 64
OUTPUT_READY = 128
class PAR... |
elif status & Poll.COMMAND_DONE != 0:
raise PARReadError("Nothing to read")
return gpib.read(self.dev, 1024)
def ask(self, cmd):
self.write(cmd)
return self.read()
def wait_for_relay(self):
cell_hw_switch = int(p.ask("CS").split()[0])
... | break | conditional_block |
modelbase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tools/modelbase.py
#
#
# MODEL DEFINITION:
# 1. create a subclass.
# 2. set each definitions as below in the subclass.
#
# __structure__ = {} # define keys and the data type
# __required_fields__ = [] # lists required keys
# __default_values__ = {} # set def... |
def serialize(self):
"""Return the json formatted dict.
1. datetime.datetime -> YYYY/mm/dd/HH/MM/SS
returns:
object (dict): pure json format dict
"""
extracted = {}
for key in self.__structure__:
extracted[key] = datetime.datetime.strftime(... | """Return an instance as dictionary format.
returns:
object (dict): object only with keys in __structure__.
"""
extracted = {}
for key in self.__structure__:
extracted[key] = self[key]
if 'search_text' in self:
extracted['search_text'] = self... | identifier_body |
modelbase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tools/modelbase.py
#
#
# MODEL DEFINITION:
# 1. create a subclass.
# 2. set each definitions as below in the subclass.
#
# __structure__ = {} # define keys and the data type
# __required_fields__ = [] # lists required keys
# __default_values__ = {} # set def... | # animal_name = 'wild boar'
# cat = Animal({
# 'name': 'cat',
# 'num_of_legs': 4
# })
#
# cat.validate() # check types in __structure__ and run __validators__
# cat.purify() # convert to dict
# cat.serialize() # convert to json compatible dict
# cat._is_required_fields_satisfied() # raise RequiredKeyIsN... | random_line_split | |
modelbase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tools/modelbase.py
#
#
# MODEL DEFINITION:
# 1. create a subclass.
# 2. set each definitions as below in the subclass.
#
# __structure__ = {} # define keys and the data type
# __required_fields__ = [] # lists required keys
# __default_values__ = {} # set def... |
return extracted
def validate(self, target=None):
"""Validate properties usually before inserted or updated.
1. validate values according to rules written in the __validators__
2. validate values according to types written in the __structure__
returns:
result ... | extracted[key] = datetime.datetime.strftime(self[key], '%Y/%m/%d/%H/%M/%S')\
if isinstance(self[key], datetime.datetime) else self[key] | conditional_block |
modelbase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tools/modelbase.py
#
#
# MODEL DEFINITION:
# 1. create a subclass.
# 2. set each definitions as below in the subclass.
#
# __structure__ = {} # define keys and the data type
# __required_fields__ = [] # lists required keys
# __default_values__ = {} # set def... | (self):
"""Return an instance as dictionary format.
returns:
object (dict): object only with keys in __structure__.
"""
extracted = {}
for key in self.__structure__:
extracted[key] = self[key]
if 'search_text' in self:
extracted['sear... | purify | identifier_name |
docker.rs | _SOCKET).exists() || cfg!(target_os = "windows"))
{
volumes.push(format!("{}:{}", DOCKER_SOCKET, DOCKER_SOCKET));
}
let mut env_vars = vec![String::from("DEBUG"),
String::from("DO_CHECK"),
String::from("HAB_AUTH_TOKEN"),
... | image_identifier | identifier_name | |
docker.rs | _cert_file);
}
}
}
fn is_image_present(docker_cmd: &Path, image: &str) -> bool {
let mut cmd = Command::new(docker_cmd);
cmd.arg("images").arg(image).arg("-q");
debug!("Running command: {:?}", cmd);
let result = cmd.output().expect("Docker command failed to spawn");
!String::from_utf8_... | use crate::{command::studio::enter::SSL_CERT_FILE_ENVVAR,
hcore::{fs::CACHE_SSL_PATH, | random_line_split | |
docker.rs | if let Ok(cache_artifact_path) = henv::var(ARTIFACT_PATH_ENVVAR) {
// Don't use Path::join here as "\" can cause problems in Docker mounts
volumes.push(format!("{}:{}/{}",
cache_artifact_path, mnt_prefix, CACHE_ARTIFACT_PATH));
}
if let Ok(cache_ssl_path) = henv:... |
fn pull_image(docker_cmd: &Path, image: &str) -> Result<()> {
let mut cmd = Command::new(docker_cmd);
cmd.arg("pull")
.arg(image)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
debug!("Running command: {:?}", cmd);
let result = cmd.spawn()
.expect("Docker... | {
let mut cmd = Command::new(docker_cmd);
cmd.arg("version").arg("--format='{{.Server.Os}}'");
debug!("Running command: {:?}", cmd);
let result = cmd.output().expect("Docker command failed to spawn");
String::from_utf8_lossy(&result.stdout).contains("windows")
} | identifier_body |
authentication.component.ts | import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { NotificationService } from "../../services";
import { SettingsService } from "../../services";
@Component({
templateUrl: "./authentication.component.html",
styleUrls: ["./authentication.compon... |
public form: FormGroup;
constructor(private settingsService: SettingsService,
private notificationService: NotificationService,
private fb: FormBuilder) { }
public ngOnInit() {
this.settingsService.getAuthentication().subscribe(x => {
this.form = this.f... | })
export class AuthenticationComponent implements OnInit { | random_line_split |
authentication.component.ts | import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { NotificationService } from "../../services";
import { SettingsService } from "../../services";
@Component({
templateUrl: "./authentication.component.html",
styleUrls: ["./authentication.compon... | lse {
this.notificationService.success("There was an error when saving the Authentication settings");
}
});
}
}
| this.notificationService.success("Successfully saved Authentication settings");
} e | conditional_block |
authentication.component.ts | import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { NotificationService } from "../../services";
import { SettingsService } from "../../services";
@Component({
templateUrl: "./authentication.component.html",
styleUrls: ["./authentication.compon... | {
this.settingsService.getAuthentication().subscribe(x => {
this.form = this.fb.group({
allowNoPassword: [x.allowNoPassword],
requiredDigit: [x.requiredDigit],
requiredLength: [x.requiredLength],
requiredLowercase: [x.requiredLowercase... | OnInit() | identifier_name |
controller.common.js | /*
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
*/
YUI.add('master', function(Y, NAME) { | * The master module.
*
* @module master
*/
var DIMENSIONS = {
device: 'smartphone',
region: 'CA',
skin : 'grey'
};
/**
* Constructor for the Controller class.
*
* @class Controller
* @constructor
*/
Y.mojito.controllers[NAME] = {
init: function(config) {
... |
/** | random_line_split |
create-factory-git.directive.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... | () {
this.controller = 'CreateFactoryGitController';
this.controllerAs = 'createFactoryGitCtrl';
this.bindToController = true;
this.restrict = 'E';
this.templateUrl = 'app/factories/create-factory/git/create-factory-git.html';
// scope values
this.scope = {
location: '=cdvyGitLocati... | constructor | identifier_name |
create-factory-git.directive.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... | * @ngInject for Dependency injection
*/
constructor() {
this.controller = 'CreateFactoryGitController';
this.controllerAs = 'createFactoryGitCtrl';
this.bindToController = true;
this.restrict = 'E';
this.templateUrl = 'app/factories/create-factory/git/create-factory-git.html';
// scop... | /**
* Default constructor that is using resource | random_line_split |
decorators.py | import functools
class memoize(object):
def __init__ (self, func):
self.func = func
def __call__ (self, *args, **kwargs):
if (args, str(kwargs)) in self.__dict__:
value = self.__dict__[args, str(kwargs)]
else:
value = self.func(*args, **kwargs)
self... | return self.__class__(self.__get, fset, self.__del)
def deleter(self, fdel):
return self.__class__(self.__get, self.__set, fdel) | if self.__del is not None:
self.__del(obj, value)
def setter(self, fset): | random_line_split |
decorators.py | import functools
class memoize(object):
def __init__ (self, func):
self.func = func
def __call__ (self, *args, **kwargs):
if (args, str(kwargs)) in self.__dict__:
value = self.__dict__[args, str(kwargs)]
else:
value = self.func(*args, **kwargs)
self... | return self.__class__(self.__get, self.__set, fdel) | identifier_body | |
decorators.py | import functools
class memoize(object):
def __init__ (self, func):
self.func = func
def | (self, *args, **kwargs):
if (args, str(kwargs)) in self.__dict__:
value = self.__dict__[args, str(kwargs)]
else:
value = self.func(*args, **kwargs)
self.__dict__[args, str(kwargs)] = value
return value
def __repr__(self):
"""
Return the fun... | __call__ | identifier_name |
decorators.py | import functools
class memoize(object):
def __init__ (self, func):
self.func = func
def __call__ (self, *args, **kwargs):
if (args, str(kwargs)) in self.__dict__:
value = self.__dict__[args, str(kwargs)]
else:
|
return value
def __repr__(self):
"""
Return the function's docstring.
"""
return self.func.__doc__ or ''
def __get__(self, obj, objtype):
"""
Support instance methods.
"""
return functools.partial(self.__call__, obj)
class cached_property(obje... | value = self.func(*args, **kwargs)
self.__dict__[args, str(kwargs)] = value | conditional_block |
plot.ts | // Plot widget
// (c) Koheron
class Plot {
public n_pts: number;
public plot: jquery.flot.plot;
public plot_data: Array<Array<number>>;
public yLabel: string = "Power Spectral Density";
private peakDatapoint: number[];
| (document: Document, private fft: FFT, private plotBasics: PlotBasics) {
this.n_pts = this.fft.fft_size / 2;
this.peakDatapoint = [];
this.plot_data = [];
this.updatePlot();
}
updatePlot() {
this.fft.read_psd(this.fft.adc_input, (psd: Float32Array) => {
let ... | constructor | identifier_name |
plot.ts | // Plot widget
// (c) Koheron
class Plot {
public n_pts: number;
public plot: jquery.flot.plot;
public plot_data: Array<Array<number>>;
public yLabel: string = "Power Spectral Density";
private peakDatapoint: number[];
constructor(document: Document, private fft: FFT, private plotBasics: Plot... | }
let yUnit: string = (<HTMLInputElement>document.querySelector(".unit-input:checked")).value;
this.peakDatapoint = [this.plotBasics.x_max / this.n_pts , this.convertValue(psd[0], yUnit)];
for (let i: number = 0; i <= this.n_pts; i++) {
let freq: number ... | if (max_x != this.plotBasics.x_max) { // Sampling frequency has changed
this.plotBasics.x_max = max_x;
this.plotBasics.setRangeX(0, this.plotBasics.x_max); | random_line_split |
plot.ts | // Plot widget
// (c) Koheron
class Plot {
public n_pts: number;
public plot: jquery.flot.plot;
public plot_data: Array<Array<number>>;
public yLabel: string = "Power Spectral Density";
private peakDatapoint: number[];
constructor(document: Document, private fft: FFT, private plotBasics: Plot... |
let yUnit: string = (<HTMLInputElement>document.querySelector(".unit-input:checked")).value;
this.peakDatapoint = [this.plotBasics.x_max / this.n_pts , this.convertValue(psd[0], yUnit)];
for (let i: number = 0; i <= this.n_pts; i++) {
let freq: number = (i + 1) * t... | { // Sampling frequency has changed
this.plotBasics.x_max = max_x;
this.plotBasics.setRangeX(0, this.plotBasics.x_max);
} | conditional_block |
vpc.read.service.spec.js | 'use strict';
| window.module(
require('./vpc.read.service.js')
)
);
beforeEach(window.inject(function ($httpBackend, $rootScope, _vpcReader_) {
service = _vpcReader_;
$http = $httpBackend;
$scope = $rootScope.$new();
}));
beforeEach(function() {
$http.whenGET('/vpcs').respond(200, [
{ nam... | describe('vpcReader', function() {
var service, $http, $scope;
beforeEach( | random_line_split |
gulpfile.js | // #####################################################################################################################
// #IMPORTS#
var gulp = require('gulp');
var gutil = require('gulp-util');
var plumber = require('gulp-plumber');
var fs = require('fs');
var autoprefixer = require('autoprefixer');
var postcss = req... |
});
};
};
gulp.task('bundle:watch', webpackBundle({ watch: true }));
gulp.task('bundle', webpackBundle());
gulp.task('watch', function() {
gulp.start('bundle:watch');
gulp.watch(PROJECT_PATTERNS.sass, ['sass']);
gulp.watch(PROJECT_PATTERNS.js, ['lint']);
});
gulp.task('default', ['sass', 'li... | {
done();
} | conditional_block |
gulpfile.js | // #####################################################################################################################
// #IMPORTS#
var gulp = require('gulp');
var gutil = require('gulp-util');
var plumber = require('gulp-plumber');
var fs = require('fs');
var autoprefixer = require('autoprefixer');
var postcss = req... | 'editContent',
'editContentTools',
'publish',
'loginToolbar',
'changeSettings',
'toolbar-login-apphooks',
'permissions-enabled',
{
serverArgs: '--CMS_PERMISSION=False --CMS_TOOLBAR_URL__EDIT_ON=test-edit',
file: 'copy-from-language'... | 'switchLanguage', | random_line_split |
extra.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/. */
//! Code for managing the layout data in the DOM.
use util::{PrivateLayoutData, LayoutDataAccess, LayoutDataWrapp... | } | random_line_split | |
extra.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/. */
//! Code for managing the layout data in the DOM.
use util::{PrivateLayoutData, LayoutDataAccess, LayoutDataWrapp... | (&self, chan: LayoutChan) {
for n in self.traverse_preorder() {
n.initialize_layout_data(chan.clone());
}
}
}
| initialize_style_for_subtree | identifier_name |
extra.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/. */
//! Code for managing the layout data in the DOM.
use util::{PrivateLayoutData, LayoutDataAccess, LayoutDataWrapp... |
/// Resets layout data and styles for a Node tree.
///
/// FIXME(pcwalton): Do this as part of fragment building instead of in a traversal.
fn initialize_style_for_subtree(&self, chan: LayoutChan) {
for n in self.traverse_preorder() {
n.initialize_layout_data(chan.clone());
... | {
let mut layout_data_ref = self.mutate_layout_data();
match *layout_data_ref {
None => {
*layout_data_ref = Some(LayoutDataWrapper {
chan: Some(chan),
shared_data: SharedLayoutData { style: None },
data: box Private... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.