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 |
|---|---|---|---|---|
views.py | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the ... | # (at your option) any later version.
#
# Archivematica 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 Public License for more details.
#
# You should have received a copy o... | random_line_split | |
views.py | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the ... | (request):
client = MCPClient()
jobs = etree.XML(client.list())
response = ''
if 0 < len(jobs):
for job in jobs:
response += etree.tostring(job)
response = '<MCP>%s</MCP>' % response
return HttpResponse(response, mimetype = 'text/xml')
| list | identifier_name |
views.py | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the ... | client = MCPClient()
jobs = etree.XML(client.list())
response = ''
if 0 < len(jobs):
for job in jobs:
response += etree.tostring(job)
response = '<MCP>%s</MCP>' % response
return HttpResponse(response, mimetype = 'text/xml') | identifier_body | |
views.py | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the ... |
return HttpResponse(result, mimetype = 'text/plain')
def list(request):
client = MCPClient()
jobs = etree.XML(client.list())
response = ''
if 0 < len(jobs):
for job in jobs:
response += etree.tostring(job)
response = '<MCP>%s</MCP>' % response
return HttpResponse(respon... | client = MCPClient()
uuid = request.REQUEST.get('uuid', '')
choice = request.REQUEST.get('choice', '')
uid = request.REQUEST.get('uid', '')
result = client.execute(uuid, choice, uid) | conditional_block |
selector_impl.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use properties::GeckoComputedValues;
use selectors::parser::{ParserContext, SelectorImpl};
use style;
use style::e... | "-moz-tree-row" => MozTreeRow,
"-moz-tree-separator" => MozTreeSeparator,
"-moz-tree-cell" => MozTreeCell,
"-moz-tree-indentation" => MozTreeIndentation,
"-moz-tree-line" => MozTreeLine,
"-moz-tree-twisty" => MozTreeTwisty,
"-moz-tree-i... | "-moz-ruby-base" => MozRubyBase,
"-moz-ruby-base-container" => MozRubyBaseContainer,
"-moz-ruby-text" => MozRubyText,
"-moz-ruby-text-container" => MozRubyTextContainer,
"-moz-tree-column" => MozTreeColumn, | random_line_split |
selector_impl.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use properties::GeckoComputedValues;
use selectors::parser::{ParserContext, SelectorImpl};
use style;
use style::e... | () -> Option<&'static Stylesheet> {
None
}
}
| get_quirks_mode_stylesheet | identifier_name |
basic.rs | // Copyright 2013 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 ... | #[cfg(test)]
mod test {
use std::task::TaskOpts;
use basic;
use PoolConfig;
use SchedPool;
fn pool() -> SchedPool {
SchedPool::new(PoolConfig {
threads: 1,
event_loop_factory: basic::event_loop,
})
}
fn run(f: proc():Send) {
let mut pool = p... | }
}
| random_line_split |
basic.rs | // Copyright 2013 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 ... |
}
None => {}
}
}
fn has_idle(&self) -> bool {
self.idle.is_some() && self.idle_active.get_ref().load(atomics::SeqCst)
}
}
impl EventLoop for BasicLoop {
fn run(&mut self) {
// Not exactly efficient, but it gets the job done.
while self.remotes.l... | {
idle.call();
} | conditional_block |
basic.rs | // Copyright 2013 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 ... |
}
#[cfg(test)]
mod test {
use std::task::TaskOpts;
use basic;
use PoolConfig;
use SchedPool;
fn pool() -> SchedPool {
SchedPool::new(PoolConfig {
threads: 1,
event_loop_factory: basic::event_loop,
})
}
fn run(f: proc():Send) {
let mut pool... | {
self.active.store(false, atomics::SeqCst);
} | identifier_body |
basic.rs | // Copyright 2013 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 ... | (&mut self) {
match self.idle {
Some(ref mut idle) => {
if self.idle_active.get_ref().load(atomics::SeqCst) {
idle.call();
}
}
None => {}
}
}
fn has_idle(&self) -> bool {
self.idle.is_some() && self.... | idle | identifier_name |
type.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { AccommodationType} from 'app/accommodation-type/Type.model'
import { Router, ActivatedRoute } from "@angular/router";
import { TypeServiceService } from 'app/accommodation-type/type-service.service'
@Component({
selector: 'app-type',
templateUrl: '... |
this.Name = undefined;
}
} | {
this.typeService.editType(new AccommodationType(this.type.Id, this.Name)).subscribe(
v =>
{
var doc = document.getElementById("successMsg");
doc.innerText = "Accommodation type successfully edited.";
doc.className = "s... | conditional_block |
type.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { AccommodationType} from 'app/accommodation-type/Type.model'
import { Router, ActivatedRoute } from "@angular/router";
import { TypeServiceService } from 'app/accommodation-type/type-service.service'
@Component({
selector: 'app-type',
templateUrl: '... | ()
{
if(this.Name == undefined || this.Name == "")
{
var doc = document.getElementById("errorMsg");
doc.innerText = "Some required fields are empty.";
doc.className = "show";
setTimeout(function(){ doc.className = doc.className.replace("show", ""); }, 3000);
... | onSubmit | identifier_name |
type.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { AccommodationType} from 'app/accommodation-type/Type.model'
import { Router, ActivatedRoute } from "@angular/router";
import { TypeServiceService } from 'app/accommodation-type/type-service.service'
@Component({
selector: 'app-type',
templateUrl: '... | {
this.type = (c as AccommodationType);
this.Name = this.type.Name;
console.log(this.type.Name);
}, error => console.log(error));
}
onSubmit()
{
if(this.Name == undefined || this.Name == "")
{
var doc = document.getElementById("errorMsg");
doc.innerText... | random_line_split | |
SchedulingComponent.py | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... | (SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super... | SchedulingComponent | identifier_name |
SchedulingComponent.py | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... |
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - event... | if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause() | random_line_split |
SchedulingComponent.py | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... |
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.hea... | self.signalEvent() | conditional_block |
SchedulingComponent.py | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... |
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(s... | """
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["... | identifier_body |
test.py | us.paragraph import Paragraph
from reportlab.platypus.frames import Frame
from reportlab.platypus.flowables import XBox, KeepTogether
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.barcode import getCodes, getCodeNames, createBarcodeDrawing, createBarcodeImageInMemory
def run():
styles = get... | from reportlab.graphics.barcode import createBarcodeDrawing
story.append(Paragraph('EAN13', styleN))
bcd = createBarcodeDrawing('EAN13', value='123456789012')
story.append(bcd)
story.append(Paragraph('EAN8', styleN))
bcd = createBarcodeDrawing('EAN8', value='1234567')
story.append(bcd)
s... | story.append(USPS_4State('01234567094987654321','01234567891'))
| random_line_split |
test.py | us.paragraph import Paragraph
from reportlab.platypus.frames import Frame
from reportlab.platypus.flowables import XBox, KeepTogether
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.barcode import getCodes, getCodeNames, createBarcodeDrawing, createBarcodeImageInMemory
def run():
styles = get... |
if height: options['height'] = height[0]
if isoScale: options['isoScale'] = isoScale[0]
scales = [x[8:].split(',') for x in sys.argv if x.startswith('--scale=')]
scales = map(float,scales and flatten(scales) or [1])
scales = map(float,scales and flatten(scales) or [1])
for scale in scales:
... | options['width'] = width[0] | conditional_block |
test.py | styleN))
story.append(Codabar("A012345B", barWidth = inch*0.02))
story.append(Paragraph('Code 11', styleN))
story.append(Code11("01234545634563"))
story.append(Paragraph('Code 39', styleN))
story.append(Standard39("A012345B%R"))
story.append(Paragraph('Extended Code 39', styleN))
story.appe... | f = open(name,'wb')
f.write(memory)
f.close() | identifier_body | |
test.py | us.paragraph import Paragraph
from reportlab.platypus.frames import Frame
from reportlab.platypus.flowables import XBox, KeepTogether
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.barcode import getCodes, getCodeNames, createBarcodeDrawing, createBarcodeImageInMemory
def run():
styles = get... | (fileName="test_full.pdf"):
"""Creates large-ish test document with a variety of parameters"""
story = []
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
styleH2 = styles['Heading2']
story = []
story.append(Paragraph('ReportLab Barcode Test Suite -... | fullTest | identifier_name |
objects.py | #
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), ... |
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists'... | return self.enum_cls._fields[value] | identifier_body |
objects.py | #
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), ... | (ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
| PlaylistItemCollection | identifier_name |
objects.py | #
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), ... | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# T... | random_line_split | |
objects.py | #
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), ... |
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(... | return field | conditional_block |
inventory_work_unit.py | # =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sour... |
host_id = inventory_job.host_id
host = db_session.query(Host).filter(Host.id == host_id).first()
if host is None:
logger.error('Unable to retrieve host: %s' % host_id)
ctx = InventoryContext(db_session, host, inventory_job)
handler_class = ... | logger.error('Unable to retrieve inventory job: %s' % self.job_id)
return | conditional_block |
inventory_work_unit.py | # =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sour... | host_id = inventory_job.host_id
host = db_session.query(Host).filter(Host.id == host_id).first()
if host is None:
logger.error('Unable to retrieve host: %s' % host_id)
ctx = InventoryContext(db_session, host, inventory_job)
handler_class = ge... | random_line_split | |
inventory_work_unit.py | # =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sour... |
def get_unique_key(self):
return self.host_id
def start(self, db_session, logger, process_name):
host = None
inventory_job = None
try:
inventory_job = db_session.query(InventoryJob).filter(InventoryJob.id == self.job_id).first()
if inventory_job is Non... | WorkUnit.__init__(self)
self.host_id = host_id
self.job_id = job_id | identifier_body |
inventory_work_unit.py | # =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sour... | (self, logger, host):
logger.exception('InventoryManager hit exception - hostname = %s, inventory job = %s',
host.hostname if host is not None else 'Unknown', self.job_id)
def archive_inventory_job(self, db_session, inventory_job, job_status, trace=None):
inventory_job.set... | log_exception | identifier_name |
DB.py | from os import environ
import logging
import rethinkdb as r
from rethinkdb.errors import RqlDriverError, ReqlError
_MCDB = "materialscommons"
_MCDB_HOST = environ.get('MCDB_HOST') or 'localhost'
probe = environ.get('MCDB_PORT')
if not probe:
print("Unable to run without a setting for MCDB_PORT")
exit(-1)
_MCDB... |
def connection(self):
if not self.conn:
self.set_connection()
ret_value = None
if self.conn:
ret_value = self.conn
return ret_value
@staticmethod
def interface():
return r
def close_connection(self):
try:
if self.con... | try:
if not self.conn:
self.conn = r.connect(host=_MCDB_HOST, port=_MCDB_PORT, db=_MCDB)
except RqlDriverError as excp:
self.conn = None
message = "Database connection could not be established: host, port, db = " + \
_MCDB_HOST + ", " + s... | identifier_body |
DB.py | from os import environ
import logging
import rethinkdb as r
from rethinkdb.errors import RqlDriverError, ReqlError
_MCDB = "materialscommons"
_MCDB_HOST = environ.get('MCDB_HOST') or 'localhost'
probe = environ.get('MCDB_PORT')
if not probe:
print("Unable to run without a setting for MCDB_PORT")
exit(-1)
_MCDB... | (self):
try:
if self.conn:
self.conn.close()
except ReqlError:
pass
self.conn = None
| close_connection | identifier_name |
DB.py | from os import environ
import logging
import rethinkdb as r
from rethinkdb.errors import RqlDriverError, ReqlError
_MCDB = "materialscommons"
_MCDB_HOST = environ.get('MCDB_HOST') or 'localhost'
probe = environ.get('MCDB_PORT')
if not probe:
print("Unable to run without a setting for MCDB_PORT")
exit(-1)
_MCDB... | def set_connection(self):
try:
if not self.conn:
self.conn = r.connect(host=_MCDB_HOST, port=_MCDB_PORT, db=_MCDB)
except RqlDriverError as excp:
self.conn = None
message = "Database connection could not be established: host, port, db = " + \
... | def __init__(self):
self.log = logging.getLogger(__name__ + "." + self.__class__.__name__)
self.conn = None
| random_line_split |
DB.py | from os import environ
import logging
import rethinkdb as r
from rethinkdb.errors import RqlDriverError, ReqlError
_MCDB = "materialscommons"
_MCDB_HOST = environ.get('MCDB_HOST') or 'localhost'
probe = environ.get('MCDB_PORT')
if not probe:
print("Unable to run without a setting for MCDB_PORT")
exit(-1)
_MCDB... |
ret_value = None
if self.conn:
ret_value = self.conn
return ret_value
@staticmethod
def interface():
return r
def close_connection(self):
try:
if self.conn:
self.conn.close()
except ReqlError:
pass
... | self.set_connection() | conditional_block |
keys.py | NA_in = 4
DA_ex = 3
DA_in = 4
# Keys for synapse models
model = 0
basic_weight = 1
# Keys for parts dictionary
k_outer = 'Outer ID'
k_outer_ids = 'Outer children IDs'
k_inner = 'Inner ID'
k_inner_ids = 'Inner children IDs'
k_name = 'Name'
k_NN = 'NN'
k_NN_inner = 'Inner NN'
k_NN_outer = 'Outer NN'
k_model = '... | # Keys for connection type
GABA = 0
Glu = 1
ACh = 2
NA_ex = 3 | random_line_split | |
arewedone.py | __author__ = 'george'
from baseclass import Plugin
import time
from apscheduler.scheduler import Scheduler
class AreWeDone(Plugin):
def __init__(self, skype):
super(AreWeDone, self).__init__(skype)
self.command = "arewedoneyet"
self.sched = Scheduler()
self.sched.start()
sel... | channel = "#stigrk85/$jvlomax;b43a0c90a2592b9b"
chat = self.skype.Chat(channel)
cur_time = time.localtime()
days_left = 1 - cur_time.tm_mday % 31
time_left = 24 - cur_time.tm_hour + days_left * 24
if cur_time.tm_hour >= 21 or cur_time.tm_hour < 6:
tod = "night... | msg.Chat.SendMessage("You are now done. Please visit http://www.nav.no for more information")
def set_topic(self): | random_line_split |
arewedone.py | __author__ = 'george'
from baseclass import Plugin
import time
from apscheduler.scheduler import Scheduler
class AreWeDone(Plugin):
def __init__(self, skype):
super(AreWeDone, self).__init__(skype)
self.command = "arewedoneyet"
self.sched = Scheduler()
self.sched.start()
sel... |
def set_topic(self):
channel = "#stigrk85/$jvlomax;b43a0c90a2592b9b"
chat = self.skype.Chat(channel)
cur_time = time.localtime()
days_left = 1 - cur_time.tm_mday % 31
time_left = 24 - cur_time.tm_hour + days_left * 24
if cur_time.tm_hour >= 21 or cur_time.tm_hour <... | msg.Chat.SendMessage("You are now done. Please visit http://www.nav.no for more information") | conditional_block |
arewedone.py | __author__ = 'george'
from baseclass import Plugin
import time
from apscheduler.scheduler import Scheduler
class AreWeDone(Plugin):
def __init__(self, skype):
|
def message_received(self, args, status, msg):
cur_time = time.localtime()
if cur_time.tm_mday == 31 or cur_time.tm_mday == 1:
time_left = 1 - cur_time.tm_mday % 31
hours_left = 23 - cur_time.tm_hour
mins_left = 59 - cur_time.tm_min
msg.Chat.SendMessa... | super(AreWeDone, self).__init__(skype)
self.command = "arewedoneyet"
self.sched = Scheduler()
self.sched.start()
self.sched.add_cron_job(self.set_topic, hour="*", minute=2, day_of_week="monun") | identifier_body |
arewedone.py | __author__ = 'george'
from baseclass import Plugin
import time
from apscheduler.scheduler import Scheduler
class AreWeDone(Plugin):
def __init__(self, skype):
super(AreWeDone, self).__init__(skype)
self.command = "arewedoneyet"
self.sched = Scheduler()
self.sched.start()
sel... | (self):
channel = "#stigrk85/$jvlomax;b43a0c90a2592b9b"
chat = self.skype.Chat(channel)
cur_time = time.localtime()
days_left = 1 - cur_time.tm_mday % 31
time_left = 24 - cur_time.tm_hour + days_left * 24
if cur_time.tm_hour >= 21 or cur_time.tm_hour < 6:
tod ... | set_topic | identifier_name |
etcd_error.rs | use hyper;
use std::io;
use std::convert::From;
use rustc_serialize::json;
#[derive(Debug)]
pub enum EtcdError {
Unsuccessful(hyper::status::StatusCode),
HttpError(hyper::error::HttpError),
IOError(io::Error),
DecodingError(json::DecoderError),
JsonParserError(json::ParserError),
}
impl From<hyper::error::H... | (err: json::DecoderError) -> EtcdError {
EtcdError::DecodingError(err)
}
}
impl From<json::ParserError> for EtcdError {
fn from(err: json::ParserError) -> EtcdError {
EtcdError::JsonParserError(err)
}
}
| from | identifier_name |
etcd_error.rs | use hyper;
use std::io;
use std::convert::From;
use rustc_serialize::json;
#[derive(Debug)]
pub enum EtcdError {
Unsuccessful(hyper::status::StatusCode),
HttpError(hyper::error::HttpError),
IOError(io::Error),
DecodingError(json::DecoderError),
JsonParserError(json::ParserError),
}
impl From<hyper::error::H... | }
}
impl From<json::ParserError> for EtcdError {
fn from(err: json::ParserError) -> EtcdError {
EtcdError::JsonParserError(err)
}
} | EtcdError::DecodingError(err) | random_line_split |
etcd_error.rs | use hyper;
use std::io;
use std::convert::From;
use rustc_serialize::json;
#[derive(Debug)]
pub enum EtcdError {
Unsuccessful(hyper::status::StatusCode),
HttpError(hyper::error::HttpError),
IOError(io::Error),
DecodingError(json::DecoderError),
JsonParserError(json::ParserError),
}
impl From<hyper::error::H... |
}
impl From<json::ParserError> for EtcdError {
fn from(err: json::ParserError) -> EtcdError {
EtcdError::JsonParserError(err)
}
}
| {
EtcdError::DecodingError(err)
} | identifier_body |
Storage.ts | import { Document } from './dom/Document';
import { GetOrSet } from '../transfer/Messages';
import { StorageLocation } from '../transfer/TransferrableStorage';
import { TransferrableMutationType } from '../transfer/TransferrableMutation';
import { store } from './strings';
import { transfer } from './MutationTransfer';... | ,
});
define(storage, 'getItem', {
value(key: string): string | null {
const value = this[key];
return value ? value : null;
},
});
define(storage, 'setItem', {
value(key: string, value: string): void {
const stringValue = String(value);
this[key] = stringValue;
transf... | {
const keys = Object.keys(this);
return n >= 0 && n < keys.length ? keys[n] : null;
} | identifier_body |
Storage.ts | import { Document } from './dom/Document';
import { GetOrSet } from '../transfer/Messages';
import { StorageLocation } from '../transfer/TransferrableStorage';
import { TransferrableMutationType } from '../transfer/TransferrableMutation';
import { store } from './strings';
import { transfer } from './MutationTransfer';... | },
});
define(storage, 'clear', {
value(): void {
Object.keys(this).forEach((key) => {
delete this[key];
});
transfer(document, [
TransferrableMutationType.STORAGE,
GetOrSet.SET,
location,
0, // key == 0 represents all keys.
0, // value == 0... | location,
store(key) + 1,
0, // value == 0 represents deletion.
]); | random_line_split |
Storage.ts | import { Document } from './dom/Document';
import { GetOrSet } from '../transfer/Messages';
import { StorageLocation } from '../transfer/TransferrableStorage';
import { TransferrableMutationType } from '../transfer/TransferrableMutation';
import { store } from './strings';
import { transfer } from './MutationTransfer';... | (n: number) {
const keys = Object.keys(this);
return n >= 0 && n < keys.length ? keys[n] : null;
},
});
define(storage, 'getItem', {
value(key: string): string | null {
const value = this[key];
return value ? value : null;
},
});
define(storage, 'setItem', {
value(key: st... | value | identifier_name |
tomConga.js | import VCO, { SINE, PINK_NOISE } from "synth/basics/vco";
import PulseTrigger from "synth/basics/pulseTrigger";
import VCF, { LOWPASS } from "synth/basics/vcf";
import VCA from "synth/basics/vca";
import ADGenerator, { LINEAR } from "synth/basics/ADGenerator";
import { equalPower } from "helpers";
// 0 = conga, 1 = to... |
click.connect(outputVCA);
// modulation routing
oscEnv.connect(oscVCA.amplitude);
noiseEnv.connect(noiseVCA.amplitude);
// output routing
outputVCA.connect(destination);
// envelope/oscillator triggering
osc.start(time);
noiseOsc.start(time);
click.trigger(time, audioCtx);
... | {
// only the toms get noise
noiseOsc.connect(noiseVCF);
noiseVCF.connect(noiseVCA);
noiseVCA.connect(outputVCA);
} | conditional_block |
tomConga.js | import VCO, { SINE, PINK_NOISE } from "synth/basics/vco";
import PulseTrigger from "synth/basics/pulseTrigger";
import VCF, { LOWPASS } from "synth/basics/vcf";
import VCA from "synth/basics/vca";
import ADGenerator, { LINEAR } from "synth/basics/ADGenerator";
import { equalPower } from "helpers";
// 0 = conga, 1 = to... | click.trigger(time, audioCtx);
oscEnv.trigger(time);
noiseEnv.trigger(time);
// cleanup
window.setTimeout(() => {
osc.stop();
noiseOsc.stop();
outputVCA.disconnect();
}, time - audioCtx.currentTime + 1000);
return outputVCA;
};
} | noiseOsc.start(time); | random_line_split |
read-modules.js | /* global requirejs, require */
/*jslint node: true */
'use strict';
import Ember from 'ember';
import _keys from 'lodash/object/keys';
/*
This function looks through all files that have been loaded by Ember CLI and
finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports
a hash cont... |
let data = module['default'];
modulesMap[moduleType][moduleKey] = data;
});
return modulesMap;
}
| { throw new Error(moduleName + ' must export a ' + moduleType); } | conditional_block |
read-modules.js | /* global requirejs, require */
/*jslint node: true */
'use strict';
import Ember from 'ember';
import _keys from 'lodash/object/keys';
/*
This function looks through all files that have been loaded by Ember CLI and
finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports
a hash cont... | */
export default function(prefix) {
let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers'];
let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`);
let modulesMap = modules.reduce((memo, name) => {
memo[name] = {};
return memo;
}, {});
_keys(requirejs.... | random_line_split | |
project-summary.component.ts | import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteParams} from 'angular2/router';
import {Response} from 'angular2/http';
import {ProjectManager} from '../commons/purifinity/ProjectManager';
import {PanelComponent} from '../components/panel.component';
import {ProjectMenuComponent} from './proje... | @Component({
selector: 'project-summary',
directives: [
ROUTER_DIRECTIVES,
ProjectMenuComponent,
PanelComponent
],
pipes: [
DefaultDatePipe,
DurationPipe
],
templateUrl: '../../html/project/summary.html'
})
export class ProjectSummaryComponent {
priva... | random_line_split | |
project-summary.component.ts | import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteParams} from 'angular2/router';
import {Response} from 'angular2/http';
import {ProjectManager} from '../commons/purifinity/ProjectManager';
import {PanelComponent} from '../components/panel.component';
import {ProjectMenuComponent} from './proje... | (private routeParams: RouteParams, private projectManager: ProjectManager) {
let projectSummaryComponent = this;
this.projectId = routeParams.get('projectId');
projectManager.getLastRun(this.projectId,
function(data, status) {
projectSummaryComponent.lastRun = data;
... | constructor | identifier_name |
project-summary.component.ts | import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteParams} from 'angular2/router';
import {Response} from 'angular2/http';
import {ProjectManager} from '../commons/purifinity/ProjectManager';
import {PanelComponent} from '../components/panel.component';
import {ProjectMenuComponent} from './proje... |
}
| {
let projectSummaryComponent = this;
this.projectId = routeParams.get('projectId');
projectManager.getLastRun(this.projectId,
function(data, status) {
projectSummaryComponent.lastRun = data;
},
function(response: Response) {
}
... | identifier_body |
site.rs | use conf::Conf;
use error::{Result, ResultContext};
use files;
use tera::{Tera, Context};
use post::{Post, PostKind};
use std::{env, fs};
use std::path::PathBuf;
#[derive(Debug)]
pub struct Site {
ctx: Context,
articles: Vec<Post>,
pages: Vec<Post>,
tera: Tera,
}
impl Site {
pub fn collect(conf: &... | assert!(dir.join("p.html").exists());
assert!(dir.join(p.ts.format("%Y/%m/%d").to_string()).join("a.html").exists());
assert!(dir.join(::INDEX_FILE).exists());
assert!(dir.join(::ARCHIVE_FILE).exists());
fs::remove_dir_all(dir).unwrap();
}
}
| {
let dir = env::temp_dir().join("site");
::new::create_site(dir.clone(), true).unwrap();
let mut c = Conf::default();
c.force = Some(true);
c.in_dir = Some(dir.to_str().unwrap().to_string());
c.out_dir = Some(dir.to_str().unwrap().to_string());
create_post(dir.... | identifier_body |
site.rs | use conf::Conf;
use error::{Result, ResultContext};
use files;
use tera::{Tera, Context};
use post::{Post, PostKind};
use std::{env, fs};
use std::path::PathBuf;
#[derive(Debug)]
pub struct Site {
ctx: Context,
articles: Vec<Post>,
pages: Vec<Post>,
tera: Tera,
}
impl Site {
pub fn collect(conf: &... | c.in_dir = Some(dir.to_str().unwrap().to_string());
c.out_dir = Some(dir.to_str().unwrap().to_string());
create_post(dir.join(::SRC_DIR).join("a.md"), c.clone(), PostKind::Article).unwrap();
create_post(dir.join(::SRC_DIR).join("p.md"), c.clone(), PostKind::Page).unwrap();
let ... | c.force = Some(true); | random_line_split |
site.rs | use conf::Conf;
use error::{Result, ResultContext};
use files;
use tera::{Tera, Context};
use post::{Post, PostKind};
use std::{env, fs};
use std::path::PathBuf;
#[derive(Debug)]
pub struct Site {
ctx: Context,
articles: Vec<Post>,
pages: Vec<Post>,
tera: Tera,
}
impl Site {
pub fn collect(conf: &... | (&self, conf: &Conf) -> Result<()> {
let out_dir = conf.out_dir.as_ref()
.map(PathBuf::from)
.unwrap_or(env::current_dir()?);
for p in self.articles.iter().chain(self.pages.iter()) {
// skip the leading slash to make the output path correct
let url = &p.u... | generate | identifier_name |
update_ingest.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... |
def get_provider_rule_set(provider):
if provider.get('rule_set'):
return superdesk.get_resource_service('rule_sets').find_one(_id=provider['rule_set'], req=None)
def get_task_ttl(provider):
update_schedule = provider.get('update_schedule', UPDATE_SCHEDULE_DEFAULT)
return update_schedule.get('mi... | try:
days_to_keep_content = provider.get('days_to_keep', DAYS_TO_KEEP)
expiration_date = utcnow() - timedelta(days=days_to_keep_content)
return [item for item in items if item.get('versioncreated', utcnow()) > expiration_date]
except Exception as ex:
raise ProviderError.providerFilte... | identifier_body |
update_ingest.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... |
ingest_item(item, provider, rule_set)
def ingest_item(item, provider, rule_set=None):
try:
item.setdefault('_id', item['guid'])
providers[provider.get('type')].provider = provider
item['ingest_provider'] = str(provider['_id'])
item.setdefault('source', provider.get('sourc... | ref.setdefault('location', 'ingest')
itemRendition = items_dict.get(ref['residRef'], {}).get('renditions')
if itemRendition:
ref.setdefault('renditions', itemRendition) | conditional_block |
update_ingest.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | (provider):
"""Test if given provider should be scheduled for update.
:param provider: ingest provider
"""
now = utcnow()
last_updated = provider.get(LAST_UPDATED, now - timedelta(days=100)) # if never updated run now
update_schedule = provider.get('update_schedule', UPDATE_SCHEDULE_DEFAULT)
... | is_scheduled | identifier_name |
update_ingest.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | file_type, ext = content_type.split('/')
metadata = process_file(content, file_type)
file_guid = app.media.put(content, filename, content_type, metadata)
inserted.append(file_guid)
rendition_spec = app.config.get('RENDITIONS', {}).get('picture', {})
renditions = generate... | def update_renditions(item, href):
inserted = []
try:
content, filename, content_type = download_file_from_url(href) | random_line_split |
table-area.tsx | import React, { useCallback } from 'react'
import { HTMLTable, Icon, InputGroup } from '@blueprintjs/core'
import { useTranslation } from 'react-i18next'
import { memoize, range } from 'lodash'
import { Selector, useDispatch, useSelector } from 'react-redux'
import { createSelector } from 'reselect'
import styled from ... |
const mainWindow = ipc.access('MainWindow')
if (mainWindow && mainWindow.ipcFocusPlugin) {
mainWindow.ipcFocusPlugin('poi-plugin-battle-detail')
}
} catch (e) {
window.toggleModal('Warning', e as string)
}
}
const parseMapInfo = (mapStr: string) => {
if (!mapStr.includes('|'))
return ... | {
battleDetail.showBattleWithTimestamp(timestamp, (message: string) => {
if (message) {
window.toggleModal("Warning", `${t('Battle Detail')}: ${message}`)
}
})
} | conditional_block |
table-area.tsx | import React, { useCallback } from 'react'
import { HTMLTable, Icon, InputGroup } from '@blueprintjs/core'
import { useTranslation } from 'react-i18next'
import { memoize, range } from 'lodash'
import { Selector, useDispatch, useSelector } from 'react-redux'
import { createSelector } from 'reselect'
import styled from ... | }
</tr>
) : (
(showLabel || showFilter) ? (
<tr>
{
getTabs(contentType).map((tab, index) =>
(index === 0) ? (
<th key={index}>
... | getTabs(contentType).map((tab, index) => (
tabVisibility[index] ? <th key={index}>{tab}</th> : null
)) | random_line_split |
table-area.tsx | import React, { useCallback } from 'react'
import { HTMLTable, Icon, InputGroup } from '@blueprintjs/core'
import { useTranslation } from 'react-i18next'
import { memoize, range } from 'lodash'
import { Selector, useDispatch, useSelector } from 'react-redux'
import { createSelector } from 'reselect'
import styled from ... | (timestamp: number, t: (o: string) => string) {
try {
if (window.ipc == null) {
throw `${t("Your POI is out of date! You may need to visit http://0u0.moe/poi to get POI's latest release.")}`
}
const battleDetailPlugin = window.getStore('plugins').find((p: any) => p.id === 'poi-plugin-battle-detail'... | showBattleDetail | identifier_name |
table-area.tsx | import React, { useCallback } from 'react'
import { HTMLTable, Icon, InputGroup } from '@blueprintjs/core'
import { useTranslation } from 'react-i18next'
import { memoize, range } from 'lodash'
import { Selector, useDispatch, useSelector } from 'react-redux'
import { createSelector } from 'reselect'
import styled from ... | if (message) {
window.toggleModal("Warning", `${t('Battle Detail')}: ${message}`)
}
})
}
const mainWindow = ipc.access('MainWindow')
if (mainWindow && mainWindow.ipcFocusPlugin) {
mainWindow.ipcFocusPlugin('poi-plugin-battle-detail')
}
} catch (e) {
window.to... | {
try {
if (window.ipc == null) {
throw `${t("Your POI is out of date! You may need to visit http://0u0.moe/poi to get POI's latest release.")}`
}
const battleDetailPlugin = window.getStore('plugins').find((p: any) => p.id === 'poi-plugin-battle-detail')
if (!battleDetailPlugin || !battleDetail... | identifier_body |
log_plays.py | # (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com>
# This file is part of Ansible
#
# Ansible 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 lat... | def on_any(self, *args, **kwargs):
pass
def runner_on_failed(self, host, res, ignore_errors=False):
log(host, 'FAILED', res)
def runner_on_ok(self, host, res):
log(host, 'OK', res)
def runner_on_error(self, host, msg):
log(host, 'ERROR', msg)
def runner_on_skipped... | """
| random_line_split |
log_plays.py | # (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com>
# This file is part of Ansible
#
# Ansible 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 lat... |
def log(host, category, data):
if type(data) == dict:
if 'verbose_override' in data:
# avoid logging extraneous data from facts
data = 'omitted'
else:
invocation = data.pop('invocation', None)
data = json.dumps(data)
if invocation is not ... | os.makedirs("/var/log/ansible/hosts") | conditional_block |
log_plays.py | # (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com>
# This file is part of Ansible
#
# Ansible 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 lat... | (self, pattern):
pass
def playbook_on_stats(self, stats):
pass
| playbook_on_play_start | identifier_name |
log_plays.py | # (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com>
# This file is part of Ansible
#
# Ansible 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 lat... |
def runner_on_async_poll(self, host, res, jid, clock):
pass
def runner_on_async_ok(self, host, res, jid):
pass
def runner_on_async_failed(self, host, res, jid):
log(host, 'ASYNC_FAILED', res)
def playbook_on_start(self):
pass
def playbook_on_notify(self, host, h... | pass | identifier_body |
sloppy-implicit-block-function.js | // Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --no-harmony-restrictive-declarations
// ES#sec-functiondeclarations-in-ifstatement-statement-clauses
// Annex B 3.4 FunctionDeclarations in ... | (function() {
assertEquals(undefined, f);
if (true) {} else function f() { };
assertEquals(undefined, f);
})();
(function() {
assertEquals(undefined, f);
if (false) {} else function f() { };
assertEquals('function', typeof f);
})();
// For legacy reasons, we also support these types of semantics as
// the... | assertEquals('function', typeof f);
})();
| random_line_split |
sloppy-implicit-block-function.js | // Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --no-harmony-restrictive-declarations
// ES#sec-functiondeclarations-in-ifstatement-statement-clauses
// Annex B 3.4 FunctionDeclarations in ... | () { };
assertEquals('function', typeof f);
})();
// For legacy reasons, we also support these types of semantics as
// the body of a for or with statement.
(function() {
for (;false;) function f() { };
assertEquals(undefined, f);
})();
(function() {
for (var x in {}) function f() { };
assertEquals(undefine... | f | identifier_name |
sloppy-implicit-block-function.js | // Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --no-harmony-restrictive-declarations
// ES#sec-functiondeclarations-in-ifstatement-statement-clauses
// Annex B 3.4 FunctionDeclarations in ... |
}
assertEquals('function', typeof bar());
})();
(function() {
function bar() {
return f;
{
x: function f() {}
}
}
assertEquals(undefined, bar());
})();
| {} | identifier_body |
app.ts | /* Implement override method that can retrieve day, month(as number as text format) and year and return Date object
Override this method for retrieve array of such parameters and retrieve array with dates. */
// SZ classes, enums and interfaces should be implemented in separete file.
interface ICustomDate {
d... |
}
if(typeof day === 'number') {
if(typeof month === 'number') {
d = new Date(year, month, day);
}
if(typeof month === 'string') {
d = new Date(year, monthes[month.toLowerCase()], day);
}
}
return d;
}
let first_call: Date = over(1, 1, 1);
consol... | {
if(typeof day[i].month === 'number') {
d.push(new Date(day[i].year, Number(day[i].month), day[i].day));
}
if(typeof day[i].month === 'string') {
let temp: string = String(day[i].month);
d.push(new Date(day[i].year, monthes[temp.toLowe... | conditional_block |
app.ts | /* Implement override method that can retrieve day, month(as number as text format) and year and return Date object
Override this method for retrieve array of such parameters and retrieve array with dates. */
// SZ classes, enums and interfaces should be implemented in separete file.
interface ICustomDate {
d... | (obj: object): number {
let result: number = 0;
if (typeof obj === 'object' && obj !== null) {
for(let key in obj) {
if (typeof obj[key] === 'object') {
result += customToValue(obj[key]);
} else {
result += getPrimitiveV(obj[key]);
}
... | customToValue | identifier_name |
app.ts | /* Implement override method that can retrieve day, month(as number as text format) and year and return Date object
Override this method for retrieve array of such parameters and retrieve array with dates. */
// SZ classes, enums and interfaces should be implemented in separete file.
interface ICustomDate {
d... | if (typeof obj === 'object' && obj !== null) {
for(let key in obj) {
if (typeof obj[key] === 'object') {
result += customToValue(obj[key]);
} else {
result += getPrimitiveV(obj[key]);
}
}
} else {
result = 0;
}
r... |
function customToValue(obj: object): number {
let result: number = 0; | random_line_split |
bootstrap-list-filter-contacts.js | //borrowed from stefanocudini bootstrap-list-filter
(function($) {
$.fn.btsListFilterContacts = function(inputEl, options) {
var searchlist = this,
searchlist$ = $(this),
inputEl$ = $(inputEl),
items$ = searchlist$,
callData,
callReq; //last callData execution
function tmpl(str, data) {
retu... | (func, timeout) {
var timeoutID;
timeout = timeout || 300;
return function () {
var scope = this , args = arguments;
clearTimeout( timeoutID );
timeoutID = setTimeout( function () {
func.apply( scope , Array.prototype.slice.call( args ) );
}, timeout);
};
}
options = $.extend({
... | debouncer | identifier_name |
bootstrap-list-filter-contacts.js | //borrowed from stefanocudini bootstrap-list-filter
(function($) {
$.fn.btsListFilterContacts = function(inputEl, options) {
var searchlist = this,
searchlist$ = $(this),
inputEl$ = $(inputEl),
items$ = searchlist$,
callData,
callReq; //last callData execution
function tmpl(str, data) |
function debouncer(func, timeout) {
var timeoutID;
timeout = timeout || 300;
return function () {
var scope = this , args = arguments;
clearTimeout( timeoutID );
timeoutID = setTimeout( function () {
func.apply( scope , Array.prototype.slice.call( args ) );
}, timeout);
};
}
op... | {
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
return data[key] || '';
});
} | identifier_body |
bootstrap-list-filter-contacts.js | //borrowed from stefanocudini bootstrap-list-filter
(function($) {
$.fn.btsListFilterContacts = function(inputEl, options) {
var searchlist = this,
searchlist$ = $(this),
inputEl$ = $(inputEl),
items$ = searchlist$,
callData,
callReq; //last callData execution
function tmpl(str, data) {
retu... | $(this).val('').trigger(options.eventKey);
});
return searchlist$;
};
})(jQuery); |
if(options.resetOnBlur)
inputEl$.on('blur', function(e) { | random_line_split |
issue-15858.rs | // Copyright 2012-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-MI... | () {
{
let _x: Foo<BarImpl> = Foo;
}
unsafe {
assert_eq!(DROP_RAN, true);
}
}
| main | identifier_name |
issue-15858.rs | // Copyright 2012-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-MI... | struct BarImpl<'b>;
impl<'b> Bar<'b> for BarImpl<'b> {
fn do_something(&mut self) {}
}
struct Foo<B>;
#[unsafe_destructor]
impl<'b, B: Bar<'b>> Drop for Foo<B> {
fn drop(&mut self) {
unsafe {
DROP_RAN = true;
}
}
}
fn main() {
{
let _x: Foo<BarImpl> = Foo;
}
... | trait Bar<'b> {
fn do_something(&mut self);
}
| random_line_split |
issue-2904.rs | // Copyright 2012-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-MI... |
mod test {
#[test]
pub fn trivial_to_string() {
assert_eq!(lambda.to_string(), "\\")
}
}
pub fn main() {}
| {
let mut input: &mut Read = &mut input;
let mut grid = Vec::new();
let mut line = [0; 10];
input.read(&mut line);
let mut row = Vec::new();
for c in &line {
row.push(square_from_char(*c as char))
}
grid.push(row);
let width = grid[0].len();
for row in &grid { assert_eq!(... | identifier_body |
issue-2904.rs | // Copyright 2012-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-MI... | <rdr:'static + Read>(mut input: rdr)
-> Vec<Vec<square>> {
let mut input: &mut Read = &mut input;
let mut grid = Vec::new();
let mut line = [0; 10];
input.read(&mut line);
let mut row = Vec::new();
for c in &line {
row.push(square_from_char(*c as char))
}
grid.... | read_board_grid | identifier_name |
issue-2904.rs | // Copyright 2012-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-MI... | match c {
'R' => { bot }
'#' => { wall }
'*' => { rock }
'\\' => { lambda }
'L' => { closed_lift }
'O' => { open_lift }
'.' => { earth }
' ' => { empty }
_ => {
println!("invalid square: {}", c);
panic!()
}
}
}
fn read_board_gr... | }
}
fn square_from_char(c: char) -> square { | random_line_split |
quantity-options.component.ts | import { ClarioGridsService } from './../../_services/clario-grids.service';
import { Location } from '@angular/common';
import { MatDialogRef } from '@angular/material';
import { Feature } from './../../feature';
import { Component, OnInit, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-qua... |
ngAfterContentChecked() {
const featureType = this.capitalizeFirstLetter(this.feature.feature_type);
this.title = featureType !== 'hush' ? `${featureType} Tiles By Quantity` : `${featureType} Blocks By Quantity`;
}
gridSizeChanged(selection) {
this.clarioGrids.gridSizeSelected(selection);
}
ti... | {} | identifier_body |
quantity-options.component.ts | import { ClarioGridsService } from './../../_services/clario-grids.service';
import { Location } from '@angular/common';
import { MatDialogRef } from '@angular/material'; | import { Feature } from './../../feature';
import { Component, OnInit, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-quantity-options',
templateUrl: './quantity-options.component.html',
styleUrls: ['../../options/options.component.css', './quantity-options.component.css']
})
export clas... | random_line_split | |
quantity-options.component.ts | import { ClarioGridsService } from './../../_services/clario-grids.service';
import { Location } from '@angular/common';
import { MatDialogRef } from '@angular/material';
import { Feature } from './../../feature';
import { Component, OnInit, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-qua... |
return valid;
}
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
}
| {
valid = valid && !!this.feature.grid_type && !!this.clarioGrids.selectedTileSize;
} | conditional_block |
quantity-options.component.ts | import { ClarioGridsService } from './../../_services/clario-grids.service';
import { Location } from '@angular/common';
import { MatDialogRef } from '@angular/material';
import { Feature } from './../../feature';
import { Component, OnInit, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-qua... | () {
this.dialogRef.close('cancel');
this.feature.navToLanding();
}
validateOptions() {
let valid = !!this.feature.design_name;
if (this.feature.feature_type === 'clario') {
valid = valid && !!this.feature.grid_type && !!this.clarioGrids.selectedTileSize;
}
return valid;
}
capita... | goToLanding | identifier_name |
index.js | import './ChapterHeader.styl'
import Store from './../../../../../../flux/store/mobile/index'
import EventsConstants from './../../../../../../flux/constants/EventsConstants'
class ChapterHeader extends React.Component {
constructor() {
super()
this.state = {
index: '',
title: ''
}
this... | <h3 className="chapter-header__title" ref="title">{ this.state.title }</h3>
</div>
)
}
componentDidUpdate() {
this.swapTl.reverse()
}
routeChanged( routes ) {
switch ( routes.newRoute ) {
case '/indochine':
this.nextState.index = '01'
this.nextState.title... | <strong className="chapter-header__index" ref="index">{ this.state.index }</strong> | random_line_split |
index.js | import './ChapterHeader.styl'
import Store from './../../../../../../flux/store/mobile/index'
import EventsConstants from './../../../../../../flux/constants/EventsConstants'
class ChapterHeader extends React.Component {
constructor() {
super()
this.state = {
index: '',
title: ''
}
this... |
routeChanged( routes ) {
switch ( routes.newRoute ) {
case '/indochine':
this.nextState.index = '01'
this.nextState.title = 'Indochine'
break
case '/troubles':
this.nextState.index = '02'
this.nextState.title = 'Troubles'
break
case '/notorie... | {
this.swapTl.reverse()
} | identifier_body |
index.js | import './ChapterHeader.styl'
import Store from './../../../../../../flux/store/mobile/index'
import EventsConstants from './../../../../../../flux/constants/EventsConstants'
class ChapterHeader extends React.Component {
constructor() {
super()
this.state = {
index: '',
title: ''
}
this... | () {
return (
<div className="chapter-header">
<strong className="chapter-header__index" ref="index">{ this.state.index }</strong>
<h3 className="chapter-header__title" ref="title">{ this.state.title }</h3>
</div>
)
}
componentDidUpdate() {
this.swapTl.reverse()
... | render | identifier_name |
3_04_exercise_spiral.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-04: Spiral | use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
r: f32,
theta: f32,
}
fn model(app: &App) -> Model {
let r = 0.0;
let theta = 0.0;
app.new_window().size(640, 360).view(view).build().unwrap();
Model { r, theta }
}
fn update(_app: &App, model:... | random_line_split | |
3_04_exercise_spiral.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-04: Spiral
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct | {
r: f32,
theta: f32,
}
fn model(app: &App) -> Model {
let r = 0.0;
let theta = 0.0;
app.new_window().size(640, 360).view(view).build().unwrap();
Model { r, theta }
}
fn update(_app: &App, model: &mut Model, _update: Update) {
// Increment the angle
model.theta += 0.01;
// Increm... | Model | identifier_name |
3_04_exercise_spiral.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-04: Spiral
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
r: f32,
theta: f32,
}
fn model(app: &App) -> Model {
let r = 0.0;
let theta = 0.0;
app.new_window().si... | {
// Begin drawing
let draw = app.draw();
//draw.background().color(WHITE);
let x = model.r * model.theta.cos();
let y = model.r * model.theta.sin();
// Draw an ellipse at x,y
draw.ellipse()
.x_y(x, y)
.w_h(16.0, 16.0)
.rgba(0.0, 0.0, 0.0, 1.0);
// Write the re... | identifier_body | |
Library.py | '''
Created on Apr 3, 2012
@author: Dan
'''
from Common.Converter import *
from Common.Module import *
from Common.Symbol import DevicePart
from Common.Device import Deviceset
class Library(object):
__slots__ = ("name", "modules", "symbols", "converter", "deviceparts")
def __init__(self, node, name, conver... | dp = DevicePart(device, symbolsHash, deviceset.getGates(), symConverter)
self.deviceparts.append(dp)
def writeLibrary(self, modFile=None, symFile=None, docFile=None):
if modFile != None:
self.writeModFile(modFile)
if symFile != None:
... | device.setFullName(deviceset.name) | random_line_split |
Library.py | '''
Created on Apr 3, 2012
@author: Dan
'''
from Common.Converter import *
from Common.Module import *
from Common.Symbol import DevicePart
from Common.Device import Deviceset
class Library(object):
__slots__ = ("name", "modules", "symbols", "converter", "deviceparts")
def __init__(self, node, name, conver... |
def writeDocFile(self, docFile):
docFile.write("EESchema-DOCLIB Version 0.0 Date: 00/00/0000 00:00:00\n")
| symFile.write("EESchema-LIBRARY Version 0.0 00/00/0000-00:00:00\n")
for devicepart in self.deviceparts:
devicepart.write(symFile)
symFile.write("# End Library") | identifier_body |
Library.py | '''
Created on Apr 3, 2012
@author: Dan
'''
from Common.Converter import *
from Common.Module import *
from Common.Symbol import DevicePart
from Common.Device import Deviceset
class Library(object):
__slots__ = ("name", "modules", "symbols", "converter", "deviceparts")
def __init__(self, node, name, conver... | (self, symFile):
symFile.write("EESchema-LIBRARY Version 0.0 00/00/0000-00:00:00\n")
for devicepart in self.deviceparts:
devicepart.write(symFile)
symFile.write("# End Library")
def writeDocFile(self, docFile):
docFile.write("EESchema-DOCLIB Version 0.0 Date: 00/00/00... | writeSymFile | identifier_name |
Library.py | '''
Created on Apr 3, 2012
@author: Dan
'''
from Common.Converter import *
from Common.Module import *
from Common.Symbol import DevicePart
from Common.Device import Deviceset
class Library(object):
__slots__ = ("name", "modules", "symbols", "converter", "deviceparts")
def __init__(self, node, name, conver... |
modFile.write("$EndINDEX\n")
for module in self.modules:
module.write(modFile)
modFile.write("$EndLIBRARY")
modFile.close()
def writeSymFile(self, symFile):
symFile.write("EESchema-LIBRARY Version 0.0 00/00/0000-00:00:00\n")
for devicepart in self.dev... | modFile.write(module.package + "\n") | conditional_block |
fields.py | # -*- coding: utf-8 -*-
import json
from odoo import fields
def monkey_patch(cls):
""" Return a method decorator to monkey-patch the given class. """
def decorate(func):
name = func.__name__
func.super = getattr(cls, name, None)
setattr(cls, name, func)
return func
return... | (fields.Field):
""" Serialized fields provide the storage for sparse fields. """
type = 'serialized'
_slots = {
'prefetch': False, # not prefetched by default
}
column_type = ('text', 'text')
def convert_to_column(self, value, record, values=None):
return json.dumps... | Serialized | identifier_name |
fields.py | # -*- coding: utf-8 -*-
import json
from odoo import fields
def monkey_patch(cls):
""" Return a method decorator to monkey-patch the given class. """
def decorate(func):
name = func.__name__
func.super = getattr(cls, name, None)
setattr(cls, name, func)
return func
return... |
fields.Serialized = Serialized
| value = value or {}
return value if isinstance(value, dict) else json.loads(value) | identifier_body |
fields.py | # -*- coding: utf-8 -*-
import json
from odoo import fields
def monkey_patch(cls):
""" Return a method decorator to monkey-patch the given class. """
def decorate(func):
name = func.__name__
func.super = getattr(cls, name, None)
setattr(cls, name, func)
return func
return... |
if self.relational:
for record in records:
record[self.name] = record[self.name].exists()
@monkey_patch(fields.Field)
def _inverse_sparse(self, records):
for record in records:
values = record[self.sparse]
value = self.convert_to_read(record[self.name], record, use_name_get... | values = record[self.sparse]
record[self.name] = values.get(self.name) | conditional_block |
fields.py | # -*- coding: utf-8 -*-
import json
from odoo import fields
| def monkey_patch(cls):
""" Return a method decorator to monkey-patch the given class. """
def decorate(func):
name = func.__name__
func.super = getattr(cls, name, None)
setattr(cls, name, func)
return func
return decorate
#
# Implement sparse fields by monkey-patching field... | random_line_split | |
MenuListItemRenderer.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2020 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', './ListItemBaseRenderer', 'sap/ui/core/Renderer'],
function(jQuery, ListItemBaseRenderer, Render... | }
};
MenuListItemRenderer.renderLIContent = function(rm, oLI) {
var sTextDir = oLI.getTitleTextDirection();
// image
if (oLI.getIcon()) {
rm.renderControl(oLI._getImage((oLI.getId() + "-img"), "sapMMenuLIImgThumb", oLI.getIcon(), oLI.getIconDensityAware()));
}
rm.write("<div");
rm.addCla... | }
if (oLI._hasSubItems()) {
rm.addClass("sapMMenuLIHasChildren"); | random_line_split |
MenuListItemRenderer.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2020 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', './ListItemBaseRenderer', 'sap/ui/core/Renderer'],
function(jQuery, ListItemBaseRenderer, Render... |
// List item text (also written when no title for keeping the space)
rm.write("<div");
rm.addClass("sapMSLITitleOnly");
rm.writeClasses();
if (sTextDir !== sap.ui.core.TextDirection.Inherit) {
rm.writeAttribute("dir", sTextDir.toLowerCase());
}
rm.write(">");
rm.writeEscaped(oLI.getTitle... | {
rm.write('<div class="sapMLIBNoFlex">');
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.