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 |
|---|---|---|---|---|
server.js | const fs = require('fs')
const http = require('http')
const mst = require('mustache')
const config = require('config')
const util = require('./util')
// Begin module
module.exports = function() {
// Create a server
http.createServer(function(req, res) {
const response = (res, output, content_type, status) =>... | })
return response(res, output)
}
else if(req.url == '/style.css') {
// Read the css file
output = fs.readFileSync(util.appPath('style'))
return response(res, output, 'text/css')
}
else if(req.url == '/json') {
// Read the JSON log file
output = fs.readFileSync... | return util.formatDate(render(date))
}
} | random_line_split |
server.js | const fs = require('fs')
const http = require('http')
const mst = require('mustache')
const config = require('config')
const util = require('./util')
// Begin module
module.exports = function() {
// Create a server
http.createServer(function(req, res) {
const response = (res, output, content_type, status) =>... |
else if(req.url == '/json') {
// Read the JSON log file
output = fs.readFileSync(util.appPath('log'))
return response(res, output, 'text/json')
}
else {
return response(res, '404 Page Not Found', 'text/html', 404)
}
}).listen(config.server_port, config.server_address)
cons... | {
// Read the css file
output = fs.readFileSync(util.appPath('style'))
return response(res, output, 'text/css')
} | conditional_block |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneFi... | return next(iter(self.sessions.filter(completed=None)), None)
@property
def latest(self):
session, _ = self.sessions.get_or_create(completed=None)
return session
@property
def last_completed(self):
return self.sessions.filter(completed__isnull=False).order_by("-started"... | return load_path_attr(self.activity_class_path)
@property
def in_progress(self): | random_line_split |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneFi... | "user_num_completions": user_num_completions,
"repeatable": activity.repeatable,
}
if state:
if state.in_progress:
activities["inprogress"].append(activity_entry)
elif activity.repeatable:
activities["repeatable"].append(act... | activities = {
"available": [],
"inprogress": [],
"completed": [],
"repeatable": []
}
for key, activity_class_path in hookset.all_activities():
activity = load_path_attr(activity_class_path)
state = ActivityState.state_for_user(user, key)
user_num_complet... | identifier_body |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneFi... | (models.Model):
"""
this stores the state of a particular session of a particular user
doing a particular activity.
"""
activity_state = models.ForeignKey(ActivityState, related_name="sessions", on_delete=models.CASCADE)
started = models.DateTimeField(default=timezone.now)
completed = mode... | ActivitySessionState | identifier_name |
models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneFi... |
else:
activities["available"].append(activity_entry)
return activities
| if state.in_progress:
activities["inprogress"].append(activity_entry)
elif activity.repeatable:
activities["repeatable"].append(activity_entry)
else:
activities["completed"].append(activity_entry) | conditional_block |
server.js | var io = require('socket.io').listen(4242);
io.set('log level', 1);
var Cube = require('./Cube');
var cubes = {};
io.sockets.on('connection', function (socket) {
// Envía la lista de cubos actual al nuevo jugador
for (var playerId in cubes) {
socket.emit('cubeUpdate', cubes[playerId]);
}
| socket.on('cubeUpdate', function (cubeData) {
var cube = cubes[socket.id];
if (cube !== undefined) cube.updateWithCubeData(cubeData);
socket.broadcast.emit('cubeUpdate', cube);
});
socket.on('disconnect', function () {
console.log(socket.id + " has disconnected from the server!");
delete cubes[socket.id];... | // Crea el nuevo cubo y lo envía a todos
var cube = new Cube (socket.id);
cubes[socket.id] = cube;
io.sockets.emit('cubeUpdate', cube);
| random_line_split |
fs.rs | .org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unix-specific extensions to primitives in the `std::fs` module.
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::v1::*;
use fs::{self, Permissions, OpenOptions};
use io;
us... | (&self) -> c_long { self.0.raw().st_mtime_nsec as c_long }
pub fn ctime(&self) -> raw::time_t { self.0.raw().st_ctime }
pub fn ctime_nsec(&self) -> c_long { self.0.raw().st_ctime_nsec as c_long }
pub fn blksize(&self) -> raw::blksize_t {
self.0.raw().st_blksize as raw::blksize_t
}
pub fn bl... | mtime_nsec | identifier_name |
fs.rs | ::{self, Permissions, OpenOptions};
use io;
use mem;
use os::raw::c_long;
use os::unix::raw;
use path::Path;
use sys::platform;
use sys;
use sys_common::{FromInner, AsInner, AsInnerMut};
#[unstable(feature = "fs_mode", reason = "recently added API")]
pub const USER_READ: raw::mode_t = 0o400;
#[unstable(feature = "fs_m... | {
sys::fs::symlink(src.as_ref(), dst.as_ref())
} | identifier_body | |
fs.rs | .org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unix-specific extensions to primitives in the `std::fs` module.
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::v1::*;
use fs::{self, Permissions, OpenOptions};
use io;
us... | impl Metadata {
pub fn dev(&self) -> raw::dev_t { self.0.raw().st_dev as raw::dev_t }
pub fn ino(&self) -> raw::ino_t { self.0.raw().st_ino as raw::ino_t }
pub fn mode(&self) -> raw::mode_t { self.0.raw().st_mode as raw::mode_t }
pub fn nlink(&self) -> raw::nlink_t { self.0.raw().st_nlink as raw::nlink_... | random_line_split | |
ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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 a... |
// EXPORTS //
module.exports = absBy;
| {
return mapBy( N, x, strideX, offsetX, y, strideY, offsetY, abs, clbk, thisArg ); // eslint-disable-line max-len
} | identifier_body |
ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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 a... | * return v * 2.0;
* }
*
* var x = [ 1.0, -2.0, 3.0, -4.0, 5.0 ];
* var y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
*
* absBy( x.length, x, 1, 0, y, 1, 0, accessor );
*
* console.log( y );
* // => [ 2.0, 4.0, 6.0, 8.0, 10.0 ]
*/
function absBy( N, x, strideX, offsetX, y, strideY, offsetY, clbk, thisArg ) {
return mapBy( N, x,... | * @returns {Collection} `y`
*
* @example
* function accessor( v ) { | random_line_split |
ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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 a... | ( N, x, strideX, offsetX, y, strideY, offsetY, clbk, thisArg ) {
return mapBy( N, x, strideX, offsetX, y, strideY, offsetY, abs, clbk, thisArg ); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = absBy;
| absBy | identifier_name |
configuration.py | #!/usr/bin/python2.5 | #
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | random_line_split | |
greatfet.rs | #![allow(missing_docs)] | use hal::lpc17xx::pin;
use hal::pin::Gpio;
use hal::pin::GpioDirection;
pub struct Led {
pin: pin::Pin,
}
impl Led {
pub fn new(idx: u8) -> Led {
Led {
pin: match idx {
0 => get_led(pin::Port::Port3, 14),
1 => get_led(pin::Port::Port2, 1),
... |
use core::intrinsics::abort; | random_line_split |
greatfet.rs | #![allow(missing_docs)]
use core::intrinsics::abort;
use hal::lpc17xx::pin;
use hal::pin::Gpio;
use hal::pin::GpioDirection;
pub struct Led {
pin: pin::Pin,
}
impl Led {
pub fn | (idx: u8) -> Led {
Led {
pin: match idx {
0 => get_led(pin::Port::Port3, 14),
1 => get_led(pin::Port::Port2, 1),
2 => get_led(pin::Port::Port3, 13),
3 => get_led(pin::Port::Port3, 12),
_ => unsaf... | new | identifier_name |
greatfet.rs | #![allow(missing_docs)]
use core::intrinsics::abort;
use hal::lpc17xx::pin;
use hal::pin::Gpio;
use hal::pin::GpioDirection;
pub struct Led {
pin: pin::Pin,
}
impl Led {
pub fn new(idx: u8) -> Led {
Led {
pin: match idx {
0 => get_led(pin::Port::Port3, 14),
... |
}
fn get_led(port: pin::Port, pin: u8) -> pin::Pin {
pin::Pin::new(
port, pin,
pin::Function::Gpio,
Some(GpioDirection::Out))
}
| {
self.pin.set_high();
} | identifier_body |
customer_form.js | import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtre... | this.$location.url("/");
this.$rootScope.$apply();
}
this._digest();
}
@Evented({
selector: "label#cancel",
type: "mouseup",
})
cancelByReturn () {
this.$location.path("/");
this.$rootScope.$apply();
}
} | birthday: this.$scope.model.age.content.toString(),
gender: this.$scope.model.gender.content,
last_contact: this.$scope.model.last_contact.content.toString(),
customer_lifetime_value: this.$scope.model.customer_lifetime_value.content,
}); | random_line_split |
customer_form.js | import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtre... |
}
@Evented({
selector: "label#save",
type: "mouseup",
})
async saveAndReturn () {
let valid = Object.getOwnPropertyNames(this.$scope.model)
.map((tupel) => {
let valid = this.$scope.model[tupel].validate();
if (!valid) {
this.log({
level: "error",
msg: `${this.$scope.model[tupel].... | {
this.log({
level: "warn",
msg: "Button Clicked, Handle Behaviour Propagation?"
});
} | conditional_block |
customer_form.js | import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtre... | (ev, { scope, triggerTokens }) {
if (scope._name.fn === "CustomersFormCtrl" &&
triggerTokens.type === "mouseup") {
this.log({
level: "warn",
msg: "Button Clicked, Handle Behaviour Propagation?"
});
}
}
@Evented({
selector: "label#save",
type: "mouseup",
})
async saveAndReturn () {
let va... | handleEvent | identifier_name |
svg_attach.js | /*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo.require("dojox.gfx.svg");
dojo.experimental("dojox.gfx.svg_attach");
(function(){
dojox.gfx.attachNode=function(_1){
i... |
var s=null;
switch(_1.tagName.toLowerCase()){
case dojox.gfx.Rect.nodeType:
s=new dojox.gfx.Rect(_1);
_2(s);
break;
case dojox.gfx.Ellipse.nodeType:
s=new dojox.gfx.Ellipse(_1);
_3(s,dojox.gfx.defaultEllipse);
break;
case dojox.gfx.Polyline.nodeType:
s=new dojox.gfx.Polyline(_1);
_3(s,dojox.gfx.defaultPolyline);
break... | {
return null;
} | conditional_block |
svg_attach.js | /*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo.require("dojox.gfx.svg");
dojo.experimental("dojox.gfx.svg_attach");
(function(){
dojox.gfx.attachNode=function(_1){
i... | }
};
var _9=function(_1a){
var _1b=_1a.rawNode.getAttribute("transform");
if(_1b.match(/^matrix\(.+\)$/)){
var t=_1b.slice(7,-1).split(",");
_1a.matrix=dojox.gfx.matrix.normalize({xx:parseFloat(t[0]),xy:parseFloat(t[2]),yx:parseFloat(t[1]),yy:parseFloat(t[3]),dx:parseFloat(t[4]),dy:parseFloat(t[5])});
}else{
_1a.matrix... | random_line_split | |
profiler.py | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$sta... | _stat_file = "last_run_func_stat.{0}".format(stat_type)
_stat_path = os.path.join(_base_path, _stat_file)
stats.save(_stat_path, type=stat_type)
sys.stdout.write("\nSaved Tendrl profiling stats at %s" % _base_path) | random_line_split | |
profiler.py | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$sta... | GreenletProfiler.stop()
sys.stdout.write("\nStopped Tendrl profiling...")
stats = GreenletProfiler.get_func_stats()
_base_path = "/var/lib/tendrl/profiling/{0}/".format(NS.publisher_id)
if not os.path.exists(_base_path):
os.makedirs(_base_path)
for stat_type in ['pstat', 'callgr... | identifier_body | |
profiler.py | import os
import sys
def | ():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$stat_type"
# eg: tendrl-node-age... | start | identifier_name |
profiler.py | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Provides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$sta... |
for stat_type in ['pstat', 'callgrind', 'ystat']:
_stat_file = "last_run_func_stat.{0}".format(stat_type)
_stat_path = os.path.join(_base_path, _stat_file)
stats.save(_stat_path, type=stat_type)
sys.stdout.write("\nSaved Tendrl profiling stats at %s" % _base_path)
| os.makedirs(_base_path) | conditional_block |
RamachandranFeature.py | DB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class Ramachand... |
plt.axis([- np.pi, np.pi, - np.pi, np.pi])
plt.show()
def save(self, data_path):
'''Save the data into a csv file.'''
data = [ (d['phi'], d['psi']) for d in self.feature_list ]
df = pd.DataFrame(data=data, columns=['phi', 'psi'])
self.append_to_csv(df, os.path.join(data_path, 'rama_feat... | else:
plt.scatter(self.clf.support_vectors_[:][0], self.clf.support_vectors_[:][1], c='red') | random_line_split |
RamachandranFeature.py | DB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class | (Feature):
'''Analyze the phi/psi torsion distributions of proteins.'''
def __init__(self):
super().__init__()
self.clf = None
self.de = None
def extract(self, input_path, total_num_threads=1, my_id=0):
'''Extract phi, psi angles from structures in the input path.'''
for f in self.list_my_... | RamachandranFeature | identifier_name |
RamachandranFeature.py | DB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class Ramachand... |
n_data = len(all_data)
training_data = all_data[0:int(0.7 * n_data)]
test_data = all_data[int(0.7 * n_data):n_data]
# Make some random data
phis = np.random.uniform(-np.pi, np.pi, 10000)
psis = np.random.uniform(-np.pi, np.pi, 10000)
random_data = list(zip(phis, psis))
if tra... | all_data = self.transform_features(all_data) | conditional_block |
RamachandranFeature.py | DB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn import mixture
from .Feature import Feature
from . import data_loading
from . import geometry
from . import machine_learning
class Ramachand... |
clf = svm.OneClassSVM(nu=nus[i], kernel="rbf", gamma='auto')
clf.fit(training_data)
predictions = clf.predict(training_data)
print("{0}/{1} training error.".format(len(predictions[-1 == predictions]), len(training_data)))
predictions = clf.predict(test_data)
... | '''Learn the distribution with a machine learning classifier'''
# Prepare the training data
all_data = [(d['phi'], d['psi']) for d in self.feature_list]
if transform_features:
all_data = self.transform_features(all_data)
n_data = len(all_data)
training_data = all_data[0:int(0.6 * n_data)]
... | identifier_body |
utils.ts | import { Model } from 'models/Model';
export function camelcaseToDashcase(camelcaseString: string) {
return camelcaseString.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
export function autoBind(object: { [index: string]: any }) |
export function toIdLookup<T extends Model = Model>(list: T[]) {
return list.reduce((lookup: {[index: number]: T}, item) => {
lookup[item.id] = item;
return lookup;
}, {});
}
export function nodeHeight(node: HTMLElement) {
return Array.from(node.children).reduce((acc, child) => {
... | {
return Object.getOwnPropertyNames(object).forEach((propName: string) => {
const prop = object[propName];
if (typeof prop === 'function') {
object[prop] = prop.bind(object);
}
});
} | identifier_body |
utils.ts | import { Model } from 'models/Model';
export function camelcaseToDashcase(camelcaseString: string) {
return camelcaseString.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
export function autoBind(object: { [index: string]: any }) {
return Object.getOwnPropertyNames(object).forEach((propName: string) ... |
});
}
export function toIdLookup<T extends Model = Model>(list: T[]) {
return list.reduce((lookup: {[index: number]: T}, item) => {
lookup[item.id] = item;
return lookup;
}, {});
}
export function nodeHeight(node: HTMLElement) {
return Array.from(node.children).reduce((acc, child) => ... | {
object[prop] = prop.bind(object);
} | conditional_block |
utils.ts | import { Model } from 'models/Model';
export function camelcaseToDashcase(camelcaseString: string) {
return camelcaseString.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
export function autoBind(object: { [index: string]: any }) {
return Object.getOwnPropertyNames(object).forEach((propName: string) ... | <T extends Model = Model>(list: T[]) {
return list.reduce((lookup: {[index: number]: T}, item) => {
lookup[item.id] = item;
return lookup;
}, {});
}
export function nodeHeight(node: HTMLElement) {
return Array.from(node.children).reduce((acc, child) => {
return acc + parseInt(getCom... | toIdLookup | identifier_name |
buffer.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { OperatorFunc... | <T> implements Operator<T, T[]> {
constructor(private closingNotifier: Observable<any>) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @exte... | BufferOperator | identifier_name |
buffer.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { OperatorFunc... | * @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link window}
*
* @param {Observable<any>} closingNotifier An Observable that signals the
* buffer to be emitted on the output Observable.
* @return {Observable<T[]>} An Observable of buffers, whi... | * ```
* | random_line_split |
gain.rs | use super::super::api;
pub fn information_gain<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let e = target_entropy(data, view);
let fe = entropy(data, view, criterion);
e - fe
}
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, vie... | {
let total = data.records.len();
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
classes[record.1 as usize] += 1;
}
for class in classes.iter() {
if *class == 0 {
return 0f64
}
}
let mut result = 0f64;
for class in classes.i... | identifier_body | |
gain.rs | use super::super::api;
pub fn | <T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let e = target_entropy(data, view);
let fe = entropy(data, view, criterion);
e - fe
}
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &ap... | information_gain | identifier_name |
gain.rs | use super::super::api;
pub fn information_gain<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, criterion: &api::Criterion<T>) -> f64 {
let e = target_entropy(data, view);
let fe = entropy(data, view, criterion);
e - fe
|
fn entropy_helper<T: api::RecordMeta>(data: &api::DataSet<T>, view: &api::DataSetView, value: bool, criterion: &api::Criterion<T>) -> f64 {
let mut total = 0;
let mut classes = vec![0; data.target_count];
for index in view.iter() {
let record = &data.records[*index];
if criterion(&record.0) == value {
... | }
| random_line_split |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedExcep... | }
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* ### Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some data... | this.readyState = ReadyStates.Done;
this.response.error(err);
} | random_line_split |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedExcep... |
}
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override providers
* to other backends, such as {@link XHRBackend}.
*
* ### Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some dat... | {
// Matches XHR semantics
this.readyState = ReadyStates.Done;
this.response.error(err);
} | identifier_body |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedExcep... | implements ConnectionBackend {
/**
* {@link EventEmitter}
* of {@link MockConnection} instances that have been created by this backend. Can be subscribed
* to in order to respond to connections.
*
* ### Example
*
* ```
* import {MockBackend, Http, BaseRequestOptions} from 'angular2/http';
... | MockBackend | identifier_name |
mock_backend.ts | import {Injectable} from 'angular2/angular2';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ReadyStates} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedExcep... |
this.readyState = ReadyStates.Done;
this.response.next(res);
this.response.complete();
}
/**
* Not yet implemented!
*
* Sends the provided {@link Response} to the `downloadObserver` of the `Request`
* associated with this connection.
*/
mockDownload(res: Response) {
// this.reques... | {
throw new BaseException('Connection has already been resolved');
} | conditional_block |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArgument... |
const newCollection = store._createSubCollection({
queryLog: store.queryLog.concat(logEntry)
});
return applyQuery ? applyQuery.call(store, newCollection, logEntry) : newCollection;
};
};
| {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
} | conditional_block |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArgument... |
if (querierFactory) {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
}
const newCollection = store._createSubCollection({
qu... | random_line_split | |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArgument... | <T>(kwArgs: QueryMethodArgs<T>): (...args: any[]) => dstore.Collection<T> {
const type = kwArgs.type;
const normalizeArguments = kwArgs.normalizeArguments;
const applyQuery = kwArgs.applyQuery;
const defaultQuerierFactory = kwArgs.querierFactory;
return function () {
const originalArguments = Array.prototype.sl... | QueryMethod | identifier_name |
QueryMethod.ts | import * as dstore from 'interfaces';
/**
* Arguments passed to the QueryMethod constructor.
* * applyQuery: Function receiving the query's new subcollection and log entry and applies it to the subcollection;
* useful for collections that need to both declare and implement new query methods
* * normalizeArgument... |
if (querierFactory) {
// Call the query factory in store context to support things like
// mapping a filter query's string argument to a custom filter method on the collection
logEntry.querier = querierFactory.apply(store, normalizedArguments);
}
const newCollection = store._createSubCollection({
qu... | {
const type = kwArgs.type;
const normalizeArguments = kwArgs.normalizeArguments;
const applyQuery = kwArgs.applyQuery;
const defaultQuerierFactory = kwArgs.querierFactory;
return function () {
const originalArguments = Array.prototype.slice.call(arguments);
const normalizedArguments = normalizeArguments ?
... | identifier_body |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... |
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_... | deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
re... | identifier_body |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... | from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLo... |
from threading import Thread
from time import sleep
import random
| random_line_split |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... | except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def cre... | nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for ... | conditional_block |
__init__.py | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... | (self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
... | ping | identifier_name |
_connectors.py | """Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
class HttpBasicClerk(_std_http.HttpStandardClerk):
"""An authen... |
def _provisionsets(self, upstream_affordances, downstream_affordances):
return (_plain.PlainAuth.PROVISIONS,)
class HttpBasicScanner(_std_http.HttpStandardScanner):
"""An authentication scanner for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_AUTHORIZATION_HEADER_RE = \
... | return (_BASIC_USER_TOKENS,) | identifier_body |
_connectors.py | """Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
class HttpBasicClerk(_std_http.HttpStandardClerk):
"""An authen... | (_std_http.HttpStandardScanner):
"""An authentication scanner for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_AUTHORIZATION_HEADER_RE = \
_re.compile(r'\s*Basic\s*(?P<creds_base64>[^\s]*)')
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _outputs(self, upstream_affordances, d... | HttpBasicScanner | identifier_name |
_connectors.py | """Connectors"""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import abc as _abc
import re as _re
from ... import plain as _plain
from .. import _std as _std_http
_BASIC_USER_TOKENS = ('user', 'password')
|
"""An authentication clerk for HTTP Basic authentication"""
__metaclass__ = _abc.ABCMeta
_BASIC_USER_TOKENS = _BASIC_USER_TOKENS
def _inputs(self, upstream_affordances, downstream_affordances):
return ((),)
def _append_response_auth_challenge(self, realm, input=None,
... | class HttpBasicClerk(_std_http.HttpStandardClerk): | random_line_split |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./... |
@htmlPy.Slot(str)
def link(self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)
sock.send(cmd)
response = sock.recv(1024)
processor(response)
app.template = (tem... | super(App, self).__init__() | identifier_body |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024) | app.static_path = os.path.abspath("./html")
template_name = 'index.html'
app_data = {
'val': '0'
}
def processor(response):
response = str(response)
response = json.loads(response)['message']
print(response)
command, data = response.split('#')
if '@' in command:
command, subcommand = ... | sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html") | random_line_split |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./... | (self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)
sock.send(cmd)
response = sock.recv(1024)
processor(response)
app.template = (template_name, app_data)
app.template... | link | identifier_name |
main.py | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./... |
if command == 'put':
app_data[subcommand] = data
class App(htmlPy.Object):
def __init__(self):
super(App, self).__init__()
@htmlPy.Slot(str)
def link(self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(s... | command, subcommand = command.split('@') | conditional_block |
index.d.ts | // Type definitions for passport-kakao 0.1
// Project: https://github.com/rotoshine/passport-kakao
// Definitions by: Park9eon <https://github.com/Park9eon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import passport = require("passport");
import express = require("exp... | implements passport.Strategy {
constructor(options: StrategyOption, verify: VerifyFunction);
authenticate: (req: express.Request, options?: any) => void;
userProfile: (accessToken: string, done: (error: any, user?: any) => void) => void;
}
| Strategy | identifier_name |
index.d.ts | // Type definitions for passport-kakao 0.1
// Project: https://github.com/rotoshine/passport-kakao
// Definitions by: Park9eon <https://github.com/Park9eon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import passport = require("passport");
import express = require("exp... | }
export type VerifyFunction =
(accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void;
export class Strategy implements passport.Strategy {
constructor(options: StrategyOption, verify: VerifyFunction);
authenticate: (req: express.Request,... | scopeSeparator?: string;
customHeaders?: string; | random_line_split |
cci_impl_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | i += 1;
}
}
} | while i < v {
f(i); | random_line_split |
cci_impl_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F>(&self, v: uint, mut f: F) where F: FnMut(uint) {
let mut i = *self;
while i < v {
f(i);
i += 1;
}
}
}
| to | identifier_name |
cci_impl_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| {
let mut i = *self;
while i < v {
f(i);
i += 1;
}
} | identifier_body |
test_educollections.py | from educollections import ArrayList
def | (lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
... | print_list_state | identifier_name |
test_educollections.py | from educollections import ArrayList
def print_list_state(lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
|
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10 - i)
arr.set(i, 10 - i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(10):
print('Append', i)
arr.append(i... | print('Prepend', i)
arr.prepend(i) | conditional_block |
test_educollections.py | from educollections import ArrayList
def print_list_state(lst):
|
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10... | print('Size is', lst.size())
print('Contents are', lst)
print() | identifier_body |
test_educollections.py | from educollections import ArrayList
def print_list_state(lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in ... | arr.append(i)
print_list_state(arr)
for i in [9, 4, 1, 6, 3, 0, 0, 0, 1, 0]:
item = arr.remove(i);
print('Removed', item, 'from index', i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8... | for i in range(10):
print('Append', i) | random_line_split |
commit.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Helper library for rendering commit info
use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use anyhow::Error;
use chrono... |
impl TryFrom<&thrift::CommitInfo> for CommitInfo {
type Error = Error;
fn try_from(commit: &thrift::CommitInfo) -> Result<CommitInfo, Error> {
let ids = map_commit_ids(commit.ids.values());
let parents = commit
.parents
.iter()
.map(|ids| map_commit_ids(ids.... | random_line_split | |
commit.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Helper library for rendering commit info
use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use anyhow::Error;
use chrono... | (commit: &thrift::CommitInfo) -> Result<CommitInfo, Error> {
let ids = map_commit_ids(commit.ids.values());
let parents = commit
.parents
.iter()
.map(|ids| map_commit_ids(ids.values()))
.collect();
let message = commit.message.clone();
let... | try_from | identifier_name |
broad_phase_filter2.rs | extern crate nalgebra as na;
use na::{Isometry2, Point2, RealField, Vector2};
use ncollide2d::broad_phase::BroadPhasePairFilter;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{FreeJ... | {
let mut testbed = Testbed::<f32>::new_empty();
init_world(&mut testbed);
testbed.run();
} | identifier_body | |
broad_phase_filter2.rs | extern crate nalgebra as na;
use na::{Isometry2, Point2, RealField, Vector2};
use ncollide2d::broad_phase::BroadPhasePairFilter;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{FreeJ... | ;
impl<N, Bodies, Colliders>
BroadPhasePairFilter<N, BroadPhasePairFilterSets<'_, N, Bodies, Colliders>>
for NoMultibodySelfContactFilter
where
N: RealField,
Bodies: BodySet<N>,
Colliders: ColliderSet<N, Bodies::Handle>,
{
fn is_pair_valid(
&self,
h1: Colliders::Handle,
... | NoMultibodySelfContactFilter | identifier_name |
broad_phase_filter2.rs | extern crate nalgebra as na;
use na::{Isometry2, Point2, RealField, Vector2};
use ncollide2d::broad_phase::BroadPhasePairFilter;
use ncollide2d::shape::{Ball, Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{FreeJ... | * This simplifies experimentation with various scalar types (f32, fixed-point numbers, etc.)
*/
pub fn init_world<N: RealField>(testbed: &mut Testbed<N>) {
/*
* World
*/
let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81)));
let geometrical_world = DefaultGeometric... |
/*
* NOTE: The `r` macro is only here to convert from f64 to the `N` scalar type. | random_line_split |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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.
from tests import TestCase, mkstemp
import os
... | (self):
self.cbes.write()
self.failUnlessEqual(self.memory, open(self.fname).read())
self.failUnlessEqual(self.saved, open(self.fname + ".saved").read())
def test_set_text_then_prepend(self):
self.cbes.get_child().set_text("foobar")
self.cbes.prepend_text("foobar")
s... | test_save | identifier_name |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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.
from tests import TestCase, mkstemp
import os
... |
def test_save(self):
self.cbes.write()
self.failUnlessEqual(self.memory, open(self.fname).read())
self.failUnlessEqual(self.saved, open(self.fname + ".saved").read())
def test_set_text_then_prepend(self):
self.cbes.get_child().set_text("foobar")
self.cbes.prepend_text(... | self.cbes.prepend_text("pattern 3")
self.memory = "pattern 3\npattern 1\n"
self.test_save() | identifier_body |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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.
from tests import TestCase, mkstemp
import os
... |
def test_text_changed_signal(self):
called = [0]
def cb(*args):
called[0] += 1
def get_count():
c = called[0]
called[0] = 0
return c
self.cbes.connect("text-changed", cb)
entry = self.cbes.get_child()
entry.set_text... | self.failUnlessEqual(row1[0], row2[0])
self.failUnlessEqual(row1[1], row2[1])
self.failUnlessEqual(row1[2], row2[2]) | conditional_block |
test_qltk_cbes.py | # -*- coding: utf-8 -*-
# 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.
from tests import TestCase, mkstemp
import os
... | data = [(row[1], row[0]) for row in self.sae.model]
self.failUnlessEqual(defaults, data)
def tearDown(self):
self.sae.destroy()
try:
os.unlink(self.fname)
os.unlink(self.fname + ".saved")
except OSError:
pass
quodlibet.config.quit(... | self.sae.write() | random_line_split |
websocket.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 dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBindi... | (global: &GlobalRef, url: DOMString) -> Temporary<WebSocket> {
let resource_task = global.resource_task();
let ws_url = Url::parse(url.as_slice()).unwrap();
let(start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(ws_url), start_chan));
let resp = start_port... | new | identifier_name |
websocket.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 dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBindi... |
pub fn Constructor(global: &GlobalRef, url: DOMString) -> Fallible<Temporary<WebSocket>> {
Ok(WebSocket::new(global, url))
}
}
impl Reflectable for WebSocket {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
impl<'a> WebSocketMethods for JSRef<'a, WebSo... | {
let resource_task = global.resource_task();
let ws_url = Url::parse(url.as_slice()).unwrap();
let(start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(ws_url), start_chan));
let resp = start_port.recv();
reflect_dom_object(box WebSocket::new_inheri... | identifier_body |
websocket.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 dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBindi... |
}
fn Close(self) {
}
fn Url(self) -> DOMString {
self.url.clone()
}
}
| {
return;
} | conditional_block |
websocket.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 dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::WebSocketBinding;
use dom::bindings::codegen::Bindings::WebSocketBinding::WebSo... | random_line_split | |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 ... | mailer.quit()
# update alert status
if ( result == 'email sent' ):
cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';')
else:
result = 'Invalid email.'
cursor.close()
def main():
emailIndex = 0
# check for command line argument for email to... | result = 'email failed'
sys.stderr.write('Email failed - ' + str(e))
trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"), emailIndex) | random_line_split |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 ... | ():
emailIndex = 0
# check for command line argument for email to use
if len(sys.argv) > 1:
emailIndex = int(sys.argv[1])
conn = ghConn()
# try sending any backed up alert mails
retryPendingMail(conn, emailIndex)
def trackEmailFailure(failureTime, emailIndex):
# Update tracking file
try:
f = open("last_no... | main | identifier_name |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 ... |
cursor.close()
if __name__ == "__main__":
main()
| fullText = row[2]
splitPos = fullText.find(" - ")
alertTitle = fullText[:splitPos]
alertBody = fullText[splitPos+3:]
result = sendAlertMail(conn, row[0], alertBody, row[3], row[4], alertTitle, emailIndex)
if result == 1:
sys.stderr.write("Delayed retrying rest of mail since quota reached.\n")
break
ro... | conditional_block |
catchupMail.py | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 ... |
def retryPendingMail(conn, emailIndex):
# open email alerts that have not been sucessfully sent less than 48 hours old
minTime = datetime.fromtimestamp(time.time()) - timedelta(days=4)
cursor = conn.cursor()
cursor.execute("SELECT userID, alertTime, alertMessage, alertLink, alertID FROM tAlerts WHERE alertType=2 ... | try:
f = open("last_notification_failure_" + emailIDs[emailIndex] + ".txt", "w")
f.write(failureTime)
f.close()
except IOError as e:
sys.stderr.write("Could not write email failure tracking file") | identifier_body |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source a... | (self):
return self._client.getAllObjects()
def getObjects(self, objDesc):
return self._client.getObjects(objDesc)
def getBusDesc(self):
return None if self._bus is None else self._bus.BUS_DESC
def getObjectsDesc(self):
return [] if self._bus is None else self._bus.BUS_DESC.objectsDesc.values()
def onBu... | getAllObjects | identifier_name |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source a... |
# To store Ids in TreeCtrl
self.treeIdBus = None
self.treeIdObj = {}
def getName(self):
if self._bus is not None:
return self._bus.BUS_DESC.name
else:
return os.path.basename(self.busInfo.xmlFile)
def getStatusStr(self):
return self._status
def start(self):
if self._client is not None:
sel... | self._client = obus.Client(mainFrame.GetTitle(), self.getBusDesc(), self)
for objDesc in self.getObjectsDesc():
self._client.registerObjectCb(objDesc, self) | conditional_block |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source a... | self.treeIdObj = {}
def getName(self):
if self._bus is not None:
return self._bus.BUS_DESC.name
else:
return os.path.basename(self.busInfo.xmlFile)
def getStatusStr(self):
return self._status
def start(self):
if self._client is not None:
self._status = "connecting"
self._client.start(self.b... | obus.BusEventCb.__init__(self)
obus.ObjectCb.__init__(self)
# Save parameters
self._mainFrame = mainFrame
self.busInfo = busInfo
# Load bus data
try:
self._status = "disconnected"
self._bus = obus.loadBus(busInfo.xmlFile)
except obus.DecodeError as ex:
self._bus = None
self._client = None
s... | identifier_body |
busdata.py | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source a... | self._client = None
self._status = str(ex)
else:
# Create obus client
self._client = obus.Client(mainFrame.GetTitle(), self.getBusDesc(), self)
for objDesc in self.getObjectsDesc():
self._client.registerObjectCb(objDesc, self)
# To store Ids in TreeCtrl
self.treeIdBus = None
self.treeIdObj = ... | self._bus = None | random_line_split |
exterior.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: Point = Point {x: 10, y: 11, z: 12};
let b: Gc<Cell<Point>> = box(GC) Cell::new(a);
assert_eq!(b.get().z, 12);
f(b);
assert_eq!(a.z, 12);
assert_eq!(b.get().z, 13);
}
| {
assert!((p.get().z == 12));
p.set(Point {x: 10, y: 11, z: 13});
assert!((p.get().z == 13));
} | identifier_body |
exterior.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn f(p: Gc<Cell<Point>>) {
assert!((p.get().z == 12));
p.set(Point {x: 10, y: 11, z: 13});
assert!((p.get().z == 13));
}
pub fn main() {
let a: Point = Point {x: 10, y: 11, z: 12};
let b: Gc<Cell<Point>> = box(GC) Cell::new(a);
assert_eq!(b.get().z, 12);
f(b);
assert_eq!(a.z, 12);
... |
struct Point {x: int, y: int, z: int} | random_line_split |
exterior.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: Point = Point {x: 10, y: 11, z: 12};
let b: Gc<Cell<Point>> = box(GC) Cell::new(a);
assert_eq!(b.get().z, 12);
f(b);
assert_eq!(a.z, 12);
assert_eq!(b.get().z, 13);
}
| main | identifier_name |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notifica... | (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if (!notificationSystem) {
const element = document.createElement... | buildToast | identifier_name |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notifica... |
warning (params: ToastParams | string): void { this.buildToast('warning', params); }
error (params: ToastParams | string): void { this.buildToast('error', params); }
}
export default new Toast();
| { this.buildToast('success', params); } | identifier_body |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notifica... |
private buildToast (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if (!notificationSystem) {
const element = d... | };
class Toast implements IToastFactory { | random_line_split |
ToastFactory.ts | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import NotificationSystem from 'react-notification-system';
import IToastFactory from './IToastFactory';
import ToastPosition from './ToastPosition';
import ToastParams from './ToastParams';
let notificationSystem = null;
const idify = (notifica... |
};
class Toast implements IToastFactory {
private buildToast (level: string, params: ToastParams | string): void {
const options = typeof params === 'string'
? { message: params }
: params;
if (!options.message) {
return;
}
const obj = Object.assign({}, new ToastParams(level), options);
if ... | {
const toastId = ['toast', notification.level, id];
notificationNode.setAttribute('id', toastId.join('-'));
} | conditional_block |
constants.py | # Copyright 2016 Twitter. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''c... | random_line_split | |
password.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { AuthProvider } from '../../../providers/auth/auth';
@IonicPage({
name: 'auth-password'
})
@Component({
selector: 'pa... | this.errorMessage = error;
break;
}
this.hasError = true;
});
}
navigatePop() {
this.navCtrl.pop();
}
}
| {
const loading = this.loadingCtrl.create({
content: 'Por favor, aguarde...'
});
loading.present();
this.auth.sendPasswordResetEmail(this.form.value.email).then(() => {
loading.dismiss();
this.hasError = false;
this.emailSent = true;
}, (error) => {
loading.dismiss();
... | identifier_body |
password.ts | import { Component } from '@angular/core'; | import { AuthProvider } from '../../../providers/auth/auth';
@IonicPage({
name: 'auth-password'
})
@Component({
selector: 'page-password',
templateUrl: 'password.html',
})
export class Password {
form : FormGroup;
hasError: boolean;
errorMessage: string;
emailSent: boolean;
constructor(
private ... | import { IonicPage, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
| random_line_split |
password.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { AuthProvider } from '../../../providers/auth/auth';
@IonicPage({
name: 'auth-password'
})
@Component({
selector: 'pa... | (
private navCtrl: NavController,
private loadingCtrl: LoadingController,
private formBuilder: FormBuilder,
private auth: AuthProvider
) {
this.form = this.formBuilder.group({
email: ['', Validators.required]
});
}
signInWithEmail() {
const loading = this.loadingCtrl.create({
... | constructor | identifier_name |
lib.rs | struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer {
Lexer { src: src, pos: 0 }
}
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn | (&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
loop {
if self.eof() {
break
}
match self.... | eof | identifier_name |
lib.rs | struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer |
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn eof(&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> {
let mut tok... | {
Lexer { src: src, pos: 0 }
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.