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 |
|---|---|---|---|---|
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-01 19:47
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class | (migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Broadcast',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, s... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-01 19:47
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
| ('image', models.ImageField(upload_to='')),
],
bases=('broadcast.broadcast',),
),
migrations.CreateModel(
name='TextBroadcast',
fields=[
('broadcast_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.de... | initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Broadcast',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=... | identifier_body |
warm_up_redis.py | from . import manager
def warm_up_redis_func(app=None, db=None, user_model=None, redis_store=None):
not_available = set()
available = set()
cur = db.session.connection().connection.cursor()
cur.execute("""
SELECT taxi.id AS taxi_id, vd.status, vd.added_by FROM taxi
LEFT OUTER JOIN vehicle ON veh... | ():
from flask import current_app
import APITaxi_models as models
from APITaxi.extensions import redis_store
warm_up_redis_func(current_app, models.db, models.User, redis_store)
| warm_up_redis | identifier_name |
warm_up_redis.py | from . import manager
def warm_up_redis_func(app=None, db=None, user_model=None, redis_store=None):
not_available = set()
available = set()
cur = db.session.connection().connection.cursor()
cur.execute("""
SELECT taxi.id AS taxi_id, vd.status, vd.added_by FROM taxi
LEFT OUTER JOIN vehicle ON veh... |
if len(not_available) > 0:
redis_store.zadd(app.config['REDIS_NOT_AVAILABLE'], **{k:0 for k in not_available})
@manager.command
def warm_up_redis():
from flask import current_app
import APITaxi_models as models
from APITaxi.extensions import redis_store
warm_up_redis_func(current_app, mode... | redis_store.zrem(app.config['REDIS_NOT_AVAILABLE'], to_remove) | conditional_block |
warm_up_redis.py | from . import manager
def warm_up_redis_func(app=None, db=None, user_model=None, redis_store=None):
| cursor, keys = redis_store.zscan(app.config['REDIS_NOT_AVAILABLE'], 0)
keys = set([k[0] for k in keys])
while cursor != 0:
to_remove.extend(keys.intersection(available))
not_available.difference_update(keys)
cursor, keys = redis_store.zscan(app.config['REDIS_N... | not_available = set()
available = set()
cur = db.session.connection().connection.cursor()
cur.execute("""
SELECT taxi.id AS taxi_id, vd.status, vd.added_by FROM taxi
LEFT OUTER JOIN vehicle ON vehicle.id = taxi.vehicle_id
LEFT OUTER JOIN vehicle_description AS vd ON vehicle.id = vd.vehicle_id
... | identifier_body |
warm_up_redis.py | from . import manager
def warm_up_redis_func(app=None, db=None, user_model=None, redis_store=None):
not_available = set()
available = set()
cur = db.session.connection().connection.cursor()
cur.execute("""
SELECT taxi.id AS taxi_id, vd.status, vd.added_by FROM taxi
LEFT OUTER JOIN vehicle ON veh... | warm_up_redis_func(current_app, models.db, models.User, redis_store) | random_line_split | |
serialization.ts | 2Array,
int32: Int32Array,
float32: Float32Array,
float64: Float64Array,
}
export const DTYPES = {
Uint8Array: "uint8" as "uint8",
Int8Array: "int8" as "int8",
Uint16Array: "uint16" as "uint16",
Int16Array: "int16" as "int16",
Uint32Array: "uint32" as "uint32",
Int32Array: "int3... |
export function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary_string = atob(base64)
const len = binary_string.length
const bytes = new Uint8Array(len)
for (let i = 0, end = len; i < end; i++) {
bytes[i] = binary_string.charCodeAt(i)
}
return bytes.buffer
}
export interface NDArray {... | {
const bytes = new Uint8Array(buffer)
const chars = Array.from(bytes).map((b) => String.fromCharCode(b))
return btoa(chars.join(""))
} | identifier_body |
serialization.ts | uint8: Uint8Array,
int8: Int8Array,
uint16: Uint16Array,
int16: Int16Array,
uint32: Uint32Array,
int32: Int32Array,
float32: Float32Array,
float64: Float64Array,
}
export const DTYPES = {
Uint8Array: "uint8" as "uint8",
Int8Array: "int8" as "int8",
Uint16Array: "uint16" as ... | import {Arrayable, TypedArray, Data} from "../types"
import {isTypedArray, isArray, isObject} from "./types"
import {is_little_endian} from "./compat"
export const ARRAY_TYPES = { | random_line_split | |
serialization.ts | 2Array,
int32: Int32Array,
float32: Float32Array,
float64: Float64Array,
}
export const DTYPES = {
Uint8Array: "uint8" as "uint8",
Int8Array: "int8" as "int8",
Uint16Array: "uint16" as "uint16",
Int16Array: "int16" as "int16",
Uint32Array: "uint32" as "uint32",
Int32Array: "int3... | (input: NDArray): [TypedArray, Shape] {
const bytes = base64ToArrayBuffer(input.__ndarray__)
const dtype = input.dtype
const shape = input.shape!
let array: TypedArray
if (dtype in ARRAY_TYPES)
array = new (ARRAY_TYPES[dtype])(bytes)
else
throw new Error(`unknown dtype: ${dtype}`)
return [array,... | decode_base64 | identifier_name |
account_bank_statement.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under ... | if context is None:
context = {}
if context.get('block_statement_line_delete', False):
raise UserError(_('Delete operation not allowed. Please go to the associated bank statement in order to delete and/or modify bank statement line.'))
return super(account_bank_statement_line, se... | identifier_body | |
account_bank_statement.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under ... |
ids = []
if name:
ids = self.search(cr, user, [('code', 'ilike', name)] + args, limit=limit)
if not ids:
ids = self.search(cr, user, [('name', operator, name)] + args, limit=limit)
if not ids and len(name.split()) >= 2:
#Separating cod... | args = [] | conditional_block |
account_bank_statement.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under ... | cr.execute("UPDATE account_bank_statement_line \
SET state='confirm' WHERE id in %s ",
(tuple(line_ids),))
bank_statement_line_obj.invalidate_cache(cr, uid, ['state'], line_ids, context=context)
return True
def button_cancel(self, cr,... | super(account_bank_statement, self).button_confirm_bank(cr, uid, ids, context=context)
for st in self.browse(cr, uid, ids, context=context):
if st.line_ids:
line_ids = [l.id for l in st.line_ids] | random_line_split |
account_bank_statement.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under ... | (osv.osv):
_name = 'account.bank.statement.line.global'
_description = 'Batch Payment Info'
_columns = {
'name': fields.char('OBI', required=True, help="Originator to Beneficiary Information"),
'code': fields.char('Code', size=64, required=True),
'parent_id': fields.many2one('accoun... | account_bank_statement_line_global | identifier_name |
filter_collector_wrapper.rs | // # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more... |
}
pub struct FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TPredicate: 'static,
TPredicateValue: FastValue,
{
fast_field_reader: DynamicFastFieldReader<TPredicateValue>,
segment_collector: TSegmentCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<T... | {
self.collector.merge_fruits(segment_fruits)
} | identifier_body |
filter_collector_wrapper.rs | // # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more... | (self) -> <TSegmentCollector as SegmentCollector>::Fruit {
self.segment_collector.harvest()
}
}
| harvest | identifier_name |
filter_collector_wrapper.rs | // # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more... |
}
fn harvest(self) -> <TSegmentCollector as SegmentCollector>::Fruit {
self.segment_collector.harvest()
}
}
| {
self.segment_collector.collect(doc, score)
} | conditional_block |
filter_collector_wrapper.rs | // # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more... | TPredicateValue: FastValue,
{
// That's the type of our result.
// Our standard deviation will be a float.
type Fruit = TCollector::Fruit;
type Child = FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>;
fn for_segment(
&self,
segment_local_id: u32,
... | where
TCollector: Collector + Send + Sync,
TPredicate: 'static + Fn(TPredicateValue) -> bool + Send + Sync + Clone, | random_line_split |
extractConstant_StatementInsertionPosition5.ts | // ==ORIGINAL==
function F0() {
function F1() {
function F2(x = /*[#|*/2 + 1/*|]*/) {
}
}
}
// ==SCOPE::Extract to constant in enclosing scope==
function F0() {
function F1() {
const newLocal = 2 + 1;
function F2(x = /*RENAME*/newLocal) {
}
}
}
... |
}
| {
function F2(x = /*RENAME*/newLocal) {
}
} | identifier_body |
extractConstant_StatementInsertionPosition5.ts | // ==ORIGINAL==
function F0() {
function F1() {
function F2(x = /*[#|*/2 + 1/*|]*/) {
}
}
}
// ==SCOPE::Extract to constant in enclosing scope== |
function F2(x = /*RENAME*/newLocal) {
}
}
}
// ==SCOPE::Extract to constant in function 'F0'==
function F0() {
const newLocal = 2 + 1;
function F1() {
function F2(x = /*RENAME*/newLocal) {
}
}
}
// ==SCOPE::Extract to constant in global scope==
const ... |
function F0() {
function F1() {
const newLocal = 2 + 1; | random_line_split |
extractConstant_StatementInsertionPosition5.ts | // ==ORIGINAL==
function F0() {
function | () {
function F2(x = /*[#|*/2 + 1/*|]*/) {
}
}
}
// ==SCOPE::Extract to constant in enclosing scope==
function F0() {
function F1() {
const newLocal = 2 + 1;
function F2(x = /*RENAME*/newLocal) {
}
}
}
// ==SCOPE::Extract to constant in function 'F... | F1 | identifier_name |
lint-unused-extern-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x: collecs::vec::Vec<uint> = Vec::new();
let y = now();
}
| main | identifier_name |
lint-unused-extern-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[allow(unused_imports)]
use rand::isaac::IsaacRng;
use time::*;
fn main() {
let x: collecs::vec::Vec<uint> = Vec::new();
let y = now();
} |
extern crate time; // no error, the use * marks it as used
| random_line_split |
lint-unused-extern-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x: collecs::vec::Vec<uint> = Vec::new();
let y = now();
} | identifier_body | |
test_telnet.py | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2004-2012 Bastian Kleineidam
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later versi... | (TelnetServerTest):
"""Test telnet: link checking."""
def test_telnet_error (self):
url = u"telnet:"
nurl = self.norm(url)
resultlines = [
u"url %s" % url,
u"cache key None",
u"real url %s" % nurl,
u"error",
]
self.direct(... | TestTelnet | identifier_name |
test_telnet.py | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2004-2012 Bastian Kleineidam
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later versi... | u"real url %s" % url,
u"valid",
]
self.direct(url, resultlines)
| url = self.get_url()
resultlines = [
u"url %s" % url,
u"cache key %s" % url,
u"real url %s" % url,
u"valid",
]
self.direct(url, resultlines)
url = self.get_url(user=u"test")
resultlines = [
u"url %s" % url,
u... | identifier_body |
test_telnet.py | # -*- coding: iso-8859-1 -*- | # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Pub... | # Copyright (C) 2004-2012 Bastian Kleineidam
#
# 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 | random_line_split |
lib.rs | //!
//!
//! ## Basic usage
//!
//! There are two main data structures in this crate that you need to be
//! concerned with: `ANSIString` and `Style`. A `Style` holds stylistic
//! information: colours, whether the text should be bold, or blinking, or
//! whatever. There are also `Colour` variants that represent simple ... | //! the same type. The `Style` struct also has a `Default` implementation if you
//! want to have a style with *nothing* set.
//!
//! use ansi_term::Style;
//! use ansi_term::Colour::Red;
//! Red.normal().paint("yet another red string");
//! Style::default().paint("a completely regular string");
//!
//!... | //! for example, you may have a method that returns `Styles`, and need to
//! represent both the “red bold” and “red, but not bold” styles with values of | random_line_split |
ApplicationMenu.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | ( application ) :
for script in application["scripts"].children() :
application["scripts"].removeChild( script )
return False # remove idle callback
__aboutWindow = None
def about( menu ) :
global __aboutWindow
if __aboutWindow is not None and __aboutWindow() :
window = __aboutWindow()
else :
window = G... | __removeAllScripts | identifier_name |
ApplicationMenu.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... |
# Defer the actual removal of scripts till an idle event - removing all
# the scripts will result in the removal of the window our menu item is
# parented to, which would cause a crash as it's deleted away from over us.
GafferUI.EventLoop.addIdleCallback( IECore.curry( __removeAllScripts, application ) )
def __r... | dialogue = GafferUI.ConfirmationDialogue(
"Discard Unsaved Changes?",
"The following files have unsaved changes : \n\n" +
"\n".join( [ " - " + n for n in unsavedNames ] ) +
"\n\nDo you want to discard the changes and quit?",
confirmLabel = "Discard and Quit"
)
if not dialogue.waitForConfirmation( pa... | conditional_block |
ApplicationMenu.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | scriptWindow = button.ancestor( GafferUI.ScriptWindow )
application = scriptWindow.scriptNode().ancestor( Gaffer.ApplicationRoot )
application.savePreferences()
button.ancestor( type=GafferUI.Window ).setVisible( False ) | identifier_body | |
ApplicationMenu.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... |
def quit( menu ) :
scriptWindow = menu.ancestor( GafferUI.ScriptWindow )
application = scriptWindow.scriptNode().ancestor( Gaffer.ApplicationRoot )
unsavedNames = []
for script in application["scripts"].children() :
if script["unsavedChanges"].getValue() :
f = script["fileName"].getValue()
f = f.rpartiti... | menuDefinition.append( prefix + "/Quit", { "command" : quit, "shortCut" : "Ctrl+Q" } ) | random_line_split |
marker.rs | <T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Sync`. A higher level example
/// of a non-`Sync` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.... | random_line_split | ||
marker.rs | pub trait Unsize<T> {
// Empty.
}
/// Types that can be copied by simply copying bits (i.e. `memcpy`).
///
/// By default, variable bindings have 'move semantics.' In other
/// words:
///
/// ```
/// #[derive(Debug)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `x` has moved into `y`, and so ... | ;
macro_rules! impls{
($t: ident) => (
impl<T:?Sized> Hash for $t<T> {
#[inline]
fn hash<H: Hasher>(&self, _: &mut H) {
}
}
impl<T:?Sized> cmp::PartialEq for $t<T> {
fn eq(&self, _other: &$t<T>) -> bool {
true
}
... | NoCopy | identifier_name |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 Dhaval Patel (dhpatel82 at gmail.com)
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole ... | {
"name": "Human Resources/Documents",
"version": "0.beta",
"author": "DeneroTeam - Didotech",
"category": "Generic Modules/Human Resources",
"description": """A generic module to manage the employee documents with web gallery""",
'depends': [
'hr' ,
],
'data': [
'hr_document... | # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
############################################################################## | random_line_split |
dialog.d.ts | import { VNode } from 'vue'
import { ElementUIComponent } from './component'
export interface DialogSlots {
/** Content of the Dialog */
default: VNode[],
/** Content of the Dialog title */
title: VNode[],
/** Content of the Dialog footer */
footer: VNode[],
[key: string]: VNode[]
}
/** Informs users... | $slots: DialogSlots
} | beforeClose: (done: Function) => void
/** Whether to align the header and footer in center */
center: boolean
| random_line_split |
dialog.d.ts | import { VNode } from 'vue'
import { ElementUIComponent } from './component'
export interface DialogSlots {
/** Content of the Dialog */
default: VNode[],
/** Content of the Dialog title */
title: VNode[],
/** Content of the Dialog footer */
footer: VNode[],
[key: string]: VNode[]
}
/** Informs users... | extends ElementUIComponent {
/** Title of Dialog */
title: string
/** Width of Dialog */
width: string
/** Whether the Dialog takes up full screen */
fullscreen: boolean
/** Value for margin-top of Dialog CSS */
top: string
/** Whether a mask is displayed */
modal: boolean
/** Whether to app... | ElDialog | identifier_name |
lib.rs | // too darn annoying to try and make them do so.
#![cfg_attr(test, allow(dead_code))]
extern crate ascii_canvas;
extern crate atty;
extern crate bit_set;
extern crate diff;
extern crate ena;
extern crate itertools;
extern crate lalrpop_util;
extern crate petgraph;
extern crate regex;
extern crate regex_syntax;
extern ... | // Need this for rusty_peg
#![recursion_limit = "256"]
// I hate this lint.
#![allow(unused_parens)]
// The builtin tests don't cover the CLI and so forth, and it's just | random_line_split | |
RelayCompilerCache.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @provides... |
const value = compute();
fs.writeFileSync(cacheFile, JSON.stringify(value), 'utf8');
return value;
}
}
module.exports = RelayCompilerCache;
| {
return JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
} | conditional_block |
RelayCompilerCache.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
* | * @providesModule RelayCompilerCache
* @flow
* @format
*/
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
/**
* A file backed cache. Values are JSON encoded on disk, so only JSON
* serializable values should be used.
*/
class Re... | random_line_split | |
plugins.js | ';
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
const
$C = require('collection.js');
const
{getThemes} = include('build/ds'),
{getThemedPathChunks, checkDeprecated} = include('build/stylus/ds/helpers'... |
}
path.push(name);
if (id !== undefined) {
path.push(String(id));
}
checkDeprecated(ds, path);
return isThemesIncluded || useCSSVarsInRuntime ?
stylus.utils.coerce($C(cssVariables).get(path)) :
$C(ds).get(path);
});
/**
* Returns the current theme value
* @returns {!string}... | {
id -= 1;
} | conditional_block |
plugins.js | strict';
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
const
$C = require('collection.js');
const
{getThemes} = include('build/ds'),
{getThemedPathChunks, checkDeprecated} = include('build/stylus/ds/h... | __diffVars__ = $C(cssVariables).get(`diff.components.${string}`);
return stylus.utils.coerce({
values,
__diffVars__
}, true);
}
return {};
});
/**
* Returns design system CSS variables with their values
*
* @param {string} [theme]
* @returns {!Object}
*
* @example
... | const | random_line_split |
redis_queues.py | # 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; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; witho... | return queue_lengths
def configure_callback(conf):
"""Receive configuration block"""
global REDIS_HOST, REDIS_PORT, VERBOSE_LOGGING, QUEUE_NAMES
for node in conf.children:
if node.key == 'Host':
REDIS_HOST = node.values[0]
elif node.key == 'Port':
REDIS_PORT = i... | random_line_split | |
redis_queues.py | # 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; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; witho... | (queue_names):
"""Connect to Redis server and request queue lengths.
Return a dictionary from queue names to integers.
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((REDIS_HOST, REDIS_PORT))
log_verbose('Connected to Redis at %s:%s' % (REDIS_H... | fetch_queue_lengths | identifier_name |
redis_queues.py | # 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; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; witho... |
def log_verbose(msg):
if not VERBOSE_LOGGING:
return
collectd.info('redis plugin [verbose]: %s' % msg)
# register callbacks
collectd.register_config(configure_callback)
collectd.register_read(read_callback)
| log_verbose('Read callback called')
queue_lengths = fetch_queue_lengths(QUEUE_NAMES)
if queue_lengths is None:
# An earlier error, reported to collectd by fetch_queue_lengths
return
for queue_name, queue_length in queue_lengths.items():
log_verbose('Sending value: %s=%s' % (queue_n... | identifier_body |
redis_queues.py | # 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; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; witho... |
else:
collectd.warning('redis_queues plugin: Unknown config key: %s.'
% node.key)
log_verbose('Configured with host=%s, port=%s' % (REDIS_HOST, REDIS_PORT))
for queue in QUEUE_NAMES:
log_verbose('Watching queue %s' % queue)
if not QUEUE_NAMES:
... | QUEUE_NAMES = list(node.values) | conditional_block |
ID3_classifier.py | # For each unique value in target.
if (subset and attval == subset) or not subset:
for j in xrange(len(tarset)):
attcnt[j] += 1
# See if matching.
if tarvals[i] == tarset[j]:
tarcnt[j] += 1
# Log com... |
def __eq__(self,other):
return self.name == other
def __ne__(self,other):
return not self.__eq__(other)
def __str__(self):
return self.name
class branch:
# A value branch.
def __init__(self,value,attr,next,parent):
self.value = value
self.attr = attr
... | self.name = name
self.branch = branch
self.parent = parent | identifier_body |
ID3_classifier.py | # For each unique value in target.
if (subset and attval == subset) or not subset:
for j in xrange(len(tarset)):
attcnt[j] += 1
# See if matching.
if tarvals[i] == tarset[j]:
tarcnt[j] += 1
# Log com... | out.append(' %s is %s.' % (self.target,node.name))
def toStringAsLogic(self):
# Gets string of the tree as if-logic.
out = []
self.__nextlevel__(self.root,0,out)
return "".join(out)
def getTargetValue(self,dic,node=None):
# Given a dictionary for a transaction... | out.append('\n%sIf %s is %s, then' \
% ('\t'*lvl,node.name,b.value))
self.__nextlevel__(b.attr,lvl+1,out)
else:
# leaf node | random_line_split |
ID3_classifier.py | For each unique value in target.
if (subset and attval == subset) or not subset:
for j in xrange(len(tarset)):
attcnt[j] += 1
# See if matching.
if tarvals[i] == tarset[j]:
tarcnt[j] += 1
# Log compu... |
return br
# Figure out what subset of the data is
# being investigated for this branch.
attr = self.bestDecision(parent,data)
if not data:
data = range(len(self.classes_target))
if not attr:
# If stopping condition reached:
... | if br:
b = branch(s,None,br,node)
br = b
else:
br = branch(s,None,None,node) | conditional_block |
ID3_classifier.py | For each unique value in target.
if (subset and attval == subset) or not subset:
for j in xrange(len(tarset)):
attcnt[j] += 1
# See if matching.
if tarvals[i] == tarset[j]:
tarcnt[j] += 1
# Log compu... | (fo,data,acc=None):
out = ""
# Get number of transactions.
numtrans = len(data[data.keys()[0]])
# Write headers.
i = 0
for attr in data:
if (i == 0):
out += "%s" % (attr)
else:
out += " %s" % (attr)
i += 1
out += "\n"
# Write values.
fo... | writeFile | identifier_name |
PrismaState.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | self.active = False
raise Exception("No transition to execute, we stop here.")
# Execute picked transition as an initiator
try:
nextState = nextTransition.executeAsInitiator(abstractionLayer)
except Exception, e:
self.active = False
ra... | "" Performs like original State; incorporates features of invalidating a Transitions Symbol (if it is to faulty)
and even the Transition itself, if it has no Symbols left. Also removes itself, if no Transitions are left.
"""
def __init__(self, name=None):
super(PrismaState, self).__init__(name=... | identifier_body |
PrismaState.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | self, transitions):
self.trans = transitions
@property
def transitions(self):
return self.trans
| etTransitions( | identifier_name |
PrismaState.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... |
self.active = True
# Pick the next transition
nextTransition = self.pickNextTransition()
if nextTransition is None:
self.active = False
raise Exception("No transition to execute, we stop here.")
# Execute picked transition as an initiator
try:
... | aise TypeError("AbstractionLayer cannot be None")
| conditional_block |
PrismaState.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | self.active = False
raise Exception("No transition to execute, we stop here.")
# Execute picked transition as an initiator
try:
nextState = nextTransition.executeAsInitiator(abstractionLayer)
except Exception, e:
self.active = False
ra... | if nextTransition is None: | random_line_split |
mod.rs | use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use serde_json::Value;
use sql_types::{FollowPolicy, Url};
pub mod follow_request;
pub mod follower;
pub mod group;
pub mod persona;
use self::follower::Follower;
use schema::base_actors;
use user::UserLike;
#[derive(Debug, AsChangeset)]
#[t... | }
pub fn save_changes(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::update(base_actors::table)
.set(&self)
.get_result(conn)
}
}
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "base_actors"]
pu... | pub fn set_follow_policy(&mut self, follow_policy: FollowPolicy) {
self.follow_policy = follow_policy; | random_line_split |
mod.rs | use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use serde_json::Value;
use sql_types::{FollowPolicy, Url};
pub mod follow_request;
pub mod follower;
pub mod group;
pub mod persona;
use self::follower::Follower;
use schema::base_actors;
use user::UserLike;
#[derive(Debug, AsChangeset)]
#[t... | (
&self,
follows: &BaseActor,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
self.is_following_id(follows.id, conn)
}
pub fn is_following_id(
&self,
follows: i32,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
... | is_following | identifier_name |
mod.rs | use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use serde_json::Value;
use sql_types::{FollowPolicy, Url};
pub mod follow_request;
pub mod follower;
pub mod group;
pub mod persona;
use self::follower::Follower;
use schema::base_actors;
use user::UserLike;
#[derive(Debug, AsChangeset)]
#[t... |
pub fn is_following(
&self,
follows: &BaseActor,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
self.is_following_id(follows.id, conn)
}
pub fn is_following_id(
&self,
follows: i32,
conn: &PgConnection,
) -> Result<bool, die... | {
ModifiedBaseActor {
id: self.id,
display_name: self.display_name,
profile_url: self.profile_url,
inbox_url: self.inbox_url,
outbox_url: self.outbox_url,
follow_policy: self.follow_policy,
original_json: self.original_json,
... | identifier_body |
Stixai.py | import random
class ai:
def __init__(self, actions, responses):
self.IN = actions
self.OUT = responses
def get_act(self, action, valres):
if action in self.IN:
mList = {}
for response in self.OUT:
if self.IN[self.OUT.index(response)] == ... | resp = random.choice(self.OUT)
else:
resp = random.choice(self.OUT)
return resp
def update(ins, outs):
self.IN = ins
self.OUT = outs
def test():
stix = ai(['attack', 'retreat', 'eat', 'attack', 'attack'... | try:
resp = keys[valres]
except:
| random_line_split |
Stixai.py | import random
class ai:
def __init__(self, actions, responses):
self.IN = actions
self.OUT = responses
def get_act(self, action, valres):
if action in self.IN:
mList = {}
for response in self.OUT:
if self.IN[self.OUT.index(response)] == ... |
#test()
| stix = ai(['attack', 'retreat', 'eat', 'attack', 'attack'], ['run', 'cheer', 'share lunch', 'fall', 'run'])
print stix.get_act('attack', 0) | identifier_body |
Stixai.py | import random
class ai:
def __init__(self, actions, responses):
self.IN = actions
self.OUT = responses
def get_act(self, action, valres):
if action in self.IN:
mList = {}
for response in self.OUT:
if self.IN[self.OUT.index(response)] == ... | (ins, outs):
self.IN = ins
self.OUT = outs
def test():
stix = ai(['attack', 'retreat', 'eat', 'attack', 'attack'], ['run', 'cheer', 'share lunch', 'fall', 'run'])
print stix.get_act('attack', 0)
#test()
| update | identifier_name |
Stixai.py | import random
class ai:
def __init__(self, actions, responses):
self.IN = actions
self.OUT = responses
def get_act(self, action, valres):
if action in self.IN:
mList = {}
for response in self.OUT:
if self.IN[self.OUT.index(response)] == ... |
elif response in mList:
mList[response] += 1
print mList
keys = []
vals = []
for v in sorted(mList.values(), reverse = True):
for k in mList.keys():
if mList[k] == v:
... | mList[response] = 1 | conditional_block |
example.py | import pyhwtherm
mytest = pyhwtherm.PyHWTherm(
username="someuser@example.com",
password="mysecretpassword",
deviceid=123456
)
print "login successful: ",mytest.login()
print "Get thermostat data:", mytest.updateStatus()
beforeChange = mytest.status
print "Status: ", beforeChange
mytes... |
print "Logout", mytest.logout() | afterChange = mytest.status
print "heat >>",beforeChange['latestData']['uiData']['HeatSetpoint'],"->",afterChange['latestData']['uiData']['HeatSetpoint']
print "cool >>",beforeChange['latestData']['uiData']['CoolSetpoint'],"->",afterChange['latestData']['uiData']['CoolSetpoint'] | random_line_split |
urls.py | # -*- coding: utf-8 -*-
"""proyectoP4 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.h... | urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}),
) | conditional_block | |
urls.py | # -*- coding: utf-8 -*-
"""proyectoP4 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.h... | urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^Workinout/', include('Workinout.urls')), # ADD THIS NEW TUPLE!media/(?P<path>.*)
]
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': setting... | from django.conf.urls import include, url, patterns
from django.contrib import admin
from Workinout import views
from django.conf import settings
| random_line_split |
fix-shoff.rs | ; radare script to fix elf.shoff
; author: pancake -- nopcode.org @ 2009
;
; Usage example:
; cp /usr/bin/gedit gedit
; # TRASH ELF SHT PTR
; echo wx 99 @ 0x21 | radare -nw gedit
; # OBJDUMP/GDB/LTRACE/... CANNOT DO ANYTHING
; objdump -d gedit # objdump: gedit: File format not recognized
; # FIX ELF SHT PTR
; e... | ? [1:$$+1]
?!.loop:
s +4-$$%4
f nsht
wv nsht @ 0x20
) | random_line_split | |
mucc.py | #!/usr/bin/env python
# Multiple URL Command Client
#
# Combine a list of mv, cp, rm, and put commands on URLs into a single commit
#
# To read the help for this program, type python mucc.py --help
import os
from csvn.core import *
from csvn.repos import RemoteRepository, RepositoryURI
from csvn.auth import User
from... |
if not args:
parser.print_help()
sys.exit(1)
# Initialize variables
root_url = options.root_url
actions = []
svn_cmdline_init("", stderr)
pool = Pool()
action = None
if root_url:
anchor = RepositoryURI(root_url)
else:
anchor = None
states = None
ancestor = None
# A list of the arguments accepted by ... | f = file(options.extra_args)
for line in f:
args.append(line.strip()) | conditional_block |
mucc.py | #!/usr/bin/env python
# Multiple URL Command Client
#
# Combine a list of mv, cp, rm, and put commands on URLs into a single commit
#
# To read the help for this program, type python mucc.py --help
import os
from csvn.core import *
from csvn.repos import RemoteRepository, RepositoryURI
from csvn.auth import User
from... | # so, we should treat copyfrom paths as possible
# repository roots
may_be_root = (len(action) == 2 and action[0] == "cp")
if not may_be_root:
arg = arg.dirname()
if ancestor:
ancestor = ancestor.longest_ancestor(arg)
... | arg = anchor.join(arg)
action.append(arg)
# It's legal to make a copy of the repository root, | random_line_split |
badge.js | import { badge } from "../variables";
/*
| To customize any core styling, copy the part you want to customize to styles/native/app/ so the core styling is overwritten.
==========================================================================
Badge
//== Design Properties
//## Helper classes to change the look and feel of the widget
=======================... | DISCLAIMER:
Do not change this file because it is core styling.
Customizing core files will make updating Atlas much more difficult in the future. | random_line_split |
index.d.ts | // Type definitions for Rappid 1.5
// Project: http://jointjs.com/about-rappid
// Definitions by: Ewout Van Gossum <https://github.com/DenEwout>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jointjs" />
import * as joint from 'jointjs';
import * as... | graph: joint.dia.Graph;
model: Backbone.Collection<joint.dia.Cell>
});
createSelectionBox(cellView: joint.dia.CellView): void;
destroySelectionBox(cellView: joint.dia.CellView): void;
startSelecting(evt: any): void;
cancelSelection(): void;
addHa... | constructor(opt: {
paper: joint.dia.Paper; | random_line_split |
index.d.ts | // Type definitions for Rappid 1.5
// Project: http://jointjs.com/about-rappid
// Definitions by: Ewout Van Gossum <https://github.com/DenEwout>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jointjs" />
import * as joint from 'jointjs';
import * as... | extends Backbone.Model {
paper: joint.dia.Paper;
graph: joint.dia.Graph;
model: Backbone.Collection<joint.dia.Cell>;
constructor(opt: {
paper: joint.dia.Paper;
graph: joint.dia.Graph;
model: Backbone.Collection<joint.dia.Cell>
});
cr... | SelectionView | identifier_name |
workspace.rs | use crate::config::{CrateDependency, CrateDependencyKind, CrateDependencySource};
use crate::database::{DatabaseCache, DatabaseClient, CRATE_DB_FILE_NAME};
use crate::download_db::download_db;
use log::info;
use ritual_common::errors::{bail, Result};
use ritual_common::file_utils::{
create_dir_all, load_json, os_st... | (&self, crate_name: &str) -> PathBuf {
self.path.join("out").join(crate_name)
}
pub fn delete_database_if_exists(&mut self, crate_name: &str) -> Result<()> {
let path = database_path(&self.path, crate_name);
let mut cache = DatabaseCache::global().lock().unwrap();
cache.remove_i... | crate_path | identifier_name |
workspace.rs | use crate::config::{CrateDependency, CrateDependencyKind, CrateDependencySource};
use crate::database::{DatabaseCache, DatabaseClient, CRATE_DB_FILE_NAME};
use crate::download_db::download_db;
use log::info;
use ritual_common::errors::{bail, Result};
use ritual_common::file_utils::{
create_dir_all, load_json, os_st... | .join("db")
.join(format!("{}.json", crate_name))
}
impl Workspace {
pub fn new(path: PathBuf) -> Result<Self> {
if !path.is_dir() {
bail!("No such directory: {}", path.display());
}
let config_path = config_path(&path);
for &dir in &["tmp", "out", "log",... |
fn database_path(workspace_path: &Path, crate_name: &str) -> PathBuf {
workspace_path | random_line_split |
workspace.rs | use crate::config::{CrateDependency, CrateDependencyKind, CrateDependencySource};
use crate::database::{DatabaseCache, DatabaseClient, CRATE_DB_FILE_NAME};
use crate::download_db::download_db;
use log::info;
use ritual_common::errors::{bail, Result};
use ritual_common::file_utils::{
create_dir_all, load_json, os_st... |
let config_path = config_path(&path);
for &dir in &["tmp", "out", "log", "backup", "db", "external_db"] {
create_dir_all(path.join(dir))?;
}
let w = Workspace {
path,
config: if config_path.exists() {
load_json(config_path)?
... | {
bail!("No such directory: {}", path.display());
} | conditional_block |
ToolProtocolHTTP.py | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the r... | http_data = ''
return http_data
def log(self, msg):
""" Sends log message to testserver
returns: Reply to message.
"""
http_data = ''
try:
http_params = urllib.urlencode({"User" : self.username, "Message" : 'LOG'... | self.isConnected = False | random_line_split |
ToolProtocolHTTP.py | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the r... | (self):
if self.isConnected:
http_params = urllib.urlencode({"User" : self.username, "Message" : 'CLOSE', "Parameter" : 'Empty'})
http_data = self.__requestreply(http_params)
def __requestreply(self,message ):
""" One http(s) request/reply.
Message:... | __del__ | identifier_name |
ToolProtocolHTTP.py | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the r... |
else:
http_params = urllib.urlencode({"User" : self.username, "Message" : 'PUT', "Parameter" : 'false'})
except Exception, e:
self.isConnected = False
return ''
try:
http_data = self.__requestreply(http_params)
... | http_params = urllib.urlencode({"User" : self.username, "Message" : 'PUT', "Parameter" : 'true'}) | conditional_block |
ToolProtocolHTTP.py | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the r... | http_response = http_connection.getresponse()
http_data = http_response.read()
http_response.close()
http_connection.close()
except Exception, e:
http_data = ''
return http_data
def init(self, host, path, port, ... | """ One http(s) request/reply.
Message: Message to send string.
Returns: Reply string.
"""
http_data = ''
try:
http_connection = None
if self.protocol == "HTTP":
http_connection = httplib.HTTPConnection(sel... | identifier_body |
trait-bounds-on-structs-and-enums.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
}
fn main() {}
| blah | identifier_name |
trait-bounds-on-structs-and-enums.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | f: Box<T<X>+'static>,
}
impl<X: U> St<X> {
fn blah() {}
}
fn main() {} | }
struct St<X: U> { | random_line_split |
app.component.ts | import { Component, Input } from '@angular/core';
import { Broadcaster } from './broadcast/broadcaster.service';
import { LocalStorageService } from './localstorage/localstorage.service';
import { CountDownTimer } from './timer/timer.service';
@Component({
selector: 'my-app', | templateUrl: './app.component.html',
providers: [Broadcaster, CountDownTimer, LocalStorageService]
})
export class AppComponent {
CLASS = "[AppComponent]";
@Input() properties = {
counter: 5,
interval: 1000,
id: "CountDownTest"
};
constructor(private broadcas... | random_line_split | |
app.component.ts | import { Component, Input } from '@angular/core';
import { Broadcaster } from './broadcast/broadcaster.service';
import { LocalStorageService } from './localstorage/localstorage.service';
import { CountDownTimer } from './timer/timer.service';
@Component({
selector: 'my-app',
templateUrl: './ap... |
}
| {
this.AppTimer.destory();
} | identifier_body |
app.component.ts | import { Component, Input } from '@angular/core';
import { Broadcaster } from './broadcast/broadcaster.service';
import { LocalStorageService } from './localstorage/localstorage.service';
import { CountDownTimer } from './timer/timer.service';
@Component({
selector: 'my-app',
templateUrl: './ap... | () {
console.log(this.CLASS, "recreate with", this.properties);
this.AppTimer.init(this.properties);
}
resume() {
this.AppTimer.start();
}
destory() {
this.AppTimer.destory();
}
}
| recreate | identifier_name |
chain.ts | import {isNumber} from "../core";
import {Metadata, FUNCTION_PARAMS} from "../injector/metadata";
/**
* @since 1.0.0
* @decorator
* @function
* @name Chain
*
* @description
* Chain propagate data from FilterBefore -> BeforeEach -> Before -> Action -> After -> AfterEach -> FilterAfter
*
* @example
* import {C... | }; | random_line_split | |
chain.ts | import {isNumber} from "../core";
import {Metadata, FUNCTION_PARAMS} from "../injector/metadata";
/**
* @since 1.0.0
* @decorator
* @function
* @name Chain
*
* @description
* Chain propagate data from FilterBefore -> BeforeEach -> Before -> Action -> After -> AfterEach -> FilterAfter
*
* @example
* import {C... |
if (!isNumber(paramIndex)) {
throw new TypeError(`@${type} is not allowed ${Metadata.getName(Class, "on class ")} on ${paramIndex}
@${type} is allowed only as parameter type!`);
}
metadata.push({
type,
key,
value: null,
paramIndex
});
Metadata.defineMetadata(Class, FUNCTION_PARAMS, ... | {
metadata = Metadata.getMetadata(Class, FUNCTION_PARAMS);
} | conditional_block |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store... | { }
| AppModule | identifier_name |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store... | BrowserAnimationsModule,
SharedModule,
appRoutes,
AngularFireModule.initializeApp(firebaseConfig),
EffectsModule.run(ArticleEffects),
EffectsModule.run(ArticlesEffects),
EffectsModule.run(PaginationEffects),
StoreModule.provideStore(rootReducer),
S... | EditorComponent,
PageNotFoundComponent
],
imports: [
BrowserModule, | random_line_split |
popover-menu.component.ts | import {Component, Input} from '@angular/core';
import {Document} from 'idai-field-core';
import {PopoverMenu, ResourcesComponent} from '../../resources.component';
import {ViewFacade} from '../../../../core/resources/view/view-facade';
import {RoutingService} from '../../../routing-service';
import {ViewModalLauncher}... |
public getExpandAllGroups = () => this.viewFacade.getExpandAllGroups();
public toggleExpandAllGroups = () => this.viewFacade.toggleExpandAllGroups();
public disableExpandAllGroups = () => !this.getExpandAllGroups() || this.toggleExpandAllGroups();
public isPopoverMenuOpened = (menu?: PopoverMenu): ... | private viewFacade: ViewFacade,
private routingService: RoutingService,
private viewModalLauncher: ViewModalLauncher) {} | random_line_split |
popover-menu.component.ts | import {Component, Input} from '@angular/core';
import {Document} from 'idai-field-core';
import {PopoverMenu, ResourcesComponent} from '../../resources.component';
import {ViewFacade} from '../../../../core/resources/view/view-facade';
import {RoutingService} from '../../../routing-service';
import {ViewModalLauncher}... | (document: FieldDocument) {
await this.routingService.jumpToResource(document);
}
public async openImageViewModal() {
await this.viewModalLauncher.openImageViewModal(this.document)
}
}
| jumpToResource | identifier_name |
pilconvert.py | #!/Users/keith.hamilton/Documents/GitHub/keithhamilton/blackmaas/bin/python
#
# The Python Imaging Library.
# $Id$
#
# convert image files
#
# History:
# 0.1 96-04-20 fl Created
# 0.2 96-10-04 fl Use draft mode when converting images
# 0.3 96-12-30 fl Optimize output (PNG, JPEG)
# 0.4 97-01-18 fl ... | ():
print("PIL Convert 0.5/1998-12-30 -- convert image files")
print("Usage: pilconvert [option] infile outfile")
print()
print("Options:")
print()
print(" -c <format> convert to format (default is given by extension)")
print()
print(" -g convert to greyscale")
print(" ... | usage | identifier_name |
pilconvert.py | #!/Users/keith.hamilton/Documents/GitHub/keithhamilton/blackmaas/bin/python
#
# The Python Imaging Library.
# $Id$
#
# convert image files
#
# History:
# 0.1 96-04-20 fl Created
# 0.2 96-10-04 fl Use draft mode when converting images
# 0.3 96-12-30 fl Optimize output (PNG, JPEG)
# 0.4 97-01-18 fl ... |
elif o == "-r":
convert = "RGB"
elif o == "-o":
options["optimize"] = 1
elif o == "-q":
options["quality"] = string.atoi(a)
if len(argv) != 2:
usage()
try:
im = Image.open(argv[0])
if convert and im.mode != convert:
im.draft(convert, im.size)
im = im.c... | convert = "P" | conditional_block |
pilconvert.py | #!/Users/keith.hamilton/Documents/GitHub/keithhamilton/blackmaas/bin/python
#
# The Python Imaging Library.
# $Id$
#
# convert image files
#
# History:
# 0.1 96-04-20 fl Created
# 0.2 96-10-04 fl Use draft mode when converting images
# 0.3 96-12-30 fl Optimize output (PNG, JPEG)
# 0.4 97-01-18 fl ... |
if len(sys.argv) == 1:
usage()
try:
opt, argv = getopt.getopt(sys.argv[1:], "c:dfgopq:r")
except getopt.error as v:
print(v)
sys.exit(1)
format = None
convert = None
options = { }
for o, a in opt:
if o == "-f":
Image.init()
id = sorted(Image.ID)
print("Supported format... | print("PIL Convert 0.5/1998-12-30 -- convert image files")
print("Usage: pilconvert [option] infile outfile")
print()
print("Options:")
print()
print(" -c <format> convert to format (default is given by extension)")
print()
print(" -g convert to greyscale")
print(" -p ... | identifier_body |
pilconvert.py | #!/Users/keith.hamilton/Documents/GitHub/keithhamilton/blackmaas/bin/python
#
# The Python Imaging Library.
# $Id$
#
# convert image files
#
# History:
# 0.1 96-04-20 fl Created
# 0.2 96-10-04 fl Use draft mode when converting images
# 0.3 96-12-30 fl Optimize output (PNG, JPEG)
# 0.4 97-01-18 fl ... |
from PIL import Image
def usage():
print("PIL Convert 0.5/1998-12-30 -- convert image files")
print("Usage: pilconvert [option] infile outfile")
print()
print("Options:")
print()
print(" -c <format> convert to format (default is given by extension)")
print()
print(" -g con... |
import site
import getopt, string, sys | random_line_split |
MessageConverter.ts | 'use strict';
import { IContext } from './IContextManager';
import { IMessage } from './IMessage';
import { GuidHelper } from './../util/GuidHelper';
import { IDateTime } from './../configuration/IDateTime';
import { IMessageConverter } from './IMessageConverter';
export class MessageConverter implements IMessageConv... |
transformedMessage.payload = JSON.stringify(payload);
return transformedMessage;
}
public createMessageEnvelope<T>(types: string[], indices: object, context: IContext): IMessage<T> {
const message: IMessage<T> = {
id: GuidHelper.newGuid(false),
context: {
id: context.id,
t... | {
transformedMessage.indices = message.indices;
} | conditional_block |
MessageConverter.ts | 'use strict';
import { IContext } from './IContextManager';
import { IMessage } from './IMessage';
import { GuidHelper } from './../util/GuidHelper';
import { IDateTime } from './../configuration/IDateTime';
import { IMessageConverter } from './IMessageConverter';
export class MessageConverter implements IMessageConv... | id: message.id,
ordinal: message.ordinal,
payload: undefined,
types: message.types,
offset: message.offset,
sent: message.sent,
agent: message.agent,
};
// don't include undefined properties, or they won't pass json schema validation
if (message.indices) {
tr... | context: message.context, | random_line_split |
MessageConverter.ts | 'use strict';
import { IContext } from './IContextManager';
import { IMessage } from './IMessage';
import { GuidHelper } from './../util/GuidHelper';
import { IDateTime } from './../configuration/IDateTime';
import { IMessageConverter } from './IMessageConverter';
export class MessageConverter implements IMessageConv... | <T>(types: string[], indices: object, context: IContext): IMessage<T> {
const message: IMessage<T> = {
id: GuidHelper.newGuid(false),
context: {
id: context.id,
type: context.type,
},
ordinal: ++MessageConverter.i,
types,
offset: this.dateTimeService.now.diff(cont... | createMessageEnvelope | identifier_name |
MessageConverter.ts | 'use strict';
import { IContext } from './IContextManager';
import { IMessage } from './IMessage';
import { GuidHelper } from './../util/GuidHelper';
import { IDateTime } from './../configuration/IDateTime';
import { IMessageConverter } from './IMessageConverter';
export class MessageConverter implements IMessageConv... |
public transformMessageForTransit<T>(message: IMessage<T>, data): IMessage<string> {
const payload = {
id: message.id,
payload: data,
ordinal: message.ordinal,
context: message.context,
types: message.types,
agent: message.agent,
offset: message.offset,
};
cons... | {
const message = this.createMessageEnvelope(types, indices, context);
const transformedMessage = this.transformMessageForTransit(message, data);
return transformedMessage;
} | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def | (self, orm):
# Adding model 'LaunchWindow'
db.create_table(u'launch_window_launchwindow', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('description', self.gf('django... | forwards | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'LaunchWindow'
db.create_table(u'launch_window_launchwindo... | 'description': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['launch_window'] | models = {
u'launch_window.launchwindow': {
'Meta': {'object_name': 'LaunchWindow'},
'cron_format': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'LaunchWindow'
|
def backwards(self, orm):
# Deleting model 'LaunchWindow'
db.delete_table(u'launch_window_launchwindow')
models = {
u'launch_window.launchwindow': {
'Meta': {'object_name': 'LaunchWindow'},
'cron_format': ('django.db.models.fields.CharField', [], {'max_length... | db.create_table(u'launch_window_launchwindow', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('description', self.gf('django.db.models.fields.TextField')()),
('cron_format... | identifier_body |
InteractiveCanvas.ts | import { Cursor } from '../diagram/Cursor';
import { DiagramElement } from '../diagram/DiagramElement';
import { Handle } from '../diagram/Handle';
import { AbstractCanvas } from './AbstractCanvas';
const zoomLevels = [1 / 8, 1 / 7, 1 / 6, 1 / 5, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 1, 3 / 2, 2, 3, 4, 5, 6, 7, 8];
export abst... | (x: number, y: number): DiagramElement<any> | null {
const realX = x / this.zoom - this.offsetX;
const realY = y / this.zoom - this.offsetY;
const handleAtPos = this.getHandleByPosition(realX, realY);
if (handleAtPos) return handleAtPos;
return this.diagram && this.diagram.getElementAtPosition(this... | getElementByPosition | identifier_name |
InteractiveCanvas.ts | import { Cursor } from '../diagram/Cursor';
import { DiagramElement } from '../diagram/DiagramElement';
import { Handle } from '../diagram/Handle';
import { AbstractCanvas } from './AbstractCanvas';
const zoomLevels = [1 / 8, 1 / 7, 1 / 6, 1 / 5, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 1, 3 / 2, 2, 3, 4, 5, 6, 7, 8];
export abst... | }
/**
* Renders the canvas
*/
protected render(): this {
super.render();
this.pushCanvasStack();
this._ctx.scale(this.zoom, this.zoom);
this._ctx.translate(this.offsetX, this.offsetY);
this._handles.forEach((handles) => handles.forEach((handle) => handle.render(this)));
this.popCanv... | * Zooms 100%
*/
zoom100(x?: number, y?: number) {
this.zoomCanvas(1, x, y); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.