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 |
|---|---|---|---|---|
app.py | # -*- coding: utf-8 -*-
# (c) 2015 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
from kotori.version import __VERSION__
from pyramid.config import Configurator
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
settings['SOFTWARE_VERSION'] = __VERSION__
confi... |
# Addons
config.include('pyramid_jinja2')
# http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/#adding-or-overriding-a-renderer
config.add_jinja2_renderer('.html')
config.include('cornice')
# Views and routes
config.add_static_view('static/app', 'static/app', cache_max_age=0)
... | random_line_split | |
test_simple_replace.rs | use std::process::{Command, Stdio};
use std::io::{Read, Write};
use common::*;
#[test]
fn | () {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let output = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-Y", "-Q", "it/file3"])
.output()
.expect("123");
assert!(output.status.success());
assert_eq!("", String::from_utf8_lossy(&output... | simple_replace1 | identifier_name |
test_simple_replace.rs | use std::process::{Command, Stdio};
use std::io::{Read, Write};
use common::*;
#[test]
fn simple_replace1() |
#[test]
fn ask_user_user_accepts_all() {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let process = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-C", "-Q", "it/file3"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.exp... | {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let output = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-Y", "-Q", "it/file3"])
.output()
.expect("123");
assert!(output.status.success());
assert_eq!("", String::from_utf8_lossy(&output.st... | identifier_body |
test_simple_replace.rs | use std::process::{Command, Stdio};
use std::io::{Read, Write};
use common::*;
#[test]
fn simple_replace1() {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let output = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-Y", "-Q", "it/file3"])
.output()
... | .args(&["-s", "a", "-x", "Z", "-C", "-Q", "it/file3"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("123");
let mut output = String::new();
let mut stdin = process.stdin.unwrap(); //.write_all("alfa".as_bytes());
// process.stdin.unwrap().write_... |
set_file_content("file3", "babababa");
let process = Command::new(BINARY_PATH) | random_line_split |
createToken.queryBuilder.ts | import { GraphqlQueryBuilder, GraphqlRequest } from './graphql.queryBuilder';
import { IsBoolean, IsNotEmpty, validateSync } from 'class-validator';
export class CreateTokenQueryBuilder implements GraphqlQueryBuilder {
@IsNotEmpty()
private username: string;
@IsNotEmpty()
private password: string;
@IsBoole... |
}
| {
this.rememberMe = rememberMe;
return this;
} | identifier_body |
createToken.queryBuilder.ts | import { GraphqlQueryBuilder, GraphqlRequest } from './graphql.queryBuilder';
import { IsBoolean, IsNotEmpty, validateSync } from 'class-validator';
export class CreateTokenQueryBuilder implements GraphqlQueryBuilder {
@IsNotEmpty()
private username: string;
@IsNotEmpty()
private password: string;
@IsBoole... | }
} | random_line_split | |
createToken.queryBuilder.ts | import { GraphqlQueryBuilder, GraphqlRequest } from './graphql.queryBuilder';
import { IsBoolean, IsNotEmpty, validateSync } from 'class-validator';
export class CreateTokenQueryBuilder implements GraphqlQueryBuilder {
@IsNotEmpty()
private username: string;
@IsNotEmpty()
private password: string;
@IsBoole... | (rememberMe: boolean) {
this.rememberMe = rememberMe;
return this;
}
}
| setRememberMe | identifier_name |
test_exteriorfuelequipment.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.exterior_equipment import ExteriorFuelEquipment
log = logging.getLogger(__name__)
class TestExteriorFuelEquipment(unittest.TestCase):
def setUp(self):
self.fd, self... |
idf2 = IDF(self.path)
self.assertEqual(idf2.exteriorfuelequipments[0].name, var_name)
self.assertEqual(idf2.exteriorfuelequipments[0].fuel_use_type, var_fuel_use_type)
self.assertEqual(idf2.exteriorfuelequipments[0].schedule_name, var_schedule_name)
self.assertAlmostEqual(idf2.... | log.debug(line.strip()) | conditional_block |
test_exteriorfuelequipment.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.exterior_equipment import ExteriorFuelEquipment
log = logging.getLogger(__name__)
class TestExteriorFuelEquipment(unittest.TestCase):
def setUp(self):
self.fd, self... | (self):
pyidf.validation_level = ValidationLevel.error
obj = ExteriorFuelEquipment()
# alpha
var_name = "Name"
obj.name = var_name
# alpha
var_fuel_use_type = "Electricity"
obj.fuel_use_type = var_fuel_use_type
# object-list
var_schedule_... | test_create_exteriorfuelequipment | identifier_name |
test_exteriorfuelequipment.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.exterior_equipment import ExteriorFuelEquipment
log = logging.getLogger(__name__)
class TestExteriorFuelEquipment(unittest.TestCase):
def setUp(self):
|
def tearDown(self):
os.remove(self.path)
def test_create_exteriorfuelequipment(self):
pyidf.validation_level = ValidationLevel.error
obj = ExteriorFuelEquipment()
# alpha
var_name = "Name"
obj.name = var_name
# alpha
var_fuel_use_type = "Elect... | self.fd, self.path = tempfile.mkstemp() | identifier_body |
test_exteriorfuelequipment.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.exterior_equipment import ExteriorFuelEquipment
log = logging.getLogger(__name__)
class TestExteriorFuelEquipment(unittest.TestCase):
def setUp(self):
self.fd, self... | self.assertEqual(idf2.exteriorfuelequipments[0].enduse_subcategory, var_enduse_subcategory) | self.assertAlmostEqual(idf2.exteriorfuelequipments[0].design_level, var_design_level) | random_line_split |
gp_media_button_v1.js | function gp_loadMediaButtonPopup(widget_name, shortcode, widget_title)
{
gp_hide_all_widget_popups();
var tag = jQuery('<div id="gold_plugins_popup"></div>');
var params = {
action: 'gold_plugins_insert_widget_popup',
widget_name: widget_name,
shortcode: shortcode
};
if (typeof(widget_title) ... |
// skip checkboxes and radio buttons that are not checked
if (jQuery(this).attr('type') == 'radio' && jQuery(this).attr('checked') != 'checked' ) {
return true;
}
else if (jQuery(this).attr('type') == 'checkbox' && jQuery(this).attr('checked') != 'checked' ) {
if(!jQuery(this).data('shortcode-v... | {
return true;
} | conditional_block |
gp_media_button_v1.js | function gp_loadMediaButtonPopup(widget_name, shortcode, widget_title)
| title: widget_title
};
tag.html(data).dialog(dialog_options).dialog('open');
}
});
gp_hide_all_media_button_menus();
//gp_close_popup_on_outside_click();
}
function gp_insertWidgetIntoPost()
{
// get the real names of all fields
var frm = jQuery('#gold_plugins_popup form');
var s... | {
gp_hide_all_widget_popups();
var tag = jQuery('<div id="gold_plugins_popup"></div>');
var params = {
action: 'gold_plugins_insert_widget_popup',
widget_name: widget_name,
shortcode: shortcode
};
if (typeof(widget_title) == 'undefined') {
widget_title = '';
}
jQuery.ajax({
... | identifier_body |
gp_media_button_v1.js | function gp_loadMediaButtonPopup(widget_name, shortcode, widget_title)
{
gp_hide_all_widget_popups();
var tag = jQuery('<div id="gold_plugins_popup"></div>');
var params = {
action: 'gold_plugins_insert_widget_popup',
widget_name: widget_name,
shortcode: shortcode
};
if (typeof(widget_title) ... | groups.on('click', '.gp_media_button_group_toggle', function () {
gp_toggle_media_button_menu(this);
});
}); | random_line_split | |
gp_media_button_v1.js | function | (widget_name, shortcode, widget_title)
{
gp_hide_all_widget_popups();
var tag = jQuery('<div id="gold_plugins_popup"></div>');
var params = {
action: 'gold_plugins_insert_widget_popup',
widget_name: widget_name,
shortcode: shortcode
};
if (typeof(widget_title) == 'undefined') {
widget_titl... | gp_loadMediaButtonPopup | identifier_name |
xxx_add_yyy_is_zzz.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::bench::bucketers::sextuple_max_bit_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::... | run_benchmark(
&format!(
"{}::xxx_add_yyy_is_zzz({}, {}, {}, {}, {}, {})",
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME
),
BenchmarkType::Single,
unsigned_sextuple_gen_var... | limit: usize,
file_name: &str,
) { | random_line_split |
xxx_add_yyy_is_zzz.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::bench::bucketers::sextuple_max_bit_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::... | })],
);
}
| {
run_benchmark(
&format!(
"{}::xxx_add_yyy_is_zzz({}, {}, {}, {}, {}, {})",
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME
),
BenchmarkType::Single,
unsigned_sextuple_gen_v... | identifier_body |
xxx_add_yyy_is_zzz.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::bench::bucketers::sextuple_max_bit_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::... | (runner: &mut Runner) {
register_unsigned_demos!(runner, demo_xxx_add_yyy_is_zzz);
register_unsigned_benches!(runner, benchmark_xxx_add_yyy_is_zzz);
}
fn demo_xxx_add_yyy_is_zzz<T: PrimitiveUnsigned>(gm: GenMode, config: GenConfig, limit: usize) {
for (x_2, x_1, x_0, y_2, y_1, y_0) in unsigned_sextuple_gen... | register | identifier_name |
Portfolio4.js | import React from 'react';
import {Link} from "react-router";
import Subheading from '../components/Subheading';
import Portfolio4col from '../components/Portfolio/Portfolio4col';
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title:"Welcome ... | () {
console.log(this.props);
}
render() {
return(
<div>
<Subheading title="Portfolio4col"/>
<Portfolio4col
projectImgPic1="http://placehold.it/700x300"
projectImgPic2="http://placehold.it/700x300"
projectImgPic3="http://placehold.it/700... | navigate | identifier_name |
Portfolio4.js | import React from 'react';
import {Link} from "react-router";
import Subheading from '../components/Subheading';
import Portfolio4col from '../components/Portfolio/Portfolio4col';
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title:"Welcome ... | } | }
| random_line_split |
Portfolio4.js | import React from 'react';
import {Link} from "react-router";
import Subheading from '../components/Subheading';
import Portfolio4col from '../components/Portfolio/Portfolio4col';
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title:"Welcome ... |
render() {
return(
<div>
<Subheading title="Portfolio4col"/>
<Portfolio4col
projectImgPic1="http://placehold.it/700x300"
projectImgPic2="http://placehold.it/700x300"
projectImgPic3="http://placehold.it/700x300"
projectImgPic4="http:/... | {
console.log(this.props);
} | identifier_body |
oaipmh.py | (self, context, config):
LOGGER.debug('Initializing OAI-PMH constants')
self.oaipmh_version = '2.0'
self.namespaces = {
'oai': 'http://www.openarchives.org/OAI/2.0/',
'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/',
'xsi': 'http://www.w3.org/2001/XMLS... | __init__ | identifier_name | |
oaipmh.py | ': ['resumptiontoken'],
'ListMetadataFormats': ['identifier'],
'GetRecord': ['identifier', 'metadataprefix'],
'ListRecords': ['from', 'until', 'set', 'resumptiontoken', 'metadataprefix'],
'ListIdentifiers': ['from', 'until', 'set', 'resumptiontoken', 'metadataprefix'],
... | elif kvp['verb'] == 'GetRecord':
kvpout['request'] = 'GetRecordById'
if 'identifier' in kvp:
kvpout['id'] = kvp['identifier']
if ('outputschema' in kvpout and
kvp['metadataprefix'] == 'oai_dc'): # just use default DC
... | """process OAI-PMH request"""
kvpout = {'service': 'CSW', 'version': '2.0.2', 'mode': 'oaipmh'}
LOGGER.debug('Incoming kvp: %s', kvp)
if 'verb' in kvp:
if 'metadataprefix' in kvp:
self.metadata_prefix = kvp['metadataprefix']
try:
kv... | identifier_body |
oaipmh.py | 'results'
kvpout['typenames'] = 'csw:Record'
kvpout['elementsetname'] = 'full'
if kvp['verb'] in ['Identify', 'ListMetadataFormats', 'ListSets']:
kvpout['request'] = 'GetCapabilities'
elif kvp['verb'] == 'GetRecord':
kvpout['reques... | if elname == 'oai:setSpec':
value = None
for k, v in self.metadata_sets.items():
if v[1] == elname:
value = k
break
el.text = value | conditional_block | |
oaipmh.py |
class OAIPMH(object):
"""OAI-PMH wrapper class"""
def __init__(self, context, config):
LOGGER.debug('Initializing OAI-PMH constants')
self.oaipmh_version = '2.0'
self.namespaces = {
'oai': 'http://www.openarchives.org/OAI/2.0/',
'oai_dc': 'http://www.openarchive... | random_line_split | ||
editor_plugin_src.js |
if (f.statusbar)
opt += ' mceStatusbar';
if (f.resizable)
opt += ' mceResizable';
if (f.minimizable)
opt += ' mceMinimizable';
if (f.maximizable)
opt += ' mceMaximizable';
if (f.movable)
opt += ' mceMovable';
// Create DOM objects
t._addAll(DOM.doc.body, ... |
opt += ' mceModal';
if (f.type)
opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1);
f.resizable = false;
}
| conditional_block | |
editor_plugin_src.js | ', href : 'javascript:;'}],
['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}]
]
]
);
DOM.setStyles(id, {top : -10000, left : -10000});
// Fix gecko rendering bug, where the editors iframe messed with window contents
if (tinym... |
eb = new Element('mceEventBlocker');
eb.update();
| random_line_split | |
editor_plugin_src.js | javascript:;'}],
['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}]
]
]
);
DOM.setStyles(id, {top : -10000, left : -10000});
// Fix gecko rendering bug, where the editors iframe messed with window contents
if (tinymce.isGecko)... |
if (eb)
return;
t._fixIELayout(id, 0);
// Setup event blocker
DOM.add(d.body, 'div', {
id : 'mceEventBlocker',
'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'),
style : {zIndex : t.zIndex + 1}
});
if (tinymce.isIE6 || (tin... | identifier_body | |
editor_plugin_src.js | tabindex : '-1', href : 'javascript:;'}],
['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}],
['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}],
['a', {id : id + '_resize_ne', 'class' : '... | tartMove( | identifier_name | |
issue-2735.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // <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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait hax { }
impl<A> hax for A { }
fn perform_hax<T: 'static>(x: Box<T>) -> Box<hax+'static> {
... | // 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 | random_line_split |
issue-2735.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 ... | <T: 'static>(x: Box<T>) -> Box<hax+'static> {
box x as Box<hax+'static>
}
fn deadcode() {
perform_hax(box "deadcode".to_string());
}
pub fn main() {
perform_hax(box 42);
}
| perform_hax | identifier_name |
issue-2735.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 deadcode() {
perform_hax(box "deadcode".to_string());
}
pub fn main() {
perform_hax(box 42);
}
| {
box x as Box<hax+'static>
} | identifier_body |
assignment.ts | import { SelectorFn, isDefined, isUndefined } from '@collectable/core';
import { remove, set } from '@collectable/red-black-tree';
import { update } from '@collectable/map';
import { Sorted, SortedSetItem, ValueMap } from './types';
var _nextIndex = 0;
export function setItem<T> (value: T, map: ValueMap<T>, tree: Sor... | <T> (value: T, map: ValueMap<T>, tree: Sorted<T>): boolean {
var entry: SortedSetItem<T>|undefined;
update(arg => {
if(isDefined(arg)) entry = arg;
return void 0;
}, value, map);
if(isDefined(entry)) {
remove(entry, tree);
return true;
}
return false;
}
| unsetItem | identifier_name |
assignment.ts | import { SelectorFn, isDefined, isUndefined } from '@collectable/core';
import { remove, set } from '@collectable/red-black-tree';
import { update } from '@collectable/map';
import { Sorted, SortedSetItem, ValueMap } from './types';
var _nextIndex = 0;
export function setItem<T> (value: T, map: ValueMap<T>, tree: Sor... |
return false;
}
export function unsetItem<T> (value: T, map: ValueMap<T>, tree: Sorted<T>): boolean {
var entry: SortedSetItem<T>|undefined;
update(arg => {
if(isDefined(arg)) entry = arg;
return void 0;
}, value, map);
if(isDefined(entry)) {
remove(entry, tree);
return true;
}
return... | random_line_split | |
assignment.ts | import { SelectorFn, isDefined, isUndefined } from '@collectable/core';
import { remove, set } from '@collectable/red-black-tree';
import { update } from '@collectable/map';
import { Sorted, SortedSetItem, ValueMap } from './types';
var _nextIndex = 0;
export function setItem<T> (value: T, map: ValueMap<T>, tree: Sor... |
export function unsetItem<T> (value: T, map: ValueMap<T>, tree: Sorted<T>): boolean {
var entry: SortedSetItem<T>|undefined;
update(arg => {
if(isDefined(arg)) entry = arg;
return void 0;
}, value, map);
if(isDefined(entry)) {
remove(entry, tree);
return true;
}
return false;
}
| {
var entry: SortedSetItem<T>|undefined;
update(arg => {
if(isUndefined(arg)) {
return entry = {
index: ++_nextIndex,
view: isDefined(select) ? select(value) : void 0,
value
};
}
}, value, map);
if(isDefined(entry)) {
set<SortedSetItem<T>, null>(entry, null, tre... | identifier_body |
graphite.py | from django.conf import settings
import requests
import logging
graphite_api = settings.GRAPHITE_API
user = settings.GRAPHITE_USER
password = settings.GRAPHITE_PASS
graphite_from = settings.GRAPHITE_FROM
auth = (user, password)
def get_data(target_pattern):
resp = requests.get(
graphite_api + 'render', a... |
else:
get_leafs_of_node(obj['path'])
get_leafs_of_node('')
return metrics
def parse_metric(metric, mins_to_check=5):
"""
Returns dict with:
- num_series_with_data: Number of series with data
- num_series_no_data: Number of total series
- max
- min
- ave... | metrics.append(obj['path']) | conditional_block |
graphite.py | from django.conf import settings
import requests
import logging
graphite_api = settings.GRAPHITE_API
user = settings.GRAPHITE_USER
password = settings.GRAPHITE_PASS
graphite_from = settings.GRAPHITE_FROM
auth = (user, password)
def get_data(target_pattern):
resp = requests.get(
graphite_api + 'render', a... | Returns dict with:
- num_series_with_data: Number of series with data
- num_series_no_data: Number of total series
- max
- min
- average_value
"""
ret = {
'num_series_with_data': 0,
'num_series_no_data': 0,
'error': None,
'all_values': [],
'raw': '... | return metrics
def parse_metric(metric, mins_to_check=5):
""" | random_line_split |
graphite.py | from django.conf import settings
import requests
import logging
graphite_api = settings.GRAPHITE_API
user = settings.GRAPHITE_USER
password = settings.GRAPHITE_PASS
graphite_from = settings.GRAPHITE_FROM
auth = (user, password)
def get_data(target_pattern):
resp = requests.get(
graphite_api + 'render', a... | (nodepath):
for obj in get_matching_metrics(nodepath)['metrics']:
if int(obj['is_leaf']) == 1:
metrics.append(obj['path'])
else:
get_leafs_of_node(obj['path'])
get_leafs_of_node('')
return metrics
def parse_metric(metric, mins_to_check=5):
""... | get_leafs_of_node | identifier_name |
graphite.py | from django.conf import settings
import requests
import logging
graphite_api = settings.GRAPHITE_API
user = settings.GRAPHITE_USER
password = settings.GRAPHITE_PASS
graphite_from = settings.GRAPHITE_FROM
auth = (user, password)
def get_data(target_pattern):
|
def get_matching_metrics(pattern):
print 'Getting metrics matching %s' % pattern
resp = requests.get(
graphite_api + 'metrics/find/', auth=auth,
params={
'query': pattern,
'format': 'completer'
},
headers={
'accept': 'application/json'
... | resp = requests.get(
graphite_api + 'render', auth=auth,
params={
'target': target_pattern,
'format': 'json',
'from': graphite_from
}
)
resp.raise_for_status()
return resp.json | identifier_body |
historical_bittrader.py | import csv
import matplotlib.pyplot as plt
import datetime
bit_history=[]
with open('bitHistory.csv','r') as bit_history_file:
hist_reader=csv.reader(bit_history_file,delimiter=',')
for line in hist_reader:
bit_history.append({'unix_time':int(line[0]),'price':float(line[1]),'amount':float(line[2])})
day=86400/2
... | elif hist_bit['price']<=(1.0-percent_swing)*last_price and (not have_coins):
# elif not have_coins:
print "Buy - Cur: " + str(hist_bit['price']) + " Last: " +str(last_price)
# buy coins
money=money-hist_bit['price']*coin_trade*(1.0+transaction_cost)-0.15
last_price=hist_bit['price']
last_trans... | last_trans_time=hist_bit['unix_time']
have_coins=False | random_line_split |
historical_bittrader.py | import csv
import matplotlib.pyplot as plt
import datetime
bit_history=[]
with open('bitHistory.csv','r') as bit_history_file:
hist_reader=csv.reader(bit_history_file,delimiter=',')
for line in hist_reader:
bit_history.append({'unix_time':int(line[0]),'price':float(line[1]),'amount':float(line[2])})
day=86400/2
... |
elif hist_bit['price']<=(1.0-percent_swing)*last_price and (not have_coins):
# elif not have_coins:
print "Buy - Cur: " + str(hist_bit['price']) + " Last: " +str(last_price)
# buy coins
money=money-hist_bit['price']*coin_trade*(1.0+transaction_cost)-0.15
last_price=hist_bit['price']
last_tran... | print "Sell - Cur: " + str(hist_bit['price']) + " Last: " +str(last_price)
money=money+hist_bit['price']*coin_trade*(1.0-transaction_cost)-0.15
last_price=hist_bit['price']
last_trans_time=hist_bit['unix_time']
have_coins=False | conditional_block |
db.rs | // Fucking Weeb
// Copyright © Jaume Delclòs Coll
//
// This file is part of Fucking Weeb.
//
// Fucking Weeb 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 o... |
pub player: String,
pub path: String,
pub autoplay: bool,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct WeebDB {
pub settings: Settings,
pub shows: Vec<Show>,
}
pub fn load_db() -> WeebDB {
let default_settings = WeebDB {
settings: Settings {
player: "mpv".to_strin... | ttings { | identifier_name |
db.rs | // Fucking Weeb
// Copyright © Jaume Delclòs Coll
//
// This file is part of Fucking Weeb.
//
// Fucking Weeb 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 o... | Ok(a) => a,
Err(e) => {
println!("error decoding db json: {}", e.to_string());
default_settings
}
}
}
pub fn save_db(settings: &Settings, items: &Vec<Show>) {
let db = WeebDB {
settings: settings.clone(),
shows: items.clone(),
};
// TODO: ... | }
Ok(_) => ()
}
match serde_json::from_str(&s) { | random_line_split |
test_MonitorManager.py | import unittest
import MonitorManager
import RamByteMonitor
import Constants
import logging
import Utils
#TODO figure out proper logging practice.
logging.basicConfig(level=logging.INFO)
class TestMonitorManager(unittest.TestCase):
def setUp(self):
self.manager = MonitorManager.MonitorManager()
... | (self):
mon1 = self.manager.create_monitor(Constants.STORAGE_BYTE_MONITOR + "ASDAS")#a garbage mount point.
self.assertIsNone(mon1)
def test_handle_config_successful_call(self):
mp = Utils.get_drive_mountpoints()[0]
cpu_mon = self.manager.create_monitor(Constants.CPU_PERCENT_MONITOR... | test_monitor_factory_fails_on_bad_option_parse | identifier_name |
test_MonitorManager.py | import unittest
import MonitorManager
import RamByteMonitor
import Constants
import logging
import Utils
#TODO figure out proper logging practice.
logging.basicConfig(level=logging.INFO)
class TestMonitorManager(unittest.TestCase):
def setUp(self):
self.manager = MonitorManager.MonitorManager()
... | unittest.main() | conditional_block | |
test_MonitorManager.py | import unittest
import MonitorManager
import RamByteMonitor
import Constants
import logging
import Utils
#TODO figure out proper logging practice.
logging.basicConfig(level=logging.INFO)
class TestMonitorManager(unittest.TestCase):
def setUp(self):
self.manager = MonitorManager.MonitorManager()
... | print(self.manager.list_monitors())
self.assertTrue(len(self.manager.list_monitors()) == 0)
def test_monitor_factory_generates_correct_monitor(self):
mon1 = self.manager.create_monitor(Constants.RAM_BYTE_MONITOR)
self.assertIsInstance(mon1, RamByteMonitor.RamByteMonitor)
def te... | random_line_split | |
test_MonitorManager.py | import unittest
import MonitorManager
import RamByteMonitor
import Constants
import logging
import Utils
#TODO figure out proper logging practice.
logging.basicConfig(level=logging.INFO)
class TestMonitorManager(unittest.TestCase):
def setUp(self):
self.manager = MonitorManager.MonitorManager()
... |
def test_handle_config_successful_call(self):
mp = Utils.get_drive_mountpoints()[0]
cpu_mon = self.manager.create_monitor(Constants.CPU_PERCENT_MONITOR)
self.manager.add_monitor(cpu_mon)
config_dict = {
"add": [
Constants.RAM_BYTE_MONITOR,
... | mon1 = self.manager.create_monitor(Constants.STORAGE_BYTE_MONITOR + "ASDAS")#a garbage mount point.
self.assertIsNone(mon1) | identifier_body |
wait.rs | `](crate::sys::signal::Signal::SIGTTOU),
/// [`SIGTSTP`](crate::sys::signal::Signal::SIGTSTP), or
/// [`SIGSTOP`](crate::sys::signal::Signal::SIGSTOP) signal.
WUNTRACED;
/// Report the status of selected processes which have terminated.
#[cfg(any(target_os = "android",
... | (status: i32) -> bool {
libc::WCOREDUMP(status)
}
fn stopped(status: i32) -> bool {
libc::WIFSTOPPED(status)
}
fn stop_signal(status: i32) -> Result<Signal> {
Signal::try_from(libc::WSTOPSIG(status))
}
#[cfg(any(target_os = "android", target_os = "linux"))]
fn syscall_stop(status: i32) -> bool {
// F... | dumped_core | identifier_name |
wait.rs | `](crate::sys::signal::Signal::SIGTTOU),
/// [`SIGTSTP`](crate::sys::signal::Signal::SIGTSTP), or
/// [`SIGSTOP`](crate::sys::signal::Signal::SIGSTOP) signal.
WUNTRACED;
/// Report the status of selected processes which have terminated.
#[cfg(any(target_os = "android",
... |
fn signaled(status: i32) -> bool {
libc::WIFSIGNALED(status)
}
fn term_signal(status: i32) -> Result<Signal> {
Signal::try_from(libc::WTERMSIG(status))
}
fn dumped_core(status: i32) -> bool {
libc::WCOREDUMP(status)
}
fn stopped(status: i32) -> bool {
libc::WIFSTOPPED(status)
}
fn stop_signal(stat... | {
libc::WEXITSTATUS(status)
} | identifier_body |
wait.rs | `](crate::sys::signal::Signal::SIGTTOU),
/// [`SIGTSTP`](crate::sys::signal::Signal::SIGTSTP), or
/// [`SIGSTOP`](crate::sys::signal::Signal::SIGSTOP) signal.
WUNTRACED;
/// Report the status of selected processes which have terminated.
#[cfg(any(target_os = "android",
... | }
fn exited(status: i32) -> bool {
libc::WIFEXITED(status)
}
fn exit_status(status: i32) -> i32 {
libc::WEXITSTATUS(status)
}
fn signaled(status: i32) -> bool {
libc::WIFSIGNALED(status)
}
fn term_signal(status: i32) -> Result<Signal> {
Signal::try_from(libc::WTERMSIG(status))
}
fn dumped_core(stat... | StillAlive => None,
#[cfg(any(target_os = "android", target_os = "linux"))]
PtraceEvent(p, _, _) | PtraceSyscall(p) => Some(p),
}
} | random_line_split |
lint-dead-code-5.rs | // Copyright 2014 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 ... | {
Variant1(int),
Variant2 //~ ERROR: variant is never used
}
enum Enum2 {
Variant3(bool),
#[allow(dead_code)]
Variant4(int),
Variant5 { _x: int }, //~ ERROR: variant is never used: `Variant5`
Variant6(int), //~ ERROR: variant is never used: `Variant6`
_Variant7,
}
enum Enum3 { //~ ERR... | Enum1 | identifier_name |
lint-dead-code-5.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // except according to those terms.
#![allow(unused_variables)]
#![deny(dead_code)]
enum Enum1 {
Variant1(int),
Variant2 //~ ERROR: variant is never used
}
enum Enum2 {
Variant3(bool),
#[allow(dead_code)]
Variant4(int),
Variant5 { _x: int }, //~ ERROR: variant is never used: `Variant5`
Va... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
lint-dead-code-5.rs | // Copyright 2014 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 ... | {
let v = Enum1::Variant1(1);
match v {
Enum1::Variant1(_) => (),
Enum1::Variant2 => ()
}
let x = Enum2::Variant3(true);
} | identifier_body | |
ami2stomp.py | #!/usr/bin/env python
# vim: set expandtab shiftwidth=4:
# http://www.voip-info.org/wiki/view/asterisk+manager+events
import asterisk.manager
import sys,os,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
from sqlobject import *
from handlers.command_handler_factory import CommandHan... | command_handler = CommandHandlerFactory(asteriskProtocolVersion).create_command_handler()
manager.register_event('Shutdown', command_handler.handle_Shutdown)
manager.register_event('Hangup', command_handler.handle_Hangup)
manager.register_event('Link', command_handler.handle_Link)
manager.register_event('Bridge', comm... | random_line_split | |
ami2stomp.py | #!/usr/bin/env python
# vim: set expandtab shiftwidth=4:
# http://www.voip-info.org/wiki/view/asterisk+manager+events
import asterisk.manager
import sys,os,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
from sqlobject import *
from handlers.command_handler_factory import CommandHan... |
command_handler = CommandHandlerFactory(asteriskProtocolVersion).create_command_handler()
manager.register_event('Shutdown', command_handler.handle_Shutdown)
manager.register_event('Hangup', command_handler.handle_Hangup)
manager.register_event('Link', command_handler.handle_Link)
manager.register_event('Bridge', co... | sys.exit() | conditional_block |
db.py | # -*- coding: utf-8 -*-
#
# 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
#... | with create_session() as session:
session.query(DagCode).delete()
def set_default_pool_slots(slots):
with create_session() as session:
default_pool = Pool.get_default_pool(session)
default_pool.slots = slots
def clear_rendered_ti_fields():
with create_session() as session:
... | session.query(Variable).delete()
def clear_db_dag_code(): | random_line_split |
db.py | # -*- coding: utf-8 -*-
#
# 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
#... | ():
with create_session() as session:
session.query(DagRun).delete()
session.query(TaskInstance).delete()
def clear_db_dags():
with create_session() as session:
session.query(DagTag).delete()
session.query(DagModel).delete()
def clear_db_sla_miss():
with create_session() ... | clear_db_runs | identifier_name |
db.py | # -*- coding: utf-8 -*-
#
# 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
#... |
def clear_db_variables():
with create_session() as session:
session.query(Variable).delete()
def clear_db_dag_code():
with create_session() as session:
session.query(DagCode).delete()
def set_default_pool_slots(slots):
with create_session() as session:
default_pool = Pool.get_... | with create_session() as session:
session.query(Connection).delete()
create_default_connections(session) | identifier_body |
index.tsx | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | export const FALLBACK_DAG_MAX_NUM_SERVICES = 100 as 100;
export const FALLBACK_TRACE_NAME = '<trace-without-root-span>' as '<trace-without-root-span>';
export const FETCH_DONE = 'FETCH_DONE' as 'FETCH_DONE';
export const FETCH_ERROR = 'FETCH_ERROR' as 'FETCH_ERROR';
export const FETCH_LOADING = 'FETCH_LOADING' as 'FET... | random_line_split | |
base.py | import os.path
from django.core.urlresolvers import reverse
from django.template import Context, Template
from django.template.defaultfilters import slugify
from django.test import TestCase
from django.test.client import Client
from radpress.compat import get_user_model
User = get_user_model()
from radpress.models imp... | (self):
# try to get response with GET method
response = self.client.get(reverse('radpress-preview'))
expected_status_code = 302 # because, login required
self.assertEqual(response.status_code, expected_status_code)
self.client.login(username='gokmen', password='secret')
... | test_preview_page | identifier_name |
base.py | import os.path
from django.core.urlresolvers import reverse
from django.template import Context, Template
from django.template.defaultfilters import slugify
from django.test import TestCase
from django.test.client import Client
from radpress.compat import get_user_model
User = get_user_model()
from radpress.models imp... | self.assertEqual(response.status_code, status_code)
def test_preview_page(self):
# try to get response with GET method
response = self.client.get(reverse('radpress-preview'))
expected_status_code = 302 # because, login required
self.assertEqual(response.status_code, exp... | def test_open_private_and_public_article_details(self):
for article in Article.objects.all():
status_code = 200 if article.is_published else 404
response = self.client.get(article.get_absolute_url()) | random_line_split |
base.py | import os.path
from django.core.urlresolvers import reverse
from django.template import Context, Template
from django.template.defaultfilters import slugify
from django.test import TestCase
from django.test.client import Client
from radpress.compat import get_user_model
User = get_user_model()
from radpress.models imp... |
def test_preview_page(self):
# try to get response with GET method
response = self.client.get(reverse('radpress-preview'))
expected_status_code = 302 # because, login required
self.assertEqual(response.status_code, expected_status_code)
self.client.login(username='gokmen'... | for article in Article.objects.all():
status_code = 200 if article.is_published else 404
response = self.client.get(article.get_absolute_url())
self.assertEqual(response.status_code, status_code) | identifier_body |
base.py | import os.path
from django.core.urlresolvers import reverse
from django.template import Context, Template
from django.template.defaultfilters import slugify
from django.test import TestCase
from django.test.client import Client
from radpress.compat import get_user_model
User = get_user_model()
from radpress.models imp... |
def test_preview_page(self):
# try to get response with GET method
response = self.client.get(reverse('radpress-preview'))
expected_status_code = 302 # because, login required
self.assertEqual(response.status_code, expected_status_code)
self.client.login(username='gokmen'... | status_code = 200 if article.is_published else 404
response = self.client.get(article.get_absolute_url())
self.assertEqual(response.status_code, status_code) | conditional_block |
ATNDeserializer.d.ts | /*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
import { ATN } from "./ATN";
import { ATNDeserializationOptions } from "./ATNDeserializationOptions";
import { ATNState } from "./ATNState";
... | import { UUID } from "../misc/UUID";
/**
*
* @author Sam Harwell
*/
export declare class ATNDeserializer {
static get SERIALIZED_VERSION(): number;
/**
* This is the earliest supported serialized UUID.
*/
private static readonly BASE_SERIALIZED_UUID;
/**
* This UUID indicat... | import { LexerActionType } from "./LexerActionType";
import { Transition } from "./Transition";
import { TransitionType } from "./TransitionType";
| random_line_split |
ATNDeserializer.d.ts | /*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
import { ATN } from "./ATN";
import { ATNDeserializationOptions } from "./ATNDeserializationOptions";
import { ATNState } from "./ATNState";
... | {
static get SERIALIZED_VERSION(): number;
/**
* This is the earliest supported serialized UUID.
*/
private static readonly BASE_SERIALIZED_UUID;
/**
* This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS}
* for the addition of lexer actions encoded as a ... | ATNDeserializer | identifier_name |
Bootstrapper.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, S. Chris Colbert
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|---------------------------------------------------------... |
if (!container.isRegistered('IRegionManager')) {
container.registerType('IRegionManager', RegionManager);
}
}
/**
* Configure the application plugins.
*
* Subclasses should reimplement this method to add the application
* plugins to the plugin list.
*
* The plugins will be initiali... | {
container.registerType('IPluginList', PluginList);
} | conditional_block |
Bootstrapper.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, S. Chris Colbert
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|---------------------------------------------------------... | {
/**
* Construct a new bootstrapper.
*/
constructor() { }
/**
* Get the dependency injection container for the application.
*
* This is created by the `createContainer` method.
*/
get container(): Container {
return this._container;
}
/**
* Get the plugin list for the applicatio... | Bootstrapper | identifier_name |
Bootstrapper.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, S. Chris Colbert
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|---------------------------------------------------------... | } // module phosphor.shell | private _container: Container = null;
private _pluginList: IPluginList = null;
}
| random_line_split |
Bootstrapper.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, S. Chris Colbert
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|---------------------------------------------------------... |
private _shell: Widget = null;
private _container: Container = null;
private _pluginList: IPluginList = null;
}
} // module phosphor.shell
| {
var shell = this.shell;
if (shell === null) {
return;
}
var elem = document.getElementById('main') || document.body;
var box = createBoxData(elem);
var doResize = () => shell.fitToHost(void 0, void 0, box);
window.addEventListener('resize', doResize);
shell.attach(elem);
shel... | identifier_body |
flags.rs | doc="and pointers used to reference data items in the database will be constant"]
#[doc="across multiple invocations. This option may not always work, depending on"]
#[doc="how the operating system has allocated memory to shared libraries and other uses."]
#[doc="The feature is highly experiment... | #[doc="`path` with `-lock` appended."]
const NO_SUB_DIR = MDB_NOSUBDIR;
#[doc="Use a writeable memory map unless `READ_ONLY` is set. This is faster and uses"]
#[doc="fewer mallocs, but loses protection from application bugs like wild pointer writes"]
#[doc="and other bad updates... | random_line_split | |
upload.py |
return join_with_separators(what_was_cleared)
def execute(self, options, args, tool):
committers = CommitterList()
for bug_id in tool.bugs.queries.fetch_bug_ids_from_pending_commit_list():
bug = self._tool.bugs.fetch_bug(bug_id)
patches = bug.patches(include_obsolet... | what_was_cleared.append("review+") | conditional_block | |
upload.py | # in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT H... | # * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer | random_line_split | |
upload.py | ://webkit.org/pending-commit." % (flags_to_clear, patch.id())
self._tool.bugs.obsolete_attachment(patch.id(), message)
# FIXME: This should be share more logic with AssignToCommitter and CleanPendingCommit
class CleanReviewQueue(AbstractDeclarativeCommand):
name = "clean-review-queue"
help_tex... | will prepare a ChangeLog. Once a patch is read, upload
will open the ChangeLogs for editing using the command in the
EDITOR environment variable and will display the diff using the
command in the PAGER environment variable."""
def _prepare_state(self, options, args, tool):
state = {}
... | name = "upload"
help_text = "Automates the process of uploading a patch for review"
argument_names = "[BUGID]"
show_in_main_help = True
steps = [
steps.ValidateChangeLogs,
steps.CheckStyle,
steps.PromptForBugOrTitle,
steps.CreateBug,
steps.PrepareChangeLog,
... | identifier_body |
upload.py | listed
in bugs.webkit.org for BUGID (or the bug ID detected from the ChangeLog).
The command then uploads the current diff to the bug and marks it for
commit by the commit-queue."""
show_in_main_help = True
steps = [
steps.UpdateChangeLogsWithReviewer,
steps.ValidateChangeLogs,
... | __init__ | identifier_name | |
api_handler.py | import requests
import json
import yaml
import pandas as pd
import pprint
from jsonld_processor import jsonld2nquads, fetchvalue
from utils import int2str
class SmartAPIHandler:
def __init__(self):
# description info about endpoint, bioentity and api
|
def find_base(self, d, relation={}):
for k, v in d.items():
if isinstance(v, dict) and "@context" in v and "@base" in v["@context"]:
if v["@context"]["@base"] not in relation:
relation[v["@context"]["@base"]] = [v["@id"]]
elif v["@context"]["... | self.endpoint_info = {}
self.bioentity_info = {}
self.api_info = {}
self.parse_id_mapping()
self.parse_openapi()
self.relation = {} | identifier_body |
api_handler.py | import requests
import json
import yaml
import pandas as pd
import pprint
from jsonld_processor import jsonld2nquads, fetchvalue
from utils import int2str
class SmartAPIHandler:
def | (self):
# description info about endpoint, bioentity and api
self.endpoint_info = {}
self.bioentity_info = {}
self.api_info = {}
self.parse_id_mapping()
self.parse_openapi()
self.relation = {}
def find_base(self, d, relation={}):
for k, v in d.items()... | __init__ | identifier_name |
api_handler.py | import requests
import json
import yaml
import pandas as pd
import pprint
from jsonld_processor import jsonld2nquads, fetchvalue
from utils import int2str
class SmartAPIHandler:
def __init__(self):
# description info about endpoint, bioentity and api
self.endpoint_info = {}
self.bioentity_i... | self.api_info[data['info']['title']]['endpoints'].append(data['servers'][0]['url'] + _name)
else:
print("invalid url for openapi: {}".format(openapi_url))
'''
construct requests params/data, based on input type and value
only handle 'in' value which is body o... | self.endpoint_info[data['servers'][0]['url'] + _name].update({'output': _output, 'relation': relation}) | random_line_split |
api_handler.py | import requests
import json
import yaml
import pandas as pd
import pprint
from jsonld_processor import jsonld2nquads, fetchvalue
from utils import int2str
class SmartAPIHandler:
def __init__(self):
# description info about endpoint, bioentity and api
self.endpoint_info = {}
self.bioentity_i... | response = self.endpoint_info[endpoint]['get']['responses']['200']['x-responseValueType']
for _response in response:
if _response['valueType'] == output:
output_path = _response['path']
outputs_command = 'json_doc'
for _item in output_path.split('.... | conditional_block | |
binary-tree-all-path-to-given-sum.py | #First case
#http://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/
'''Print all the paths from root, with a specified sum in Binary tree - For that Second If condition'''
'''Print all the paths from root, with a specified node in Binary tree - For that first If condition'''
class Node:
def | (self, key):
self.key = key
self.left = None
self.right = None
def findPath( root, path, k):
if root is None:
return False
path.append(root.key)
findPath(root.left, path, k)
findPath(root.right, path, k)
# If want to print all the path, from root to given node
... | __init__ | identifier_name |
binary-tree-all-path-to-given-sum.py | #First case
#http://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/
'''Print all the paths from root, with a specified sum in Binary tree - For that Second If condition'''
'''Print all the paths from root, with a specified node in Binary tree - For that first If condition'''
class Node:
def ... |
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(3)
path = []
findPath(root, path, 7)
| if root is None:
return False
path.append(root.key)
findPath(root.left, path, k)
findPath(root.right, path, k)
# If want to print all the path, from root to given node
if path[-1]==k:# path of -1 will give the las element
# if just appended element is the element that we are looking... | identifier_body |
binary-tree-all-path-to-given-sum.py | #First case
#http://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/
'''Print all the paths from root, with a specified sum in Binary tree - For that Second If condition''' | def __init__(self, key):
self.key = key
self.left = None
self.right = None
def findPath( root, path, k):
if root is None:
return False
path.append(root.key)
findPath(root.left, path, k)
findPath(root.right, path, k)
# If want to print all the path, from root... | '''Print all the paths from root, with a specified node in Binary tree - For that first If condition'''
class Node: | random_line_split |
binary-tree-all-path-to-given-sum.py | #First case
#http://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/
'''Print all the paths from root, with a specified sum in Binary tree - For that Second If condition'''
'''Print all the paths from root, with a specified node in Binary tree - For that first If condition'''
class Node:
def ... |
path.pop()
return False
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(3)
path = []
findPath(root, path, 7)
| print (path) | conditional_block |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | 'sequence': 14,
'summary': '',
'description': """
Portal Partner Fix
==================
Let user read his commercial partner
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'images': [
],
'depends': [
'portal',
],
'data': [
'security/portal_security... | 'version': '8.0.1.0.0',
'category': '', | random_line_split |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | let client = Client::new(&shared_config);
start_instance(&client, &instance_id).await
} |
let shared_config = aws_config::from_env().region(region_provider).load().await; | random_line_split |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | (client: &Client, id: &str) -> Result<(), Error> {
client.start_instances().instance_ids(id).send().await?;
println!("Started instance.");
Ok(())
}
// snippet-end:[ec2.rust.start-instance]
/// Starts an Amazon EC2 instance.
/// # Arguments
///
/// * `-i INSTANCE-ID` - The ID of the instances to start.
//... | start_instance | identifier_name |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
start_instance(&client, &instance_id).await
}
| {
println!("EC2 client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Instance ID: {}", instance_id);
println!();
} | conditional_block |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
start_instance(&client, &instance_id).await
}
| {
tracing_subscriber::fmt::init();
let Opt {
region,
instance_id,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbo... | identifier_body |
classificationTools.py | import nltk
import os
from random import shuffle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from datetime import datetime
from nltk imp... |
featuresets = [(find_features(rev), category) for (rev, category) in documents]
try:
d = SklearnClassifier(MultinomialNB())
d.train(featuresets[:300])
print(classify.accuracy(d, featuresets[300:]))
except:
print("d")
try:
a = NaiveBayesClassifier.train(featuresets[:300])
print(classify.accur... | words = set(document)
features = {}
for w in word_features:
features[w] = (w in words)
return features | identifier_body |
classificationTools.py | import nltk
import os
from random import shuffle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from datetime import datetime
from nltk imp... | from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
import pickle
def listOfFiles(flagged):
files = os.listdir(os.getcwd() + "/emai... | from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF | random_line_split |
classificationTools.py | import nltk
import os
from random import shuffle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from datetime import datetime
from nltk imp... | (classifier):
pickleClassifier = open(classifier.__name__ + datetime.now().strftime('%H:%M:%S') + ".pickle", "wb")
pickle.dump(classifier, pickleClassifier)
pickleClassifier.close()
return classifier
def loadClassifier(name):
pickledClassifier = open(name, "rb")
classifier = pickle.load(pickle... | saveClassifier | identifier_name |
classificationTools.py | import nltk
import os
from random import shuffle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from datetime import datetime
from nltk imp... |
return features
featuresets = [(find_features(rev), category) for (rev, category) in documents]
try:
d = SklearnClassifier(MultinomialNB())
d.train(featuresets[:300])
print(classify.accuracy(d, featuresets[300:]))
except:
print("d")
try:
a = NaiveBayesClassifier.train(featuresets[:300])
... | features[w] = (w in words) | conditional_block |
wordpress-media-upload.tsx | import styled from '@emotion/styled';
import debugFactory from 'debug';
import { useTranslate } from 'i18n-calypso';
import { useState } from 'react';
import placeholder from 'calypso/assets/images/difm/placeholder.svg';
import FilePicker from 'calypso/components/file-picker';
import Spinner from 'calypso/components/sp... | setUploadState( UPLOAD_STATES.FAILED );
onMediaUploadFailed && onMediaUploadFailed( { mediaIndex } );
debug( 'Image upload failed' );
debug( e.message );
}
};
switch ( uploadState ) {
case UPLOAD_STATES.COMPLETED:
return (
<FilePicker key={ mediaIndex } accept="image/*" onPick={ onPick }>
... | {
const [ uploadedImageUrl, setUploadedImageUrl ] = useState( initialUrl );
const [ uploadState, setUploadState ] = useState(
initialUrl ? UPLOAD_STATES.COMPLETED : UPLOAD_STATES.NOT_SELECTED
);
const [ imageCaption, setImageCaption ] = useState( initialCaption );
const translate = useTranslate();
const addMedi... | identifier_body |
wordpress-media-upload.tsx | import styled from '@emotion/styled';
import debugFactory from 'debug';
import { useTranslate } from 'i18n-calypso';
import { useState } from 'react';
import placeholder from 'calypso/assets/images/difm/placeholder.svg';
import FilePicker from 'calypso/components/file-picker';
import Spinner from 'calypso/components/sp... | ( {
mediaIndex,
site,
onMediaUploadComplete,
onMediaUploadStart,
onMediaUploadFailed,
initialUrl,
initialCaption,
}: WordpressMediaUploadProps ) {
const [ uploadedImageUrl, setUploadedImageUrl ] = useState( initialUrl );
const [ uploadState, setUploadState ] = useState(
initialUrl ? UPLOAD_STATES.COMPLETED :... | WordpressMediaUpload | identifier_name |
wordpress-media-upload.tsx | import styled from '@emotion/styled';
import debugFactory from 'debug';
import { useTranslate } from 'i18n-calypso';
import { useState } from 'react';
import placeholder from 'calypso/assets/images/difm/placeholder.svg';
import FilePicker from 'calypso/components/file-picker';
import Spinner from 'calypso/components/sp... | margin: 0 auto;
}
`;
export interface MediaUploadData {
title?: string;
URL?: string;
uploadID?: string;
mediaIndex: number;
}
interface WordpressMediaUploadProps {
onMediaUploadComplete: ( imageData: MediaUploadData ) => void;
onMediaUploadStart?: ( imageData: MediaUploadData ) => void;
onMediaUploadFailed?... | img {
max-height: 100%;
max-width: 100%; | random_line_split |
test.ts | import { Connection, Address } from './Connection';
import { BotRunner, BotConfig } from './BotRunner';
import { Client } from './Client';
import { MatchParams, MatchRunner } from './MatchRunner';
import { ClientLogger } from './Logger';
const tokens = ["aaaa", "bbbb"]; |
const addr: Address = {
host: "127.0.0.1",
port: 9142
};
const simpleBot: BotConfig = {
command: "python3",
args: ["../planetwars/bots/simplebot/simple.py"],
}
const bin_path = "../gameserver/target/debug/mozaic_bot_driver";
const players = [
{
name: 'timp',
token: "aaaa",
... | random_line_split | |
build.serializer.ts | /*
* VPDB - Virtual Pinball Database
* Copyright (C) 2019 freezy <freezy@vpdb.io>
*
* 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 2
* of the License, or (at your option) ... |
protected _simple(ctx: Context, doc: BuildDocument, opts: SerializerOptions): BuildDocument {
return pick(doc, ['id', 'label', 'platform', 'major_version', 'download_url', 'built_at', 'type', 'is_range']) as BuildDocument;
}
protected _detailed(ctx: Context, doc: BuildDocument, opts: SerializerOptions): BuildDo... | {
return pick(doc, ['id']) as BuildDocument;
} | identifier_body |
build.serializer.ts | /*
* VPDB - Virtual Pinball Database
* Copyright (C) 2019 freezy <freezy@vpdb.io>
*
* 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 2
* of the License, or (at your option) ... |
return build;
}
}
| {
build.created_by = state.serializers.User.reduced(ctx, doc._created_by as UserDocument, opts);
} | conditional_block |
build.serializer.ts | /*
* VPDB - Virtual Pinball Database
* Copyright (C) 2019 freezy <freezy@vpdb.io>
*
* 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 2
* of the License, or (at your option) ... | return pick(doc, ['id', 'label', 'platform', 'major_version', 'download_url', 'built_at', 'type', 'is_range']) as BuildDocument;
}
protected _detailed(ctx: Context, doc: BuildDocument, opts: SerializerOptions): BuildDocument {
const build = this._simple(ctx, doc, opts);
assign(build, pick(doc, ['support_url', ... | protected _reduced(ctx: Context, doc: BuildDocument, opts: SerializerOptions): BuildDocument {
return pick(doc, ['id']) as BuildDocument;
}
protected _simple(ctx: Context, doc: BuildDocument, opts: SerializerOptions): BuildDocument { | random_line_split |
build.serializer.ts | /*
* VPDB - Virtual Pinball Database
* Copyright (C) 2019 freezy <freezy@vpdb.io>
*
* 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 2
* of the License, or (at your option) ... | (ctx: Context, doc: BuildDocument, opts: SerializerOptions): BuildDocument {
const build = this._simple(ctx, doc, opts);
assign(build, pick(doc, ['support_url', 'description', 'is_active']));
if (this._populated(doc, '_created_by')) {
build.created_by = state.serializers.User.reduced(ctx, doc._created_by as Us... | _detailed | identifier_name |
WorkerClient.js | const JSONRPC = {
Client: require("../Client")
};
/**
* Extend this class to link to extra worker RPC APIs on the master.
*/
class WorkerClient extends JSONRPC.Client
{
/**
* @returns {never}
*/
async gracefulExit()
{
return this.rpc("gracefulExit", [], /*bNotification*/ true);
}
/*... |
};
module.exports = WorkerClient;
| {
return this.rpc("rpcToInternalEndpointAsLibrary", [...arguments]);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.