file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_django.py | from kaneda.backends import LoggerBackend, ElasticsearchBackend
from kaneda.queues import CeleryQueue
from django_kaneda import settings # NOQA
class TestDjango(object):
def test_django_kaneda_with_backend(self, mocker, django_settings_backend):
mocker.patch('django_kaneda.settings', django_settings_bac... | assert isinstance(metrics.queue, CeleryQueue)
result = metrics.gauge('test_gauge', 42)
assert result |
def test_django_kaneda_with_queue(self, mocker, django_settings_queue):
mocker.patch('django_kaneda.settings', django_settings_queue)
from django_kaneda import LazyMetrics
metrics = LazyMetrics() | random_line_split |
test_django.py | from kaneda.backends import LoggerBackend, ElasticsearchBackend
from kaneda.queues import CeleryQueue
from django_kaneda import settings # NOQA
class TestDjango(object):
def test_django_kaneda_with_backend(self, mocker, django_settings_backend):
mocker.patch('django_kaneda.settings', django_settings_bac... | (self, mocker, django_settings_queue):
mocker.patch('django_kaneda.settings', django_settings_queue)
from django_kaneda import LazyMetrics
metrics = LazyMetrics()
assert isinstance(metrics.queue, CeleryQueue)
result = metrics.gauge('test_gauge', 42)
assert result
| test_django_kaneda_with_queue | identifier_name |
todo_user.steps.ts | import { | ItemStatus,
Start,
TodoListItems,
} from 'todomvc-model';
import { See } from 'serenity-js/lib/screenplay-protractor';
import { expect } from '../../src/expect';
import { listOf } from '../../src/text';
export = function todoUserSteps() {
this.Given(/^.*that (.*) has an empty todo list$/, function(n... | AddATodoItem,
CompleteATodoItem,
FilterItems, | random_line_split |
UserTest.py | # Copyright (C) 2014 Adam Schubert <adam.schubert@sg1-game.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Th... |
def testPassword(self):
data_token = self.user.token(self.credential)
data = self.user.password({'old_password': self.credential['password'], 'new_password': self.credential['password'], 'user_token': data_token['token'], 'user_id': data_token['id']})
self.assertEqual(data['message'], 'Password chan... | data = self.user.token(self.credential)
self.assertEqual(data['message'], 'Token created')
self.assertEqual(len(data['token']), 32)
self.assertIsNotNone(data['id'])
self.assertRegexpMatches(data['token_expiration'], '(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})') | identifier_body |
UserTest.py | # Copyright (C) 2014 Adam Schubert <adam.schubert@sg1-game.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Th... |
data = self.user.request_password_reset({'email': email, 'email_content': 'URL: example.com/password/reset/{reset_token}' + content_fill, 'email_subject': 'Password reset unittest', 'email_from': 'unittest@example.com'})
#self.assertEqual(data['message'], 'Email with reset token has been send')
self.as... | email = self.credential['username'] + '@example.com';
content_fill = 'abc' * 5333 #16k of shit | random_line_split |
UserTest.py | # Copyright (C) 2014 Adam Schubert <adam.schubert@sg1-game.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Th... | (self):
DwaTestCase.DwaTestCase.setUp(self)
self.user = self.d.user()
self.username = self.credential['username'] + 'UserTest' + str(time.time())
def testCreate(self):
params = {}
params['password'] = self.credential['password']
params['username'] = self.username
params['nickname'] = Dw... | setUp | identifier_name |
StartCheck.py | #!/usr/bin/env python
import rospy
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxyPublisher
from smach import CBState
class StartCheck(EventState):
'''
Example for a state to demonstrate which functionality is available for state implementation.
This example lets the behavior wai... | (self, userdata):
# This method is called periodically while the state is active.
# Main purpose is to check state conditions and trigger a corresponding outcome.
# If no outcome is returned, the state will stay active.
##if rospy.Time.now() - self._start_time < self._target_time:
return 'succeeded' # One of... | execute | identifier_name |
StartCheck.py | #!/usr/bin/env python
import rospy
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxyPublisher
from smach import CBState
class StartCheck(EventState):
'''
Example for a state to demonstrate which functionality is available for state implementation.
This example lets the behavior wai... |
def on_stop(self):
# This method is called whenever the behavior stops execution, also if it is cancelled.
# Use this event to clean up things like claimed resources.
pass # Nothing to do in this example.
| pass | identifier_body |
StartCheck.py | #!/usr/bin/env python
import rospy
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxyPublisher
from smach import CBState
class StartCheck(EventState):
'''
Example for a state to demonstrate which functionality is available for state implementation.
This example lets the behavior wai... | # This method is called when the behavior is started.
# If possible, it is generally better to initialize used resources in the constructor
# because if anything failed, the behavior would not even be started.
# In this example, we use this event to set the correct start time.
##self._start_time = rospy.Time... | pass # Nothing to do in this example.
def on_start(self): | random_line_split |
abstract_models.py | from decimal import Decimal
from django.core import exceptions
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from oscar.core.compat import AUTH_USER_MODEL, user_is_authenticated
@py... | :
abstract = True
app_label = 'voucher'
verbose_name = _("Voucher Application")
verbose_name_plural = _("Voucher Applications")
def __str__(self):
return _("'%(voucher)s' used by '%(user)s'") % {
'voucher': self.voucher,
'user': self.user}
| Meta | identifier_name |
abstract_models.py | from decimal import Decimal
from django.core import exceptions
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from oscar.core.compat import AUTH_USER_MODEL, user_is_authenticated
@py... | on_delete=models.CASCADE,
verbose_name=_("Order"))
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
app_label = 'voucher'
verbose_name = _("Voucher Application")
verbose_name_plural = _("Voucher Applications")
def __str__(se... | verbose_name=_("User"))
order = models.ForeignKey(
'order.Order', | random_line_split |
abstract_models.py | from decimal import Decimal
from django.core import exceptions
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from oscar.core.compat import AUTH_USER_MODEL, user_is_authenticated
@py... |
return is_available, message
def record_usage(self, order, user):
"""
Records a usage of this voucher in an order.
"""
if user_is_authenticated(user):
self.applications.create(voucher=self, order=order, user=user)
else:
self.applications.crea... | if not user_is_authenticated(user):
is_available = False
message = _(
"This voucher is only available to signed in users")
else:
is_available = not self.applications.filter(
voucher=self, user=user).exists()
... | conditional_block |
abstract_models.py | from decimal import Decimal
from django.core import exceptions
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from oscar.core.compat import AUTH_USER_MODEL, user_is_authenticated
@py... | return _("'%(voucher)s' used by '%(user)s'") % {
'voucher': self.voucher,
'user': self.user} | identifier_body | |
process-phase-zero.ts | import types = module('./ast-types');
var globalScope = require('./global-scope');
import AnglScope = module('./angl-scope');
import scopeVariable = module('./scope-variable');
// Wrap the entire AST in a "file" node
// TODO fix typing of ast argument
export var transform = (ast:any):types.AstNode => {
var anglSco... | }; | random_line_split | |
process-phase-zero.ts | import types = module('./ast-types');
var globalScope = require('./global-scope');
import AnglScope = module('./angl-scope');
import scopeVariable = module('./scope-variable');
// Wrap the entire AST in a "file" node
// TODO fix typing of ast argument
export var transform = (ast:any):types.AstNode => {
var anglSco... |
return <types.AstNode>{
type: "file",
stmts: ast.list,
globalAnglScope: globalAnglScope,
anglScope: anglScope
}
};
| {
throw new Error('Unexpected root node from Angl parser. Expected type "statements", got "' + ast.type + '".');
} | conditional_block |
app.py | from flask import Flask, render_template, flash, session, redirect, url_for
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from flask.ext.wtf.recaptcha import RecaptchaField
DEBUG = True
SECRET_KEY = 'secret'
# keys for localhost. Change as appropriate.
... |
if __name__ == "__main__":
app.run()
| form = CommentForm()
if form.validate_on_submit():
comments = session.pop('comments', [])
comments.append(form.comment.data)
session['comments'] = comments
flash("You have added a new comment")
return redirect(url_for("index"))
return index(form) | identifier_body |
app.py | from flask import Flask, render_template, flash, session, redirect, url_for
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from flask.ext.wtf.recaptcha import RecaptchaField
DEBUG = True
SECRET_KEY = 'secret'
# keys for localhost. Change as appropriate.
... | (form=None):
if form is None:
form = CommentForm()
comments = session.get("comments", [])
return render_template("index.html",
comments=comments,
form=form)
@app.route("/add/", methods=("POST",))
def add_comment():
form = CommentForm()
... | index | identifier_name |
app.py | from flask import Flask, render_template, flash, session, redirect, url_for
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from flask.ext.wtf.recaptcha import RecaptchaField
DEBUG = True
SECRET_KEY = 'secret'
# keys for localhost. Change as appropriate.
... | app.run() |
if __name__ == "__main__": | random_line_split |
app.py | from flask import Flask, render_template, flash, session, redirect, url_for
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from flask.ext.wtf.recaptcha import RecaptchaField
DEBUG = True
SECRET_KEY = 'secret'
# keys for localhost. Change as appropriate.
... |
return index(form)
if __name__ == "__main__":
app.run()
| comments = session.pop('comments', [])
comments.append(form.comment.data)
session['comments'] = comments
flash("You have added a new comment")
return redirect(url_for("index")) | conditional_block |
movement.js | import settings from './../settings'
import {findDistance, limitPositions, chooseOne, randomInt, getAvgPostion} from './general'
module.exports = {
applyLimbForces: (Eves) => {
for(var i = 0; i < Eves.length; i++) {
var eve = Eves[i];
for(var j = 0; j < eve.limbs.length; j++) {
var limb = eve... | }
},
updateBodyPartPositions: (Eves) => {
for(var i = 0; i < Eves.length; i++) {
var eve = Eves[i];
for(var j = 0; j < eve.bodyParts.length; j++) {
var bodyPart = eve.bodyParts[j];
bodyPart.pos.x += bodyPart.vel.x;
//check if offscreen
if(bodyPart.pos.x <= bodyPa... | b1.vel.x = Math.min( 20, Math.max( b1.vel.x + dVx1, -20 ));
b1.vel.y = Math.min( 20, Math.max( b1.vel.y + dVy1, -20 ));
} | random_line_split |
movement.js | import settings from './../settings'
import {findDistance, limitPositions, chooseOne, randomInt, getAvgPostion} from './general'
module.exports = {
applyLimbForces: (Eves) => {
for(var i = 0; i < Eves.length; i++) {
var eve = Eves[i];
for(var j = 0; j < eve.limbs.length; j++) {
var limb = eve... |
}
var xPosDiff = b1.pos.x - b0.pos.x;
var yPosDiff = b1.pos.y - b0.pos.y;
if(xPosDiff === 0) {
var theta = Math.PI;
} else {
var theta = Math.atan(yPosDiff / xPosDiff);
}
if (xPosDiff >= 0) {
force *= -1;
}
var moveme... | {
limb.growing = true;
} | conditional_block |
zip-code-input-test.js | import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import startApp from '../../helpers/start-app';
var App;
moduleForComponent('zip-code-input', 'zip-code-input component', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
},
... | // append the component to the DOM
this.render();
// testing filled in value
fillIn('input', '12345');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345');
assert.equal(component.get('unmaskedValue'), 12345);
});
});... | random_line_split | |
header.js | var svg = d3.select("svg.header")
.append("g")
.translate((window.innerWidth-620)/2, 120)
var radius = d3.scale.linear()
.domain([0, 5])
.range([50, 10])
var theta = function(d){
switch(d){
case 0: return 102;
case 1: return 173;
case 2: return 232;
case 3: return 2... | }
svg.selectAll("circle")
.data(d3.range(6))
.enter()
.append("circle")
.attr("r", radius)
.attr("transform", function(d){ return "translate(90, 0) rotate("+theta(d)+",-90,0)"})
.attr("class", function(d){ return ["x", "y"][Math.floor(d/3)]+((d%3)+1) })
svg = d3.select("svg.footer")
.appe... | random_line_split | |
checkbox.unit.js | describe('Ionic Checkbox', function() {
var el, scope, compile;
beforeEach(module('ionic'));
beforeEach(inject(function($compile, $rootScope) {
compile = $compile;
scope = $rootScope;
}));
it('should set the checkbox name', function() {
el = compile('<ion-checkbox name="myname"></ion-checkbox>'... | expect(input[0].hasAttribute('checked')).toBe(true);
scope.$apply('shouldCheck = false');
expect(input[0].hasAttribute('checked')).toBe(false);
});
it('should ngChange properly', function() {
el = compile('<ion-checkbox ng-change="change(val)" ng-model="val">')(scope);
scope.change = jasmine.c... | scope.$apply();
var input = el.find('input');
expect(input[0].hasAttribute('checked')).toBe(false);
scope.$apply('shouldCheck = true'); | random_line_split |
file.js | import fs from 'fs-extra';
import path from 'path';
import express from 'express';
import multer from 'multer';
import config from 'config';
import logger from '../lib/logger';
import { basename } from '../public/js/core/utils';
const publicDirectory = path.resolve(__dirname, '..', 'public');
const uploadDirectory = p... |
promises.push(
uploadFile(req, res, req.files[field], `theme/${fragment}/shape`)
);
}
}
return Promise.all(promises)
.then(results => {
res.send(results);
})
.catch(() => {
res.sendStatus(500);
});
}
static postNonOsmDataFile(req, r... | {
return res.sendStatus(415);
} | conditional_block |
file.js | import fs from 'fs-extra';
import path from 'path';
import express from 'express';
import multer from 'multer';
import config from 'config';
import logger from '../lib/logger';
import { basename } from '../public/js/core/utils';
const publicDirectory = path.resolve(__dirname, '..', 'public');
const uploadDirectory = p... |
function cleanObsoleteLayerFiles(themeModel) {
cleanObsoleteLayerFilesInThatDirectory(themeModel, 'shape');
cleanObsoleteLayerFilesInThatDirectory(themeModel, 'overPassCache');
}
function uploadFile(req, res, file, directory, osmId, tagName) {
file.originalname = file.originalname.toLowerCase();
let i = 2;
... | {
const fragment = themeModel.get('fragment');
const layers = themeModel.get('layers').models;
const directory = path.resolve(
publicDirectory,
`files/theme/${fragment}/${directoryName}/`
);
try {
fs.statSync(directory);
} catch (e) {
return false;
}
const re = new RegExp(`^/files/them... | identifier_body |
file.js | import fs from 'fs-extra';
import path from 'path';
import express from 'express';
import multer from 'multer';
import config from 'config';
import logger from '../lib/logger';
import { basename } from '../public/js/core/utils';
const publicDirectory = path.resolve(__dirname, '..', 'public');
const uploadDirectory = p... | {
static postShapeFile(req, res) {
const fragment = req.query.fragment;
const promises = [];
for (const field in req.files) {
if ({}.hasOwnProperty.call(req.files, field)) {
const file = req.files[field];
const fileSize = file.size / 1024;
const maxFileSize = config.get('cl... | Api | identifier_name |
file.js | import fs from 'fs-extra';
import path from 'path';
import express from 'express';
import multer from 'multer';
import config from 'config';
import logger from '../lib/logger';
import { basename } from '../public/js/core/utils';
const publicDirectory = path.resolve(__dirname, '..', 'public');
const uploadDirectory = p... | const modelFiles = [];
for (const layer of layers) {
const fileUri = layer.get('fileUri');
if (fileUri && re.test(fileUri)) {
const fileUriBaseName = basename(fileUri);
modelFiles.push(fileUriBaseName);
if (cacheRe.test(fileUriBaseName)) {
const layerUuid = layer.get('uuid');
... | }
const re = new RegExp(`^/files/theme/${fragment}/${directoryName}/`);
const cacheRe = /^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}.geojson$/; | random_line_split |
security_related.py | # (C) Copyright 2016 Vit Mojzis, vmojzis@redhat.com
#
# This program is distributed under the terms of the GNU General Public License
#
# 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 v... |
#get types corresponding to given packages
domains, resources = grouping.get_types(groups)
domains = domains | types
# remove excluded types
domains = domains - exclude
resources = resources - exclude
return domains, resources
except IOError as e:
print('Could not read "security_related.conf"!', ... | groups.add(group) | conditional_block |
security_related.py | # (C) Copyright 2016 Vit Mojzis, vmojzis@redhat.com
#
# This program is distributed under the terms of the GNU General Public License
#
# 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 v... | try:
packages = set()
types = set()
exclude = set()
txt = open("/etc/sepolicyanalysis/security_related.conf", "r")
packages = {}
for line in txt:
if (len(line) < 1) or (line[0] == '#'):
continue
if line.startswith("packages="):
packages = set([x.strip() for x in line[9:].split(",")])
i... | identifier_body | |
security_related.py | # (C) Copyright 2016 Vit Mojzis, vmojzis@redhat.com
#
# This program is distributed under the terms of the GNU General Public License
#
# 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 v... | return domains, resources
except IOError as e:
print('Could not read "security_related.conf"!', file=sys.stderr)
return set(), set() | domains = domains | types
# remove excluded types
domains = domains - exclude
resources = resources - exclude
| random_line_split |
security_related.py | # (C) Copyright 2016 Vit Mojzis, vmojzis@redhat.com
#
# This program is distributed under the terms of the GNU General Public License
#
# 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 v... | ():
try:
packages = set()
types = set()
exclude = set()
txt = open("/etc/sepolicyanalysis/security_related.conf", "r")
packages = {}
for line in txt:
if (len(line) < 1) or (line[0] == '#'):
continue
if line.startswith("packages="):
packages = set([x.strip() for x in line[9:].split(",")])
... | get_security_types | identifier_name |
provider.tmpl.js | import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
/*
Generated class for the <%= jsClassName %> provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class <%= jsClassName %> {
constructo... |
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('path/to/data... | {
// already loaded data
return Promise.resolve(this.data);
} | conditional_block |
provider.tmpl.js | import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
/*
Generated class for the <%= jsClassName %> provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class <%= jsClassName %> {
| (http: Http) {
this.http = http;
this.data = null;
}
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on... | constructor | identifier_name |
provider.tmpl.js | import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
/*
Generated class for the <%= jsClassName %> provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable() | }
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object... | export class <%= jsClassName %> {
constructor(http: Http) {
this.http = http;
this.data = null; | random_line_split |
list.js | "use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder"); | var canLog = require("can-log");
var canLogDev = require("can-log/dev/dev");
var defineHelpers = require("../define-helpers/define-helpers");
var assign = require("can-assign");
var diff = require("can-diff/list/list");
var ns = require("can-namespace");
var canReflect = require("can-reflect");
var canSymbol = require... | random_line_split | |
list.js | "use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder");
var canLog = require("can-log");
var canLogDev... | () {
var definitions = this.prototype._define.definitions;
var schema = {
type: "list",
keys: {}
};
schema = define.updateSchemaKeys(schema, definitions);
if(schema.keys["#"]) {
schema.values = definitions["#"].Type;
delete schema.keys["#"];
}
return schema;
}
/** @add can-define/list/list */
var Defin... | getSchema | identifier_name |
list.js | "use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder");
var canLog = require("can-log");
var canLogDev... |
/** @add can-define/list/list */
var DefineList = Construct.extend("DefineList",
/** @static */
{
setup: function(base) {
if (DefineList) {
addTypeEvents(this);
var prototype = this.prototype;
var result = define(prototype, prototype, base.prototype._define);
define.makeDefineInstanceKey(this, ... | {
var definitions = this.prototype._define.definitions;
var schema = {
type: "list",
keys: {}
};
schema = define.updateSchemaKeys(schema, definitions);
if(schema.keys["#"]) {
schema.values = definitions["#"].Type;
delete schema.keys["#"];
}
return schema;
} | identifier_body |
list.js | "use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder");
var canLog = require("can-log");
var canLogDev... |
}
return true;
};
};
var onKeyValue = define.eventsProto[canSymbol.for("can.onKeyValue")];
var offKeyValue = define.eventsProto[canSymbol.for("can.offKeyValue")];
var getSchemaSymbol = canSymbol.for("can.getSchema");
var inSetupSymbol = canSymbol.for("can.initializing");
function getSchema() {
var definitions ... | {
return false;
} | conditional_block |
find_files.py | from __future__ import division
from libtbx.path import walk_source_tree
from libtbx.str_utils import show_string
from libtbx.utils import Sorry
from libtbx.option_parser import option_parser
from fnmatch import fnmatch
import re
import sys, os
def read_lines_if_possible(file_path):
try: f = open(file_path, "r")
e... | run(sys.argv[1:]) | conditional_block | |
find_files.py | from __future__ import division
from libtbx.path import walk_source_tree
from libtbx.str_utils import show_string
from libtbx.utils import Sorry
from libtbx.option_parser import option_parser
from fnmatch import fnmatch
import re
import sys, os
def | (file_path):
try: f = open(file_path, "r")
except IOError: return []
return f.read().splitlines()
def run(args, command_name="libtbx.find_files"):
if (len(args) == 0): args = ["--help"]
command_line = (option_parser(
usage="%s [options] pattern ..." % command_name,
description="Recursively finds all ... | read_lines_if_possible | identifier_name |
find_files.py | from __future__ import division
from libtbx.path import walk_source_tree
from libtbx.str_utils import show_string
from libtbx.utils import Sorry
from libtbx.option_parser import option_parser
from fnmatch import fnmatch
import re
import sys, os
def read_lines_if_possible(file_path):
|
def run(args, command_name="libtbx.find_files"):
if (len(args) == 0): args = ["--help"]
command_line = (option_parser(
usage="%s [options] pattern ..." % command_name,
description="Recursively finds all files matching patterns,\n"
"excluding CVS and .svn directories and .pyc files.")
.option("-t... | try: f = open(file_path, "r")
except IOError: return []
return f.read().splitlines() | identifier_body |
find_files.py | from __future__ import division
from libtbx.path import walk_source_tree
from libtbx.str_utils import show_string
from libtbx.utils import Sorry
from libtbx.option_parser import option_parser
from fnmatch import fnmatch
import re
import sys, os
def read_lines_if_possible(file_path):
try: f = open(file_path, "r")
e... | print "%s: match in binary file" % fp
break
else:
print "%s: %s" % (fp, line)
if (__name__ == "__main__"):
run(sys.argv[1:]) | if (line_matches_all_grep_patterns()):
if (co.file_names_only):
print fp
break
elif (is_binary_file): | random_line_split |
query.py | #!/usr/bin/env python
# -*- encoding: 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... | :param topology:
:param component:
:param instance:
:param timerange:
:param envirn:
:return:
'''
pass
def fetch_max(self, cluster, metric, topology, component, instance, timerange, envirn=None):
'''
:param cluster:
:param metric:
:param topology:
:param component:... | :param cluster:
:param metric: | random_line_split |
query.py | #!/usr/bin/env python
# -*- encoding: 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... | (self, cluster, metric, topology, component, instance, \
timerange, is_max, environ=None):
'''
:param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param is_max:
:param environ:
:return:
'''
pass
| fetch_backpressure | identifier_name |
query.py | #!/usr/bin/env python
# -*- encoding: 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... | ''' QueryHandler '''
def fetch(self, cluster, metric, topology, component, instance, timerange, envirn=None):
'''
:param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param envirn:
:return:
'''
pass
def fetch_max(self, cl... | identifier_body | |
boxed.rs | // Copyright 2012-2015 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... |
fn write_i8(&mut self, i: i8) {
(**self).write_i8(i)
}
fn write_i16(&mut self, i: i16) {
(**self).write_i16(i)
}
fn write_i32(&mut self, i: i32) {
(**self).write_i32(i)
}
fn write_i64(&mut self, i: i64) {
(**self).write_i64(i)
}
fn write_i128(&mut sel... | {
(**self).write_usize(i)
} | identifier_body |
boxed.rs | // Copyright 2012-2015 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... | <T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
if self.is::<T>() {
unsafe {
let raw: *mut dyn Any = Box::into_raw(self);
Ok(Box::from_raw(raw as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<dyn Any + Send> {
#[inline]... | downcast | identifier_name |
boxed.rs | // Copyright 2012-2015 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... | }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool {
PartialOrd::l... | random_line_split | |
boxed.rs | // Copyright 2012-2015 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... |
}
}
impl Box<dyn Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
///
/// # Examples
///
/// ```
/// use std::any::Any;
///
/// fn print_if_string(value: Box<dyn Any + Send>) {
/// if let Ok(st... | {
Err(self)
} | conditional_block |
exec_commands.rs | use arguments::{VERBOSE_MODE, JOBLOG};
use execute::command::{self, CommandErr};
use input_iterator::InputsLock;
use numtoa::NumToA;
use time::{self, Timespec};
use tokenizer::Token;
use verbose;
use super::pipe::disk::State;
use super::job_log::JobLog;
use super::child::handle_child;
use std::io::{self, Read, Write};... |
}
}
}
| {
verbose::task_complete(&stdout, job_id, self.num_inputs, &input);
} | conditional_block |
exec_commands.rs | use arguments::{VERBOSE_MODE, JOBLOG};
use execute::command::{self, CommandErr};
use input_iterator::InputsLock;
use numtoa::NumToA;
use time::{self, Timespec};
use tokenizer::Token;
use verbose;
use super::pipe::disk::State;
use super::job_log::JobLog;
use super::child::handle_child;
use std::io::{self, Read, Write};... | <IO: Read> {
pub slot: usize,
pub num_inputs: usize,
pub flags: u16,
pub timeout: Duration,
pub inputs: InputsLock<IO>,
pub output_tx: Sender<State>,
pub arguments: &'static [Token],
pub tempdir: String,
}
impl<IO: Read> ExecCommands<IO> {
pub fn run(&mut self... | ExecCommands | identifier_name |
exec_commands.rs | use arguments::{VERBOSE_MODE, JOBLOG};
use execute::command::{self, CommandErr};
use input_iterator::InputsLock;
use numtoa::NumToA;
use time::{self, Timespec};
use tokenizer::Token;
use verbose;
use super::pipe::disk::State;
use super::job_log::JobLog;
use super::child::handle_child;
use std::io::{self, Read, Write};... |
}
| {
let stdout = io::stdout();
let stderr = io::stderr();
let slot = &self.slot.to_string();
let mut command_buffer = &mut String::with_capacity(64);
let has_timeout = self.timeout != Duration::from_millis(0);
let mut input = String::with_capa... | identifier_body |
exec_commands.rs | use arguments::{VERBOSE_MODE, JOBLOG};
use execute::command::{self, CommandErr};
use input_iterator::InputsLock;
use numtoa::NumToA;
use time::{self, Timespec};
use tokenizer::Token;
use verbose;
use super::pipe::disk::State;
use super::job_log::JobLog;
use super::child::handle_child;
use std::io::{self, Read, Write};... | let mut command_buffer = &mut String::with_capacity(64);
let has_timeout = self.timeout != Duration::from_millis(0);
let mut input = String::with_capacity(64);
let mut id_buffer = [0u8; 20];
let mut job_buffer = [0u8; 20];
let mut total_buffer =... | pub fn run(&mut self) {
let stdout = io::stdout();
let stderr = io::stderr();
let slot = &self.slot.to_string(); | random_line_split |
lib.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 ... |
/* The libcore prelude, not as all-encompassing as the libstd prelude */
pub mod prelude;
/* Core modules for ownership management */
pub mod intrinsics;
pub mod mem;
pub mod nonzero;
pub mod ptr;
/* Core language traits */
pub mod marker;
pub mod ops;
pub mod cmp;
pub mod clone;
pub mod default;
/* Core types a... | pub mod num; | random_line_split |
borrowck-borrow-overloaded-deref-mut.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 ... | <T> {
value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
fn deref_imm(x: Own<isize>) {
let _i... | Own | identifier_name |
borrowck-borrow-overloaded-deref-mut.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 ... | }
pub fn main() {} | **x = 3; | random_line_split |
borrowck-borrow-overloaded-deref-mut.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 ... |
pub fn main() {}
| {
**x = 3;
} | identifier_body |
infinite-scroll.directive.ts | import { AfterViewInit, Directive, ElementRef, EventEmitter, Input, OnDestroy, Output } from '@angular/core';
import { fromEvent, Observable, Subscription } from 'rxjs';
import { filter, map, pairwise } from 'rxjs/operators';
interface ScrollPosition {
scrollHeight: number;
scrollTop: number;
clientHeight... | (): void {
this.infiniteScrollSubscription.unsubscribe();
}
private isScrollingDown(positions: ScrollPosition[]): boolean {
return positions[0].scrollTop < positions[1].scrollTop;
}
private isScrollExpected(position: ScrollPosition): boolean {
return (position.scrollHeight - (p... | ngOnDestroy | identifier_name |
infinite-scroll.directive.ts | import { filter, map, pairwise } from 'rxjs/operators';
interface ScrollPosition {
scrollHeight: number;
scrollTop: number;
clientHeight: number;
}
@Directive({
selector: '[gdInfiniteScroll]',
})
export class InfiniteScrollDirective implements AfterViewInit, OnDestroy {
@Input() threshold = 50;
... | import { AfterViewInit, Directive, ElementRef, EventEmitter, Input, OnDestroy, Output } from '@angular/core';
import { fromEvent, Observable, Subscription } from 'rxjs'; | random_line_split | |
infinite-scroll.directive.ts | import { AfterViewInit, Directive, ElementRef, EventEmitter, Input, OnDestroy, Output } from '@angular/core';
import { fromEvent, Observable, Subscription } from 'rxjs';
import { filter, map, pairwise } from 'rxjs/operators';
interface ScrollPosition {
scrollHeight: number;
scrollTop: number;
clientHeight... |
ngAfterViewInit(): void {
this.scrolledDown = fromEvent(this.elementRef.nativeElement, 'scroll').pipe(
map((event: Event): ScrollPosition => {
const target = <HTMLElement>event.target;
const scrollHeight = target.scrollHeight;
const scrollTop = ... | {
} | identifier_body |
utils.py | from os import path
from errbot import BotPlugin, botcmd
def tail(f, window=20):
return ''.join(f.readlines()[-window:])
class Utils(BotPlugin):
# noinspection PyUnusedLocal
@botcmd
def echo(self, _, args):
""" A simple echo command. Useful for encoding tests etc ...
"""
re... | resp = "| key | value\n"
resp += "| -------- | --------\n"
resp += "| person | `%s`\n" % frm.person
resp += "| nick | `%s`\n" % frm.nick
resp += "| fullname | `%s`\n" % frm.fullname
resp += "| client | `%s`\n\n" % frm.client
# extra info if it is a ... | """
if args:
frm = self.build_identifier(str(args).strip('"'))
else:
frm = msg.frm | random_line_split |
utils.py | from os import path
from errbot import BotPlugin, botcmd
def tail(f, window=20):
return ''.join(f.readlines()[-window:])
class Utils(BotPlugin):
# noinspection PyUnusedLocal
@botcmd
def echo(self, _, args):
|
@botcmd
def whoami(self, msg, args):
""" A simple command echoing the details of your identifier. Useful to debug identity problems.
"""
if args:
frm = self.build_identifier(str(args).strip('"'))
else:
frm = msg.frm
resp = "| key | value\n"
... | """ A simple echo command. Useful for encoding tests etc ...
"""
return args | identifier_body |
utils.py | from os import path
from errbot import BotPlugin, botcmd
def tail(f, window=20):
return ''.join(f.readlines()[-window:])
class Utils(BotPlugin):
# noinspection PyUnusedLocal
@botcmd
def echo(self, _, args):
""" A simple echo command. Useful for encoding tests etc ...
"""
re... |
resp += "\n\n- string representation is '%s'\n" % frm
resp += "- class is '%s'\n" % frm.__class__.__name__
return resp
# noinspection PyUnusedLocal
@botcmd(historize=False)
def history(self, msg, args):
"""display the command history"""
answer = []
user_cmd... | resp += "\n`room` is %s\n" % frm.room | conditional_block |
utils.py | from os import path
from errbot import BotPlugin, botcmd
def tail(f, window=20):
return ''.join(f.readlines()[-window:])
class Utils(BotPlugin):
# noinspection PyUnusedLocal
@botcmd
def | (self, _, args):
""" A simple echo command. Useful for encoding tests etc ...
"""
return args
@botcmd
def whoami(self, msg, args):
""" A simple command echoing the details of your identifier. Useful to debug identity problems.
"""
if args:
frm = self.... | echo | identifier_name |
compliance_checks.py | import logging
import threading
import time
from django.utils.functional import cached_property, SimpleLazyObject
import jmespath
from zentral.core.compliance_checks import register_compliance_check_class
from zentral.core.compliance_checks.compliance_checks import BaseComplianceCheck
from zentral.core.compliance_check... | def process_tree(self, tree, last_seen):
machine_tag_set = None
compliance_check_statuses = []
serial_number = tree["serial_number"]
source_name = tree["source"]["name"]
platform = tree.get("platform")
if not platform:
logger.warning("Cannot process %s %s ... | with self._lock:
self._load()
return self._source_platform_checks.get((source_name.lower(), platform), [])
| random_line_split |
compliance_checks.py | import logging
import threading
import time
from django.utils.functional import cached_property, SimpleLazyObject
import jmespath
from zentral.core.compliance_checks import register_compliance_check_class
from zentral.core.compliance_checks.compliance_checks import BaseComplianceCheck
from zentral.core.compliance_check... | (self):
try:
return self.compliance_check.jmespath_check
except JMESPathCheck.DoesNotExist:
return
def get_redirect_url(self):
return self.jmespath_check.get_absolute_url()
register_compliance_check_class(InventoryJMESPathCheck)
class JMESPathChecksCache:
# T... | jmespath_check | identifier_name |
compliance_checks.py | import logging
import threading
import time
from django.utils.functional import cached_property, SimpleLazyObject
import jmespath
from zentral.core.compliance_checks import register_compliance_check_class
from zentral.core.compliance_checks.compliance_checks import BaseComplianceCheck
from zentral.core.compliance_check... |
compliance_check_statuses.append((jmespath_check.compliance_check, status, last_seen))
if not compliance_check_statuses:
# nothing to update, no events
return
status_updates = update_machine_statuses(serial_number, compliance_check_statuses)
for compliance_ch... | logger.warning("JMESPath check %s result is not a boolean", jmespath_check.pk) | conditional_block |
compliance_checks.py | import logging
import threading
import time
from django.utils.functional import cached_property, SimpleLazyObject
import jmespath
from zentral.core.compliance_checks import register_compliance_check_class
from zentral.core.compliance_checks.compliance_checks import BaseComplianceCheck
from zentral.core.compliance_check... |
jmespath_checks_cache = SimpleLazyObject(lambda: JMESPathChecksCache())
| machine_tag_set = None
compliance_check_statuses = []
serial_number = tree["serial_number"]
source_name = tree["source"]["name"]
platform = tree.get("platform")
if not platform:
logger.warning("Cannot process %s %s tree: missing platform", source_name, serial_number)
... | identifier_body |
parseInput.js | /**
* Takes an array of strings that represent functional dependencies and returns
* them as an array of objects containing functionaldependency objects.
*/
var parseInput = function(lines) {
lines = lines.split('\n');
var functionalDependencies = new DependencySet();
for(var i = 0; i < lines.length; ++i) {
... |
}
}
return functionalDependencies;
}; | {
var functionalDependency = new FunctionalDependency(lhs, rhs);
functionalDependencies.add(functionalDependency);
} | conditional_block |
parseInput.js | /**
* Takes an array of strings that represent functional dependencies and returns
* them as an array of objects containing functionaldependency objects.
*/
var parseInput = function(lines) {
lines = lines.split('\n');
var functionalDependencies = new DependencySet();
for(var i = 0; i < lines.length; ++i) {
... |
return functionalDependencies;
}; | }
} | random_line_split |
environment.js | module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
EXTEND_PROTOTYPES: false,
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'wit... | // ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console o... | random_line_split | |
environment.js | module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
EXTEND_PROTOTYPES: false,
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'wit... |
if (environment === 'production') {
ENV.baseURL = '/ember-collection';
ENV.locationType = 'hash';
}
return ENV;
};
| {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
} | conditional_block |
notetranslator_tests.py | from nose.tools import *
from DeckMaker.notetranslator import NoteTranslator
def setup():
print "SETUP!"
def teardown():
print "TEAR DOWN!"
def test_basic():
t = NoteTranslator()
assert_equal(t.GetMidiCodeForHumans("E5"),64)
assert_equal(t.GetMidiCodeForHumans("C1"),12)
assert_equal(t.GetM... | assert_equal(t.GetHexString(t.GetMidiCodeForHumans("D#2")),"1b")
pass
def test_GetTriadCodes():
t = NoteTranslator()
assert_equal(t.GetTriadCodes( t.GetMidiCodeForHumans("C4"), "minor", 3),[48, 53, 56])
assert_equal(t.GetTriadCodes( t.GetMidiCodeForHumans("Ab2"), "major", 2),[32, 40, 35])
assert_equal(t.G... | assert_equal(t.GetHexString(t.GetMidiCodeForHumans("C1")),"c")
assert_equal(t.GetHexString(t.GetMidiCodeForHumans("Ab6")),"50")
assert_equal(t.GetHexString(t.GetMidiCodeForHumans("Gb7")),"5a")
| random_line_split |
notetranslator_tests.py | from nose.tools import *
from DeckMaker.notetranslator import NoteTranslator
def setup():
print "SETUP!"
def | ():
print "TEAR DOWN!"
def test_basic():
t = NoteTranslator()
assert_equal(t.GetMidiCodeForHumans("E5"),64)
assert_equal(t.GetMidiCodeForHumans("C1"),12)
assert_equal(t.GetMidiCodeForHumans("Ab6"),80)
assert_equal(t.GetMidiCodeForHumans("Gb7"),90)
assert_equal(t.GetMidiCodeForHumans("D#2"),27)
pas... | teardown | identifier_name |
notetranslator_tests.py | from nose.tools import *
from DeckMaker.notetranslator import NoteTranslator
def setup():
print "SETUP!"
def teardown():
print "TEAR DOWN!"
def test_basic():
t = NoteTranslator()
assert_equal(t.GetMidiCodeForHumans("E5"),64)
assert_equal(t.GetMidiCodeForHumans("C1"),12)
assert_equal(t.GetM... | t = NoteTranslator()
assert_equal(t.GetTriadHexCodeStrings( t.GetMidiCodeForHumans("C4"), "major", 1),['30', '34', '37'])
assert_equal(t.GetTriadHexCodeStrings( t.GetMidiCodeForHumans("Ab2"), "major", 2),['20', '28', '23'])
assert_equal(t.GetTriadHexCodeStrings( t.GetMidiCodeForHumans("G#6"), "minor", 1),['50', '... | identifier_body | |
lib.rs | extern crate ai_behavior;
extern crate find_folder;
extern crate gfx_device_gl;
extern crate graphics;
extern crate nalgebra;
extern crate ncollide;
extern crate piston_window;
extern crate rand;
extern crate sprite;
extern crate uuid;
mod mobs;
use gfx_device_gl::Resources;
use graphics::Image;
use graphics::rectang... | let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.unwrap();
let ref font = assets.join("Fresca-Regular.ttf");
let factory = w.factory.clone();
let mut glyphs = Glyphs::new(font, factory).unwrap();
let Size { height, width } = ... | }
}
pub fn on_draw(&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) { | random_line_split |
lib.rs | extern crate ai_behavior;
extern crate find_folder;
extern crate gfx_device_gl;
extern crate graphics;
extern crate nalgebra;
extern crate ncollide;
extern crate piston_window;
extern crate rand;
extern crate sprite;
extern crate uuid;
mod mobs;
use gfx_device_gl::Resources;
use graphics::Image;
use graphics::rectang... |
pub fn on_draw(&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) {
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.unwrap();
let ref font = assets.join("Fresca-Regular.ttf");
let factory = w.factory.clone();
let mut gl... | {
if self.pause || self.victory || self.loss {
return;
}
self.scene.event(e);
let mut grew = false;
for mut star in &mut self.stars {
if !star.destroyed && self.player.collides(&star) {
star.destroy(&mut self.scene, upd.dt);
... | identifier_body |
lib.rs | extern crate ai_behavior;
extern crate find_folder;
extern crate gfx_device_gl;
extern crate graphics;
extern crate nalgebra;
extern crate ncollide;
extern crate piston_window;
extern crate rand;
extern crate sprite;
extern crate uuid;
mod mobs;
use gfx_device_gl::Resources;
use graphics::Image;
use graphics::rectang... | (&mut self, e: &Input, _: RenderArgs, w: &mut PistonWindow) {
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.unwrap();
let ref font = assets.join("Fresca-Regular.ttf");
let factory = w.factory.clone();
let mut glyphs = Glyphs::new(f... | on_draw | identifier_name |
lib.rs | extern crate ai_behavior;
extern crate find_folder;
extern crate gfx_device_gl;
extern crate graphics;
extern crate nalgebra;
extern crate ncollide;
extern crate piston_window;
extern crate rand;
extern crate sprite;
extern crate uuid;
mod mobs;
use gfx_device_gl::Resources;
use graphics::Image;
use graphics::rectang... |
Button::Keyboard(Key::Down) => {
self.player.dir = (self.player.dir.0, 0.0);
}
Button::Keyboard(Key::Left) => {
self.player.dir = (0.0, self.player.dir.1);
}
Button::Keybo... | {
self.player.dir = (self.player.dir.0, 0.0);
} | conditional_block |
paste_data.rs | use rocket::Outcome;
use rocket::Request;
use rocket::data::{self, FromData, Data};
use rocket::http::{Status, ContentType};
use std::io::{Read};
#[derive(Serialize, Deserialize)]
pub struct | {
content: String,
}
impl PasteData {
pub fn get_content_cloned(&self) -> String {
self.content.clone()
}
}
impl FromData for PasteData {
type Error = String;
fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> {
let corr_content_type = ContentType::new("text",... | PasteData | identifier_name |
paste_data.rs | use rocket::Outcome;
use rocket::Request;
use rocket::data::{self, FromData, Data};
use rocket::http::{Status, ContentType};
use std::io::{Read};
#[derive(Serialize, Deserialize)]
pub struct PasteData {
content: String,
}
impl PasteData {
pub fn get_content_cloned(&self) -> String |
}
impl FromData for PasteData {
type Error = String;
fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> {
let corr_content_type = ContentType::new("text", "plain");
if req.content_type().expect("Could not extract content type") != corr_content_type {
return Out... | {
self.content.clone()
} | identifier_body |
paste_data.rs | use rocket::Outcome;
use rocket::Request;
use rocket::data::{self, FromData, Data};
use rocket::http::{Status, ContentType};
use std::io::{Read};
#[derive(Serialize, Deserialize)]
pub struct PasteData {
content: String,
}
impl PasteData {
pub fn get_content_cloned(&self) -> String {
self.content.clone... | let mut data_string = String::new();
if let Err(e) = data.open().read_to_string(&mut data_string) {
return Outcome::Failure((Status::InternalServerError, format!("{:?}", e)));
}
// remove the "paste=" from the raw data //TODO Problem: paste= must be at end of request
... | random_line_split | |
onboarding.rs | use std::io;
struct Enemy {
name: String,
dist: i32,
}
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
fn debugScanInformation(enemys: &Vec<&Enemy>) {
eprintln!("Debug Scan Data");
let mut i: i16;
i = 0;
for e in enemys.iter() {
eprintln!("- ... | () {
// game loop
loop {
// Vec (list) of enemys
let mut enemys: Vec<&Enemy> = Vec::new();
// Enemy 1
let mut input_line = String::new();
io::stdin().read_line(&mut input_line).unwrap();
let enemy_1 = input_line.trim().to_string(); // name of enemy 1
let ... | main | identifier_name |
onboarding.rs | use std::io;
struct Enemy {
name: String,
dist: i32,
}
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
fn debugScanInformation(enemys: &Vec<&Enemy>) |
/**
* CodinGame planet is being attacked by slimy insectoid aliens.
* <---
* Hint:To protect the planet, you can implement the pseudo-code provided in the statement, below the player.
**/
fn main() {
// game loop
loop {
// Vec (list) of enemys
let mut enemys: Vec<&Enemy> = Vec::new();
... | {
eprintln!("Debug Scan Data");
let mut i: i16;
i = 0;
for e in enemys.iter() {
eprintln!("- enemy_{}: {}", i, e.name);
eprintln!("- dist_{} : {}", i, e.dist);
i = i + 1;
}
} | identifier_body |
onboarding.rs | use std::io;
struct Enemy {
name: String,
dist: i32,
}
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
fn debugScanInformation(enemys: &Vec<&Enemy>) {
eprintln!("Debug Scan Data");
let mut i: i16;
i = 0;
for e in enemys.iter() {
eprintln!("- ... | }
/**
* CodinGame planet is being attacked by slimy insectoid aliens.
* <---
* Hint:To protect the planet, you can implement the pseudo-code provided in the statement, below the player.
**/
fn main() {
// game loop
loop {
// Vec (list) of enemys
let mut enemys: Vec<&Enemy> = Vec::new();
... | i = i + 1;
} | random_line_split |
rebel_commandant.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def addTemplate(cor... |
mobileTemplate.setCreatureName('corvette_rebel_commandant')
mobileTemplate.setLevel(82)
mobileTemplate.setDifficulty(Difficulty.ELITE)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale(1)
mobileTemplate.setSocialGroup("rebel")... | mobileTemplate = MobileTemplate() | random_line_split |
rebel_commandant.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def addTemplate(cor... | mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('corvette_rebel_commandant')
mobileTemplate.setLevel(82)
mobileTemplate.setDifficulty(Difficulty.ELITE)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale(1)
mobi... | identifier_body | |
rebel_commandant.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def | (core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('corvette_rebel_commandant')
mobileTemplate.setLevel(82)
mobileTemplate.setDifficulty(Difficulty.ELITE)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale... | addTemplate | identifier_name |
unwind-rec2.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 ... | () -> ~[int] {
~[0,0,0,0,0,0,0]
}
fn build2() -> ~[int] {
fail!();
}
struct Blk { node: ~[int], span: ~[int] }
fn main() {
let _blk = Blk {
node: build1(),
span: build2()
};
}
| build1 | identifier_name |
unwind-rec2.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 |
// error-pattern:fail
fn build1() -> ~[int] {
~[0,0,0,0,0,0,0]
}
fn build2() -> ~[int] {
fail!();
}
struct Blk { node: ~[int], span: ~[int] }
fn main() {
let _blk = Blk {
node: build1(),
span: build2()
};
} | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
unwind-rec2.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 ... |
struct Blk { node: ~[int], span: ~[int] }
fn main() {
let _blk = Blk {
node: build1(),
span: build2()
};
}
| {
fail!();
} | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
| # Replace image
(r'\.\.\s? image::.*', ''),
# Remove travis ci badge
(r'.*travis-ci\.org/.*', ''),
# Remove pypip.in badges
(r'.*pypip\.in/.*', ''),
(r'.*crate\.io/.*', ''),
(r'.*coveralls\.io/.*', ''),
)
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsuppo... | PYPI_RST_FILTERS = (
# Replace code-blocks
(r'\.\.\s? code-block::\s*(\w|\+)+', '::'), | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
PYPI_RST_FILTERS = (
# Replace code-blocks
(r'\.\.\s? code-block::\s*(\... | (filename):
with open(filename) as f:
packages = f.read().splitlines()
return packages
setup(
name="serialkiller-plugins",
version="0.0.2",
description="Plugins for serialkiller project",
long_description=rst('README.rst') + rst('CHANGELOG.txt'),
author="Bruno Adelé",
author_e... | required | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
PYPI_RST_FILTERS = (
# Replace code-blocks
(r'\.\.\s? code-block::\s*(\... |
return content
def required(filename):
with open(filename) as f:
packages = f.read().splitlines()
return packages
setup(
name="serialkiller-plugins",
version="0.0.2",
description="Plugins for serialkiller project",
long_description=rst('README.rst') + rst('CHANGELOG.txt'),
... | content = re.sub(regex, replacement, content) | conditional_block |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
PYPI_RST_FILTERS = (
# Replace code-blocks
(r'\.\.\s? code-block::\s*(\... |
def required(filename):
with open(filename) as f:
packages = f.read().splitlines()
return packages
setup(
name="serialkiller-plugins",
version="0.0.2",
description="Plugins for serialkiller project",
long_description=rst('README.rst') + rst('CHANGELOG.txt'),
author="Bruno Adelé... | '''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge
'''
content = open(filename).read()
for regex, replacement in PYPI_RST_FILTERS:
content = re.sub(regex, replacement, content)
return content | identifier_body |
1138_08_03-flood-fill.py | """
Crawls a terrain raster from a starting
point and "floods" everything at the same
or lower elevation by producing a mask
image of 1,0 values.
"""
import numpy as np
from linecache import getline
def floodFill(c,r,mask):
"""
Crawls a mask array containing
only 1 and 0 values from the
starting... | sx = 2582
sy = 2057
print "Beginning flood fill"
fld = floodFill(sx,sy, a)
print "Finished Flood fill"
header=""
for i in range(6):
header += hdr[i]
print "Saving grid"
# Open the output file, add the hdr, save the array
with open(target, "wb") as f:
f.write(header)
np.savetxt(f, fld, fmt=... | xres = cell
yres = cell * -1
# Starting point for the
# flood inundation
| random_line_split |
1138_08_03-flood-fill.py | """
Crawls a terrain raster from a starting
point and "floods" everything at the same
or lower elevation by producing a mask
image of 1,0 values.
"""
import numpy as np
from linecache import getline
def | (c,r,mask):
"""
Crawls a mask array containing
only 1 and 0 values from the
starting point (c=column,
r=row - a.k.a. x,y) and returns
an array with all 1 values
connected to the starting cell.
This algorithm performs a 4-way
check non-recursively.
"""
# cells already filled
filled ... | floodFill | identifier_name |
1138_08_03-flood-fill.py | """
Crawls a terrain raster from a starting
point and "floods" everything at the same
or lower elevation by producing a mask
image of 1,0 values.
"""
import numpy as np
from linecache import getline
def floodFill(c,r,mask):
"""
Crawls a mask array containing
only 1 and 0 values from the
starting... |
print "Saving grid"
# Open the output file, add the hdr, save the array
with open(target, "wb") as f:
f.write(header)
np.savetxt(f, fld, fmt="%1i")
print "Done!"
| header += hdr[i] | conditional_block |
1138_08_03-flood-fill.py | """
Crawls a terrain raster from a starting
point and "floods" everything at the same
or lower elevation by producing a mask
image of 1,0 values.
"""
import numpy as np
from linecache import getline
def floodFill(c,r,mask):
|
source = "terrain.asc"
target = "flood.asc"
print "Opening image..."
img = np.loadtxt(source, skiprows=6)
print "Image opened"
a = np.where(img<70, 1,0)
print "Image masked"
# Parse the headr using a loop and
# the built-in linecache module
hdr = [getline(source, i) for i in range(1,7)]
values = [f... | """
Crawls a mask array containing
only 1 and 0 values from the
starting point (c=column,
r=row - a.k.a. x,y) and returns
an array with all 1 values
connected to the starting cell.
This algorithm performs a 4-way
check non-recursively.
"""
# cells already filled
filled = set()
# ce... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.