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
sfp_template.py
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_XXX # Purpose: Description of the plug-in. # # Author: Name and e-mail address # # Created: Date # Copyright: (c) Name # Licence: GPL # ----------------------------...
(self): return ["*"] # What events this module produces # This is to support the end user in selecting modules based on events # produced. def producedEvents(self): return None # Handle events sent to this module def handleEvent(self, event): eventName = even...
watchedEvents
identifier_name
content_type.rs
use mime::Mime; header! { /// `Content-Type` header, defined in /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5) /// /// The `Content-Type` header field indicates the media type of the /// associated representation: either the representation enclosed in the /// message payload ...
/// /// let mut headers = Headers::new(); /// /// headers.set( /// ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![])) /// ); /// ``` /// ``` /// use hyper::header::{Headers, ContentType}; /// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; /// /// let...
/// ``` /// use hyper::header::{Headers, ContentType}; /// use hyper::mime::{Mime, TopLevel, SubLevel};
random_line_split
content_type.rs
use mime::Mime; header! { /// `Content-Type` header, defined in /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5) /// /// The `Content-Type` header field indicates the media type of the /// associated representation: either the representation enclosed in the /// message payload ...
/// A constructor to easily create a `Content-Type: application/www-form-url-encoded` header. #[inline] pub fn form_url_encoded() -> ContentType { ContentType(mime!(Application/WwwFormUrlEncoded)) } /// A constructor to easily create a `Content-Type: image/jpeg` header. #[inline] ...
{ ContentType(mime!(Text/Html; Charset=Utf8)) }
identifier_body
content_type.rs
use mime::Mime; header! { /// `Content-Type` header, defined in /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5) /// /// The `Content-Type` header field indicates the media type of the /// associated representation: either the representation enclosed in the /// message payload ...
() -> ContentType { ContentType(mime!(Text/Plain; Charset=Utf8)) } /// A constructor to easily create a `Content-Type: text/html; charset=utf-8` header. #[inline] pub fn html() -> ContentType { ContentType(mime!(Text/Html; Charset=Utf8)) } /// A constructor to easily create a...
plaintext
identifier_name
main.js
// Authors: Valery Bogdanov $(document).ready(function () { searchBox(); fancyboxInit(); }); $(window).resize(function () { }); $(window).load(function () { }); function searchBox() { $('.js-searchShow, .js-searchHide').on('click', function(e){ e.preventDefault(); $('.js-searchForm').fadeToggle('fa...
() { $('.b-text a[href$=".jpg"], .b-text a[href$=".jpeg"], .b-text a[href$=".png"]').fancybox({ openEffect : 'none', closeEffect : 'none', beforeShow : function() { var alt = this.element.find('img').attr('alt'); this.inner.find('img').attr('alt', alt); this.title = alt; } }); $(...
fancyboxInit
identifier_name
main.js
// Authors: Valery Bogdanov $(document).ready(function () { searchBox(); fancyboxInit(); }); $(window).resize(function () { }); $(window).load(function () { }); function searchBox() { $('.js-searchShow, .js-searchHide').on('click', function(e){ e.preventDefault(); $('.js-searchForm').fadeToggle('fa...
}); } function fancyboxInit() { $('.b-text a[href$=".jpg"], .b-text a[href$=".jpeg"], .b-text a[href$=".png"]').fancybox({ openEffect : 'none', closeEffect : 'none', beforeShow : function() { var alt = this.element.find('img').attr('alt'); this.inner.find('img').attr('alt', alt); thi...
{ $('.js-searchForm').find('input[name="s"]').trigger('focus'); }
conditional_block
main.js
// Authors: Valery Bogdanov $(document).ready(function () { searchBox(); fancyboxInit(); }); $(window).resize(function () { }); $(window).load(function () { });
$('.js-searchForm').find('input[name="s"]').trigger('focus'); } }); } function fancyboxInit() { $('.b-text a[href$=".jpg"], .b-text a[href$=".jpeg"], .b-text a[href$=".png"]').fancybox({ openEffect : 'none', closeEffect : 'none', beforeShow : function() { var alt = this.element.find('im...
function searchBox() { $('.js-searchShow, .js-searchHide').on('click', function(e){ e.preventDefault(); $('.js-searchForm').fadeToggle('fast', 'linear'); if ($(this).hasClass('js-searchShow')) {
random_line_split
main.js
// Authors: Valery Bogdanov $(document).ready(function () { searchBox(); fancyboxInit(); }); $(window).resize(function () { }); $(window).load(function () { }); function searchBox()
function fancyboxInit() { $('.b-text a[href$=".jpg"], .b-text a[href$=".jpeg"], .b-text a[href$=".png"]').fancybox({ openEffect : 'none', closeEffect : 'none', beforeShow : function() { var alt = this.element.find('img').attr('alt'); this.inner.find('img').attr('alt', alt); this.title ...
{ $('.js-searchShow, .js-searchHide').on('click', function(e){ e.preventDefault(); $('.js-searchForm').fadeToggle('fast', 'linear'); if ($(this).hasClass('js-searchShow')) { $('.js-searchForm').find('input[name="s"]').trigger('focus'); } }); }
identifier_body
chan_mark.py
""" Markup class allows the use of easy-to-write characters to style the text instead of using escape codes. ==text== --> reverse video '''text''' --> bold ~~text~~ --> strikethrough Copyright (c) 2015 makos <https://github.com/makos>, chibi <http://neetco.de/chibi> under GNU GPL v3, see LICENSE for details """ impo...
def demarkify(self, input_text): """Prints out a marked-up piece of text.""" output_text = self.esc(input_text) # strikethrough output_text = re.sub( '~~(?P<substring>.*?)~~', '\033[0;9m\g<substring>\033[0m', output_text) # bold output_text =...
input_text = input_text.replace('\033', '\\033') return input_text
identifier_body
chan_mark.py
""" Markup class allows the use of easy-to-write characters to style the text instead of using escape codes. ==text== --> reverse video '''text''' --> bold ~~text~~ --> strikethrough Copyright (c) 2015 makos <https://github.com/makos>, chibi <http://neetco.de/chibi> under GNU GPL v3, see LICENSE for details """ impo...
(self, input_text): """Prints out a marked-up piece of text.""" output_text = self.esc(input_text) # strikethrough output_text = re.sub( '~~(?P<substring>.*?)~~', '\033[0;9m\g<substring>\033[0m', output_text) # bold output_text = re.sub( ...
demarkify
identifier_name
chan_mark.py
""" Markup class allows the use of easy-to-write characters to style the text instead of using escape codes. ==text== --> reverse video '''text''' --> bold ~~text~~ --> strikethrough Copyright (c) 2015 makos <https://github.com/makos>, chibi <http://neetco.de/chibi> under GNU GPL v3, see LICENSE for details """ impo...
def demarkify(self, input_text): """Prints out a marked-up piece of text.""" output_text = self.esc(input_text) # strikethrough output_text = re.sub( '~~(?P<substring>.*?)~~', '\033[0;9m\g<substring>\033[0m', output_text) # bold output_text = ...
random_line_split
gpmdp.py
# -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 ma...
response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
= ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**dat...
conditional_block
gpmdp.py
# -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 ma...
result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response i f __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test ...
" """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': ...
identifier_body
gpmdp.py
# -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 ma...
""" """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': ...
class Py3status:
random_line_split
gpmdp.py
# -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 ma...
f, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: ...
p(sel
identifier_name
db.ts
import Dexie from 'dexie'; import dexieCloud, { DexieCloudTable } from 'dexie-cloud-addon'; import { populate } from '../models/populate'; import { TodoItem } from '../models/TodoItem'; import { TodoList } from '../models/TodoList'; export class TodoDB extends Dexie { todoLists!: DexieCloudTable<TodoList>; todoIte...
} export const db = new TodoDB(); db.on('populate', populate); export async function resetDatabase() { await db.delete(); window.location.reload(); /*return db.transaction('rw', db.todoLists, db.todoItems, async () => { await db.todoItems .filter((tdi) => !tdi.realmId || tdi.realmId === db.cloud.cur...
{ return this.transaction('rw', this.todoItems, this.todoLists, () => { this.todoItems.where({ todoListId }).delete(); this.todoLists.delete(todoListId); }); }
identifier_body
db.ts
import Dexie from 'dexie'; import dexieCloud, { DexieCloudTable } from 'dexie-cloud-addon'; import { populate } from '../models/populate'; import { TodoItem } from '../models/TodoItem'; import { TodoList } from '../models/TodoList'; export class TodoDB extends Dexie { todoLists!: DexieCloudTable<TodoList>; todoIte...
(todoListId: string) { return this.transaction('rw', this.todoItems, this.todoLists, () => { this.todoItems.where({ todoListId }).delete(); this.todoLists.delete(todoListId); }); } } export const db = new TodoDB(); db.on('populate', populate); export async function resetDatabase() { await db....
deleteList
identifier_name
db.ts
import Dexie from 'dexie'; import dexieCloud, { DexieCloudTable } from 'dexie-cloud-addon'; import { populate } from '../models/populate'; import { TodoItem } from '../models/TodoItem'; import { TodoList } from '../models/TodoList'; export class TodoDB extends Dexie { todoLists!: DexieCloudTable<TodoList>; todoIte...
}
});*/
random_line_split
ml_collector.py
#!/usr/local/bin python from __future__ import print_function import psutil import time import getopt import sys import django_initial from QueueDB.models import Training vrt_mem_list = [] mem_list = [] cpu_list = [] read_list = [] write_list = [] def get_mem(pid): running_process = psutil.Process(pid) if ru...
else: break cpu_usage, mem_usage, vrt_mem_usage = get_cpu_mem(cpu_list, mem_list, vrt_mem_list) try: training_item = Training.objects.get(id=job_id) training_item.mem = mem_usage training_item.vrt_mem = vrt_mem_usage training_...
break
random_line_split
ml_collector.py
#!/usr/local/bin python from __future__ import print_function import psutil import time import getopt import sys import django_initial from QueueDB.models import Training vrt_mem_list = [] mem_list = [] cpu_list = [] read_list = [] write_list = [] def get_mem(pid):
def get_cpu(pid): running_process = psutil.Process(pid) if running_process.is_running(): cpu = running_process.cpu_percent(interval=1) return cpu else: return 0 def get_io(pid): running_process = psutil.Process(pid) if running_process.is_running(): io = running_p...
running_process = psutil.Process(pid) if running_process.is_running(): mem = running_process.memory_info() return mem[0], mem[1] else: return 0, 0
identifier_body
ml_collector.py
#!/usr/local/bin python from __future__ import print_function import psutil import time import getopt import sys import django_initial from QueueDB.models import Training vrt_mem_list = [] mem_list = [] cpu_list = [] read_list = [] write_list = [] def get_mem(pid): running_process = psutil.Process(pid) if ru...
else: return 0 def get_io(pid): running_process = psutil.Process(pid) if running_process.is_running(): io = running_process.io_counters() return io[2], io[3] else: return 0 def get_cpu_mem(cpu_list, mem_list, virt_mem_list): """ Get CPU and memory usage :...
cpu = running_process.cpu_percent(interval=1) return cpu
conditional_block
ml_collector.py
#!/usr/local/bin python from __future__ import print_function import psutil import time import getopt import sys import django_initial from QueueDB.models import Training vrt_mem_list = [] mem_list = [] cpu_list = [] read_list = [] write_list = [] def get_mem(pid): running_process = psutil.Process(pid) if ru...
(pid): running_process = psutil.Process(pid) if running_process.is_running(): cpu = running_process.cpu_percent(interval=1) return cpu else: return 0 def get_io(pid): running_process = psutil.Process(pid) if running_process.is_running(): io = running_process.io_coun...
get_cpu
identifier_name
update_lib_doc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2016 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licens...
write_disclaimer(f2) if module.endswith('.h'): #full = package + '/' + module fn_h = package.replace('.', '/') + '/' + module underline('``%s`` -- %s' % (fn_h, get_first_doxygenline(fn_h)), '#', f2) print >> f2, '.. doxygenfile::', ...
packages = discover() # Write new/updated rst files if needed fns_rst = [] for package, modules in sorted(packages.iteritems()): # write the new file to a StringIO f1 = StringIO() write_disclaimer(f1) underline('``%s`` -- %s' % (package, get_first_docline(package)), '#', f1)...
identifier_body
update_lib_doc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2016 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licens...
packages['horton.%s' % subpackage] = [] # find modules for package, modules in packages.iteritems(): stub = package.replace('.', '/') for fn in sorted(glob('../%s/*.py' % stub) + glob('../%s/*.so' % stub)): module = fn.split('/')[-1][:-3] if module == '__init__':...
continue
conditional_block
update_lib_doc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2016 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licens...
(): # find packages packages = {'horton': []} for fn in glob('../horton/*/__init__.py'): subpackage = fn.split('/')[2] if subpackage == 'test': continue packages['horton.%s' % subpackage] = [] # find modules for package, modules in packages.iteritems(): st...
discover
identifier_name
update_lib_doc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2016 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licens...
for package, modules in sorted(packages.iteritems()): # write the new file to a StringIO f1 = StringIO() write_disclaimer(f1) underline('``%s`` -- %s' % (package, get_first_docline(package)), '#', f1) print >> f1 print >> f1, '.. automodule::', package print >...
fns_rst = []
random_line_split
amavis.py
# coding=utf-8 """ Collector that reports amavis metrics as reported by amavisd-agent #### Dependencies * amavisd-agent must be present in PATH """ import os import subprocess import re import diamond.collector import diamond.convertor from diamond.collector import str_to_bool class AmavisCollector(diamond.coll...
mtype = 'GAUGE' precision = 2 if metric in ('count', 'time'): mtype = 'COUNTER' precision = 0 self.publish("{}.{}".format(name, metric), ...
continue
conditional_block
amavis.py
# coding=utf-8 """ Collector that reports amavis metrics as reported by amavisd-agent #### Dependencies * amavisd-agent must be present in PATH """ import os import subprocess import re import diamond.collector import diamond.convertor from diamond.collector import str_to_bool class AmavisCollector(diamond.coll...
def get_default_config(self): config = super(AmavisCollector, self).get_default_config() config.update({ 'path': 'amavis', 'amavisd_exe': '/usr/sbin/amavisd-agent', 'use_sudo': False, 'sudo_exe': '/usr/bin/sudo', 'sudo_user': 'amavis', ...
matchers = [ re.compile(r'^\s*(?P<name>[\w]+)\s+(?P<time>[\d]+) s\s+' r'(?P<frequency>[\d.]+) s/msg\s+\([\w]+\)\s*$'), re.compile(r'^\s*(?P<name>[\w.-]+)\s+(?P<count>[\d]+)\s+' r'(?P<frequency>[\d.]+)/h\s+(?P<percentage>[\d.]+) %' r'\s\([\w]+\)\s*...
identifier_body
amavis.py
# coding=utf-8 """ Collector that reports amavis metrics as reported by amavisd-agent #### Dependencies * amavisd-agent must be present in PATH """ import os import subprocess import re import diamond.collector import diamond.convertor from diamond.collector import str_to_bool class AmavisCollector(diamond.coll...
(self): config = super(AmavisCollector, self).get_default_config() config.update({ 'path': 'amavis', 'amavisd_exe': '/usr/sbin/amavisd-agent', 'use_sudo': False, 'sudo_exe': '/usr/bin/sudo', 'sudo_user': 'amavis', }) return conf...
get_default_config
identifier_name
amavis.py
# coding=utf-8 """ Collector that reports amavis metrics as reported by amavisd-agent #### Dependencies * amavisd-agent must be present in PATH """ import os import subprocess import re import diamond.collector import diamond.convertor from diamond.collector import str_to_bool class AmavisCollector(diamond.coll...
err) return None return True
random_line_split
notifiers.py
urllib import urlencode else: from urllib.parse import urlencode def create_notification_handler(application_name=None, level=NOTSET, icon=None): """Creates a handler perfectly fit the current platform. On Linux systems this creates a :class:`LibNotifyHandler`, on OS X sy...
(self, application_name=None, apikey=None, userkey=None, device=None, priority=0, sound=None, record_limit=None, record_delta=None, level=NOTSET, filter=None, bubble=False): super(PushoverHandler, self).__init__(None, record_limit, record_delta, ...
__init__
identifier_name
notifiers.py
, bubble=False): Handler.__init__(self, level, filter, bubble) LimitingHandlerMixin.__init__(self, record_limit, record_delta) if application_name is None: application_name = get_application_name() self.application_name = application_name def make_title(self, record): ...
message = record.message
conditional_block
notifiers.py
urllib import urlencode else: from urllib.parse import urlencode def create_notification_handler(application_name=None, level=NOTSET, icon=None): """Creates a handler perfectly fit the current platform. On Linux systems this creates a :class:`LibNotifyHandler`, on OS X sy...
def emit(self, record): if not self.check_delivery(record)[1]: return notifier = self._pynotify.Notification(self.make_title(record), self.make_text(record)) notifier.set_urgency(self.get_urgency(record)) notifier.set_timeo...
"""Returns the urgency flag for pynotify. Errors and criticals are get highest urgency (CRITICAL), warnings get higher priority (NORMAL) and the rest gets LOW. """ pn = self._pynotify if record.level >= ERROR: return pn.URGENCY_CRITICAL elif record.level == W...
identifier_body
notifiers.py
urllib import urlencode else: from urllib.parse import urlencode def create_notification_handler(application_name=None, level=NOTSET, icon=None): """Creates a handler perfectly fit the current platform. On Linux systems this creates a :class:`LibNotifyHandler`, on OS X sy...
return body = urlencode({ 'notification[from_screen_name]': self.get_screen_name(record).encode('utf-8'), 'notification[message]': self.make_text(record).encode('utf-8'), 'notification[from_remote_service_id]': str(int(time() * 100)...
def emit(self, record): if not self.check_delivery(record)[1]:
random_line_split
huge-largest-array.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 ...
assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1); } #[cfg(target_pointer_width = "64")] pub fn main() { assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); }
use std::mem::size_of; #[cfg(target_pointer_width = "32")] pub fn main() {
random_line_split
huge-largest-array.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 ...
#[cfg(target_pointer_width = "64")] pub fn main() { assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); }
{ assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1); }
identifier_body
huge-largest-array.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 ...
() { assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); }
main
identifier_name
api.js
var express = require("express") var bodyParser = require("body-parser") var app = express() var alerts = [] var trends = [ { alertId: 1, delta: 10 }, { alertId: 2, delta: 100 }, { alertId: 3, delta: 0 }, { alertId: 4, delta: ...
app.get("/api/trends/alert-id/:id", (req, res) => { res.status(200).json(trends.filter(trend => trend.alertId == req.params.id)[0]) }) app.listen(9000, function () { /* eslint-disable */ console.log("Example app listening on port 9000!") /* eslint-enable */ })
alerts.push(req.body) res.send(req.body) })
random_line_split
server.ts
import {Environment} from "./environment"; import {WebhookNest} from "../nest/webhookNest"; import {WebhookJob} from "../job/webhookJob"; import * as express from "express"; import {InterfaceManager} from "../ui/interfaceManager"; import {Logger, LogQueryOptions} from "./logger"; import {Job} from "../job/job"; import ...
; /** * Sends the actual hook response. * @param holdResponse Flag to bypass sending now for held responses. * @param job Webhook job * @param nest Webhook nest * @param req * @param res * @param customHandler * @param message */ publ...
{ let s = this; // Job arrive let job = new WebhookJob(s.e, req, res); nest.arrive(job); s.sendHookResponse(nest.holdResponse, job, nest, req, res, customHandler); }
identifier_body
server.ts
import {Environment} from "./environment"; import {WebhookNest} from "../nest/webhookNest"; import {WebhookJob} from "../job/webhookJob"; import * as express from "express"; import {InterfaceManager} from "../ui/interfaceManager"; import {Logger, LogQueryOptions} from "./logger"; import {Job} from "../job/job"; import ...
(im: InterfaceManager) { let s = this; let nest = im.nest; let hook_path = s.config.hooks_prefix + nest.path; let hook_ui_path = s.config.hooks_ui_prefix + im.path; s.e.log(1, `Watching webhook interface GET ${hook_ui_path}`, s); this.hookInterfaceRoutes.push({ ...
addWebhookInterface
identifier_name
server.ts
import {Environment} from "./environment"; import {WebhookNest} from "../nest/webhookNest"; import {WebhookJob} from "../job/webhookJob"; import * as express from "express"; import {InterfaceManager} from "../ui/interfaceManager"; import {Logger, LogQueryOptions} from "./logger"; import {Job} from "../job/job"; import ...
*/ export class Server { protected server: express.Application; protected e: Environment; protected hookRoutes = []; protected hookInterfaceRoutes = []; protected upload; protected config = { hooks_prefix: "/hooks", hooks_ui_prefix: "/hooks-ui", log_prefix: "/log" ...
async = require("async"); /** * Webhook and logging server.
random_line_split
server.ts
import {Environment} from "./environment"; import {WebhookNest} from "../nest/webhookNest"; import {WebhookJob} from "../job/webhookJob"; import * as express from "express"; import {InterfaceManager} from "../ui/interfaceManager"; import {Logger, LogQueryOptions} from "./logger"; import {Job} from "../job/job"; import ...
} }; }
{ res.json(ui.getTransportInterface()); }
conditional_block
bulletBill.js
/** Represents a bullet bill enemy. Code by Rob Kleffner, 2011 */ Mario.BulletBill = function(world, x, y, dir) { this.Image = Enjine.Resources.Images["enemies"]; this.World = world; this.X = x; this.Y = y; this.Facing = dir; this.XPicO = 8; this.YPicO = 31; this.Height = 12; this.Width = 4...
return; } this.Xa = this.Facing * sideWaysSpeed; this.XFlip = this.Facing === -1; this.Move(this.Xa, 0); }; Mario.BulletBill.prototype.SubMove = function(xa, ya) { this.X += xa; return true; }; Mario.BulletBill.prototype.FireballCollideCheck = function(fireball) {...
this.X += this.Xa; this.Y += this.Ya; this.Ya *= 0.95; this.Ya += 1;
random_line_split
bulletBill.js
/** Represents a bullet bill enemy. Code by Rob Kleffner, 2011 */ Mario.BulletBill = function(world, x, y, dir) { this.Image = Enjine.Resources.Images["enemies"]; this.World = world; this.X = x; this.Y = y; this.Facing = dir; this.XPicO = 8; this.YPicO = 31; this.Height = 12; this.Width = 4...
} return false; }; Mario.BulletBill.prototype.ShellCollideCheck = function(shell) { if (this.DeadTime !== 0) { return false; } var xD = shell.X - this.X, yD = shell.Y - this.Y; if (xD > -16 && xD < 16) { if (yD > -this.Height && yD < shell.Height) { ...
{ return true; }
conditional_block
chat.js
var net = require('net'); var chatServer = net.createServer(); clientList = []; chatServer.on("connection", function(client) { client.write('Hi!\n'); client.name = client.remoteAddress + ":" + client.remotePort; client.write('Hi' + client.name + '\n'); clientList.push(client);
}); //客户端退出 client.on('end', function() { console.log(client.name + " quit"); clientList.splice(clientList.indexOf(client), 1); }); //记录错误日志 client.on('error', function(e) { console.log(e); }) }); function broadcast(msg, client) { var cleanup = []; for (var ...
client.on('data', function(data) { broadcast(data, client);
random_line_split
chat.js
var net = require('net'); var chatServer = net.createServer(); clientList = []; chatServer.on("connection", function(client) { client.write('Hi!\n'); client.name = client.remoteAddress + ":" + client.remotePort; client.write('Hi' + client.name + '\n'); clientList.push(client); client.on('data', func...
; for (var i = 0, clen = clientList.length; i < clen; i++) { if (client !== clientList[i]) { //检查socket是否可写 if (clientList[i].writable) { clientList[i].write(client.name + " says " + msg + "\n"); } else { cleanup.push(clientList[i]); ...
identifier_body
chat.js
var net = require('net'); var chatServer = net.createServer(); clientList = []; chatServer.on("connection", function(client) { client.write('Hi!\n'); client.name = client.remoteAddress + ":" + client.remotePort; client.write('Hi' + client.name + '\n'); clientList.push(client); client.on('data', func...
9000);
conditional_block
chat.js
var net = require('net'); var chatServer = net.createServer(); clientList = []; chatServer.on("connection", function(client) { client.write('Hi!\n'); client.name = client.remoteAddress + ":" + client.remotePort; client.write('Hi' + client.name + '\n'); clientList.push(client); client.on('data', func...
r cleanup = []; for (var i = 0, clen = clientList.length; i < clen; i++) { if (client !== clientList[i]) { //检查socket是否可写 if (clientList[i].writable) { clientList[i].write(client.name + " says " + msg + "\n"); } else { cleanup.push(clientLi...
{ va
identifier_name
incr_transfer_tree.py
#!/usr/bin/env python from __future__ import print_function import argparse import os import subprocess import sys from test_util import TestFailedError, run_command, \ serializeIncrParseMarkupFile def
(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='Utility for testing incremental syntax tree transfer', epilog=''' Based of a single template the utility generates a pre-edit and a post-edit file. It then verifies that the incr...
main
identifier_name
incr_transfer_tree.py
#!/usr/bin/env python from __future__ import print_function import argparse import os import subprocess import sys from test_util import TestFailedError, run_command, \ serializeIncrParseMarkupFile def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, ...
main()
conditional_block
incr_transfer_tree.py
#!/usr/bin/env python from __future__ import print_function import argparse import os import subprocess import sys from test_util import TestFailedError, run_command, \ serializeIncrParseMarkupFile def main():
help='The template file to test') parser.add_argument( '--test-case', default='', help='The test case to execute. If no test case is specified all ' 'unnamed substitutions are applied') parser.add_argument( '--temp-dir', required=True, help='A temporary direc...
parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='Utility for testing incremental syntax tree transfer', epilog=''' Based of a single template the utility generates a pre-edit and a post-edit file. It then verifies that the incrementall...
identifier_body
incr_transfer_tree.py
#!/usr/bin/env python
import argparse import os import subprocess import sys from test_util import TestFailedError, run_command, \ serializeIncrParseMarkupFile def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='Utility for testing incremental syntax tre...
from __future__ import print_function
random_line_split
children.test.js
import Microcosm from 'microcosm' describe('History node children', function() { const action = n => n it('can determine children', function() { const repo = new Microcosm() const a = repo.append(action) const b = repo.append(action) repo.checkout(a) const c = repo.append(action) expec...
expect(b.children).toEqual([c, d]) }) })
random_line_split
forknotify.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -alertnotify option.""" import os import time from test_framework.test_framework import Bitco...
if os.path.exists(self.alert_filename) and os.path.getsize(self.alert_filename): break time.sleep(0.1) timeout -= 0.1 else: assert False, "-alertnotify did not warn of up-version blocks" with open(self.alert_filename, 'r', encoding='utf8')...
self.sync_all() # Give bitcoind 10 seconds to write the alert notification timeout = 10.0 while timeout > 0:
random_line_split
forknotify.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -alertnotify option.""" import os import time from test_framework.test_framework import Bitco...
(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 def setup_network(self): self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") with open(self.alert_filename, 'w', encoding='utf8'): pass # Just open then close to create zero-length file ...
ForkNotifyTest
identifier_name
forknotify.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -alertnotify option.""" import os import time from test_framework.test_framework import Bitco...
else: assert False, "-alertnotify did not warn of up-version blocks" with open(self.alert_filename, 'r', encoding='utf8') as f: alert_text = f.read() # Mine more up-version blocks, should not get more alerts: self.nodes[1].generate(1) self.sync_all() ...
if os.path.exists(self.alert_filename) and os.path.getsize(self.alert_filename): break time.sleep(0.1) timeout -= 0.1
conditional_block
forknotify.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -alertnotify option.""" import os import time from test_framework.test_framework import Bitco...
def setup_network(self): self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") with open(self.alert_filename, 'w', encoding='utf8'): pass # Just open then close to create zero-length file self.extra_args = [["-blockversion=2", "-alertnotify=echo %s >> \"" + self...
self.num_nodes = 2
identifier_body
baseAnimationNode.py
from RGT.XML.SVG.basicSvgNode import BasicSvgNode from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes from RGT.XML.SVG.Attribs.xlinkAttributes import XlinkAttributes from RGT.XML.SVG.Attribs.animationTimingAttributes import AnimationTimingAttributes class BaseAnimatio...
def getExternalResourcesRequired(self): node = self._getNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED) if node is not None: return node.nodeValue return None
self._setNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED, data)
conditional_block
baseAnimationNode.py
from RGT.XML.SVG.basicSvgNode import BasicSvgNode from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes from RGT.XML.SVG.Attribs.xlinkAttributes import XlinkAttributes from RGT.XML.SVG.Attribs.animationTimingAttributes import AnimationTimingAttributes class
(BasicSvgNode): ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED = 'externalResourcesRequired' def __init__(self, ownerDoc, tagName): BasicSvgNode.__init__(self, ownerDoc, tagName) ConditionalProcessingAttributes.__init__(self) XlinkAttributes.__init__(self) AnimationTimingAttribu...
BaseAnimationNode
identifier_name
baseAnimationNode.py
from RGT.XML.SVG.basicSvgNode import BasicSvgNode from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes from RGT.XML.SVG.Attribs.xlinkAttributes import XlinkAttributes from RGT.XML.SVG.Attribs.animationTimingAttributes import AnimationTimingAttributes class BaseAnimatio...
node = self._getNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED) if node is not None: return node.nodeValue return None
identifier_body
baseAnimationNode.py
from RGT.XML.SVG.basicSvgNode import BasicSvgNode from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes from RGT.XML.SVG.Attribs.xlinkAttributes import XlinkAttributes from RGT.XML.SVG.Attribs.animationTimingAttributes import AnimationTimingAttributes class BaseAnimatio...
return node.nodeValue return None
node = self._getNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED) if node is not None:
random_line_split
__init__.py
"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNo...
if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoo...
hass.data[DOMAIN][BTLE_LOCK] = Lock()
conditional_block
__init__.py
"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNo...
# Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it...
random_line_split
__init__.py
"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNo...
(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.con...
_async_update_listener
identifier_name
__init__.py
"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNo...
"""Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id)
identifier_body
coerce-match-calls.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 _: Box<[isize]> = if true { Box::new([1, 2, 3]) } else { Box::new([1]) }; let _: Box<[isize]> = match true { true => Box::new([1, 2, 3]), false => Box::new([1]) }; // Check we don't get over-keen at propagating coercions in the case of casts. let x = if true { 42 } else { 42u8 } as u16; l...
main
identifier_name
coerce-match-calls.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 ...
// Check we don't get over-keen at propagating coercions in the case of casts. let x = if true { 42 } else { 42u8 } as u16; let x = match true { true => 42, false => 42u8 } as u16; }
let _: Box<[isize]> = match true { true => Box::new([1, 2, 3]), false => Box::new([1]) };
random_line_split
coerce-match-calls.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 _: Box<[isize]> = if true { Box::new([1, 2, 3]) } else { Box::new([1]) }; let _: Box<[isize]> = match true { true => Box::new([1, 2, 3]), false => Box::new([1]) }; // Check we don't get over-keen at propagating coercions in the case of casts. let x = if true { 42 } else { 42u8 } as u16; let ...
identifier_body
logger.js
'use strict' var stringifySync = require('./safe-json').stringifySync var util = require('util') var Readable = require('readable-stream') var os = require('os') module.exports = Logger var LEVELS = { 'trace': 10, 'debug': 20, 'info': 30, 'warn': 40, 'error': 50, 'fatal': 60 } util.inherits(Logger, Read...
return LEVELS[value] || 50 } Logger.prototype.child = function child(extra) { var childLogger = Object.create(loggingFunctions) childLogger.extra = util._extend({}, this.extra) util._extend(childLogger.extra, extra) var parent = this childLogger.write = function write(level, args, extra) { extra = ...
{ // value is numeric if (value < 10) value = 10 if (value > 60) value = 60 return value }
conditional_block
logger.js
'use strict' var stringifySync = require('./safe-json').stringifySync var util = require('util') var Readable = require('readable-stream') var os = require('os') module.exports = Logger var LEVELS = { 'trace': 10, 'debug': 20, 'info': 30, 'warn': 40, 'error': 50, 'fatal': 60 } util.inherits(Logger, Read...
{ this.v = 0 this.level = level this.name = logger.name this.hostname = logger.hostname this.pid = process.pid this.time = new Date().toISOString() this.msg = msg }
identifier_body
logger.js
'use strict' var stringifySync = require('./safe-json').stringifySync var util = require('util') var Readable = require('readable-stream') var os = require('os') module.exports = Logger var LEVELS = { 'trace': 10, 'debug': 20, 'info': 30, 'warn': 40, 'error': 50, 'fatal': 60 } util.inherits(Logger, Read...
(options, extra) { if (!(this instanceof Logger)) { return new Logger(options, extra) } Readable.call(this) this.name = options.name this._level = this.coerce(options.level) this.hostname = options.hostname || os.hostname() this.extra = extra || {} this.buffer = '' this.enabled = options.enabled ...
Logger
identifier_name
logger.js
'use strict' var stringifySync = require('./safe-json').stringifySync var util = require('util') var Readable = require('readable-stream') var os = require('os') module.exports = Logger var LEVELS = { 'trace': 10, 'debug': 20, 'info': 30, 'warn': 40, 'error': 50, 'fatal': 60 } util.inherits(Logger, Read...
this.v = 0 this.level = level this.name = logger.name this.hostname = logger.hostname this.pid = process.pid this.time = new Date().toISOString() this.msg = msg }
} function Entry(logger, level, msg) {
random_line_split
orf.rs
// Copyright 2014-2016 Johannes Köster, Martin Larralde. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! One-way orf finder algorithm. //! //! Complexity: O(n). //! //! # Example //! //! ``` //! use ...
for (index, &nuc) in self.seq.by_ref() { // update the codon if self.state.codon.len() >= 3 { self.state.codon.pop_front(); } self.state.codon.push_back(nuc); offset = (index + 1) % 3; // inside orf if self.stat...
let mut offset: usize;
random_line_split
orf.rs
// Copyright 2014-2016 Johannes Köster, Martin Larralde. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! One-way orf finder algorithm. //! //! Complexity: O(n). //! //! # Example //! //! ``` //! use ...
else if self.finder.start_codons.contains(&self.state.codon) { self.state.start_pos[offset] = Some(index); } if result.is_some() { return result; } } None } } #[cfg(test)] mod tests { use super::*; #[test] fn test_orf(...
// check if leaving orf if self.finder.stop_codons.contains(&self.state.codon) { // check if length is sufficient if index + 1 - self.state.start_pos[offset].unwrap() > self.finder.min_len { // build results ...
conditional_block
orf.rs
// Copyright 2014-2016 Johannes Köster, Martin Larralde. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! One-way orf finder algorithm. //! //! Complexity: O(n). //! //! # Example //! //! ``` //! use ...
{ pub start: usize, pub end: usize, pub offset: i8, } /// The current algorithm state. struct State { start_pos: [Option<usize>; 3], codon: VecDeque<u8>, } impl State { /// Create new state. pub fn new() -> Self { State { start_pos: [None, None, None], codon...
rf
identifier_name
Verifier.ts
import ArgumentNullException from '../ArgumentNullException'; import ArgumentException from '../ArgumentException'; /** * Verifier is an instance, usually created using the Verify utility, to * chain argument validations for a particular value. */ class Verifier { private _argument: any; private _argumentName...
return this; } /** * Throws an error if the arguments contains a null or empty value. * @returns Verifier - The Verifier instance, used for chaining. */ public isNotNullOrEmpty(): Verifier { this.isNotNull(); if (this._argument.length === 0) { throw new ArgumentExcept...
{ throw new ArgumentNullException(this._argumentName); }
conditional_block
Verifier.ts
import ArgumentNullException from '../ArgumentNullException'; import ArgumentException from '../ArgumentException'; /** * Verifier is an instance, usually created using the Verify utility, to * chain argument validations for a particular value. */ class Verifier { private _argument: any; private _argumentName...
(): Verifier { if (this._argument === null || this._argument === undefined) { throw new ArgumentNullException(this._argumentName); } return this; } /** * Throws an error if the arguments contains a null or empty value. * @returns Verifier - The Verifier instance, used for chai...
isNotNull
identifier_name
Verifier.ts
import ArgumentNullException from '../ArgumentNullException'; import ArgumentException from '../ArgumentException'; /** * Verifier is an instance, usually created using the Verify utility, to * chain argument validations for a particular value. */ class Verifier { private _argument: any; private _argumentName...
} export default Verifier;
{ this.isNotNull(); if (this._argument.length === 0) { throw new ArgumentException(this._argumentName, this._argumentName + ' cannot be empty.'); } return this; }
identifier_body
Verifier.ts
import ArgumentNullException from '../ArgumentNullException'; import ArgumentException from '../ArgumentException'; /** * Verifier is an instance, usually created using the Verify utility, to
private _argumentName: string; /** * Creates a new instance. * @param {any} argument - The value of the argument being validated. * @param {string} argumentName - The name of the argument being validated. */ constructor(argument: any, argumentName: string) { if (argumentName == undefin...
* chain argument validations for a particular value. */ class Verifier { private _argument: any;
random_line_split
settings.py
""" Django settings for findtorun project. Generated by 'django-admin startproject' using Django 1.11.2. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import ...
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://d...
AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {
random_line_split
urls.py
# -*- coding: utf-8 -*- # # Copyright 2016 edX PDR Lab, National Central University, Taiwan. # # http://edxpdrlab.ncu.cc/ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
urlpatterns += [ url(r'^400/$', 'django.views.defaults.bad_request'), url(r'^403/$', 'django.views.defaults.permission_denied'), url(r'^404/$', 'django.views.defaults.page_not_found'), url(r'^500/$', 'django.views.defaults.server_error'), ]
conditional_block
urls.py
# -*- coding: utf-8 -*- # # Copyright 2016 edX PDR Lab, National Central University, Taiwan. # # http://edxpdrlab.ncu.cc/ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
url(r'^403/$', 'django.views.defaults.permission_denied'), url(r'^404/$', 'django.views.defaults.page_not_found'), url(r'^500/$', 'django.views.defaults.server_error'), ]
urlpatterns += [ url(r'^400/$', 'django.views.defaults.bad_request'),
random_line_split
workers.controller.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ class Workers { con...
glBreadcrumbService.setBreadcrumb(breadcrumb); }; $scope.$on('$stateChangeSuccess', setupGl); setupGl(); $scope.worker_infos = []; for (worker of Array.from(workers)) { worker.num_connections = worker.connected_to.length; ...
} // reinstall breadcrumb when coming back from forcesched const setupGl = function() { glTopbarContextualActionsService.setContextualActions(actions);
random_line_split
workers.controller.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ class Workers { con...
}); } else { actions.push({ caption: "Actions...", extra_class: "btn-default", action() { return $state.go("workers.actions"); } }); } ...
{ return $state.go("worker.actions"); }
identifier_body
workers.controller.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ class Workers { con...
if ($stateParams.worker != null) { $scope.builds = (builds = data.getBuilds({ limit: $scope.numbuilds, workerid: +$stateParams.worker, order: '-started_at'})); } else { builds = data.getBuilds({limit: $scope.numbuilds, order: '-started_at'}); } da...
{ $scope.numbuilds = +$stateParams.numbuilds; }
conditional_block
workers.controller.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ class Workers {
($scope, dataService, bbSettingsService, resultsService, dataGrouperService, $stateParams, $state, glTopbarContextualActionsService, glBreadcrumbService) { let builds; $scope.capitalize = _.capitalize; _.mixin($scope, resultsService); $scope.getUniqueBuilders = function(worker) { ...
constructor
identifier_name
echo_cmdline_client.py
#!/usr/bin/env python3 """ echo_cmdline_client.py Copyright (c) 2018-2019 Alan Yorinks All right reserved. Python Banyan is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your ...
def __init__(self, **kwargs): """ kwargs is a dictionary that will contain the following keys: :param back_plane_ip_address: banyan_base back_planeIP Address - if not specified, it will be set to the local computer ...
-n PROCESS_NAME Set process name in banner -p PUBLISHER_PORT Publisher IP port -s SUBSCRIBER_PORT Subscriber IP port -t LOOP_TIME Event Loop Timer in seconds """
random_line_split
echo_cmdline_client.py
#!/usr/bin/env python3 """ echo_cmdline_client.py Copyright (c) 2018-2019 Alan Yorinks All right reserved. Python Banyan is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your ...
args = parser.parse_args() if args.back_plane_ip_address == 'None': args.back_plane_ip_address = None kw_options = {'back_plane_ip_address': args.back_plane_ip_address, 'number_of_messages': int(args.number_of_messages), 'publisher_port': args.publisher_port, ...
parser = argparse.ArgumentParser() # allow user to bypass the IP address auto-discovery. # This is necessary if the component resides on a computer # other than the computing running the backplane. parser.add_argument("-b", dest="back_plane_ip_address", default="None", help="None...
identifier_body
echo_cmdline_client.py
#!/usr/bin/env python3 """ echo_cmdline_client.py Copyright (c) 2018-2019 Alan Yorinks All right reserved. Python Banyan is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your ...
(BanyanBase): """ This is an echo client that will allow the user to specify command line arguments to change the default behavior of the client. It sends out a series of messages and expects an echo reply from the server. When it completes, press enter, and it will send a message to the se...
EchoCmdClient
identifier_name
echo_cmdline_client.py
#!/usr/bin/env python3 """ echo_cmdline_client.py Copyright (c) 2018-2019 Alan Yorinks All right reserved. Python Banyan is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your ...
echo_cmdline_client()
conditional_block
datamanager.py
import os import string import types import time import shutil import log import copy #import logging #import utility from testproblem import TestProblem from mafrw import Agent from .. import config class DataManager(Agent): """ An object of this class is responsable to collect data, support access to...
def collect_data(self, message): (paramValues, problem, measureFile) = message.content['proposition'] f = open(measureFile) f.close() return # Private methods def query_data(self, parameters=None, problem=None): return None
(paramValues, problem) = message.content['proposition'] measureValues = self.query_data(parameters=paramValues, problem=problem) # If getting data is successful if measureValues is not None: # Create a reply message whose content contains the ...
identifier_body
datamanager.py
import os import string import types import time import shutil import log import copy #import logging #import utility from testproblem import TestProblem from mafrw import Agent from .. import config class DataManager(Agent): """ An object of this class is responsable to collect data, support access to...
self.send_message(msg) return def find_data(self, info): (paramValues, problem) = message.content['proposition'] measureValues = self.query_data(parameters=paramValues, problem=problem) # If getting data is successful if meas...
msg = Message(sender=self.id, performative='inform', content={'proposition':{'what':'data-availability', 'how':'partial', 'data':dataEntry} ...
conditional_block
datamanager.py
import os import string import types import time import shutil import log import copy #import logging #import utility from testproblem import TestProblem from mafrw import Agent from .. import config class DataManager(Agent): """ An object of this class is responsable to collect data, support access to...
return # Message handlers def add_data(self, info): if info is None: return paramTag = info['proposition']['parameter-tag'] prob = info['proposition']['problem'] data = info['proposition']['values'] # Update the entry self.update(parameterTag...
random_line_split
datamanager.py
import os import string import types import time import shutil import log import copy #import logging #import utility from testproblem import TestProblem from mafrw import Agent from .. import config class DataManager(Agent): """ An object of this class is responsable to collect data, support access to...
(self, info): (paramValues, problem) = message.content['proposition'] measureValues = self.query_data(parameters=paramValues, problem=problem) # If getting data is successful if measureValues is not None: # Create a reply message whose...
find_data
identifier_name
ibos.select2.js
/** * 基于jquery.select2扩展的select插件,基本使用请参考select2相关文档 * 默认是多选模式,并提供了input模式下的初始化方法,对应的数据格式是{ id: 1, text: "Hello" } * 这里的参数只对扩展的部分作介绍 * filter、includes、excludes、query四个参数是互斥的,理论只能有其一个参数 * @method ibosSelect * @param option.filter * @param {Function} option.filter 用于过滤源数据的函数 * @param {Array} option.includes...
} // 当有filter属性时,将使用自定义的query方法替代原来的query方法,filter用于从源数据层面上过滤不需要出现的数据 if(option.filter){ option.query = function(query) { _queryWithFilter(query, option.filter); } } // 使用pinyin搜索引擎 if(option.pinyin) { var _customMatcher = option.matcher; option.matcher = function(term){ if(...
option.filter = function(datum){ return $.inArray(datum.id, option.excludes) === -1; }
random_line_split
ibos.select2.js
/** * 基于jquery.select2扩展的select插件,基本使用请参考select2相关文档 * 默认是多选模式,并提供了input模式下的初始化方法,对应的数据格式是{ id: 1, text: "Hello" } * 这里的参数只对扩展的部分作介绍 * filter、includes、excludes、query四个参数是互斥的,理论只能有其一个参数 * @method ibosSelect * @param option.filter * @param {Function} option.filter 用于过滤源数据的函数 * @param {Array} option.includes...
tTextById(id, data[i].children); if(typeof ret !== "undefined"){ break; } } else { if(data[i].id + "" === id) { ret = data[i].text; break; } } } return ret; } var defaults = { multiple: true, pinyin: true, formatResultCssClass: function(data){ return data.cls; }, ...
a.length; i++){ if(data[i].children){ ret = _ge
conditional_block
gproc.e.py
''' This script demonstrates how to create a periodic Gaussian process using the *gpiso* function. ''' import numpy as np import matplotlib.pyplot as plt from sympy import sin, exp, pi from rbf.basis import get_r, get_eps, RBF from rbf.gproc import gpiso np.random.seed(1) period = 5.0 cls = 0.5 # characteristic le...
plt.show()
random_line_split
face-detection-rectangle.js
var cv = require('../lib/opencv'); var COLOR = [0, 255, 0]; // default red var thickness = 2; // default 1 cv.readImage('./files/mona.png', function(err, im) { if (err) throw err; if (im.width() < 1 || im.height() < 1) throw new Error('Image has no size'); im.detectObject('../data/haarcascade_frontalface_alt2....
}); });
random_line_split
wordomat.py
switch to text or grep panel depending # Panel 3 - Options self.g3 = Group((padd, 5, groupW, 48)) self.g3.checkbox0 = CheckBox((bPadd, 2, 18, 18), "", sizeStyle="small", value=self.banRepetitions) self.g3.checkLabel = TextBox((18, 4, -bPadd, 18), "No repeating characters per word", siz...
conditional_block
wordomat.py
"wordCount": [0, self.wordCount, 20], "minLength": [108, self.minLength, 3], "maxLength": [145, self.maxLength, 10], } topLineLabels = { "wcText": [31, 78, 'words with', 'left'], "lenTextTwo": [133, 10, u'–', 'center'], "lenTextTh...
"Initialize word-o-mat UI, open the window.""" # load stuff self.loadPrefs() self.loadDictionaries() # Observers for font events addObserver(self, lambda: self.g1.base.enable(True), "fontDidOpen") addObserver(self, "fontClosed", "fontWillClose") # The rest of t...
identifier_body