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 |
|---|---|---|---|---|
views.py | from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from django.utils.importlib import import_module
from djangae.core.pa... | (request):
errors = Error.objects.all()
# Filter by user email
if request.GET.get('user', None):
errors_pks = [e.error.pk for e in Event.objects.filter(logged_in_user_email=request.GET.get('user'))]
errors = errors.filter(pk__in=errors_pks)
errors = errors.order_by("-last_event")
... | index | identifier_name |
directives.js | 'use strict';
/* Directives */
angular.module('myApp.directives', [])
.directive('appVersion', function (version) {
return function(scope, elm, attrs) {
elm.text(version);
};
})
.directive('modal', function () {
return {
templateUrl: './app/common/modal.html',
// template: '<div class="modal fa... | $(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
... | random_line_split | |
pacman_conf.py | #!/usr/bin/env python3
#
# pacman_conf.py
#
# Based on pyalpm code Copyright (C) 2011 Rémy Oudompheng <remy@archlinux.org>
# Copyright © 2013-2015 DSGos
#
# This file is part of DSGos_Installer.
#
# DSGos_Installer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | else:
conf = '{0}{1} = {2}\n'.format(conf, key, value)
conf += '\n'
return conf | if key in LIST_OPTIONS:
for v in value:
conf = '{0}{1} = {2}\n'.format(conf, key, v)
elif key in BOOLEAN_OPTIONS:
conf = '{0}{1}\n'.format(conf, key) | random_line_split |
pacman_conf.py | #!/usr/bin/env python3
#
# pacman_conf.py
#
# Based on pyalpm code Copyright (C) 2011 Rémy Oudompheng <remy@archlinux.org>
# Copyright © 2013-2015 DSGos
#
# This file is part of DSGos_Installer.
#
# DSGos_Installer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | ollections.OrderedDict):
def __init__(self, conf=None, options=None):
super(PacmanConfig, self).__init__()
self['options'] = collections.OrderedDict()
self.options = self['options']
self.repos = collections.OrderedDict()
self.options["RootDir"] = "/"
self.options["DBP... | cmanConfig(c | identifier_name |
pacman_conf.py | #!/usr/bin/env python3
#
# pacman_conf.py
#
# Based on pyalpm code Copyright (C) 2011 Rémy Oudompheng <remy@archlinux.org>
# Copyright © 2013-2015 DSGos
#
# This file is part of DSGos_Installer.
#
# DSGos_Installer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | def __str__(self):
conf = ''
for section, options in self.items():
conf = '{0}[{1}]\n'.format(conf, section)
for key, value in options.items():
if key in LIST_OPTIONS:
for v in value:
conf = '{0}{1} = {2}\n'.format(c... | = handle.register_syncdb(repo, 0)
db_servers = []
for raw_url in servers:
url = raw_url.replace("$repo", repo)
url = url.replace("$arch", self.options["Architecture"])
db_servers.append(url)
db.servers = db_servers
| conditional_block |
pacman_conf.py | #!/usr/bin/env python3
#
# pacman_conf.py
#
# Based on pyalpm code Copyright (C) 2011 Rémy Oudompheng <remy@archlinux.org>
# Copyright © 2013-2015 DSGos
#
# This file is part of DSGos_Installer.
#
# DSGos_Installer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | def __str__(self):
return "unable to parse {0}, {1}: {2}".format(self.filename, self.problem, self.arg)
# Options that may occur several times in a section. Their values should be accumulated in a list.
LIST_OPTIONS = (
'CacheDir',
'HoldPkg',
'SyncFirst',
'IgnoreGroup',
'IgnorePkg',
... | lf.filename = filename
self.problem = problem
self.arg = arg
| identifier_body |
capitalize_test.js | import Ember from "ember-metal/core";
import {capitalize} from "ember-runtime/system/string";
QUnit.module('EmberStringUtils.capitalize');
if (!Ember.EXTEND_PROTOTYPES && !Ember.EXTEND_PROTOTYPES.String) {
test("String.prototype.capitalize is not modified without EXTEND_PROTOTYPES", function() {
ok("undefined" ... | test("capitalize underscored string", function() {
deepEqual(capitalize('action_name'), 'Action_name');
if (Ember.EXTEND_PROTOTYPES) {
deepEqual('action_name'.capitalize(), 'Action_name');
}
});
test("capitalize camelcased string", function() {
deepEqual(capitalize('innerHTML'), 'InnerHTML');
if (Ember.E... | deepEqual('css-class-name'.capitalize(), 'Css-class-name');
}
});
| random_line_split |
capitalize_test.js | import Ember from "ember-metal/core";
import {capitalize} from "ember-runtime/system/string";
QUnit.module('EmberStringUtils.capitalize');
if (!Ember.EXTEND_PROTOTYPES && !Ember.EXTEND_PROTOTYPES.String) {
test("String.prototype.capitalize is not modified without EXTEND_PROTOTYPES", function() {
ok("undefined" ... |
});
test("does nothing with capitalized string", function() {
deepEqual(capitalize('Capitalized string'), 'Capitalized string');
if (Ember.EXTEND_PROTOTYPES) {
deepEqual('Capitalized string'.capitalize(), 'Capitalized string');
}
});
| {
deepEqual('innerHTML'.capitalize(), 'InnerHTML');
} | conditional_block |
setup.py | from setuptools import setup
from setuptools.extension import Extension
import numpy as np
import os
if os.path.exists('MANIFEST'):
|
include_dirs = [np.get_include()]
setup(name="pystruct",
version="0.3.2",
install_requires=["ad3", "numpy"],
packages=['pystruct', 'pystruct.learners', 'pystruct.inference',
'pystruct.models', 'pystruct.utils', 'pystruct.datasets',
'pystruct.tests', 'pystruct.tests.t... | os.remove('MANIFEST') | conditional_block |
mod.rs | //! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
//! chapter for more info.
//!
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
use hir::Node;
use rustc_arena::DroplessArena;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle:... |
fn crate_variances(tcx: TyCtxt<'_>, (): ()) -> CrateVariancesMap<'_> {
let arena = DroplessArena::default();
let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &arena);
let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
solve::solve_constraints(constraints_cx)
}
fn va... | {
*providers = Providers { variances_of, crate_variances, ..*providers };
} | identifier_body |
mod.rs | //! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
//! chapter for more info.
//!
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
use hir::Node;
use rustc_arena::DroplessArena;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle:... | (tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
let id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
let unsupported = || {
// Variance not relevant.
span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item")
};
match tcx.hir().get(id) ... | variances_of | identifier_name |
mod.rs | //! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
//! chapter for more info.
//!
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
use hir::Node;
use rustc_arena::DroplessArena;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle:... |
_ => unsupported(),
},
Node::ImplItem(item) => match item.kind {
hir::ImplItemKind::Fn(..) => {}
_ => unsupported(),
},
Node::ForeignItem(item) => match item.kind {
hir::ForeignItemKind::Fn(..) => {}
_ => unsupported(),
... | {} | conditional_block |
mod.rs | //! Module for inferring the variance of type and lifetime parameters. See the [rustc dev guide]
//! chapter for more info.
//!
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/variance.html
use hir::Node;
use rustc_arena::DroplessArena;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle:... |
_ => unsupported(),
}
// Everything else must be inferred.
let crate_map = tcx.crate_variances(());
crate_map.variances.get(&item_def_id).copied().unwrap_or(&[])
} | random_line_split | |
prf.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
| {
Box::new(self.clone())
} | identifier_body |
prf.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (&self) -> Box<dyn Prf> {
Box::new(self.clone())
}
}
| box_clone | identifier_name |
prf.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | /// same key is used. `compute_prf(input, length1)` will be a prefix of `compute_prf(input,
/// length2)` if `length1` < `length2` and the same key is used.
/// * It is indistinguishable from a random function: Given the evaluation of n different inputs,
/// an attacker cannot distinguish between the PRF ... | /// The `Prf` trait is an abstraction for an element of a pseudo random
/// function family, selected by a key. It has the following property:
/// * It is deterministic. `compute_prf(input, length)` will always return the same output if the | random_line_split |
Simulation.py | #! /usr/bin/python
from TOSSIM import *
from sets import Set
import sys
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] filename",
version="%prog 1.0")
parser.add_option("-g", "--gainfile",
action="store",
dest="gainfile",
default="topology.txt",
help="file containing gains ... |
for node in nodes:
print "Creating noise model for node " + str(node) + "."
t.getNode(node).createNoiseModel()
# Boot time spread
boot_time = 0
for node in nodes:
t.getNode(node).bootAtTime(0 + boot_time);
boot_time += 50000000 # equal to 5 ms
# This runs the network for 50 seconds:
time = t.time()
while (time... | t.getNode(node).addNoiseTraceReading(val) | conditional_block |
Simulation.py | #! /usr/bin/python
from TOSSIM import *
from sets import Set
import sys
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] filename",
version="%prog 1.0")
parser.add_option("-g", "--gainfile",
action="store",
dest="gainfile",
default="topology.txt",
help="file containing gains ... | m = t.getNode(node)
v = m.getVariable("MacPerformanceC.received_packets")
received_packets = v.getData()
c = m.getVariable("MacPerformanceC.counter")
sent_packets = c.getData()
print "The node id", node, "has sent", sent_packets, "and received", received_packets, "in total.";
resultfile.write("%d,%d,%d\n" % (... | resultfile.write("%d\n" % (t.time()))
for node in nodes: | random_line_split |
observer.py | from twisted.internet import defer
from nodeset.common import log
from nodeset.core import config
class Observer(object):
def __init__(self, callable, *args, **kwargs):
self.callable = callable
self.args = args
self.kwargs = kwargs
#print "-- %s, %s" % (self.args, se... |
for i in observers:
defers.append(defer.maybeDeferred(i.run, eventDict))
return defers
| log.msg("twist carousel %s, %s" % (observers, eventDict)) | conditional_block |
observer.py | from twisted.internet import defer
from nodeset.common import log
from nodeset.core import config
class Observer(object):
def __init__(self, callable, *args, **kwargs):
self.callable = callable
self.args = args
self.kwargs = kwargs
#print "-- %s, %s" % (self.args, se... | (self, observers, eventDict):
defers = []
if config.Configurator['verbose']:
log.msg("twist carousel %s, %s" % (observers, eventDict))
for i in observers:
defers.append(defer.maybeDeferred(i.run, eventDict))
return defers
| twist | identifier_name |
observer.py | from twisted.internet import defer
from nodeset.common import log
from nodeset.core import config
class Observer(object):
def __init__(self, callable, *args, **kwargs):
self.callable = callable
self.args = args
self.kwargs = kwargs
#print "-- %s, %s" % (self.args, se... | defers = []
if config.Configurator['verbose']:
log.msg("twist carousel %s, %s" % (observers, eventDict))
for i in observers:
defers.append(defer.maybeDeferred(i.run, eventDict))
return defers | identifier_body | |
observer.py | from twisted.internet import defer
from nodeset.common import log
from nodeset.core import config
class Observer(object):
def __init__(self, callable, *args, **kwargs):
self.callable = callable
self.args = args
self.kwargs = kwargs
#print "-- %s, %s" % (self.args, se... | def twist(self, observers, eventDict):
defers = []
if config.Configurator['verbose']:
log.msg("twist carousel %s, %s" % (observers, eventDict))
for i in observers:
defers.append(defer.maybeDeferred(i.run, eventDict))
re... | class ObserverCarousel(object):
| random_line_split |
F95COMSTR.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... |
else:
f95pp = 'f95pp'
test.write('SConstruct', """
env = Environment(F95COM = r'%(_python_)s myfc.py f95 $TARGET $SOURCES',
F95COMSTR = 'Building f95 $TARGET from $SOURCES',
F95PPCOM = r'%(_python_)s myfc.py f95pp $TARGET $SOURCES',
F95PPCOMSTR = 'Building f9... | f95pp = 'f95' | conditional_block |
F95COMSTR.py | #!/usr/bin/env python | #
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell co... | #
# __COPYRIGHT__ | random_line_split |
dellemc_idrac_export_tsr.py | #! /usr/bin/python
# _*_ coding: utf-8 _*_
#
# Dell EMC OpenManage Ansible Modules
#
# Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved.
# Dell, EMC, and other trademarks are trademarks of Dell Inc. or its
# subsidiaries. Other trademarks may be trademarks of their respective owners.
#
# This progra... | module.exit_json(**msg)
if __name__ == '__main__':
main()
| odule.fail_json(**msg)
| conditional_block |
dellemc_idrac_export_tsr.py | #! /usr/bin/python
# _*_ coding: utf-8 _*_
#
# Dell EMC OpenManage Ansible Modules
#
# Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved.
# Dell, EMC, and other trademarks are trademarks of Dell Inc. or its
# subsidiaries. Other trademarks may be trademarks of their respective owners.
#
# This progra... | if not HAS_OMSDK:
module.fail_json(msg="Dell EMC OpenManage Python SDK required for this module")
# Connect to iDRAC
idrac_conn = iDRACConnection(module)
idrac = idrac_conn.connect()
# Export Tech Support Report (TSR)
msg, err = export_tech_support_report(idrac, module)
# Disconne... | odule = AnsibleModule(
argument_spec=dict(
# iDRAC Handle
idrac=dict(required=False, type='dict'),
# iDRAC Credentials
idrac_ip=dict(required=True, type='str'),
idrac_user=dict(required=True, type='str'),
idrac_pwd=dict(required=True, typ... | identifier_body |
dellemc_idrac_export_tsr.py | #! /usr/bin/python
# _*_ coding: utf-8 _*_
#
# Dell EMC OpenManage Ansible Modules
#
# Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved.
# Dell, EMC, and other trademarks are trademarks of Dell Inc. or its
# subsidiaries. Other trademarks may be trademarks of their respective owners.
#
# This progra... | ):
module = AnsibleModule(
argument_spec=dict(
# iDRAC Handle
idrac=dict(required=False, type='dict'),
# iDRAC Credentials
idrac_ip=dict(required=True, type='str'),
idrac_user=dict(required=True, type='str'),
idrac_pwd=dict(required=... | ain( | identifier_name |
dellemc_idrac_export_tsr.py | #! /usr/bin/python
# _*_ coding: utf-8 _*_
#
# Dell EMC OpenManage Ansible Modules
#
# Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved.
# Dell, EMC, and other trademarks are trademarks of Dell Inc. or its
# subsidiaries. Other trademarks may be trademarks of their respective owners.
#
# This progra... | idrac_conn = iDRACConnection(module)
idrac = idrac_conn.connect()
# Export Tech Support Report (TSR)
msg, err = export_tech_support_report(idrac, module)
# Disconnect from iDRAC
idrac_conn.disconnect()
if err:
module.fail_json(**msg)
module.exit_json(**msg)
if __name__ == '__... |
if not HAS_OMSDK:
module.fail_json(msg="Dell EMC OpenManage Python SDK required for this module")
# Connect to iDRAC | random_line_split |
infinite-loops.rs | // Copyright 2012-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-MI... |
loop { }
}
pub fn main() {
// Commenting this out, as this will hang forever otherwise.
// Even after seeing the comment above, I'm not sure what the
// intention of this test is.
// spawn(move|| { loopy(5) });
}
| { spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); } | conditional_block |
infinite-loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// 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
// except according to those terms.
/*
A simple wa... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
infinite-loops.rs | // Copyright 2012-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-MI... | {
// Commenting this out, as this will hang forever otherwise.
// Even after seeing the comment above, I'm not sure what the
// intention of this test is.
// spawn(move|| { loopy(5) });
} | identifier_body | |
infinite-loops.rs | // Copyright 2012-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-MI... | (n: isize) {
if n > 0 { spawn(move|| { loopy(n - 1) }); spawn(move|| { loopy(n - 1) }); }
loop { }
}
pub fn main() {
// Commenting this out, as this will hang forever otherwise.
// Even after seeing the comment above, I'm not sure what the
// intention of this test is.
// spawn(move|| { loopy(5... | loopy | identifier_name |
clock.js | /**
* Created by kerry on 15/5/20.
*/
(function($){
$.fn.clock = function(options){
var o=this; | o.day=0;
o.hour=0;
o.min=0;
o.sec=0;
o.load=__call__.load
__call__.auto_run.call(o);
return o;
}
var __call__={
load:function(seconds){
var w=this;
__function__.getTime.call(w,seconds);
__function__.showTime.call(... | random_line_split | |
clock.js | /**
* Created by kerry on 15/5/20.
*/
(function($){
$.fn.clock = function(options){
var o=this;
o.day=0;
o.hour=0;
o.min=0;
o.sec=0;
o.load=__call__.load
__call__.auto_run.call(o);
return o;
}
var __call__={
load:function(seconds){
... |
if(w.min==60){
w.min=0;
w.hour= w.hour+1;
}
if(w.hour==24){
w.hour=0;
w.day= w.day+1;
}
__function__.showTime.call(w);
},1000);
}
};
... | {
w.sec=0;
w.min= w.min+1;
} | conditional_block |
0010_remove_userstory_watchers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connection
from django.db import models, migrations
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.management import update_all_contenttypes
def | (apps, schema_editor):
update_all_contenttypes(verbosity=0)
sql="""
INSERT INTO notifications_watched (object_id, created_date, content_type_id, user_id, project_id)
SELECT userstory_id AS object_id, now() AS created_date, {content_type_id} AS content_type_id, user_id, project_id
FROM userstories_userstory_watc... | create_notifications | identifier_name |
0010_remove_userstory_watchers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connection
from django.db import models, migrations
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.management import update_all_contenttypes
def create_notifications(apps, schema_editor):... |
dependencies = [
('notifications', '0004_watched'),
('userstories', '0009_remove_userstory_is_archived'),
]
operations = [
migrations.RunPython(create_notifications),
migrations.RemoveField(
model_name='userstory',
name='watchers',
),
] |
class Migration(migrations.Migration): | random_line_split |
0010_remove_userstory_watchers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connection
from django.db import models, migrations
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.management import update_all_contenttypes
def create_notifications(apps, schema_editor):... | dependencies = [
('notifications', '0004_watched'),
('userstories', '0009_remove_userstory_is_archived'),
]
operations = [
migrations.RunPython(create_notifications),
migrations.RemoveField(
model_name='userstory',
name='watchers',
),
] | identifier_body | |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to g... | pub use custom::*;
pub use generated::*; | random_line_split | |
ovs_before_network_setup_ip.py | #!/usr/bin/env python
# Copyright 2015 Red Hat, Inc.
#
# 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) any later version.
#
# This program ... |
def _get_ipv6_model(attrs):
address = attrs.get('ipv6addr')
gateway = attrs.get('ipv6gateway')
default_route = attrs.get('defaultRoute')
autoconf = attrs.get('ipv6autoconf')
dhcp = attrs.get('dhcpv6')
return IPv6(address, gateway, default_route, autoconf, dhcp)
def _run_dhclient(iface, block... | return IPv4(address, netmask, gateway, default_route, bootproto) | random_line_split |
ovs_before_network_setup_ip.py | #!/usr/bin/env python
# Copyright 2015 Red Hat, Inc.
#
# 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) any later version.
#
# This program ... |
def _drop_ip_config(iface):
"""Remove IP configuration of a new nic controlled by VDSM"""
if os.path.exists(os.path.join('/sys/class/net', iface)):
kill_dhclient(iface, family=4) # kill_dhclient flushes IP
kill_dhclient(iface, family=6)
def configure_ip(nets, init_nets):
def _gather_i... | with suppress(ipwrapper.IPRoute2Error): # device does not exist
ipwrapper.addrFlush(iface) | conditional_block |
ovs_before_network_setup_ip.py | #!/usr/bin/env python
# Copyright 2015 Red Hat, Inc.
#
# 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) any later version.
#
# This program ... | (ip_config):
iface = ip_config.top_dev
ipv4 = ip_config.ipv4
ipv6 = ip_config.ipv6
net_dev = NetDevice(iface, iproute2, ipv4=ipv4, ipv6=ipv6)
DynamicSourceRoute.addInterfaceTracking(net_dev)
DhcpClient(iface).shutdown()
iproute2._removeSourceRoute(net_dev, DynamicSourceRoute)
if ipv4.ad... | _remove_ip_config | identifier_name |
ovs_before_network_setup_ip.py | #!/usr/bin/env python
# Copyright 2015 Red Hat, Inc.
#
# 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) any later version.
#
# This program ... |
def _run_dhclient(iface, blockingdhcp, default_route, family):
dhclient = DhcpClient(iface, family, default_route)
rc = dhclient.start(blockingdhcp)
if blockingdhcp and rc:
log('failed to start dhclient%s on iface %s' % (family, iface))
def _set_ip_config(ip_config):
iface = ip_config.top_d... | address = attrs.get('ipv6addr')
gateway = attrs.get('ipv6gateway')
default_route = attrs.get('defaultRoute')
autoconf = attrs.get('ipv6autoconf')
dhcp = attrs.get('dhcpv6')
return IPv6(address, gateway, default_route, autoconf, dhcp) | identifier_body |
__init__.py | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Web Editor Utils
# (see https://mukit.at). | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | random_line_split | |
makeSuite.js | var vows = require('vows'),
_ = require('underscore')._,
RawTests = require('./selenium.vows');
// makeSuite takes a configuration and makes a batch of tests, splitting
// up tests according to 'conf.processes'
exports.makeSuite = function(conf) {
var getCapText = function(conf, cap) {
return " (" + cap.bro... |
});
return batches;
}
};
| {
if (typeof batches[i] === 'undefined') {
batches[i] = {};
}
batches[i][testName] = test;
if (i < numBatches - 1) {
i++;
} else {
i = 0;
}
total++;
} | conditional_block |
makeSuite.js | var vows = require('vows'),
_ = require('underscore')._,
RawTests = require('./selenium.vows');
// makeSuite takes a configuration and makes a batch of tests, splitting
// up tests according to 'conf.processes'
exports.makeSuite = function(conf) {
var getCapText = function(conf, cap) { | // gets a version of the testbase relativized to a particular config
// and capability request
var getTestsForCap = function(cap) {
var capText = getCapText(conf, cap);
var allTests = RawTests.allTests(conf, cap, capText);
var capTests = {};
// Replace the name of each test with a relativized name... | return " (" + cap.browserName+"_"+cap.version+"_"+cap.platform+"_"+conf.serviceName+")";
};
| random_line_split |
stream.controller.js | (function () {
'use strict';
var _ = require('lodash');
var Jelps = require('../jelp/jelp.model');
// --------------------------------------------------------------------------------
// Private functions
// --------------------------------------------------------------------------------
function error... | array = _.map(array,function(item){
var newItem = new Jelps(item.obj)
newItem.location.dist = item.dis;
return newItem;
})
return array;
}
// --------------------------------------------------------------------------------
// Public methods
// -------------------------------------------------... | return res.json(200,_.assign({stream:found},props));
}
}
function mapDistance(array){ | random_line_split |
stream.controller.js | (function () {
'use strict';
var _ = require('lodash');
var Jelps = require('../jelp/jelp.model');
// --------------------------------------------------------------------------------
// Private functions
// --------------------------------------------------------------------------------
function error... |
if(err) { return errorhandler(err,res); }
if(!found.length) { return res.send(404); }
return res.json(200,_.assign({stream:found},props));
}
}
function mapDistance(array){
array = _.map(array,function(item){
var newItem = new Jelps(item.obj)
newItem.location.dist = item.dis;
return n... | { found = action.apply( action, _.rest(arguments) ); } | conditional_block |
stream.controller.js | (function () {
'use strict';
var _ = require('lodash');
var Jelps = require('../jelp/jelp.model');
// --------------------------------------------------------------------------------
// Private functions
// --------------------------------------------------------------------------------
function error... |
function callback(res,props,action) {
action = _.filter(_.rest(arguments),_.isFunction)[0];
return function(err,found){
if(action){ found = action.apply( action, _.rest(arguments) ); }
if(err) { return errorhandler(err,res); }
if(!found.length) { return res.send(404); }
return res.json(200,_.a... | {
console.log('Error...: ',err);
return res.send(500).json(err);
} | identifier_body |
stream.controller.js | (function () {
'use strict';
var _ = require('lodash');
var Jelps = require('../jelp/jelp.model');
// --------------------------------------------------------------------------------
// Private functions
// --------------------------------------------------------------------------------
function | (err,res) {
console.log('Error...: ',err);
return res.send(500).json(err);
}
function callback(res,props,action) {
action = _.filter(_.rest(arguments),_.isFunction)[0];
return function(err,found){
if(action){ found = action.apply( action, _.rest(arguments) ); }
if(err) { return errorhandler(err... | errorhandler | identifier_name |
gulpfile.js | const { dest, series, src, symlink } = require('gulp');
const del = require('del');
const inject = require('gulp-inject');
const map = require('map-stream')
const path = require('path');
const rename = require('gulp-rename');
const sort = require('gulp-sort');
function deleteSymlinks() {
return del(['components/mo... |
return `* xref:${filepath}[${maybeName[1]}]`;
}
}))
.pipe(rename('nav.adoc'))
.pipe(dest('components/modules/ROOT/'))
}
const symlinks = series(deleteSymlinks, createSymlinks);
exports.symlinks = symlinks;
exports.nav = nav;
exports.default = series(symlinks, nav);... | {
throw new Error(`${file.path} doesn't contain Asciidoc heading ('== <Title>') or ('## <Title')`);
} | conditional_block |
gulpfile.js | const { dest, series, src, symlink } = require('gulp');
const del = require('del');
const inject = require('gulp-inject'); | const sort = require('gulp-sort');
function deleteSymlinks() {
return del(['components/modules/ROOT/pages/*', '!components/modules/ROOT/pages/index.adoc']);
}
function createSymlinks() {
return src('../components/*/src/main/docs/*.adoc')
.pipe(map((file, done) => {
// this flattens the out... | const map = require('map-stream')
const path = require('path');
const rename = require('gulp-rename'); | random_line_split |
gulpfile.js | const { dest, series, src, symlink } = require('gulp');
const del = require('del');
const inject = require('gulp-inject');
const map = require('map-stream')
const path = require('path');
const rename = require('gulp-rename');
const sort = require('gulp-sort');
function | () {
return del(['components/modules/ROOT/pages/*', '!components/modules/ROOT/pages/index.adoc']);
}
function createSymlinks() {
return src('../components/*/src/main/docs/*.adoc')
.pipe(map((file, done) => {
// this flattens the output to just .../pages/....adoc
// instead of ..... | deleteSymlinks | identifier_name |
gulpfile.js | const { dest, series, src, symlink } = require('gulp');
const del = require('del');
const inject = require('gulp-inject');
const map = require('map-stream')
const path = require('path');
const rename = require('gulp-rename');
const sort = require('gulp-sort');
function deleteSymlinks() {
return del(['components/mo... |
function nav() {
return src('nav.adoc.template')
.pipe(inject(src('../components/*/src/main/docs/*.adoc').pipe(sort()), {
removeTags: true,
transform: (filename, file) => {
const filepath = path.basename(filename);
const maybeName = /(?:==|##) (.*)/.... | {
return src('../components/*/src/main/docs/*.adoc')
.pipe(map((file, done) => {
// this flattens the output to just .../pages/....adoc
// instead of .../pages/camel-.../src/main/docs/....adoc
file.base = path.dirname(file.path);
done(null, file);
}))
... | identifier_body |
app.js | adiodan.player.create('main');
/*
Connect to default audio device.
*/
var audio = window.radiodan.audio.create('default');
/*
Create device object (to issue shutdown commands)
*/
var device = window.radiodan.device.create();
/*
Libby's additions - get the rss feed and add to playlist
*/
getRSS("/rss",functio... | var streamsEl = document.querySelector('.streams');
window.getJSON(
'http://bbcradioservices.pixelblend.co.uk/services.json',
buildServicesList
);
function buildServicesList(json) {
streamsEl.innerHTML = json.services
.map(createServiceListItem)
.join('');
... | Live streams list
*/ | random_line_split |
app.js | adiodan.player.create('main');
/*
Connect to default audio device.
*/
var audio = window.radiodan.audio.create('default');
/*
Create device object (to issue shutdown commands)
*/
var device = window.radiodan.device.create();
/*
Libby's additions - get the rss feed and add to playlist
*/
getRSS("/rss",functio... | (evt) {
var targetEl = evt.target,
url;
// Prevent any links being followed
evt.preventDefault();
// This will run for any click | handleAddStream | identifier_name |
app.js | (urls && urls.length>0){
for (var i=0; i< urls.length; i++){
addToPlaylist(urls[i]);
}
play();
}else{
console.log("nothing to add to playlist");
}
});
/*
Playback controls
*/
var playPauseEl = document.querySelector('#play-pause');
// Listen for the play-pause button to be pressed
playPauseEl.... | {
url = targetEl.getAttribute('href');
} | conditional_block | |
app.js | adiodan.player.create('main');
/*
Connect to default audio device.
*/
var audio = window.radiodan.audio.create('default');
/*
Create device object (to issue shutdown commands)
*/
var device = window.radiodan.device.create();
/*
Libby's additions - get the rss feed and add to playlist
*/
getRSS("/rss",functio... |
/*
Perform a search
*/
var searchPanelEl = document.querySelector('.search');
var searchInputEl = searchPanelEl.querySelector('input');
var searchButtonEl = searchPanelEl.querySelector('button');
var searchResultsEl = searchPanelEl.querySelector('tbody');
// Perform a search when the text box changes or
// a ... | {
var row = currentPlaylistEl.querySelector('.is-next');
if (row) {
row.classList.remove('is-next');
}
} | identifier_body |
deriving-via-extension-struct.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 ... |
pub fn main() {
let a = Foo { x: 1, y: 2, z: 3 };
let b = Foo { x: 1, y: 2, z: 3 };
assert_eq!(a, b);
assert!(!(a != b));
assert!(a.eq(&b));
assert!(!a.ne(&b));
} | x: int,
y: int,
z: int,
} | random_line_split |
deriving-via-extension-struct.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 ... | () {
let a = Foo { x: 1, y: 2, z: 3 };
let b = Foo { x: 1, y: 2, z: 3 };
assert_eq!(a, b);
assert!(!(a != b));
assert!(a.eq(&b));
assert!(!a.ne(&b));
}
| main | identifier_name |
nto_test_custom_tuning.py | #!/usr/bin/env python
from utils import *
########################################################
# Test: Node Tuning Operator: custom tuning is working #
########################################################
# Changes: #
# skordas: ... |
# Getting node where pod with 'web' name is running
node_where_app_is_running = execute_command("oc get pod web --no-headers -o=custom-columns=NODE:.spec.nodeName").rstrip()
tuned_operator_pod = execute_command("oc get pods -n openshift-cluster-node-tuning-operator -o wide | grep {} | cut -d ' ' -f 1".form... | print_title("Node Tuning Operator: Custom tuning is working")
# Getting all nodes
print_step("Gathering information about nodes")
nodes = execute_command("oc get nodes --no-headers -o=custom-columns=NAME:.metadata.name").split("\n")
del nodes[-1]
passed("List of nodes:\n" + str(nodes))
# Getti... | identifier_body |
nto_test_custom_tuning.py | #!/usr/bin/env python
from utils import *
########################################################
# Test: Node Tuning Operator: custom tuning is working #
########################################################
# Changes: #
# skordas: ... |
else:
fail("It shouldn't be any tuned nf-conntrack-max, but it was: {}".format(number_of_tuned_router), cleanup)
return False
# All steps passed
return True
if __name__ == "__main__":
test()
| passed(None) | conditional_block |
nto_test_custom_tuning.py | #!/usr/bin/env python
from utils import *
########################################################
# Test: Node Tuning Operator: custom tuning is working #
########################################################
# Changes: #
# skordas: ... | ():
print("Cleaning after test")
execute_command("oc delete tuned nf-conntrack-max -n openshift-cluster-node-tuning-operator")
execute_command("oc delete project my-logging-project")
def test():
# Test execution:
print_title("Node Tuning Operator: Custom tuning is working")
# Getting all node... | cleanup | identifier_name |
nto_test_custom_tuning.py | #!/usr/bin/env python
from utils import *
########################################################
# Test: Node Tuning Operator: custom tuning is working #
########################################################
# Changes: #
# skordas: ... | if (pod in tuned_operator_pod and "nf-conntrack-max" not in log) or (pod not in tuned_operator_pod and "nf-conntrack-max" in log):
fail("On pod: {} founded log: {}".format(pod, log), cleanup)
return False
passed(None)
# Cleaning after test
print_step("Cleaning after test")
... | random_line_split | |
main.js | var booksApp = angular.module("booksApp", []);
booksApp.controller("MainCtrl", function($scope, Models) {
$scope.books = Models.books();
$scope.levels = Models.levels();
$scope.selectedBook = null;
$scope.selectBook = function(book) {
$scope.selectedBook = book;
};
$scope.createBook... | ];
};
var levels = function() {
return [
"très bon", "bon", "débutant"
];
};
return {
books: books,
levels: levels
}
}); | random_line_split | |
MatchListItem.js | import './MatchListItem.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import { connect } from 'react-redux';
import Icon from '../Icon.js';
import MatchEdit from '../MatchEdit/MatchEdit';
import { updateMatch, deleteMatch } from '../../a... | saveData.home_team = home_team;
}
if (quest_team != this.props.match.quest_team.team_id) {
saveData.quest_team = quest_team;
}
this.setState({ loading: true });
this.props.updateMatch({ ...saveData }).then((data) => {
this.setState({ edit: !this.state.edit, loading: false });
this.context.router... | location
};
if (home_team != this.props.match.home_team.team_id) { | random_line_split |
MatchListItem.js | import './MatchListItem.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import { connect } from 'react-redux';
import Icon from '../Icon.js';
import MatchEdit from '../MatchEdit/MatchEdit';
import { updateMatch, deleteMatch } from '../../a... | else {
return (
<div className="info">
<Link to={ `/match/${match._id}` } className="link">
<span className="logos">
<img src={ `./images/${ match.home_team.team_id }.jpg` } alt=""/>
<img src={ `./images/${ match.quest_team.team_id }.jpg` } alt=""/>
</span>
<span cla... | {
return (
<MatchEdit
onSubmit={ this.onSubmit.bind(this) }
onCancel={ this.toogleActive.bind(this) }
title="Edit match"
btn="Save"
match={{ ...match }}
loading={ this.state.loading }
onDelete={ this.deleteHandler.bind(this) }
/>
);
} | conditional_block |
MatchListItem.js | import './MatchListItem.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import { connect } from 'react-redux';
import Icon from '../Icon.js';
import MatchEdit from '../MatchEdit/MatchEdit';
import { updateMatch, deleteMatch } from '../../a... | () {
super();
this.state = { edit: false, loading: false }
}
onSubmit (match) {
const { date, home_team, location, quest_team, start } = match;
var saveData = {
match_id: this.props.match._id,
date: moment(`${match.date} ${match.start}`, "DD.MM.YYYY HH:mm").format(),
location
};
if (home_team... | constructor | identifier_name |
MatchListItem.js | import './MatchListItem.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import { connect } from 'react-redux';
import Icon from '../Icon.js';
import MatchEdit from '../MatchEdit/MatchEdit';
import { updateMatch, deleteMatch } from '../../a... |
render () {
const { match } = this.props;
const matchItemRender = () => {
if (this.state.edit) {
return (
<MatchEdit
onSubmit={ this.onSubmit.bind(this) }
onCancel={ this.toogleActive.bind(this) }
title="Edit match"
btn="Save"
match={{ ...match }}
loading={ this.s... | {
const { match, deleteMatch } = this.props;
this.setState({ loading: true });
deleteMatch({ id: match._id });
} | identifier_body |
abdt_repooptions.py | """Per-repository configuration options."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdt_repooptions
#
# Public Classes:
# Data
#
# Public Functions:
# merge_override_into_data
# me... |
def make_default_data():
"""Returns a 'Data' with sensible default values.
:returns: a 'Data'
"""
data = Data()
data.description = "(unnamed repo)"
return data
def data_from_json(json_string):
"""Returns a 'Data' from the supplied 'json_string'.
The 'json_string' doesn't have to ... | """Merge many Data objects, precedence increases with index in the list.
if an item in the list is None then it is ignored.
:object_list: multiple Data() args
:returns: a Data() that represents the composite of all the configs
"""
result = data_list[0]
data_list = data_list[1:]
for data i... | identifier_body |
abdt_repooptions.py | """Per-repository configuration options."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdt_repooptions
#
# Public Classes:
# Data
#
# Public Functions:
# merge_override_into_data
# me... | (*data_list):
"""Merge many Data objects, precedence increases with index in the list.
if an item in the list is None then it is ignored.
:object_list: multiple Data() args
:returns: a Data() that represents the composite of all the configs
"""
result = data_list[0]
data_list = data_list[... | merge_data_objects | identifier_name |
abdt_repooptions.py | """Per-repository configuration options."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdt_repooptions
#
# Public Classes:
# Data
#
# Public Functions:
# merge_override_into_data
# me... | return False
def __ne__(self, other):
return not self.__eq__(other)
def _merge_lists_as_sets(*list_list):
# sets aren't serializable as json so we want to store as list
new_set = set()
for l in list_list:
if l is not None:
new_set |= set(l)
return list(new_... | return self.__dict__ == other.__dict__
else: | random_line_split |
abdt_repooptions.py | """Per-repository configuration options."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdt_repooptions
#
# Public Classes:
# Data
#
# Public Functions:
# merge_override_into_data
# me... |
else:
setattr(result, key, value)
return result
def merge_data_objects(*data_list):
"""Merge many Data objects, precedence increases with index in the list.
if an item in the list is None then it is ignored.
:object_list: multiple Data() args
:returns: a Dat... | left = getattr(result, key)
right = getattr(override, key)
setattr(result, key, _merge_lists_as_sets(left, right)) | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection # | # 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; version 2 of the License. #
# #
... | # --------------------------------------------------------------------------- #
# Copyright (c) 2008-2015 OpenLP Developers #
# --------------------------------------------------------------------------- # | random_line_split |
enterInfo.py | __author__ = 'Reuven'
import sys
class GetInfo():
def | (self):
self.u_name = ""
self.age = ""
self.uid = ""
def get_name(self):
while self.u_name.isalpha() is False:
self.u_name = raw_input("Please enter your name:")[:20]
if self.u_name == "exit" or self.u_name == "quit":
sys.exit()
return... | __init__ | identifier_name |
enterInfo.py | __author__ = 'Reuven'
import sys
class GetInfo():
def __init__(self):
self.u_name = ""
self.age = ""
self.uid = ""
def get_name(self):
while self.u_name.isalpha() is False:
self.u_name = raw_input("Please enter your name:")[:20]
if self.u_name == "exit... | if self.uid == "exit" or self.uid == "quit":
sys.exit()
return self.uid
def print_info(self):
name = self.get_name()
age = self.get_age()
uid = self.get_user_id()
print "You are %s, aged %s. next year you will be %d, with user id %s, the next user... | self.uid = raw_input("Please enter your User ID:") | random_line_split |
enterInfo.py | __author__ = 'Reuven'
import sys
class GetInfo():
def __init__(self):
self.u_name = ""
self.age = ""
self.uid = ""
def get_name(self):
while self.u_name.isalpha() is False:
self.u_name = raw_input("Please enter your name:")[:20]
if self.u_name == "exit... | get_stuff = GetInfo()
get_stuff.print_info() | conditional_block | |
enterInfo.py | __author__ = 'Reuven'
import sys
class GetInfo():
def __init__(self):
self.u_name = ""
self.age = ""
self.uid = ""
def get_name(self):
while self.u_name.isalpha() is False:
self.u_name = raw_input("Please enter your name:")[:20]
if self.u_name == "exit... |
if __name__ == "__main__":
get_stuff = GetInfo()
get_stuff.print_info()
| name = self.get_name()
age = self.get_age()
uid = self.get_user_id()
print "You are %s, aged %s. next year you will be %d, with user id %s, the next user is %s."\
% (name, age, int(age)+1, uid, int(uid)+1) | identifier_body |
stat.py | # -*- coding: utf-8 -*-
'''
Created on 21 janv. 2016
@author: christian
'''
import falcon
import os
import config
import db
class | (object):
'''
Get global statistics
'''
def on_get(self, req, resp):
'''Return global statistics
'''
dbc = db.connect()
cur = dbc.cursor()
query = """select format('{"nb_maps":%s,"nb_addr":%s,"last_map":"%s"}',
... | Stat | identifier_name |
stat.py | # -*- coding: utf-8 -*-
'''
Created on 21 janv. 2016
@author: christian
'''
import falcon
import os
import config
import db
class Stat(object):
'''
Get global statistics
'''
def on_get(self, req, resp):
'''Return global statistics
'''
dbc = db.conne... |
cur.close()
dbc.close()
| resp.status = falcon.HTTP_200
resp.set_header('Access-Control-Allow-Origin', '*')
resp.set_header('Access-Control-Allow-Headers',
'X-Requested-With')
resp.body = (stats) | conditional_block |
stat.py | # -*- coding: utf-8 -*-
'''
Created on 21 janv. 2016
@author: christian
'''
import falcon
import os
import config
import db
class Stat(object):
'''
Get global statistics
'''
def on_get(self, req, resp):
| 'X-Requested-With')
resp.body = (stats)
cur.close()
dbc.close()
| '''Return global statistics
'''
dbc = db.connect()
cur = dbc.cursor()
query = """select format('{"nb_maps":%s,"nb_addr":%s,"last_map":"%s"}',
count(*),
count(distinct(address)),
left(max(time)::text... | identifier_body |
stat.py | # -*- coding: utf-8 -*-
'''
Created on 21 janv. 2016
@author: christian
'''
import falcon
import os
import config
import db
class Stat(object):
'''
Get global statistics
'''
def on_get(self, req, resp):
'''Return global statistics
'''
dbc = db.conne... | cur.close()
dbc.close() | random_line_split | |
test_microsite.py | """
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeu... |
class TestMicrosite(TestCase):
"""Test for Account Creation from a white labeled Micro-Sites"""
def setUp(self):
super(TestMicrosite, self).setUp()
self.username = "test_user"
self.url = reverse("create_account")
self.params = {
"username": self.username,
... | """
create a fake microsite site name
"""
return FAKE_MICROSITE.get(name, default) | identifier_body |
test_microsite.py | """
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeu... | },
"extended_profile_fields": [
"address1", "state", "company", "title"
]
}
def fake_site_name(name, default=None):
"""
create a fake microsite site name
"""
if name == 'SITE_NAME':
return 'openedx.localhost'
else:
return default
def fake_microsite_get_value(n... | "title": "required" | random_line_split |
test_microsite.py | """
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeu... | (TestCase):
"""Test for Account Creation from a white labeled Micro-Sites"""
def setUp(self):
super(TestMicrosite, self).setUp()
self.username = "test_user"
self.url = reverse("create_account")
self.params = {
"username": self.username,
"email": "test@exam... | TestMicrosite | identifier_name |
test_microsite.py | """
Test for User Creation from Micro-Sites
"""
from django.test import TestCase
from student.models import UserSignupSource
import mock
import json
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
FAKE_MICROSITE = {
"SITE_NAME": "openedx.localhost",
"university": "fakeu... |
else:
return default
def fake_microsite_get_value(name, default=None):
"""
create a fake microsite site name
"""
return FAKE_MICROSITE.get(name, default)
class TestMicrosite(TestCase):
"""Test for Account Creation from a white labeled Micro-Sites"""
def setUp(self):
supe... | return 'openedx.localhost' | conditional_block |
moveit_canceler.py | #!/usr/bin/env python
import rospy
import os
import roslib
roslib.load_manifest("denso_pendant_publisher")
roslib.load_manifest("actionlib_msgs")
import denso_pendant_publisher.msg
import std_msgs.msg
import actionlib_msgs.msg
rospy.init_node("moveit_canceler")
g_runnable = True
g_prev_status = None
def | (msg):
global g_runnable, g_prev_status
if g_prev_status:
if (not g_prev_status.button_cancel and msg.button_cancel) or (not g_prev_status.button_stop and msg.button_stop): # canceled or stopped
g_runnable = False
# here we should send cancel
cancel = actionlib_msgs.m... | pendantCB | identifier_name |
moveit_canceler.py | #!/usr/bin/env python
import rospy
import os
import roslib
roslib.load_manifest("denso_pendant_publisher")
roslib.load_manifest("actionlib_msgs")
import denso_pendant_publisher.msg
import std_msgs.msg
import actionlib_msgs.msg
rospy.init_node("moveit_canceler")
g_runnable = True
g_prev_status = None
def pendantC... | rospy.spin() | random_line_split | |
moveit_canceler.py | #!/usr/bin/env python
import rospy
import os
import roslib
roslib.load_manifest("denso_pendant_publisher")
roslib.load_manifest("actionlib_msgs")
import denso_pendant_publisher.msg
import std_msgs.msg
import actionlib_msgs.msg
rospy.init_node("moveit_canceler")
g_runnable = True
g_prev_status = None
def pendantC... |
sub = rospy.Subscriber("/denso_pendant_publisher/status", denso_pendant_publisher.msg.PendantStatus, pendantCB)
cancel_pub = rospy.Publisher("/arm_controller/follow_joint_trajectory/cancel", actionlib_msgs.msg.GoalID);
# cancel_pub = rospy.Publisher("/move_group/cancel", actionlib_msgs.msg.GoalID);
rospy.spin()
| global g_runnable, g_prev_status
if g_prev_status:
if (not g_prev_status.button_cancel and msg.button_cancel) or (not g_prev_status.button_stop and msg.button_stop): # canceled or stopped
g_runnable = False
# here we should send cancel
cancel = actionlib_msgs.msg.GoalID()... | identifier_body |
moveit_canceler.py | #!/usr/bin/env python
import rospy
import os
import roslib
roslib.load_manifest("denso_pendant_publisher")
roslib.load_manifest("actionlib_msgs")
import denso_pendant_publisher.msg
import std_msgs.msg
import actionlib_msgs.msg
rospy.init_node("moveit_canceler")
g_runnable = True
g_prev_status = None
def pendantC... |
g_prev_status = msg
sub = rospy.Subscriber("/denso_pendant_publisher/status", denso_pendant_publisher.msg.PendantStatus, pendantCB)
cancel_pub = rospy.Publisher("/arm_controller/follow_joint_trajectory/cancel", actionlib_msgs.msg.GoalID);
# cancel_pub = rospy.Publisher("/move_group/cancel", actionlib_msgs.msg.Go... | g_runnable = False
# here we should send cancel
cancel = actionlib_msgs.msg.GoalID()
cancel.id = ""
cancel_pub.publish(cancel)
rospy.loginfo("cancel") | conditional_block |
buffer_map.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use geom::size::Size2D;
... | mem: usize,
/// The maximum allowed memory. Unused buffers will be deleted
/// when this threshold is exceeded.
max_mem: usize,
/// A monotonically increasing counter to track how recently tile sizes were used.
counter: usize,
}
/// A key with which to store buffers. It is based on the size of ... | pub struct BufferMap {
/// A HashMap that stores the Buffers.
map: HashMap<BufferKey, BufferValue>,
/// The current amount of memory stored by the BufferMap's buffers. | random_line_split |
buffer_map.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use geom::size::Size2D;
... |
};
if {
let list = &mut self.map.get_mut(&old_key).unwrap().buffers;
let condemned_buffer = list.pop().take().unwrap();
self.mem -= condemned_buffer.get_mem();
condemned_buffer.destroy(graphics_context);
list.is_emp... | {
match self.map.iter().min_by(|&(_, x)| x.last_action) {
Some((k, _)) => *k,
None => panic!("BufferMap: tried to delete with no elements in map"),
}
} | conditional_block |
buffer_map.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use geom::size::Size2D;
... | {
/// An array of buffers, all the same size
buffers: Vec<Box<LayerBuffer>>,
/// The counter when this size was last requested
last_action: usize,
}
impl BufferMap {
// Creates a new BufferMap with a given buffer limit.
pub fn new(max_mem: usize) -> BufferMap {
BufferMap {
... | BufferValue | identifier_name |
logger.ts | export enum LogLevel {
VERBOSE = 1,
DEBUG = 2,
INFO = 3,
WARNING = 4,
ERROR = 5,
}
export interface Logger {
verbose(...items: any[]): void;
debug(...items: any[]): void;
info(...items: any[]): void;
warn(...items: any[]): void;
error(...items: any[]): void; | * If error is passed, it will append the message to the error object.
*/
export class ConsoleLogger implements Logger {
private threshold: LogLevel;
constructor(threshold: LogLevel = 2) {
this.threshold = threshold;
const groups = Array<string>();
const hr =
'----------------------------------... | }
/**
* Default implementation of the Logger. Wraps standards console calls.
* Logs only calls that are at or above the threshold (verbose/debug/info/warn/error) | random_line_split |
logger.ts | export enum LogLevel {
VERBOSE = 1,
DEBUG = 2,
INFO = 3,
WARNING = 4,
ERROR = 5,
}
export interface Logger {
verbose(...items: any[]): void;
debug(...items: any[]): void;
info(...items: any[]): void;
warn(...items: any[]): void;
error(...items: any[]): void;
}
/**
* Default implementation of the ... |
}
}
export class EmptyLogger implements Logger {
/* tslint:disable:no-empty */
verbose(...items: any[]) {}
debug(...items: any[]) {}
info(...items: any[]) {}
warn(...items: any[]) {}
error(...items: any[]) {}
/* tslint:enable:no-empty */
}
| {
logFunction(`${loggerSignature}: `, item);
} | conditional_block |
logger.ts | export enum LogLevel {
VERBOSE = 1,
DEBUG = 2,
INFO = 3,
WARNING = 4,
ERROR = 5,
}
export interface Logger {
verbose(...items: any[]): void;
debug(...items: any[]): void;
info(...items: any[]): void;
warn(...items: any[]): void;
error(...items: any[]): void;
}
/**
* Default implementation of the ... | (...items: any[]) {}
error(...items: any[]) {}
/* tslint:enable:no-empty */
}
| warn | identifier_name |
engine_aware.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use crate::core::Value;
use crate::externs;
use crate::nodes::{lift_directory_digest, lift_file_digest};
use crate::Failure;
use crate::Types;
use cpython::{PyDict, PyString, Python};
u... | };
output.push((key_name, artifact_output));
}
Some(output)
}
}
pub struct DebugHint {}
impl EngineAwareInformation for DebugHint {
type MaybeOutput = String;
fn retrieve(_types: &Types, value: &Value) -> Option<String> {
externs::call_method(&value, "debug_hint", &[])
.ok()
... | return None;
}
} | random_line_split |
engine_aware.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use crate::core::Value;
use crate::externs;
use crate::nodes::{lift_directory_digest, lift_file_digest};
use crate::Failure;
use crate::Types;
use cpython::{PyDict, PyString, Python};
u... | (_types: &Types, value: &Value) -> Option<Level> {
let new_level_val = externs::call_method(value.as_ref(), "level", &[]).ok()?;
let new_level_val = externs::check_for_python_none(new_level_val)?;
externs::val_to_log_level(&new_level_val).ok()
}
}
pub struct Message {}
impl EngineAwareInformation for Me... | retrieve | identifier_name |
engine_aware.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use crate::core::Value;
use crate::externs;
use crate::nodes::{lift_directory_digest, lift_file_digest};
use crate::Failure;
use crate::Types;
use cpython::{PyDict, PyString, Python};
u... |
};
output.push((key_name, Value::from(value)));
}
Some(output)
}
}
pub struct Artifacts {}
impl EngineAwareInformation for Artifacts {
type MaybeOutput = Vec<(String, ArtifactOutput)>;
fn retrieve(types: &Types, value: &Value) -> Option<Self::MaybeOutput> {
let artifacts_val = match e... | {
log::error!(
"Error in EngineAware.metadata() implementation - non-string key: {:?}",
e
);
return None;
} | conditional_block |
index.tsx | };
private onBeforeInstallPromptEvent = (event: BeforeInstallPromptEvent) => {
// Don't show the mini-infobar on mobile
event.preventDefault();
// Save the beforeinstallprompt event so it can be called later.
this.setState({ beforeInstallEvent: event });
// Log the event.
const gaEventInfo... | </SlideOnScroll>
</div>
</section> | random_line_split | |
index.tsx | (
items: ClipboardItem[],
): Promise<undefined | Blob> {
for (const item of items) {
const type = item.types.find((type) => type.startsWith('image/'));
if (type) return item.getType(type);
}
}
interface Props {
onFile?: (file: File) => void;
showSnack?: SnackBarElement['showSnackbar'];
}
interface St... | getImageClipboardItem | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.