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 |
|---|---|---|---|---|
horizon.py | # Copyright 2012 Nebula, 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 agree... |
@register.tag
def jstemplate(parser, token):
"""Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``,
``[[`` and ``]]`` with ``{{`` and ``}}`` and
``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts
with Django's template engine when using any of the Mustache-based
templating libraries.... | """Helper node for the ``jstemplate`` template tag."""
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context,):
output = self.nodelist.render(context)
output = output.replace('[[[', '{{{').replace(']]]', '}}}')
output = output.replace('[[', '{{').replac... | identifier_body |
TAToolsHandler.py | #!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2013-2015 First Flamingo Enterprise B.V.
#
# 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... |
def stopDictionary(self, direction, stopKey):
dictionary = self.results[direction].get(stopKey, None)
if dictionary == None:
dictionary = dict()
self.results[direction][stopKey] = dictionary
return dictionary
def histogram(self, direction, stopKey, dataKey)... | if mission.up: direction = Direction.up
else: direction = Direction.down
for stop in mission.stopsList:
stopKey = stop.station_id
if stop.status == StopStatuses.planned:
departureHist = self.histogram(direction, stopKey, 'v')
... | conditional_block |
TAToolsHandler.py | #!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2013-2015 First Flamingo Enterprise B.V.
#
# 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... |
def analyzeOffset(self, missionIDs):
self.offset = [None, None]
self.data=[[], []]
firstHalfHist = dict()
firstHalfItems = 0
secondHalfHist = dict()
secondHalfItems = 0
for missionID in missionIDs:
mission = TAMission.get(missionID)
... | self.departure = [series.first_point.upDeparture, series.last_point.downDeparture]
self.startStation = [series.first_point.stationName, series.last_point.stationName]
self.foundOffset = [None, None]
self.doc.main.add(markup.heading(2, 'Heenrichting'))
self.analyzeOffset(series.all_missi... | identifier_body |
TAToolsHandler.py | #!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2013-2015 First Flamingo Enterprise B.V.
#
# 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... | paper = markup.div('paper')
self.main = markup.div('main_content')
paper.add(self.main)
self.sidebar = markup.element_with_id('aside', 'sidebar')
self.sidebar.add(markup.main_menu(MENU_LIST))
paper.add(self.sidebar)
paper.add(markup.div('pushbottom'))
self... | random_line_split | |
TAToolsHandler.py | #!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2013-2015 First Flamingo Enterprise B.V.
#
# 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... | (self, halfHour, direction):
if self.offset[halfHour] != None:
self.doc.main.add(markup.heading(3, '%s halfuur :%02d' % (ORD_LABEL[halfHour], self.offset[halfHour])))
table = self.doc.add_table('table_%d' % (2 * direction + halfHour), self.tableTitles, self.tableFormat)
table... | reportOffset | identifier_name |
resultados.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router';
import { LocalStorage, SessionStorage } from "angular2-localstorage/WebStorage";
import { Logger } from '../logger';
import { Title, SafeResourceUrl, DomSanitizationService } from '@angular/pl... | import 'app/js/results.js';
@Component({
selector: 'q-results',
templateUrl: 'app/templates/results.component.html',
directives: [ROUTER_DIRECTIVES]
})
export class ResultsComponent implements OnInit {
surveyObj: Survey = new Survey();
sessionObj: Session = new Session();
firebase: AngularFire;
sanitize... | import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
declare var ResultsVar: any; | random_line_split |
resultados.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router';
import { LocalStorage, SessionStorage } from "angular2-localstorage/WebStorage";
import { Logger } from '../logger';
import { Title, SafeResourceUrl, DomSanitizationService } from '@angular/pl... | implements OnInit {
surveyObj: Survey = new Survey();
sessionObj: Session = new Session();
firebase: AngularFire;
sanitizer: DomSanitizationService;
surveyID: any;
isEmpty: boolean = false;
isLoaded: boolean = false;
proyectedUrl: SafeResourceUrl;
constructor(
private router : Router,
pri... | ResultsComponent | identifier_name |
test_auto_FSL2Scheme.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.camino.convert import FSL2Scheme
def test_FSL2Scheme_inputs():
|
def test_FSL2Scheme_outputs():
output_map = dict(scheme=dict(),
)
outputs = FSL2Scheme.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| input_map = dict(args=dict(argstr='%s',
),
bscale=dict(argstr='-bscale %d',
units='NA',
),
bval_file=dict(argstr='-bvalfile %s',
mandatory=True,
position=2,
),
bvec_file=dict(argstr='-bvecfile %s',
mandatory=True,
position=1,
),
diffusiontime=dict(argstr='-diffusionti... | identifier_body |
test_auto_FSL2Scheme.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.camino.convert import FSL2Scheme
def | ():
input_map = dict(args=dict(argstr='%s',
),
bscale=dict(argstr='-bscale %d',
units='NA',
),
bval_file=dict(argstr='-bvalfile %s',
mandatory=True,
position=2,
),
bvec_file=dict(argstr='-bvecfile %s',
mandatory=True,
position=1,
),
diffusiontime=dict(argstr='-dif... | test_FSL2Scheme_inputs | identifier_name |
test_auto_FSL2Scheme.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.camino.convert import FSL2Scheme
def test_FSL2Scheme_inputs():
input_map = dict(args=dict(argstr='%s',
),
bscale=dict(argstr='-bscale %d',
units='NA',
),
bval_file=dict(argstr='-... |
def test_FSL2Scheme_outputs():
output_map = dict(scheme=dict(),
)
outputs = FSL2Scheme.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| yield assert_equal, getattr(inputs.traits()[key], metakey), value | conditional_block |
test_auto_FSL2Scheme.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.camino.convert import FSL2Scheme
def test_FSL2Scheme_inputs():
input_map = dict(args=dict(argstr='%s',
),
bscale=dict(argstr='-bscale %d',
units='NA',
),
bval_file=dict(argstr='-... | )
outputs = FSL2Scheme.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value | def test_FSL2Scheme_outputs():
output_map = dict(scheme=dict(), | random_line_split |
connection.js | /**
* Module dependencies.
*/
var Connection = require('../../connection')
, mongo = require('mongodb')
, Server = mongo.Server
, ReplSetServers = mongo.ReplSetServers;
/**
* Connection for mongodb-native driver
*
* @api private
*/
function | () {
Connection.apply(this, arguments);
};
/**
* Inherits from Connection.
*/
NativeConnection.prototype.__proto__ = Connection.prototype;
/**
* Opens the connection.
*
* Example server options:
* auto_reconnect (default: false)
* poolSize (default: 1)
*
* Example db options:
* pk - custom primary ... | NativeConnection | identifier_name |
connection.js | /**
* Module dependencies.
*/
var Connection = require('../../connection')
, mongo = require('mongodb')
, Server = mongo.Server
, ReplSetServers = mongo.ReplSetServers;
/**
* Connection for mongodb-native driver
*
* @api private
*/
function NativeConnection() | ;
/**
* Inherits from Connection.
*/
NativeConnection.prototype.__proto__ = Connection.prototype;
/**
* Opens the connection.
*
* Example server options:
* auto_reconnect (default: false)
* poolSize (default: 1)
*
* Example db options:
* pk - custom primary key factory to generate `_id` values
*
* ... | {
Connection.apply(this, arguments);
} | identifier_body |
connection.js | /**
* Module dependencies.
*/
var Connection = require('../../connection')
, mongo = require('mongodb')
, Server = mongo.Server
, ReplSetServers = mongo.ReplSetServers;
/**
* Connection for mongodb-native driver
*
* @api private
*/
function NativeConnection() {
Connection.apply(this, arguments);
};
/*... | if (!this.db) {
server = new mongo.Server(this.host, Number(this.port), this.options.server);
this.db = new mongo.Db(this.name, server, this.options.db);
}
this.db.open(fn);
return this;
};
/**
* Opens a set connection
*
* See description of doOpen for server options. In this case options.replset
... | */
NativeConnection.prototype.doOpen = function (fn) {
var server;
| random_line_split |
defaults-nb_NO.min.js | /*!
* Bootstrap-select v1.12.2 (http://silviomoreto.github.io/bootstrap-select) | *
* Copyright 2013-2017 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof module&&module.exports?module.exports=b(require("jquery")):b(a.jQu... | random_line_split | |
aquifer.py | import numpy as np
import matplotlib.pyplot as plt
import inspect # Used for storing the input
class AquiferData:
def __init__(self, model, kaq, z, Haq, Hll, c, Saq, Sll, poraq, porll,
ltype, topboundary, phreatictop, kzoverkh=None, model3d=False):
'''kzoverkh and model3d only need to be ... |
def findlayer(self, z):
'''
Returns layer-number, layer-type and model-layer-number'''
if z > self.z[0]:
modellayer = -1
ltype = 'above'
layernumber = None
elif z < self.z[-1]:
modellayer = len(self.layernumber)
ltype ... | '''Returns -9999 if above top of system,
+9999 if below bottom of system,
negative for in leaky layer.
leaky layer -n is on top of aquifer n'''
if z > self.zt[0]:
return -9999
for i in range(self.naq-1):
if z >= self.zb[i]:
return i
... | identifier_body |
aquifer.py | import numpy as np
import matplotlib.pyplot as plt
import inspect # Used for storing the input
class AquiferData:
def __init__(self, model, kaq, z, Haq, Hll, c, Saq, Sll, poraq, porll,
ltype, topboundary, phreatictop, kzoverkh=None, model3d=False):
'''kzoverkh and model3d only need to be ... | '''
eigval[naq, npval]: Array with eigenvalues
lab[naq, npval]: Array with lambda values
lab2[naq, nint, npint]: Array with lambda values reorganized per
interval
eigvec[naq, naq, npval]: Array with eigenvector matrices
coef[naq ,naq, npval]: Array with coefficien... | def __repr__(self):
return 'Inhom T: ' + str(self.T)
def initialize(self): | random_line_split |
aquifer.py | import numpy as np
import matplotlib.pyplot as plt
import inspect # Used for storing the input
class AquiferData:
def __init__(self, model, kaq, z, Haq, Hll, c, Saq, Sll, poraq, porll,
ltype, topboundary, phreatictop, kzoverkh=None, model3d=False):
'''kzoverkh and model3d only need to be ... |
#
self.eigval = np.zeros((self.naq, self.model.npval), 'D')
self.lab = np.zeros((self.naq, self.model.npval), 'D')
self.eigvec = np.zeros((self.naq, self.naq, self.model.npval), 'D')
self.coef = np.zeros((self.naq, self.naq, self.model.npval), 'D')
b = np.diag(np.ones(se... | self.c[1:] = \
0.5 * self.Haq[:-1] / (self.kzoverkh[:-1] * self.kaq[:-1]) + \
0.5 * self.Haq[1:] / (self.kzoverkh[1:] * self.kaq[1:]) | conditional_block |
aquifer.py | import numpy as np
import matplotlib.pyplot as plt
import inspect # Used for storing the input
class AquiferData:
def __init__(self, model, kaq, z, Haq, Hll, c, Saq, Sll, poraq, porll,
ltype, topboundary, phreatictop, kzoverkh=None, model3d=False):
'''kzoverkh and model3d only need to be ... | (self):
return 'Inhom T: ' + str(self.T)
def initialize(self):
'''
eigval[naq, npval]: Array with eigenvalues
lab[naq, npval]: Array with lambda values
lab2[naq, nint, npint]: Array with lambda values reorganized per
interval
eigvec[naq, naq, npval]: Arra... | __repr__ | identifier_name |
tokens.ts | export type AllTokens = Bracket | Literal | Operator | WhiteSpace | ColorValue | NumberValue | StringValue | Field;
export const enum OperatorType {
Sibling = '+', | ValueDelimiter = '-',
PropertyDelimiter = ':'
}
export interface Token {
type: string;
/** Location of token start in source */
start?: number;
/** Location of token end in source */
end?: number;
}
export interface Operator extends Token {
type: 'Operator';
operator: OperatorTyp... | Important = '!',
ArgumentDelimiter = ',', | random_line_split |
file-manager.service.ts | import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import {FileModel} from '../models/file.model';
@Injectable()
export class FileManagerService {
headers = ... |
}
});
return formData;
}
postFormData(formData: FormData, path: string): Observable<any> {
const url = `${this.getRequestUrl()}/upload`;
const headers = new HttpHeaders({
'enctype': 'multipart/form-data',
'Accept': 'application/json',
... | {
formData.append(key, item[key] || '');
} | conditional_block |
file-manager.service.ts | import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import {FileModel} from '../models/file.model';
| 'X-Requested-With': 'XMLHttpRequest'
});
requestUrl = '';
constructor(
public http: HttpClient
) {
this.requestUrl = '/admin/file_manager';
}
getRequestUrl() {
return this.requestUrl;
}
getList(options ?: any): Observable<FileModel[]> {
let para... | @Injectable()
export class FileManagerService {
headers = new HttpHeaders({
'Content-Type': 'application/json', | random_line_split |
file-manager.service.ts | import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import {FileModel} from '../models/file.model';
@Injectable()
export class FileManagerService {
headers = ... |
deleteFile(path: string, file: FileModel): Observable<any> {
const url = `${this.getRequestUrl()}/file_delete`;
return this.http.post<any>(url, {path: path, name: file.fileName}, {headers: this.headers}).pipe(
catchError(this.handleError<any>())
);
}
rename(path: strin... | {
const url = `${this.getRequestUrl()}/folder_delete`;
return this.http.post<any>(url, {path: path}, {headers: this.headers}).pipe(
catchError(this.handleError<any>())
);
} | identifier_body |
file-manager.service.ts | import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import {FileModel} from '../models/file.model';
@Injectable()
export class FileManagerService {
headers = ... | (options ?: any): Observable<FileModel[]> {
let params = new HttpParams();
for (const name in options) {
if (!options.hasOwnProperty(name)
|| typeof options[name] === 'undefined') {
continue;
}
params = params.append(name, options[name]... | getList | identifier_name |
rekall_offset_finder.py | #!/usr/bin/env python3
"""
Rekall offset finder.
Usage:
rekall_offset_finder.py [options] <domain> [<url>]
Options:
-d --debug Enable debug output
-u URI, --uri=URI Specify Libvirt URI [Default: qemu:///system]
-o --old Use the old config format
-h --help ... |
def format_config(domain, config, old_format=False):
if not old_format:
formatted_config = """
%s {
ostype = "Windows";
rekall_profile = "%s";
}
""" % (domain, config['rekall_profile'])
else:
formatted_config = """
%s {
ostype = "Windows";
win_pdbase = %s;
win_pid = %s;
... | s = session.Session(
filename=url,
autodetect=["rsds"],
logger=logging.getLogger(),
autodetect_build_local='none',
format='data',
profile_path=[
"http://profiles.rekall-forensic.com"
])
strio = StringIO()
s.RunP... | identifier_body |
rekall_offset_finder.py | #!/usr/bin/env python3
"""
Rekall offset finder.
Usage:
rekall_offset_finder.py [options] <domain> [<url>]
Options:
-d --debug Enable debug output
-u URI, --uri=URI Specify Libvirt URI [Default: qemu:///system]
-o --old Use the old config format
-h --help ... | con = libvirt.open(uri)
domain = con.lookupByName(domain_name)
# take dump
logging.info('Dumping %s physical memory to %s', domain.name(),
ram_dump.name)
flags = libvirt.VIR_DUMP_MEMORY_ONLY
dump... | os.chmod(ram_dump.name,
stat.S_IRUSR | stat.S_IWUSR |
stat.S_IRGRP | stat.S_IWGRP |
stat.S_IROTH | stat.S_IWOTH) | random_line_split |
rekall_offset_finder.py | #!/usr/bin/env python3
"""
Rekall offset finder.
Usage:
rekall_offset_finder.py [options] <domain> [<url>]
Options:
-d --debug Enable debug output
-u URI, --uri=URI Specify Libvirt URI [Default: qemu:///system]
-o --old Use the old config format
-h --help ... | (domain, url):
s = session.Session(
filename=url,
autodetect=["rsds"],
logger=logging.getLogger(),
autodetect_build_local='none',
format='data',
profile_path=[
"http://profiles.rekall-forensic.com"
])
strio = St... | extract_offsets | identifier_name |
rekall_offset_finder.py | #!/usr/bin/env python3
"""
Rekall offset finder.
Usage:
rekall_offset_finder.py [options] <domain> [<url>]
Options:
-d --debug Enable debug output
-u URI, --uri=URI Specify Libvirt URI [Default: qemu:///system]
-o --old Use the old config format
-h --help ... |
raise RuntimeError('Cannot find {} with version_modules '
'plugin'.format(NT_KRNL_PDB))
def extract_offsets(domain, url):
s = session.Session(
filename=url,
autodetect=["rsds"],
logger=logging.getLogger(),
autodetect_build_local='none',
... | e_data = entry[1]
if e_data['pdb'] in NT_KRNL_PDB:
return (e_data['pdb'], e_data['guid']) | conditional_block |
has-create.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | (value: RuleTiming): boolean {
return this.createTimings.indexOf(value) >= 0;
}
}
| transform | identifier_name |
has-create.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | } | random_line_split | |
edit-shift.ts | import { translate } from "./Translate"
import * as bootbox from "bootbox"
var updatePublishEvent = function () {
let $eventPublished = $('[name=evntIsPublished]');
var evtPublished = $eventPublished.is(':checked');
var publishIndicator = $('#eventPublishedIndicator');
publishIndicator.removeClass('fa... | publishIndicator.addClass('fa-check-square-o').addClass('text-success');
} else {
publishIndicator.addClass('fa-square-o').addClass('text-danger');
}
var isPrivateInput = $('[name=isPrivate]');
if (isPrivateInput.is(':checked')) {
publishBtn.removeClass('hidden');
} else {
... | var publishBtn = $('#publishBtn');
if (evtPublished) { | random_line_split |
edit-shift.ts |
import { translate } from "./Translate"
import * as bootbox from "bootbox"
var updatePublishEvent = function () {
let $eventPublished = $('[name=evntIsPublished]');
var evtPublished = $eventPublished.is(':checked');
var publishIndicator = $('#eventPublishedIndicator');
publishIndicator.removeClass('f... |
};
$(window).on('load', updatePublishEvent);
$('#publishBtn').click(function () {
if ($('[name=evntIsPublished]').is(':checked')) {
$('[name=evntIsPublished]').prop('checked', !$('[name=evntIsPublished]').is(':checked'));
updatePublishEvent();
} else {
bootbox.confirm({
titl... | {
publishBtn.addClass("hidden");
$('[name=evntIsPublished]').prop("checked", false);
} | conditional_block |
ServerPeriod.ts | /**
* The Reincarnation
* No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: beta
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the c... | armageddon?: number;
end?: number;
start?: number;
} | export interface ServerPeriod {
| random_line_split |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?... |
fn get_num_particles(&self) -> usize {
self.0.len()
}
}
fn dot_product(left: &(f64, f64, f64), right: &(f64, f64, f64)) -> f64 {
left.0 * right.0 + left.1 * right.1 + left.2 * right.2
}
fn get_norm(vec: &(f64, f64, f64)) -> f64 {
dot_product(&vec, &vec).sqrt()
}
fn main() {
let mut inp... | {
let (idx, part, _) = self.0
.iter()
.enumerate()
.map(|(idx, part)| {
let norm = get_norm(&part.acc);
(idx, part, norm)
})
.min_by(|&(_, _, l_norm), &(_, _, r_norm)| {
l_norm.partial_cmp(&r_norm).unwra... | identifier_body |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?... | else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (idx, part, _) = self.0
.iter()
... | {
acc + 1
} | conditional_block |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?P... | acc + 1
} else {
acc
},
);
occurrence_count <= 1
})
.cloned()
.collect();
}
fn get_longterm_closest_particle(&self) -> (usize, &Particle) {
let (i... | let occurrence_count = self.0.iter().fold(
0,
|acc, particle_2| if particle_1.pos ==
particle_2.pos
{ | random_line_split |
main.rs |
extern crate regex;
#[macro_use]
extern crate lazy_static;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
use regex::Regex;
lazy_static! {
static ref PARTICLE_RE: Regex = Regex::new(r"^p=<(?P<pos_x>-?[0-9]+),(?P<pos_y>-?[0-9]+),(?P<pos_z>-?[0-9]+)>, v=<(?P<vel_x>-?[0-9]+),(?P<vel_y>-?[0-9]+),(?... | (s: &str) -> Result<Self, Self::Err> {
Ok(Simulation(s.lines()
.map(|line| line.parse())
.collect::<Result<Vec<Particle>, ()>>()?))
}
}
impl Simulation {
fn do_step(&mut self) {
for particle in self.0.iter_mut() {
particle.vel.0 += particle.acc.0;
... | from_str | identifier_name |
auth.service.ts | import {EventEmitter, Injectable} from '@angular/core';
import {Headers, Http, Response, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {Logger} from './logger.service';
@Injectable()
export class AuthService {
private locationWatcher = new EventEmitter();
private loginUrl = 'ht... | this.authenticated = true;
this.login = userName;
this.password = password;
// store permissions
this.permissions = data.permissions;
}
return this.authenticated;
}
public subscribe(
onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void) {... | if (res.status === 200) { | random_line_split |
auth.service.ts | import {EventEmitter, Injectable} from '@angular/core';
import {Headers, Http, Response, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {Logger} from './logger.service';
@Injectable()
export class AuthService {
private locationWatcher = new EventEmitter();
private loginUrl = 'ht... |
return this.authenticated;
}
public subscribe(
onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void) {
return this.locationWatcher.subscribe(onNext, onThrow, onReturn);
}
}
| {
this.authenticated = true;
this.login = userName;
this.password = password;
// store permissions
this.permissions = data.permissions;
} | conditional_block |
auth.service.ts | import {EventEmitter, Injectable} from '@angular/core';
import {Headers, Http, Response, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {Logger} from './logger.service';
@Injectable()
export class | {
private locationWatcher = new EventEmitter();
private loginUrl = 'https://localhost:8443/simple-jee7/rest/login';
constructor(private http: Http, private log: Logger) { log.info('Instantiating AuthService'); }
authenticated: boolean = false;
login: string = '';
password: string = '';
permissions: str... | AuthService | identifier_name |
base64.js | // Base 64 encoding
const BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BASE_64_VALS = Object.create(null);
const getChar = val => BASE_64_CHARS.charAt(val);
const getVal = ch => ch === '=' ? -1 : BASE_64_VALS[ch];
for (let i = 0; i < BASE_64_CHARS.length; i++) {
BASE_6... | "Not ascii. Base64.encode can only take ascii strings.");
}
array[i] = ch;
}
}
const answer = [];
let a = null;
let b = null;
let c = null;
let d = null;
for (let i = 0; i < array.length; i++) {
switch (i % 3) {
case 0:
a = (array[i] >> 2) & 0x3F;
b =... | const ch = str.charCodeAt(i);
if (ch > 0xFF) {
throw new Error( | random_line_split |
movie_clip.js | /**
* Smokescreen Player - A Flash player written in JavaScript
* http://smokescreen.us/
*
* Copyright 2011, Chris Smoak
* Released under the MIT License.
* http://www.opensource.org/licenses/mit-license.php
*/
define(function(require, exports, module) {
var ext = require('lib/ext')
var env = require('lib/env'... |
var MovieClip = function(def, loader, parent, renderer) {
this.def = def
this.loader = loader
this.parent = parent
this.renderer = renderer
DisplayObject.call(this)
this.timeline = def.timeline
this.playhead = null
this.onEnterFrameCallback = ext.bind(this.onEnterFrame, this)
this.d... | var as2_MovieClip = require('as2/movie_clip').MovieClip
var DisplayList = require('player/display_list').DisplayList | random_line_split |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... |
}
impl CefProcessMessage {
pub unsafe fn from_c_object(c_object: *mut cef_process_message_t) -> CefProcessMessage {
CefProcessMessage {
c_object: c_object,
}
}
pub unsafe fn from_c_object_addref(c_object: *mut cef_process_message_t) -> CefProcessMessage {
if !c_object.is_null() {
((*c_o... | {
unsafe {
if !self.c_object.is_null() {
((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base);
}
}
} | identifier_body |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... |
CefProcessMessage {
c_object: c_object,
}
}
pub fn c_object(&self) -> *mut cef_process_message_t {
self.c_object
}
pub fn c_object_addrefed(&self) -> *mut cef_process_message_t {
unsafe {
if !self.c_object.is_null() {
eutil::add_ref(self.c_object as *mut types::cef_base_t)... | {
((*c_object).base.add_ref.unwrap())(&mut (*c_object).base);
} | conditional_block |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... | pub fn is_not_null_cef_object(&self) -> bool {
!self.c_object.is_null()
}
//
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
//
pub fn is_valid(&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF metho... | } | random_line_split |
cef_process_message.rs | // Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of ... | (&self) -> libc::c_int {
if self.c_object.is_null() {
panic!("called a CEF method on a null object")
}
unsafe {
CefWrap::to_rust(
((*self.c_object).is_read_only.unwrap())(
self.c_object))
}
}
//
// Returns a writable copy of this object.
//
pub fn copy(&self) -> ... | is_read_only | identifier_name |
gulpfile.js | var gulp = require('gulp');
var gutil = require("gulp-util");
var webpack = require("webpack");
var WebpackDevServer = require("webpack-dev-server");
var path = require('path');
var Server = require('karma').Server;
var config = {
entry: path.resolve(__dirname, 'app/main.js'),
output: {
path: path.resolv... | callback();
});
}); | // keep the server alive or continue? | random_line_split |
org.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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 appli... | (value):
return validate_username(value, "Organization name")
@cli.command("create", short_help="Create a new organization")
@click.argument(
"orgname", callback=lambda _, __, value: validate_orgname(value),
)
@click.option(
"--email", callback=lambda _, __, value: validate_email(value) if value else valu... | validate_orgname | identifier_name |
org.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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 appli... |
data.append(
(
"Owners:",
", ".join((owner.get("username") for owner in org.get("owners"))),
)
)
click.echo(tabulate(data, tablefmt="plain"))
return click.echo()
@cli.command("update", short_help="Update organization")
@click.argumen... | data.append(("Email:", org.get("email"))) | conditional_block |
org.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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 appli... |
@cli.command("create", short_help="Create a new organization")
@click.argument(
"orgname", callback=lambda _, __, value: validate_orgname(value),
)
@click.option(
"--email", callback=lambda _, __, value: validate_email(value) if value else value
)
@click.option("--displayname",)
def org_create(orgname, email... | return validate_username(value, "Organization name") | identifier_body |
org.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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 appli... | @click.argument("orgname",)
@click.argument("username",)
def org_add_owner(orgname, username):
client = AccountClient()
client.add_org_owner(orgname, username)
return click.secho(
"The new owner %s has been successfully added to the %s organization."
% (username, orgname),
fg="green"... |
@cli.command("add", short_help="Add a new owner to organization") | random_line_split |
videotracklist.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... |
}
track.add_track_list(self);
}
pub fn clear(&self) {
self.tracks
.borrow()
.iter()
.for_each(|t| t.remove_track_list());
self.tracks.borrow_mut().clear();
}
}
impl VideoTrackListMethods for VideoTrackList {
// https://html.spec.what... | {
self.set_selected(idx, false);
} | conditional_block |
videotracklist.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... | let this = Trusted::new(self);
let (source, canceller) = global
.as_window()
.task_manager()
.media_element_task_source_with_canceller();
if let Some(current) = self.selected_index() {
self.tracks.borrow()[current].set_selected(false);
}
... | random_line_split | |
videotracklist.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... |
pub fn find(&self, track: &VideoTrack) -> Option<usize> {
self.tracks.borrow().iter().position(|t| &**t == track)
}
pub fn item(&self, idx: usize) -> Option<DomRoot<VideoTrack>> {
self.tracks
.borrow()
.get(idx)
.map(|track| DomRoot::from_ref(&**track))... | {
self.tracks.borrow().len()
} | identifier_body |
videotracklist.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackListBinding::{... | {
eventtarget: EventTarget,
tracks: DomRefCell<Vec<Dom<VideoTrack>>>,
media_element: Option<Dom<HTMLMediaElement>>,
}
impl VideoTrackList {
pub fn new_inherited(
tracks: &[&VideoTrack],
media_element: Option<&HTMLMediaElement>,
) -> VideoTrackList {
VideoTrackList {
... | VideoTrackList | identifier_name |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc;
pub mod ffi;
pub mod initiator;
pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registe... |
/// Scan for discoverable supported devices
pub fn list_devices(context: *mut ffi::nfc_context, connstrings: *mut ffi::nfc_connstring, constrings_len: size_t) -> size_t {
unsafe { ffi::nfc_list_devices(context, connstrings, constrings_len) }
}
/// Switches the NFC device to idle mode
pub fn idle(pnd: *mut ffi::n... | {
unsafe { ffi::nfc_close(pnd); }
} | identifier_body |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc; | pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registers an NFC device driver with libnfc
pub fn register_driver(ndr: *const ffi::nfc_driver) -> i32 {
u... |
pub mod ffi;
pub mod initiator; | random_line_split |
lib.rs | #![crate_name = "nfc"]
#![crate_type = "dylib"]
extern crate libc;
pub mod ffi;
pub mod initiator;
pub mod target;
pub mod device;
pub mod context;
pub mod error;
pub mod misc;
pub mod to_str;
use libc::size_t;
// Library initialization/deinitialization
// See http://www.libnfc.org/api/group__lib.html
/// Registe... | (ndr: *const ffi::nfc_driver) -> i32 {
unsafe { ffi::nfc_register_driver(ndr) }
}
/// Initializes libnfc. This function must be called before calling any other libnfc function
pub fn init(context: *mut *mut ffi::nfc_context) {
unsafe { ffi::nfc_init(context); }
}
/// Deinitializes libnfc. Should be called aft... | register_driver | identifier_name |
connection.js | var EventEmitter = require('events').EventEmitter;
var util = require('util');
var MongoClient = require('mongodb').MongoClient;
var Channel = require('./channel');
/**
* Connection constructor.
*
* @param {String|Db} uri string or Db instance
* @param {Object} mongo driver options
* @api public
*/
function Conn... |
module.exports = Connection;
util.inherits(Connection, EventEmitter);
/**
* Current connection state.
*
* @type {String}
* @api public
*/
Object.defineProperty(Connection.prototype, 'state', {
enumerable: true,
get: function () {
var state;
// Using 'destroyed' to be compatible with th... | {
var self = this;
options || (options = {});
options.autoReconnect != null || (options.autoReconnect = true);
// It's a Db instance.
if (uri.collection) {
this.db = uri;
} else {
MongoClient.connect(uri, options, function (err, db) {
if (err) return self.emit('erro... | identifier_body |
connection.js | var EventEmitter = require('events').EventEmitter;
var util = require('util');
var MongoClient = require('mongodb').MongoClient;
var Channel = require('./channel');
/**
* Connection constructor.
*
* @param {String|Db} uri string or Db instance
* @param {Object} mongo driver options
* @api public
*/
function Conn... | var state;
// Using 'destroyed' to be compatible with the driver.
if (this.destroyed) {
state = 'destroyed';
}
else if (this.db) {
state = this.db.serverConfig.isConnected()
? 'connected' : 'disconnected';
} else {
stat... | get: function () { | random_line_split |
connection.js | var EventEmitter = require('events').EventEmitter;
var util = require('util');
var MongoClient = require('mongodb').MongoClient;
var Channel = require('./channel');
/**
* Connection constructor.
*
* @param {String|Db} uri string or Db instance
* @param {Object} mongo driver options
* @api public
*/
function Conn... | else {
state = 'connecting';
}
return state;
}
});
/**
* Creates or returns a channel with the passed name.
*
* @see Channel
* @return {Channel}
* @api public
*/
Connection.prototype.channel = function (name, options) {
if (typeof name === 'object') {
options = name;... | {
state = this.db.serverConfig.isConnected()
? 'connected' : 'disconnected';
} | conditional_block |
connection.js | var EventEmitter = require('events').EventEmitter;
var util = require('util');
var MongoClient = require('mongodb').MongoClient;
var Channel = require('./channel');
/**
* Connection constructor.
*
* @param {String|Db} uri string or Db instance
* @param {Object} mongo driver options
* @api public
*/
function | (uri, options) {
var self = this;
options || (options = {});
options.autoReconnect != null || (options.autoReconnect = true);
// It's a Db instance.
if (uri.collection) {
this.db = uri;
} else {
MongoClient.connect(uri, options, function (err, db) {
if (err) return ... | Connection | identifier_name |
order.py | from ..cw_model import CWModel
class Order(CWModel):
def __init__(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String... | self.poNumber = None # (String(50))
self.locationId = None # (Integer)
self.businessUnitId = None # (Integer)
self.salesRep = None # *(MemberReference)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (... | self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
| random_line_split |
order.py | from ..cw_model import CWModel
class Order(CWModel):
def __init__(self, json_dict=None):
| self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
self.site = None # (SiteReference)
self.status = N... | identifier_body | |
order.py | from ..cw_model import CWModel
class | (CWModel):
def __init__(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
... | Order | identifier_name |
io.py | """Microscoper is a wrapper around bioformats using a forked
python-bioformats to extract the raw images from Olympus IX83
CellSense .vsi format, into a more commonly used TIFF format.
Images are bundled together according to their channels.
This code is used internally in SCB Lab, TCIS, TIFR-H.
You're free to modify... | extensions = [".vsi"]
arg = arguments()
files = get_files(arg.f, arg.k)
if 0 == len(files):
print("No file matching *{}* keyword.".format(arg.k))
exit()
if arg.list:
for f in files:
print(f)
print("======================")
print("Total files found:"... | identifier_body | |
io.py | """Microscoper is a wrapper around bioformats using a forked
python-bioformats to extract the raw images from Olympus IX83
CellSense .vsi format, into a more commonly used TIFF format.
Images are bundled together according to their channels.
This code is used internally in SCB Lab, TCIS, TIFR-H.
You're free to modify... | c_total = reader.rdr.getSizeC()
z_total = reader.rdr.getSizeZ()
t_total = reader.rdr.getSizeT()
# Since we don't support hyperstacks yet...
if 1 not in [z_total, t_total]:
raise TypeError("Only 4D images are currently supported.")
metadata = get_metadata(pat... | random_line_split | |
io.py | """Microscoper is a wrapper around bioformats using a forked
python-bioformats to extract the raw images from Olympus IX83
CellSense .vsi format, into a more commonly used TIFF format.
Images are bundled together according to their channels.
This code is used internally in SCB Lab, TCIS, TIFR-H.
You're free to modify... | (images, channel, save_directory, big=False,
save_separate=False):
"""Saves the images as TIFs with channel name as the filename.
Channel names are saved as numbers when names are not available."""
# Make the output directory, if it doesn't alredy exist.
if not os.path.exists(save_direc... | save_images | identifier_name |
io.py | """Microscoper is a wrapper around bioformats using a forked
python-bioformats to extract the raw images from Olympus IX83
CellSense .vsi format, into a more commonly used TIFF format.
Images are bundled together according to their channels.
This code is used internally in SCB Lab, TCIS, TIFR-H.
You're free to modify... |
save_metadata(metadata, save_directory)
jb.kill_vm()
| metadata = read_images(path, save_directory, big=arg.big,
save_separate=arg.separate) | conditional_block |
assess_unbinned_reads_across_samples.py | import os
import pandas as pd
#import seaborn as sns
total_reads = pd.read_csv('../data/sample_info/sample_read_counts.tsv', sep='\t', names = ['fastq filename', 'number of reads'])
total_reads['cryptic metagenome name'] = total_reads['fastq filename'].str.strip('.fastq.gz') | sample_translation = pd.read_csv('../data/sample_info/meta4_sample_names--cryptic_to_sample_number.tsv', sep='\t')
read_mappings = pd.read_csv('./data/num_reads_mapped--can_double_count_multiple_mappings.tsv', sep='\t')
reads = pd.merge(sample_info, sample_translation)
reads = pd.merge(reads, total_reads)
reads = pd.... | sample_info = pd.read_csv('../data/sample_info/sample_info.tsv', sep='\t') | random_line_split |
api.py | # -*- coding: utf-8 -*-
#
# Copyright (C)2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consis... | (req, panel):
"""Process a request for a preference panel.
This function should return a tuple of the form `(template, data)`,
where `template` is the name of the template to use and `data` is the
data to be passed to the template.
"""
| render_preference_panel | identifier_name |
api.py | # -*- coding: utf-8 -*-
#
# Copyright (C)2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consis... | This function should return a tuple of the form `(template, data)`,
where `template` is the name of the template to use and `data` is the
data to be passed to the template.
""" | random_line_split | |
api.py | # -*- coding: utf-8 -*-
#
# Copyright (C)2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consis... |
def render_preference_panel(req, panel):
"""Process a request for a preference panel.
This function should return a tuple of the form `(template, data)`,
where `template` is the name of the template to use and `data` is the
data to be passed to the template.
"""
| """Return a list of available preference panels.
The items returned by this function must be tuple of the form
`(panel, label)`.
""" | identifier_body |
development.js | 'use strict';
module.exports = {
db: 'mongodb://lolo:tazkypass@dogen.mongohq.com:10048/todo-database',
app: {
title: 'TuDu - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callbac... | },
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/ca... | clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback' | random_line_split |
LanScan.py | import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddress = []
executionTime = 0
... | (self):
# execute the shells & determine whether the host is up or not
for shellInQueue in self.__shellPings:
pingResult = ""
shellInQueue.wait()
while True:
line = shellInQueue.stdout.readline()
if line != "":
... | __checkIfUp | identifier_name |
LanScan.py | import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddress = []
executionTime = 0
... | self.__getRange(fromIp,toIp)
self.__shellToQueue()
#self.__checkIfUp() # run by the shellToQueue queue organizer
self.__computerInfoInQueue()
endTime = time.time()
self.executionTime = round(endTime - startTime,3)
def __checkIfIpIsValid(self,ip):
... | random_line_split | |
LanScan.py | import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddress = []
executionTime = 0
... |
addIp = str(currentIp0)+"."+str(currentIp1)+"."+str(currentIp2)+"."+str(currentIp3)
self.__ipsToCheck.append(addIp)
def __shellToQueue(self):
# write them in the shell queue
maxPingsAtOnce = 200
currentQueuedPings = 0
for pingIp in self.__ips... | currentIp3 = 0
currentIp2 += 1
if currentIp2 > 255:
currentIp2 = 0
currentIp1 += 1
if currentIp1 > 255:
currentIp1 = 0
currentIp0 += 1 | conditional_block |
LanScan.py | import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddress = []
executionTime = 0
... |
def __shellToQueue(self):
# write them in the shell queue
maxPingsAtOnce = 200
currentQueuedPings = 0
for pingIp in self.__ipsToCheck:
proc = subprocess.Popen(['ping','-n','1',pingIp],stdout=subprocess.PIPE,shell=True)
self.__shellPings.appen... | fromIp = fromIp.split(".")
toIp = toIp.split(".")
# toIp must be > fromIp
def ip3chars(ipBlock):
# input 1; output 001
ipBlock = str(ipBlock)
while len(ipBlock) != 3:
ipBlock = "0"+ipBlock
return ipBlock
fromIpRaw... | identifier_body |
models.py | from django.db import models
from django.template.defaultfilters import truncatechars
class Setting(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
value = models.TextField(blank=True, default='')
value_type = models.CharField(max_length=1, choices=(('s', 'string'), ('i'... | verbose_name = 'Параметр'
verbose_name_plural = 'Параметры'
| identifier_name | |
models.py | from django.db import models
from django.template.defaultfilters import truncatechars
class Setting(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
value = models.TextField(blank=True, default='')
value_type = models.CharField(max_length=1, choices=(('s', 'string'), ('i'... | verbose_name = 'Параметр'
verbose_name_plural = 'Параметры' | random_line_split | |
models.py | from django.db import models
from django.template.defaultfilters import truncatechars
class Setting(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
value = models.TextField(blank=True, default='')
value_type = models.CharField(max_length=1, choices=(('s', 'string'), ('i'... | class Meta:
verbose_name = 'Параметр'
verbose_name_plural = 'Параметры'
| self.value
types = {'s': str, 'i': int, 'b': (lambda v: v.lower() == "true"), 'f': float}
return types[self.value_type](val)
| identifier_body |
fi.py | # -*- coding: iso-8859-1 -*-
# Text translations for Suomi (fi).
# Automatically generated - DO NOT EDIT, edit fi.po instead!
meta = {
'language': 'Suomi',
'maintainer': '***vacant***',
'encoding': 'iso-8859-1',
'direction': 'ltr',
}
text = { | '''Muokkaa "%(pagename)s"''',
'''Reduce editor size''':
'''Pienennä editointi ikkunan kokoa''',
'''Describe %s here.''':
'''Kuvaile %s tässä.''',
'''Check Spelling''':
'''Oikolue''',
'''Save Changes''':
'''Talleta muutokset''',
'''Cancel''':
'''Peruuta''',
'''Preview''':
'''Esikatsele''',
'''Edit was cancelled.''':
'''... | '''Create this page''':
'''Luo tämä sivu''',
'''Edit "%(pagename)s"''': | random_line_split |
datastore_loader.py | #!/usr/bin/env python
"""Process that loads the datastore"""
__author__ = 'Michael Meisinger, Thomas Lennan'
"""
Possible Features
- load objects into different datastores
- load from a directory of YML files in ion-definitions
- load from a ZIP of YMLs
- load an additional directory (not under GIT control)
- change... | (ImmediateProcess):
"""
bin/pycc -x ion.process.bootstrap.datastore_loader.DatastoreLoader op=clear prefix=ion
bin/pycc -x ion.process.bootstrap.datastore_loader.DatastoreLoader op=dump path=res/preload/local/my_dump
bin/pycc -fc -x ion.process.bootstrap.datastore_loader.DatastoreLoader op=load path=res... | DatastoreAdmin | identifier_name |
datastore_loader.py | #!/usr/bin/env python
"""Process that loads the datastore"""
__author__ = 'Michael Meisinger, Thomas Lennan'
"""
Possible Features
- load objects into different datastores
- load from a directory of YML files in ion-definitions
- load from a ZIP of YMLs
- load an additional directory (not under GIT control)
- change... |
def on_start(self):
# print env temporarily to debug cei
import os
log.info('ENV vars: %s' % str(os.environ))
op = self.CFG.get("op", None)
datastore = self.CFG.get("datastore", None)
path = self.CFG.get("path", None)
prefix = self.CFG.get("prefix", get_sys_... | pass | identifier_body |
datastore_loader.py | #!/usr/bin/env python
"""Process that loads the datastore"""
__author__ = 'Michael Meisinger, Thomas Lennan'
"""
Possible Features
- load objects into different datastores
- load from a directory of YML files in ion-definitions
- load from a ZIP of YMLs
- load an additional directory (not under GIT control)
- change... | rrh = ResourceRegistryHelper()
rrh.dump_resources_as_xlsx(path)
elif op == "blame":
# TODO make generic
self.da.get_blame_objects()
elif op == "clear":
self.da.clear_datastore(datastore, prefix)
else:
... | elif op == "dumpres":
from ion.util.datastore.resources import ResourceRegistryHelper | random_line_split |
datastore_loader.py | #!/usr/bin/env python
"""Process that loads the datastore"""
__author__ = 'Michael Meisinger, Thomas Lennan'
"""
Possible Features
- load objects into different datastores
- load from a directory of YML files in ion-definitions
- load from a ZIP of YMLs
- load an additional directory (not under GIT control)
- change... |
else:
raise iex.BadRequest("Operation unknown")
else:
raise iex.BadRequest("No operation specified")
def on_quit(self):
pass
DatastoreLoader = DatastoreAdmin
| self.da.clear_datastore(datastore, prefix) | conditional_block |
IngestListController.ts | import _ from 'lodash';
import {BaseListController} from 'apps/archive/controllers';
export class IngestListController extends BaseListController {
constructor($scope, $injector, $location, api, $rootScope, search, desks) {
super($scope, $location, search, desks);
$scope.type = 'ingest';
$... |
var query = this.getQuery($location.search());
this.fetchItems({source: query});
oldQuery = newquery;
});
$scope.$on('ingest:update', update);
$scope.$on('item:fetch', update);
$scope.$on('item:deleted', update);
$scope.$watchCollection(func... | {
$location.search('page', null);
} | conditional_block |
IngestListController.ts | import _ from 'lodash';
import {BaseListController} from 'apps/archive/controllers';
export class IngestListController extends BaseListController {
constructor($scope, $injector, $location, api, $rootScope, search, desks) |
}
IngestListController.$inject = ['$scope', '$injector', '$location', 'api', '$rootScope', 'search', 'desks'];
| {
super($scope, $location, search, desks);
$scope.type = 'ingest';
$scope.loading = false;
$scope.repo = {
ingest: true,
archive: false,
search: 'local',
};
$scope.api = api.ingest;
$rootScope.currentModule = 'ingest';
... | identifier_body |
IngestListController.ts | import _ from 'lodash';
import {BaseListController} from 'apps/archive/controllers';
export class IngestListController extends BaseListController {
| ($scope, $injector, $location, api, $rootScope, search, desks) {
super($scope, $location, search, desks);
$scope.type = 'ingest';
$scope.loading = false;
$scope.repo = {
ingest: true,
archive: false,
search: 'local',
};
$scope.api = ap... | constructor | identifier_name |
IngestListController.ts | import _ from 'lodash';
import {BaseListController} from 'apps/archive/controllers';
export class IngestListController extends BaseListController {
constructor($scope, $injector, $location, api, $rootScope, search, desks) {
super($scope, $location, search, desks);
$scope.type = 'ingest';
$... | api.query('ingest', criteria).then((items) => {
$scope.items = search.mergeItems(items, $scope.items, next);
$scope.total = items._meta.total;
})
.finally(() => {
$scope.loading = false;
});
};
t... | random_line_split | |
test_bleuscore.py | # ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems 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.apa... | # check against references
for score, reference in zip(bleu_metric.bleu_n, bleu_score_references):
assert round(score, 1) == reference
if __name__ == '__main__':
test_bleuscore() | bleu_metric(sentences, references)
| random_line_split |
test_bleuscore.py | # ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems 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.apa... | ():
# dataset with two sentences
sentences = ["a quick brown fox jumped",
"the rain in spain falls mainly on the plains"]
references = [["a fast brown fox jumped",
"a quick brown fox vaulted",
"a rapid fox of brown color jumped",
"th... | test_bleuscore | identifier_name |
test_bleuscore.py | # ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems 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.apa... |
if __name__ == '__main__':
test_bleuscore()
| assert round(score, 1) == reference | conditional_block |
test_bleuscore.py | # ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems 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.apa... |
if __name__ == '__main__':
test_bleuscore()
| sentences = ["a quick brown fox jumped",
"the rain in spain falls mainly on the plains"]
references = [["a fast brown fox jumped",
"a quick brown fox vaulted",
"a rapid fox of brown color jumped",
"the dog is running on the grass"],
... | identifier_body |
TrustTokensView.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as DataGrid from '../../../ui/components/data_grid/data_grid.js';
import * as ComponentHelper... | extends HTMLElement {
static readonly litTagName = LitHtml.literal`devtools-trust-tokens-storage-view`;
readonly #shadow = this.attachShadow({mode: 'open'});
#tokens: Protocol.Storage.TrustTokens[] = [];
#deleteClickHandler: (issuerOrigin: string) => void = () => {};
connectedCallback(): void {
this.#sh... | TrustTokensView | identifier_name |
TrustTokensView.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as DataGrid from '../../../ui/components/data_grid/data_grid.js';
import * as ComponentHelper... |
const gridData: DataGrid.DataGridController.DataGridControllerData = {
columns: [
{
id: 'issuer',
title: i18nString(UIStrings.issuer),
widthWeighting: 10,
hideable: false,
visible: true,
sortable: true,
},
{
id: 'c... | {
return LitHtml.html`<div class="no-tt-message">${i18nString(UIStrings.noTrustTokensStored)}</div>`;
} | conditional_block |
TrustTokensView.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as DataGrid from '../../../ui/components/data_grid/data_grid.js';
import * as ComponentHelper... | id: 'issuer',
title: i18nString(UIStrings.issuer),
widthWeighting: 10,
hideable: false,
visible: true,
sortable: true,
},
{
id: 'count',
title: i18nString(UIStrings.storedTokenCount),
widthWeighting: 5,
h... | }
const gridData: DataGrid.DataGridController.DataGridControllerData = {
columns: [
{ | random_line_split |
log.js | /**
* @file log.js
*/
import window from 'global/window';
/**
* Log plain debug messages
*/
const log = function(){
_logType(null, arguments);
};
/**
* Keep a history of log messages
* @type {Array}
*/
log.history = [];
/**
* Log error messages
*/
log.error = function(){
_logType('... | (type, args){
// convert args to an array to get array functions
let argsArray = Array.prototype.slice.call(args);
// if there's no console then don't try to output messages
// they will still be stored in log.history
// Was setting these once outside of this function, but containing them
// in the fu... | _logType | identifier_name |
log.js | /**
* @file log.js
*/
import window from 'global/window';
/**
* Log plain debug messages
*/
const log = function(){
_logType(null, arguments);
|
/**
* Keep a history of log messages
* @type {Array}
*/
log.history = [];
/**
* Log error messages
*/
log.error = function(){
_logType('error', arguments);
};
/**
* Log warning messages
*/
log.warn = function(){
_logType('warn', arguments);
};
/**
* Log messages to the console and ... | };
| random_line_split |
log.js | /**
* @file log.js
*/
import window from 'global/window';
/**
* Log plain debug messages
*/
const log = function(){
_logType(null, arguments);
};
/**
* Keep a history of log messages
* @type {Array}
*/
log.history = [];
/**
* Log error messages
*/
log.error = function(){
_logType('... |
export default log;
| {
// convert args to an array to get array functions
let argsArray = Array.prototype.slice.call(args);
// if there's no console then don't try to output messages
// they will still be stored in log.history
// Was setting these once outside of this function, but containing them
// in the function makes... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.