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 |
|---|---|---|---|---|
util.ts | /**
* PaperDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,... | <T>(obj: { [key: string]: T }, prefix: string): { [key: string]: T } {
const newObj = Object.create(null);
for (const key of Object.keys(obj))
if (key.indexOf(prefix) === 0)
newObj[key.substring(prefix.length)] = obj[key];
return newObj;
}
| pickPrefixed | identifier_name |
util.ts | /**
* PaperDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,... | return res;
}
export function pickPrefixed<T>(obj: { [key: string]: T }, prefix: string): { [key: string]: T } {
const newObj = Object.create(null);
for (const key of Object.keys(obj))
if (key.indexOf(prefix) === 0)
newObj[key.substring(prefix.length)] = obj[key];
return newObj;
} | console.log(el);
res.push(el);
} | random_line_split |
util.ts | /**
* PaperDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,... |
export function pickPrefixed<T>(obj: { [key: string]: T }, prefix: string): { [key: string]: T } {
const newObj = Object.create(null);
for (const key of Object.keys(obj))
if (key.indexOf(prefix) === 0)
newObj[key.substring(prefix.length)] = obj[key];
return newObj;
}
| {
const res = [];
for (const el of generator) {
console.log(el);
res.push(el);
}
return res;
} | identifier_body |
main.rs | #[macro_use] extern crate libeuler;
use libeuler::prime::SieveOfAtkin;
/// The first two consecutive numbers to have two distinct prime factors are:
///
/// 14 = 2 × 7
/// 15 = 3 × 5
///
/// The first three consecutive numbers to have three distinct prime factors are:
///
/// 644 = 2² × 7 × 23
/// 645 = 3 × 5 × 43
///... | return first;
}
}
None
}
}
}
| utions! {
inputs: (num: usize = 4)
sol naive {
let sieve = SieveOfAtkin::new(1_000_000);
let mut first = None;
let mut count = 0;
for i in 0..1_000_000 {
if sieve.factors(i).len() == num {
first = match first {
... | identifier_body |
main.rs | #[macro_use] extern crate libeuler;
use libeuler::prime::SieveOfAtkin;
/// The first two consecutive numbers to have two distinct prime factors are:
///
/// 14 = 2 × 7
/// 15 = 3 × 5
///
/// The first three consecutive numbers to have three distinct prime factors are:
///
/// 644 = 2² × 7 × 23
/// 645 = 3 × 5 × 43
///... | if count == num {
return first;
}
}
None
}
}
} | random_line_split | |
main.rs | #[macro_use] extern crate libeuler;
use libeuler::prime::SieveOfAtkin;
/// The first two consecutive numbers to have two distinct prime factors are:
///
/// 14 = 2 × 7
/// 15 = 3 × 5
///
/// The first three consecutive numbers to have three distinct prime factors are:
///
/// 644 = 2² × 7 × 23
/// 645 = 3 × 5 × 43
///... | solutions! {
inputs: (num: usize = 4)
sol naive {
let sieve = SieveOfAtkin::new(1_000_000);
let mut first = None;
let mut count = 0;
for i in 0..1_000_000 {
if sieve.factors(i).len() == num {
first = match first {
... | identifier_name | |
Signature.d.ts | declare namespace jsrsasign.KJUR.crypto {
/**
* Signature class which is very similar to java.security.Signature class
* @param params parameters for constructor
* @description
* As for params of constructor's argument, it can be specify following attributes:
* - alg - signature algorithm n... | {
/** Current state of this signature object whether 'SIGN', 'VERIFY' or null */
static readonly state: 'SIGN' | 'VERIFY' | null;
constructor(params?: { alg?: string | undefined });
/**
* set signature algorithm and provider
* @param alg signature algorithm name
... | Signature | identifier_name |
Signature.d.ts | declare namespace jsrsasign.KJUR.crypto {
/**
* Signature class which is very similar to java.security.Signature class
* @param params parameters for constructor
* @description
* As for params of constructor's argument, it can be specify following attributes:
* - alg - signature algorithm n... | * var sigValueHex = sig.sign();
*
* // ECDSA verifying
* var sig2 = new KJUR.crypto.Signature({'alg':'SHA1withECDSA'});
* sig.init(certPEM);
* sig.updateString('aaa');
* var isValid = sig.verify(sigValueHex);
*/
class Signature {
/** Current state of this signature ob... | random_line_split | |
imports.py | from __future__ import absolute_import
import pkgutil
import six
MODEL_MOVES = {
"sentry.models.tagkey.TagKey": "sentry.tagstore.legacy.models.tagkey.TagKey",
"sentry.models.tagvalue.tagvalue": "sentry.tagstore.legacy.models.tagvalue.TagValue",
"sentry.models.grouptagkey.GroupTagKey": "sentry.tagstore.le... | (context, root_module, path):
"""
Import all submodules and register them in the ``context`` namespace.
>>> import_submodules(locals(), __name__, __path__)
"""
for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + "."):
# this causes a Runtime error with model conflic... | import_submodules | identifier_name |
imports.py | from __future__ import absolute_import
import pkgutil
import six
MODEL_MOVES = {
"sentry.models.tagkey.TagKey": "sentry.tagstore.legacy.models.tagkey.TagKey",
"sentry.models.tagvalue.tagvalue": "sentry.tagstore.legacy.models.tagvalue.TagValue",
"sentry.models.grouptagkey.GroupTagKey": "sentry.tagstore.le... |
_cache = ModuleProxyCache()
def import_string(path):
"""
Path must be module.path.ClassName
>>> cls = import_string('sentry.models.Group')
"""
path = MODEL_MOVES.get(path, path)
result = _cache[path]
return result
def import_submodules(context, root_module, path):
"""
Import ... | def __missing__(self, key):
if "." not in key:
return __import__(key)
module_name, class_name = key.rsplit(".", 1)
module = __import__(module_name, {}, {}, [class_name])
handler = getattr(module, class_name)
# We cache a NoneType for missing imports to avoid repeat... | identifier_body |
imports.py | from __future__ import absolute_import
import pkgutil
import six
MODEL_MOVES = {
"sentry.models.tagkey.TagKey": "sentry.tagstore.legacy.models.tagkey.TagKey",
"sentry.models.tagvalue.tagvalue": "sentry.tagstore.legacy.models.tagvalue.TagValue",
"sentry.models.grouptagkey.GroupTagKey": "sentry.tagstore.le... | module = __import__(module_name, globals(), locals(), ["__name__"])
for k, v in six.iteritems(vars(module)):
if not k.startswith("_"):
context[k] = v
context[module_name] = module | conditional_block | |
imports.py | from __future__ import absolute_import
import pkgutil
import six
MODEL_MOVES = {
"sentry.models.tagkey.TagKey": "sentry.tagstore.legacy.models.tagkey.TagKey",
"sentry.models.tagvalue.tagvalue": "sentry.tagstore.legacy.models.tagvalue.TagValue",
"sentry.models.grouptagkey.GroupTagKey": "sentry.tagstore.le... | class ModuleProxyCache(dict):
def __missing__(self, key):
if "." not in key:
return __import__(key)
module_name, class_name = key.rsplit(".", 1)
module = __import__(module_name, {}, {}, [class_name])
handler = getattr(module, class_name)
# We cache a NoneType f... | "sentry.models.eventtag.EventTag": "sentry.tagstore.legacy.models.eventtag.EventTag",
}
| random_line_split |
image_texture.rs | use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimen... | else {
None
}
}
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn o... | {
Some(self.get_pixel(x, y))
} | conditional_block |
image_texture.rs | use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimen... | fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn outline() -> Rgba<u8> {
Rgba([255, ... | random_line_split | |
image_texture.rs | use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 |
fn get(&self, x: u32, y: u32) -> Option<I::Pixel> {
if self.in_bounds(x, y) {
Some(self.get_pixel(x, y))
} else {
None
}
}
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_tra... | {
self.dimensions().1
} | identifier_body |
image_texture.rs | use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimen... | () -> Rgb<u8> {
Rgb([255, 0, 0])
}
}
| outline | identifier_name |
backup.rs | // id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing ... |
}
| { "backup".into() } | identifier_body |
backup.rs | // id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing ... | {
pub id: f64,
pub name: String,
#[serde(rename = "type")]
pub b_type: String,
pub distribution: String,
pub slug: Option<String>,
pub public: bool,
pub regions: Vec<String>,
pub min_disk_size: f64,
}
impl response::NotArray for Backup {}
impl fmt::Display for Backup {
fn fmt(... | Backup | identifier_name |
backup.rs | // id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing ... | // how long the image is stored. This is one of "snapshot", "temporary" or
// "backup".
// distribution string The base distribution used for this image.
// slug nullable string A uniquely identifying string that is
// associated with each of the DigitalOcean-provided public images. These can
// be... | random_line_split | |
contextMenu.js |
import BasePlugin from './../_base';
import {arrayEach} from './../../helpers/array';
import {CommandExecutor} from './commandExecutor';
import {EventManager} from './../../eventManager';
import {hasClass} from './../../helpers/dom/element';
import {ItemsFactory} from './itemsFactory';
import {Menu} from './menu';
imp... | () {
if (!this.menu) {
return;
}
this.menu.close();
}
/**
* Execute context menu command.
*
* You can execute all predefined commands:
* * `'row_above'` - Insert row above
* * `'row_below'` - Insert row below
* * `'col_left'` - Insert column on the left
* * `'col_right'` ... | close | identifier_name |
contextMenu.js | import BasePlugin from './../_base';
import {arrayEach} from './../../helpers/array';
import {CommandExecutor} from './commandExecutor';
import {EventManager} from './../../eventManager';
import {hasClass} from './../../helpers/dom/element';
import {ItemsFactory} from './itemsFactory';
import {Menu} from './menu';
impo... | * * `'alignment:center'` - Alignment to the center (justify)
*
* Or you can execute command registered in settings where `key` is your command name.
*
* @param {String} commandName
* @param {*} params
*/
executeCommand(...params) {
this.commandExecutor.execute.apply(this.commandExecutor, par... | * * `'alignment:bottom'` - Alignment to the bottom
* * `'alignment:middle'` - Alignment to the middle | random_line_split |
contextMenu.js |
import BasePlugin from './../_base';
import {arrayEach} from './../../helpers/array';
import {CommandExecutor} from './commandExecutor';
import {EventManager} from './../../eventManager';
import {hasClass} from './../../helpers/dom/element';
import {ItemsFactory} from './itemsFactory';
import {Menu} from './menu';
imp... |
constructor(hotInstance) {
super(hotInstance);
/**
* Instance of {@link EventManager}.
*
* @type {EventManager}
*/
this.eventManager = new EventManager(this);
/**
* Instance of {@link CommandExecutor}.
*
* @type {CommandExecutor}
*/
this.commandExecutor = ... | {
return [
ROW_ABOVE, ROW_BELOW,
SEPARATOR,
COLUMN_LEFT, COLUMN_RIGHT,
SEPARATOR,
REMOVE_ROW, REMOVE_COLUMN,
SEPARATOR,
UNDO, REDO,
SEPARATOR,
READ_ONLY,
SEPARATOR,
ALIGNMENT,
];
} | identifier_body |
msgsend-pipes.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 ... |
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Port<request>, responses: &Chan<uint>) {
let mut count: uint = 0;
let mut done = false;
while !done {
match requests.try_recv() {
Some(get_count) => { responses.send(count.clone()); }
Some(bytes(b))... | {} | identifier_body |
msgsend-pipes.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 args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"1000000", ~"8"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"4"]
} else {
args.clone()
};
info!("%?", args);
run(args);
}
| main | identifier_name |
msgsend-pipes.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 ... |
}
}
responses.send(count);
//error!("server exiting");
}
fn run(args: &[~str]) {
let (from_child, to_parent) = stream();
let (from_parent, to_child) = stream();
let to_child = SharedChan::new(to_child);
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<ui... | { } | conditional_block |
msgsend-pipes.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.
// | // except according to those terms.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
extern mod extra;
use std::comm::{SharedChan, Chan, stream};
use std::io;
use std::os;
use std::task;
use std::uint;
fn move_out<T>(_x:... | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
important-test.js |
describe("Important plugin", () => {
it("should add !important to every number and string", () => {
const style = {
color: "blue",
fontSize: 15
};
expect(important()(style)).toEqual({
color: "blue!important",
fontSize: "15!important"
});
});
it("should add !important to every value in an array... | import important from "../../plugins/important/index"; | random_line_split | |
docchooser.js | if(typeof sne == "undefined") sne = { steps: {} };
sne.steps.docchooser = {};
(function ()
{
var docchooserCallback = null;
var usernameMap = null;
var docs = [];
var $docs = $('#docs');
sne.steps.docchooser.show = function (cb)
{
logNavigation('docchoser');
$('#docChooser').addClass('active');
... | );
$td.find('button.download').click(
function ()
{
downloadDoc(doc.id, doc.name);
}
);
$td.find('button.edit').click(
function ()
{
if(doc.owner != sne.uid)
return alert("You can only edit your own documents.");
sne.steps.docedit.show("ed... | {
var $btns = $('#btnsTemplate').clone();
var accessDate = moment(doc.accessDate).format("DD.MM.YYYY");
var owner = (usernameMap[doc.owner] || {}).name || "Unnamed";
var $td = tabletools.addRow($docs, [ doc.name, accessDate, owner, $btns ]);
$btns = $td.find('.btns').parent().addClass('btns');
... | identifier_body |
docchooser.js | if(typeof sne == "undefined") sne = { steps: {} };
sne.steps.docchooser = {};
(function ()
{
var docchooserCallback = null;
var usernameMap = null;
var docs = [];
var $docs = $('#docs');
sne.steps.docchooser.show = function (cb)
{
logNavigation('docchoser');
$('#docChooser').addClass('active');
... | (id, cb)
{
var res = confirm("Do you really want to delete this document?");
if(!res)
return;
shownoteseditor.connectors[sne.connectorName].deleteDocument(sne.connectorOptions, id, cb);
}
})();
| deleteDoc | identifier_name |
docchooser.js | if(typeof sne == "undefined") sne = { steps: {} };
sne.steps.docchooser = {};
(function ()
{
var docchooserCallback = null;
var usernameMap = null;
var docs = [];
var $docs = $('#docs');
sne.steps.docchooser.show = function (cb)
{
logNavigation('docchoser');
$('#docChooser').addClass('active');
... | function (e)
{
var $target = $(e.target);
if($target.prop('tagName').toLowerCase() == "button" ||
$target.parent().prop('tagName').toLowerCase() == "button")
{
return;
}
openDoc(doc.id);
}
);
$td.find('button.download').click(
... | var $td = tabletools.addRow($docs, [ doc.name, accessDate, owner, $btns ]);
$btns = $td.find('.btns').parent().addClass('btns');
$td.click( | random_line_split |
metrics.model.ts | import * as Lazy from 'lazy.js';
import {Pattern} from './patterns';
import {RemainingChars} from './remainingChars.model';
export class Metrics {
password = '';
wordIndexes = [];
remainingPasswordChars: RemainingChars = new RemainingChars('', 0, 0, 0, 0);
goodColor = '#66cc66';
badColor = '#ff6666';
up... | return this.badColor;
}
}
| return this.goodColor;
}
| conditional_block |
metrics.model.ts | import * as Lazy from 'lazy.js';
import {Pattern} from './patterns';
import {RemainingChars} from './remainingChars.model';
export class Metrics {
password = '';
wordIndexes = [];
remainingPasswordChars: RemainingChars = new RemainingChars('', 0, 0, 0, 0);
goodColor = '#66cc66';
badColor = '#ff6666';
up... |
inWordbookPoints() {
let points = 0;
Lazy(this.wordIndexes).each(function(word) {
points -= word.length * 2 // Abzug für Passwort aus Wörterbuch vorher 3
});
return points;
}
getUpperLetterPoints() {
return Pattern.upperChars.test(this.remainingPasswordChars.word) ? this.upperLetter... | {
return this.password.length * 5;
} | identifier_body |
metrics.model.ts | import * as Lazy from 'lazy.js';
import {Pattern} from './patterns';
import {RemainingChars} from './remainingChars.model';
export class Metrics {
password = '';
wordIndexes = [];
remainingPasswordChars: RemainingChars = new RemainingChars('', 0, 0, 0, 0);
goodColor = '#66cc66';
badColor = '#ff6666';
up... | return this.badColor;
}
} | if (this.timeToBreak() >= this.timeLimit) {
return this.goodColor;
} | random_line_split |
metrics.model.ts | import * as Lazy from 'lazy.js';
import {Pattern} from './patterns';
import {RemainingChars} from './remainingChars.model';
export class Metrics {
password = '';
wordIndexes = [];
remainingPasswordChars: RemainingChars = new RemainingChars('', 0, 0, 0, 0);
goodColor = '#66cc66';
badColor = '#ff6666';
up... | {
if (this.timeToBreak() >= this.timeLimit) {
return this.goodColor;
}
return this.badColor;
}
}
| meToBreakColor() | identifier_name |
exchanger.rs | use select::handle::{self, Handle};
use util::Backoff;
/// Waiting strategy in an exchange operation.
enum Wait {
/// Yield once and then time out.
YieldOnce,
/// Wait until an optional deadline.
Until(Option<Instant>),
}
/// Enumeration of possible exchange errors.
pub enum ExchangeError<T> {
//... |
use parking_lot::Mutex;
use select::CaseId; | random_line_split | |
exchanger.rs | /// There are two wait queues, one per side.
wait_queues: [WaitQueue<T>; 2],
/// `true` if the exchanger is closed.
closed: bool,
}
/// A two-sided exchanger.
///
/// This is a concurrent data structure with two sides: left and right. A thread can offer a
/// message on one side, and if there is another ... |
}
/// Returns `true` if the exchanger is closed.
pub fn is_closed(&self) -> bool {
self.inner.lock().closed
}
}
/// One side of an exchanger.
pub struct Side<'a, T: 'a> {
/// The index is 0 or 1.
index: usize,
/// A reference to the parent exchanger.
exchanger: &'a Exchanger<... | {
inner.closed = true;
inner.wait_queues[0].abort_all();
inner.wait_queues[1].abort_all();
true
} | conditional_block |
exchanger.rs | 0].abort_all();
inner.wait_queues[1].abort_all();
true
}
}
/// Returns `true` if the exchanger is closed.
pub fn is_closed(&self) -> bool {
self.inner.lock().closed
}
}
/// One side of an exchanger.
pub struct Side<'a, T: 'a> {
/// The index is 0 or 1.
i... | into_inner | identifier_name | |
exchanger.rs | /// There are two wait queues, one per side.
wait_queues: [WaitQueue<T>; 2],
/// `true` if the exchanger is closed.
closed: bool,
}
/// A two-sided exchanger.
///
/// This is a concurrent data structure with two sides: left and right. A thread can offer a
/// message on one side, and if there is another ... |
/// Fulfills the previously made promise.
pub fn fulfill(&self, msg: T) -> T {
finish_exchange(msg, self.exchanger)
}
/// Exchanges `msg` if there is an offer or promise on the opposite side.
pub fn try_exchange(
&self,
msg: T,
case_id: CaseId,
) -> Result<T, E... | {
self.exchanger.inner.lock().wait_queues[self.index].revoke(case_id);
} | identifier_body |
manage_keywords.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
| from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.default_behavior import Cancel
from pontus.form import FormView
from pontus.schema import Schema
from pontus.widget import Select2Widget
from pontus.view import BasicView
from pontus.view_operation impor... | import colander | random_line_split |
manage_keywords.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import colander
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.default_behavior import Cancel
from ... | (BasicView):
title = 'Alert for keywords'
name = 'alertforkeywordsmanagement'
template = 'lac:views/admin_process/templates/alert_event_keywords.pt'
def update(self):
result = {}
values = {}
body = self.content(args=values, template=self.template)['body']
item = self.ada... | ManageKeywordsViewStudyReport | identifier_name |
manage_keywords.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import colander
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.default_behavior import Cancel
from ... |
class ManageKeywordsFormView(FormView):
title = _('Manage keywords')
schema = ManageKeywordsSchema()
behaviors = [ManageKeywords, Cancel]
formid = 'formmanagekeywords'
name = 'formmanagekeywords'
@view_config(
name='managekeywords',
context=CreationCulturelleApplication,
renderer='... | targets = colander.SchemaNode(
colander.Set(),
widget=targets_choice,
title=_("Keywords")
)
source = colander.SchemaNode(
colander.String(),
title=_("New keyword")
) | identifier_body |
manage_keywords.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import colander
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.default_behavior import Cancel
from ... |
values = [(v, v) for v in sorted(keywords)]
return Select2Widget(
values=values,
multiple=True
)
class ManageKeywordsSchema(Schema):
targets = colander.SchemaNode(
colander.Set(),
widget=targets_choice,
title=_("Keywords")
)
source = colander... | keywords.remove(ROOT_TREE) | conditional_block |
filters.rs | use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64)... |
fn neighbours(&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
let ok_pixel = |x, y| {
0 <= x && x < self.resolution[0] as i32 &&
... | {
let mut image = Image::fill(self.resolution, Color::new(0.0, 0.0, 0.0));
let mut weights = Matrix::<f64>::fill(self.resolution, 0.0);
for &(sample, radiance) in samples.iter() {
for pixel in self.neighbours(sample.pixel) {
let diff = ScreenPoint::from(pixel) - from_... | identifier_body |
filters.rs | use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64)... |
}
}
result
}
}
| {
result.push([x as u32, y as u32]);
} | conditional_block |
filters.rs | use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64)... | (&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
let ok_pixel = |x, y| {
0 <= x && x < self.resolution[0] as i32 &&
0 <= y &... | neighbours | identifier_name |
filters.rs | use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64)... | image[i] = image[i] / weight;
}
}
image
}
fn neighbours(&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
... | if weight != 0.0 { | random_line_split |
DropDownSelect.tsx | /*
* 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/.
*/
import * as React from 'react';
import styled, { css } from 'react-emotion';
import { cloneDeep } from 'lodash... |
public render() {
const customStyles = this.props.styles || {};
return (
<Container style={customStyles.container} onKeyDown={this.onKeyDown}>
<Selected style={customStyles.selected} onClick={() => this.setState({ dropDownOpen: !this.state.dropDownOpen })}>
<SelectedItem style={cust... | {
super(props);
const items = cloneDeep(this.props.items);
this.state = {
items,
selectedItem: this.props.selectedItem || items[0],
keyboardIndex: -1,
dropDownOpen: false,
};
} | identifier_body |
DropDownSelect.tsx | /*
* 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/.
*/
import * as React from 'react';
import styled, { css } from 'react-emotion';
import { cloneDeep } from 'lodash... | (props: DropDownSelectProps<ItemType, DataType>) {
super(props);
const items = cloneDeep(this.props.items);
this.state = {
items,
selectedItem: this.props.selectedItem || items[0],
keyboardIndex: -1,
dropDownOpen: false,
};
}
public render() {
const customStyles = this.p... | constructor | identifier_name |
DropDownSelect.tsx | /*
* 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/.
*/
import * as React from 'react';
import styled, { css } from 'react-emotion';
import { cloneDeep } from 'lodash... | }
`;
const SelectedItem = styled('div')`
flex: 1;
`;
export interface DropDownSelectProps<ItemType, DataType extends {}> {
items: ItemType[];
selectedItem?: ItemType;
renderListItem: (item: ItemType, renderType: DataType) => JSX.Element;
renderSelectedItem: (item: ItemType, renderData: DataType) => JSX.El... | background-color: rgba(0, 0, 0, 0.1);
&:hover {
background-color: rgba(0, 0, 0, 0.2); | random_line_split |
main.rs | extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> |
static HTTP_ADDR: &'static str = "localhost:4242";
fn main() {
let mut size: usize = 20;
let mut reverse: bool = false;
let mut server_mode: bool = false;
let mut skin = "███".to_string();
let padding = vec![" ", " ", "", " ", " ", " ", " ", " "];
{
// this block limits scop... | {
Ok(Response::with((iron::status::Ok, "Rust server")))
} | identifier_body |
main.rs | extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Rust server")))
}
static HTTP_ADDR: &'static str = "localhost:4242";
fn main() {
let mut size: usi... | // this block limits scope of borrows by ap.refer() method
let mut ap = ArgumentParser::new();
ap.set_description("Print a beautiful millipede (written in rust)");
ap.refer(&mut size)
.add_option(&["-w", "--width"], Store, "millipede width");
ap.refer(&mut skin)
... |
{ | random_line_split |
main.rs | extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Rust server")))
}
static HTTP_ADDR: &'static str = "localhost:4242";
fn | () {
let mut size: usize = 20;
let mut reverse: bool = false;
let mut server_mode: bool = false;
let mut skin = "███".to_string();
let padding = vec![" ", " ", "", " ", " ", " ", " ", " "];
{
// this block limits scope of borrows by ap.refer() method
let mut ap = Argume... | main | identifier_name |
main.rs | extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Rust server")))
}
static HTTP_ADDR: &'static str = "localhost:4242";
fn main() {
let mut size: usi... | t i: usize = size;
while i > 0 {
println!("{}╔═({})═╗", padding[i % 8], skin);
i = i - 1;
}
println!(" ╔⊙ ⊙╗");
}
}
| let mut i: usize = 0;
println!(" ╚⊙ ⊙╝");
while i < size {
println!("{}╚═({})═╝", padding[i % 8], skin);
i = i + 1;
}
} else {
let mu | conditional_block |
pipe.rs | use gfx;
use gfx_phase;
use gfx_scene;
use std::cmp::Ordering;
/// Custom ordering function to draw opaque objects first in a
/// front-to-back order, and transparent objects on top in a
/// back-to-front order.
pub fn | <S: PartialOrd, R: gfx::Resources>(
a: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>,
b: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>)
-> Ordering {
use ::Transparency::*;
match (a.kernel.transparency, b.kernel.transparency) {
(Blen... | order | identifier_name |
pipe.rs | use gfx;
use gfx_phase; | use gfx_scene;
use std::cmp::Ordering;
/// Custom ordering function to draw opaque objects first in a
/// front-to-back order, and transparent objects on top in a
/// back-to-front order.
pub fn order<S: PartialOrd, R: gfx::Resources>(
a: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>,
... | random_line_split | |
pipe.rs | use gfx;
use gfx_phase;
use gfx_scene;
use std::cmp::Ordering;
/// Custom ordering function to draw opaque objects first in a
/// front-to-back order, and transparent objects on top in a
/// back-to-front order.
pub fn order<S: PartialOrd, R: gfx::Resources>(
a: &gfx_phase::Object<S, super::Kernel, super... |
}
| {
// prepare
self.phase.technique.update(stream);
// clear
if let Some(color) = self.background {
stream.clear(gfx::ClearData {
color: color,
depth: 1.0,
stencil: 0,
});
}
// draw
scene.draw(&... | identifier_body |
hierarchy-utils.js | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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 ... |
export const reduceToSelectedNodesOnly = (nodes, selectedNodeIds = []) => {
const byId = _.keyBy(nodes, d => d.id);
const selectedNodesOnly = _
.chain(selectedNodeIds)
.map(nId => byId[nId])
.compact()
.value();
const selectedWithParents = _
.chain(selectedNodesOn... | {
// only give back root element/s
return _.reject(populateParents(nodes, parentsAsRefs), n => n.parent);
} | identifier_body |
hierarchy-utils.js | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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 ... |
return result;
}
| {
result.push(ptr);
ptr = getParentFn(ptr);
} | conditional_block |
hierarchy-utils.js | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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 ... | }
/**
* The given `termStr` will be tokenised and
* all nodes (given in `searchNodes`) which contain all tokens
* will be returned (de-duped).
*
* Use `prepareSearchNodes` to prepare the search nodes.
* @param termStr
* @param searchNodes
*/
export function doSearch(termStr = "", searchNodes = []) {
const... | nodePath
};
}); | random_line_split |
hierarchy-utils.js | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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 ... | (node, acc = []) {
_.forEach(node.children || [], child => {
acc.push(child);
flattenChildren(child, acc);
});
return acc;
}
/**
The wix tree widget does deep comparisons.
Having parents as refs therefore blows the callstack.
This method will replace refs with id's.
*/
export function ... | flattenChildren | identifier_name |
panel.js | ("sdk/deprecated/sync-worker");
const { Disposable } = require("sdk/core/disposable");
const { WeakReference } = require('sdk/core/reference');
const { contract: loaderContract } = require("sdk/content/loader");
const { contract } = require("sdk/util/contract");
const { on, off, emit, setListeners } = require("sdk/even... | () {
return modelFor(this).height;
},
set height(value) {
return this.resize(this.width, value);
},
/* Public API: Panel.focus */
get focus() {
return modelFor(this).focus;
},
/* Public API: Panel.position */
get position() {
return modelFor(this).position;
},
get contentURL() {
... | height | identifier_name |
panel.js | sdk/deprecated/sync-worker");
const { Disposable } = require("sdk/core/disposable");
const { WeakReference } = require('sdk/core/reference');
const { contract: loaderContract } = require("sdk/content/loader");
const { contract } = require("sdk/util/contract");
const { on, off, emit, setListeners } = require("sdk/event/... | ,
/* Public API: Panel.isShowing */
get isShowing() {
return !isDisposed(this) && domPanel.isOpen(viewFor(this));
},
/* Public API: Panel.show */
show: function show(options={}, anchor) {
if (options instanceof Ci.nsIDOMElement) {
[anchor, options] = [options, null];
}
if (anchor inst... | {
let model = modelFor(this);
model.contentURL = panelContract({ contentURL: value }).contentURL;
domPanel.setURL(viewFor(this), model.contentURL);
// Detach worker so that messages send will be queued until it's
// reatached once panel content is ready.
workerFor(this).detach();
} | identifier_body |
panel.js | const { events } = require("./panel/events");
const systemEvents = require("sdk/system/events");
const { filter, pipe, stripListeners } = require("sdk/event/utils");
const { getNodeView, getActiveView } = require("sdk/view/core");
const { isNil, isObject, isNumber } = require("sdk/lang/type");
const { getAttachEventTyp... | // Panel event emitted when the contents of the panel has been loaded. | random_line_split | |
Game.js | 400;
const INVULNERABLE_AFTER_DAMAGE_COOLDOWN = 2000;
const STARTING_BULLETS = 100;
const STARTING_TIMER = 5000;
export default class extends Phaser.State {
init() { }
preload() {
game.load.audio('bullet', 'assets/audio/SoundEffects/laser.wav');
game.load.audio('explosion', 'assets/audio/SoundEffects/exp... | (wave) {
this.inbetweenWave = false;
if (this.waveNumber > 0) {
this.sfxVictory.play();
}
this.waveNumber++;
this.gameTimer += 20000;
this.player.resetPosition();
this.player.set | startWave | identifier_name |
Game.js | 00;
const INVULNERABLE_AFTER_DAMAGE_COOLDOWN = 2000;
const STARTING_BULLETS = 100;
const STARTING_TIMER = 5000;
export default class extends Phaser.State {
init() { }
preload() {
game.load.audio('bullet', 'assets/audio/SoundEffects/laser.wav');
game.load.audio('explosion', 'assets/audio/SoundEffects/expl... |
return false;
}
startWave(wave) {
this.inbetweenWave = false;
if (this.waveNumber > 0) {
this.sfxVictory.play();
}
this.waveNumber++;
this.gameTimer += 20000;
this.player.resetPosition();
this.player | {
this.inbetweenWave = true;
return true;
} | conditional_block |
Game.js | }
preload() {
game.load.audio('bullet', 'assets/audio/SoundEffects/laser.wav');
game.load.audio('explosion', 'assets/audio/SoundEffects/explosion.wav');
game.load.audio('music', 'assets/audio/Music/Corruption.mp3');
game.load.audio('damage', 'assets/audio/SoundEffects/alarm.wav');
game.load.aud... | pickup.destroy();
}
this.pickups = []; | random_line_split | |
Game.js | 00;
const INVULNERABLE_AFTER_DAMAGE_COOLDOWN = 2000;
const STARTING_BULLETS = 100;
const STARTING_TIMER = 5000;
export default class extends Phaser.State {
init() { }
preload() {
game.load.audio('bullet', 'assets/audio/SoundEffects/laser.wav');
game.load.audio('explosion', 'assets/audio/SoundEffects/expl... |
startWave(wave) {
this.inbetweenWave = false;
if (this.waveNumber > 0) {
this.sfxVictory.play();
}
this.waveNumber++;
this.gameTimer += 20000;
this.player.resetPosition();
this.player | {
if (this.inbetweenWave === false && this.asteroidsGroup.countLiving() === 0) {
this.inbetweenWave = true;
return true;
}
return false;
} | identifier_body |
node-tests.ts | }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.wr... |
////////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html
////////////////////////////////////////////////////
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
var blah = ctx.context;
/////////////////////... | {
var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
var cipherBuffers:Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherB... | identifier_body |
node-tests.ts | }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.wr... | () {
var r = fs.createReadStream('file.txt');
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
r.close();
}
////////////////////////////////////////////////////
/// Crypto tests : http://nodejs.org/api/crypto.html
///////////////////////////////////////////... | stream_readable_pipe_test | identifier_name |
node-tests.ts | }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.wr... |
});
///////////////////////////////////////////////////////
/// Buffer tests : https://nodejs.org/api/buffer.html
///////////////////////////////////////////////////////
function bufferTests() {
var utf8Buffer = new Buffer('test');
var base64Buffer = new Buffer('','base64');
var octets: Uint8Array = nul... | {
errno = err.errno;
} | conditional_block |
node-tests.ts | "; }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.... | pathname: 'search',
query: { q: "you're a lizard, gary" }
});
var helloUrl = url.parse('http://example.com/?hello=world', true)
assert.equal(helloUrl.query.hello, 'world');
// Old and new util.inspect APIs
util.inspect(["This is nice"], false, 5);
util.inspect(["This is nice"], { colors: true, depth: 5, cust... | random_line_split | |
lib.rs | (url: ServoUrl,
creator_pipeline_id: Option<PipelineId>,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<ServoUrl>)
-> LoadData {
LoadData {
url: url,
creator_pipeline_id: creator_pipeline_id,
method: M... | new | identifier_name | |
lib.rs | BrowsingContextId,
/// Id of the top-level browsing context associated with this pipeline.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// Network request data which will be initiated by the script thread.
pub load_data: LoadData,
/// Information about the initial window size.
... | DispatchIFrameLoadEvent {
/// The frame that has been marked as loaded.
target: BrowsingContextId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId,
/// The pipeline that has completed loading.
child: PipelineId,
},
/// Ca... | /// Cause a `load` event to be dispatched at the appropriate iframe element. | random_line_split |
NamespaceItemMenu.js | import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import NoteAdd from 'material-ui/svg-icons/action/note-add';
import Delete from 'material-ui/svg-icons/action/delete';
import IconMenu from 'material-ui/IconMenu';
import ShowChart from 'mate... | extends Component {
createKey(name) {
this.props.newKey(name);
}
deleteNamespace(name) {
this.props.deleteNamespace(name);
}
render() {
const { name, ...props } = this.props;
return (
<IconMenu disableAutoFocus
iconButtonElement={... | NamespaceItemMenu | identifier_name |
NamespaceItemMenu.js | import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux'; | import NoteAdd from 'material-ui/svg-icons/action/note-add';
import Delete from 'material-ui/svg-icons/action/delete';
import IconMenu from 'material-ui/IconMenu';
import ShowChart from 'material-ui/svg-icons/editor/show-chart';
import MenuItem from 'material-ui/MenuItem';
import History from 'material-ui/svg-icons/act... | import { Link } from 'react-router'; | random_line_split |
NamespaceItemMenu.js | import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import NoteAdd from 'material-ui/svg-icons/action/note-add';
import Delete from 'material-ui/svg-icons/action/delete';
import IconMenu from 'material-ui/IconMenu';
import ShowChart from 'mate... | Delete
</MenuItem>
</IconMenu>
);
}
}
NamespaceItemMenu.propTypes = {
name: PropTypes.string,
deleteNamespace: PropTypes.func,
newKey: PropTypes.func,
};
const mapDispatchToProps = (dispatch) => ({
deleteNamespace(namespace) {
... | {
const { name, ...props } = this.props;
return (
<IconMenu disableAutoFocus
iconButtonElement={ <IconButtonElement /> }
anchorOrigin={ anchorOrigin }
targetOrigin={ targetOrigin }
{...props}
>
... | identifier_body |
test_googlenet.py | from skimage.data import coffee, camera
from sklearn_theano.feature_extraction.caffe.googlenet import (
GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os
co = coffee().astype(np.float32)
ca = camera().astype(np.float32)[:, :, np.newaxis] * np.ones((1, 1, 3),
... | ():
"""smoke test for googlenet classifier"""
if os.environ.get('CI', None) is not None:
raise SkipTest("Skipping heavy data loading on CI")
c = GoogLeNetClassifier()
c.predict(co)
c.predict(ca)
| test_googlenet_classifier | identifier_name |
test_googlenet.py | from skimage.data import coffee, camera
from sklearn_theano.feature_extraction.caffe.googlenet import (
GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os
co = coffee().astype(np.float32) |
def test_googlenet_transformer():
"""smoke test for googlenet transformer"""
if os.environ.get('CI', None) is not None:
raise SkipTest("Skipping heavy data loading on CI")
t = GoogLeNetTransformer()
t.transform(co)
t.transform(ca)
def test_googlenet_classifier():
"""smoke test for go... | ca = camera().astype(np.float32)[:, :, np.newaxis] * np.ones((1, 1, 3),
dtype='float32')
| random_line_split |
test_googlenet.py | from skimage.data import coffee, camera
from sklearn_theano.feature_extraction.caffe.googlenet import (
GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os
co = coffee().astype(np.float32)
ca = camera().astype(np.float32)[:, :, np.newaxis] * np.ones((1, 1, 3),
... | """smoke test for googlenet classifier"""
if os.environ.get('CI', None) is not None:
raise SkipTest("Skipping heavy data loading on CI")
c = GoogLeNetClassifier()
c.predict(co)
c.predict(ca) | identifier_body | |
test_googlenet.py | from skimage.data import coffee, camera
from sklearn_theano.feature_extraction.caffe.googlenet import (
GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os
co = coffee().astype(np.float32)
ca = camera().astype(np.float32)[:, :, np.newaxis] * np.ones((1, 1, 3),
... |
c = GoogLeNetClassifier()
c.predict(co)
c.predict(ca)
| raise SkipTest("Skipping heavy data loading on CI") | conditional_block |
0070-check_recommended_services.ts | #!/bin/bash
export BASH_TAP_ROOT=$(dirname $0)
. $(dirname $0)/bash-tap-bootstrap
plan tests 6
MAX_WAIT=300
tmpcount=$MAX_WAIT
# Service enabled and started
for srv in \
obsdodup \
obssigner \
obsdeltastore
do
STATE=` systemctl is-enabled $srv\.service 2>/dev/null`
is "$STATE" "enabled" "Checking recommended ... | sleep 1
done
is "$ACTIVE" "active" "Checking recommended service '$srv' status"
done | ACTIVE=`systemctl is-active $srv\.service`
if [[ $tmpcount -le 0 ]];then
ACTIVE='timeout'
break
fi | random_line_split |
items.ts | import { runCommand } from '../../util/command';
import { listArgumentsDefault } from '../util';
import { itemOutputFormat } from './util';
export = {
command: 'items <connection>',
desc: 'Traverse connection items',
builder: yargs => yargs.options({
...listArgumentsDefault,
parent: {
desc: 'Parent ID',
t... |
const items = await client.connectionItems.list(argv.connection, params);
output.writeTable(items, itemOutputFormat);
});
}
}; | headers: argv.connectAs && {
'X-Connect-As': argv.connectAs
} || undefined
}; | random_line_split |
test_geopackage.py |
import logging
import os
import os.path
import shutil
import sys
import tempfile
import unittest
import pytest
import fiona
from fiona.collection import supported_drivers
from fiona.errors import FionaValueError, DriverError, SchemaError, CRSError
from fiona.ogrext import calc_gdal_version_num, get_gdal_version_num
... |
@pytest.mark.skipif(not os.path.exists('tests/data/coutwildrnp.gpkg'),
reason="Requires geopackage fixture")
def test_gpkg(self):
schema = {'geometry': 'Point',
'properties': [('title', 'str')]}
crs = {
'a': 6370997,
'lon_0': -1... | shutil.rmtree(self.tempdir) | identifier_body |
test_geopackage.py | import logging
import os
import os.path
import shutil
import sys
import tempfile
import unittest
import pytest |
import fiona
from fiona.collection import supported_drivers
from fiona.errors import FionaValueError, DriverError, SchemaError, CRSError
from fiona.ogrext import calc_gdal_version_num, get_gdal_version_num
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class ReadingTest(unittest.TestCase):
def se... | random_line_split | |
test_geopackage.py |
import logging
import os
import os.path
import shutil
import sys
import tempfile
import unittest
import pytest
import fiona
from fiona.collection import supported_drivers
from fiona.errors import FionaValueError, DriverError, SchemaError, CRSError
from fiona.ogrext import calc_gdal_version_num, get_gdal_version_num
... |
class WritingTest(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tempdir)
@pytest.mark.skipif(not os.path.exists('tests/data/coutwildrnp.gpkg'),
reason="Requires geopackage fixture")
def test_gpk... | with fiona.open('tests/data/coutwildrnp.gpkg', 'r', driver="GPKG") as c:
self.assertEquals(len(c), 48) | conditional_block |
test_geopackage.py |
import logging
import os
import os.path
import shutil
import sys
import tempfile
import unittest
import pytest
import fiona
from fiona.collection import supported_drivers
from fiona.errors import FionaValueError, DriverError, SchemaError, CRSError
from fiona.ogrext import calc_gdal_version_num, get_gdal_version_num
... | (self):
pass
@pytest.mark.skipif(not os.path.exists('tests/data/coutwildrnp.gpkg'),
reason="Requires geopackage fixture")
def test_gpkg(self):
if get_gdal_version_num() < calc_gdal_version_num(1, 11, 0):
self.assertRaises(DriverError, fiona.open, 'tests/data/... | tearDown | identifier_name |
chemid.js | 'use strict';
const Q = require("q");
const util = require("util");
const https = require("https");
const http = require("http");
const fs = require("fs");
const xml2js = require("xml2js");
const paths = {
"inchikey" : "inchikey",
"name" : "name/startswith",
"rn" : "rn"
};
function ChemIDDB () {
... |
res.on("data", function( chunk ) {
result += chunk;
});
res.on("end", function( ) {
deferred.resolve( result );
})
});
req.on("error", function(err) {
deferred.reject(err);
})
return deferred.promise;
}
module.exports.query =... | {
deferred.reject( res.statusCode );
} | conditional_block |
chemid.js | 'use strict';
const Q = require("q");
const util = require("util");
const https = require("https");
const http = require("http");
const fs = require("fs");
const xml2js = require("xml2js");
const paths = {
"inchikey" : "inchikey",
"name" : "name/startswith",
"rn" : "rn"
};
function ChemIDDB () |
module.exports.DB = ChemIDDB;
ChemIDDB.prototype.load = function( filename ) {
var parser = new xml2js.Parser();
if (verbose) console.log("loading: ", filename);
fs.readFile(filename, function( err, data ){
parser.parseString(data, function(err, results) {
if(err) {
co... | {
var database = {};
} | identifier_body |
chemid.js | 'use strict';
const Q = require("q");
const util = require("util");
const https = require("https");
const http = require("http");
const fs = require("fs");
const xml2js = require("xml2js");
const paths = {
"inchikey" : "inchikey",
"name" : "name/startswith",
"rn" : "rn"
};
function ChemIDDB () {
... |
res.on("end", function( ) {
deferred.resolve( result );
})
});
req.on("error", function(err) {
deferred.reject(err);
})
return deferred.promise;
}
module.exports.query = query; | res.on("data", function( chunk ) {
result += chunk;
}); | random_line_split |
chemid.js | 'use strict';
const Q = require("q");
const util = require("util");
const https = require("https");
const http = require("http");
const fs = require("fs");
const xml2js = require("xml2js");
const paths = {
"inchikey" : "inchikey",
"name" : "name/startswith",
"rn" : "rn"
};
function | () {
var database = {};
}
module.exports.DB = ChemIDDB;
ChemIDDB.prototype.load = function( filename ) {
var parser = new xml2js.Parser();
if (verbose) console.log("loading: ", filename);
fs.readFile(filename, function( err, data ){
parser.parseString(data, function(err, results) {
... | ChemIDDB | identifier_name |
models.py | import time
from codebox.utils.models import Model, String, Float
from codebox.apps.auth.models import User
class Snippet(Model):
org = String()
user = String()
text = String()
keywords = String(required=False)
lang = String()
created_at = Float(default=time.time)
languages = [
(... | (self):
from codebox.apps.organizations.models import Organization
# Fill our dashboard index
for user in Organization.objects.get(self.org).get_all_members():
Snippet.objects.add_to_index(self.pk, dashboard=user.pk)
def get_user(self):
return User.objects.get(self.u... | post_create | identifier_name |
models.py | import time
from codebox.utils.models import Model, String, Float
from codebox.apps.auth.models import User
class Snippet(Model):
org = String()
user = String()
text = String()
keywords = String(required=False)
lang = String()
created_at = Float(default=time.time)
languages = [
(... |
def get_user(self):
return User.objects.get(self.user) | random_line_split | |
models.py | import time
from codebox.utils.models import Model, String, Float
from codebox.apps.auth.models import User
class Snippet(Model):
org = String()
user = String()
text = String()
keywords = String(required=False)
lang = String()
created_at = Float(default=time.time)
languages = [
(... |
def get_user(self):
return User.objects.get(self.user) | Snippet.objects.add_to_index(self.pk, dashboard=user.pk) | conditional_block |
models.py | import time
from codebox.utils.models import Model, String, Float
from codebox.apps.auth.models import User
class Snippet(Model):
org = String()
user = String()
text = String()
keywords = String(required=False)
lang = String()
created_at = Float(default=time.time)
languages = [
(... |
def get_user(self):
return User.objects.get(self.user) | from codebox.apps.organizations.models import Organization
# Fill our dashboard index
for user in Organization.objects.get(self.org).get_all_members():
Snippet.objects.add_to_index(self.pk, dashboard=user.pk) | identifier_body |
starship.js | "use strict";
/*
starship.js - Prototype for 'Game' object. 'Game' runs the whole show.
Copyright (c) 2013 Robin Norwood <robin.norwood@gmail.com>
This file is part of Starship.
Starship is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License ... |
if (Utils.contains(controller.state.keyspressed, "m")) {
var is_muted = controller.audio.toggle_mute();
if (is_muted) {
controller.entities.audio_indicator = new Indicator(this.canvas.width - 25, this.canvas.height - 25, 'audio_mute');
}
else {
... | {
this.play_next(controller); // FIXME: This causes the game to 'jump' - figure out how to load next track in the background.
} | conditional_block |
starship.js | "use strict";
/*
starship.js - Prototype for 'Game' object. 'Game' runs the whole show.
Copyright (c) 2013 Robin Norwood <robin.norwood@gmail.com>
This file is part of Starship.
Starship is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License ... | loadCallback: function(controller) {
// A short delay to give the various data (especially the music) time to load.
// FIXME: Instead, watch for a ready event on the audio object.
controller.screen.context.save();
controller.screen.context.font = 'bold 50px sans-serif';
cont... | },
| random_line_split |
tag_box.js | /**
* @todo
*/
(function($) {
/**
* @todo
*/
Drupal.behaviors.luggageUTagInput = {
attach: function (context) {
$('body', context).once('luggageUTagInput', function() {
var $inputs = $('.field-type-taxonomy-term-reference input[type="text"]'),
block = false;
$inputs/*.cs... |
});
}
};
})(jQuery); | {
if($(el).find('input').val() != "") {
addTag($(el).parent(),$(el).parent().find('.luggage_ux-tag-input-tag').length, $(el).find('input').val().replace(",",""));
var t = $(el).parent().parent().find('.form-text').val() + ',' + $(el).find('input').val();
$(el).parent().pare... | identifier_body |
tag_box.js | /**
* @todo
*/
(function($) {
/**
* @todo
*/
Drupal.behaviors.luggageUTagInput = {
attach: function (context) {
$('body', context).once('luggageUTagInput', function() {
var $inputs = $('.field-type-taxonomy-term-reference input[type="text"]'),
block = false;
$inputs/*.cs... | (el) {
if($(el).find('input').val() != "") {
addTag($(el).parent(),$(el).parent().find('.luggage_ux-tag-input-tag').length, $(el).find('input').val().replace(",",""));
var t = $(el).parent().parent().find('.form-text').val() + ',' + $(el).find('input').val();
$(el).parent()... | processNewTag | identifier_name |
tag_box.js | /**
* @todo
*/
(function($) {
/**
* @todo
*/
Drupal.behaviors.luggageUTagInput = {
attach: function (context) {
$('body', context).once('luggageUTagInput', function() {
var $inputs = $('.field-type-taxonomy-term-reference input[type="text"]'), | $('.luggage_ux-tag-input-text-wrapper').append('<div class="tags-container"><div class="add-tag"><input type="text" value=""></div></div><div class="term-autocomplete-select" style="display: none"></div>');
$inputs.each(function(i, val) {
var arr = $(this).val().split(",");
for(var i... | block = false;
$inputs/*.css('color', '#fff')*/.wrap('<div class="luggage_ux-tag-input-text-wrapper"></div>'); | random_line_split |
tag_box.js | /**
* @todo
*/
(function($) {
/**
* @todo
*/
Drupal.behaviors.luggageUTagInput = {
attach: function (context) {
$('body', context).once('luggageUTagInput', function() {
var $inputs = $('.field-type-taxonomy-term-reference input[type="text"]'),
block = false;
$inputs/*.cs... | else {
var thiss = this;
var $s = $(this).parent().parent().find('.term-autocomplete-select');
$.get('http://local.dev/ent/taxonomy/autocomplete/field_tags/' + encodeURI($(this).find('input').val()),
function(data) {
//$(thiss).unbind('focusout');
... | {
// Comma pressed, add to tags
processNewTag(this);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.