file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
HypothermicPresence.tsx
import React from "react"; import Analyzer, { Options } from "parser/core/Analyzer"; import SPELLS from "common/SPELLS"; import Statistic from "parser/ui/Statistic"; import { STATISTIC_ORDER } from "parser/ui/StatisticBox";
import BoringSpellValue from "parser/ui/BoringSpellValue"; import RunicPowerTracker from "../runicpower/RunicPowerTracker"; /** reduces the Runic Power cost of your abilities by 35% for 8 sec */ class HypothermicPresence extends Analyzer { static dependencies = { runicPowerTracker: RunicPowerTracker, } pro...
random_line_split
HypothermicPresence.tsx
import React from "react"; import Analyzer, { Options } from "parser/core/Analyzer"; import SPELLS from "common/SPELLS"; import Statistic from "parser/ui/Statistic"; import { STATISTIC_ORDER } from "parser/ui/StatisticBox"; import BoringSpellValue from "parser/ui/BoringSpellValue"; import RunicPowerTracker from "../...
(options: Options) { super(options); this.active = this.selectedCombatant.hasTalent(SPELLS.HYPOTHERMIC_PRESENCE_TALENT.id); if (!this.active) { return; } } statistic() { return ( <Statistic position={STATISTIC_ORDER.OPTIONAL(50)} size="flexible" > <BoringSp...
constructor
identifier_name
non_ts_pseudo_class_list.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/. */ /* * This file contains a helper macro includes all supported non-tree-structural * pseudo-classes. * * FIXME...
("focus", Focus, focus, IN_FOCUS_STATE, _), ("focus-within", FocusWithin, focusWithin, IN_FOCUS_WITHIN_STATE, _), ("hover", Hover, hover, IN_HOVER_STATE, _), ("-moz-drag-over", MozDragOver, mozDragOver, IN_DRAGOVER_STATE, _), ("target", Tar...
("visited", Visited, visited, IN_VISITED_STATE, _), ("active", Active, active, IN_ACTIVE_STATE, _), ("checked", Checked, checked, IN_CHECKED_STATE, _), ("disabled", Disabled, disabled, IN_DISABLED_STATE, _), ("enabled", Enabled, enabled, IN...
random_line_split
view-pulse.js
var Gelato_Pulse = { form : null, init: function() { Gelato_Pulse.form = jQuery( '.pulse-form' ); jQuery('<input />') .attr( 'type', 'hidden' ) .attr( 'class', 'ss_synctime' ) .attr( 'name', 'ss_synctime' ) .appendTo( Gelato_Pulse.form ); Gelato_Pulse.form.find( 'textarea').keyup( function(...
for ( index in list ) { Gelato_Pulse.addPulse( list[index], list[index].synctime, false ); } }, addPulse: function( data, start, sort ) { var new_pulse = Pulse_CPT_Form.single_pulse_template( data ); Gelato_Media.media.pulse( { start: start, end: Gelato_Media.media.duration(), text: new_pulse...
random_line_split
view-pulse.js
var Gelato_Pulse = { form : null, init: function() { Gelato_Pulse.form = jQuery( '.pulse-form' ); jQuery('<input />') .attr( 'type', 'hidden' ) .attr( 'class', 'ss_synctime' ) .attr( 'name', 'ss_synctime' ) .appendTo( Gelato_Pulse.form ); Gelato_Pulse.form.find( 'textarea').keyup( function(...
}, loadMarkers: function() { if( typeof gelatoScoop.bookmarks != 'undefined') { for ( index in gelatoScoop.bookmarks.list ) { var bookmark = gelatoScoop.bookmarks.list[index]; Gelato_Media.media.pulse( { start: bookmark.synctime, end: Gelato_Media.media.duration(), text: '<a ...
{ // We are interested var pulse_data = jQuery.parseJSON(data.data); Gelato_Pulse.addPulse( pulse_data, pulse_data.synctime, true ); }
conditional_block
aurelia-loader.d.ts
declare module 'aurelia-loader' { import * as core from 'core-js'; import { relativeToFile } from 'aurelia-path'; import { Origin } from 'aurelia-metadata'; /*eslint no-unused-vars:0*/ export interface LoaderPlugin { fetch(address: string): Promise<any>; } export class TemplateDependency { co...
loadAllModules(ids: string[]): Promise<any[]>; loadTemplate(url: string): Promise<TemplateRegistryEntry>; loadText(url: string): Promise<string>; applyPluginToUrl(url: string, pluginName: string): string; addPlugin(pluginName: string, implementation: LoaderPlugin): void; getOrCreateTemplateRegis...
constructor(); loadModule(id: string): Promise<any>;
random_line_split
aurelia-loader.d.ts
declare module 'aurelia-loader' { import * as core from 'core-js'; import { relativeToFile } from 'aurelia-path'; import { Origin } from 'aurelia-metadata'; /*eslint no-unused-vars:0*/ export interface LoaderPlugin { fetch(address: string): Promise<any>; } export class
{ constructor(src: string, name?: string); } export class TemplateRegistryEntry { constructor(address: string); templateIsLoaded(): boolean; isReady(): boolean; setTemplate(template: Element): void; addDependency(src: string | Function, name?: string): void; setResources(resources: any)...
TemplateDependency
identifier_name
setup.py
from distutils.core import setup, Extension include_dirs = ['/usr/include', '/usr/local/include'] library_dirs = ['/usr/lib', '/usr/local/lib'] libraries = ['jpeg'] runtime_library_dirs = [] extra_objects = [] define_macros = [] setup(name = "pyjpegoptim",
version = "0.1.1", author = "Guangming Li", author_email = "leeful@gmail.com", license = "GPL", description = 'a utility for optimizing JPEG files', url = "https://github.com/cute/pyjpegoptim", keywords = ['JpegOptim', 'TinyJpeg'], packages = ["pyjpegoptim"], ext_pa...
random_line_split
update.rs
#![feature(test)] extern crate protocoll; extern crate test; use test::Bencher; use protocoll::Map; use std::collections::HashMap; #[bench] fn imperative(b: &mut Bencher) { let sent = "a short treatise on fungi"; b.iter(|| { let mut letters = HashMap::new(); for ch in sent.chars() { ...
let sent = "a short treatise on fungi"; b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update_in_place(c, 0, |n| *n += 1))) }
#[bench] fn in_place(b: &mut Bencher) {
random_line_split
update.rs
#![feature(test)] extern crate protocoll; extern crate test; use test::Bencher; use protocoll::Map; use std::collections::HashMap; #[bench] fn imperative(b: &mut Bencher) { let sent = "a short treatise on fungi"; b.iter(|| { let mut letters = HashMap::new(); for ch in sent.chars() { ...
#[bench] fn in_place(b: &mut Bencher) { let sent = "a short treatise on fungi"; b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update_in_place(c, 0, |n| *n += 1))) }
{ let sent = "a short treatise on fungi"; b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update(c, |n| 1 + n.unwrap_or(0)))) }
identifier_body
update.rs
#![feature(test)] extern crate protocoll; extern crate test; use test::Bencher; use protocoll::Map; use std::collections::HashMap; #[bench] fn imperative(b: &mut Bencher) { let sent = "a short treatise on fungi"; b.iter(|| { let mut letters = HashMap::new(); for ch in sent.chars() { ...
(b: &mut Bencher) { let sent = "a short treatise on fungi"; b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update(c, |n| 1 + n.unwrap_or(0)))) } #[bench] fn in_place(b: &mut Bencher) { let sent = "a short treatise on fungi"; b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update_in_place(c, ...
functional
identifier_name
module_geokick.py
# -*- coding: utf-8 -*- import sys import pygeoip import os.path import socket import sqlite3 import time import re DATAFILE = os.path.join(sys.path[0], "GeoIP.dat") # STANDARD = reload from disk # MEMORY_CACHE = load to memory # MMAP_CACHE = memory using mmap gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE) def ...
(createTable=False, db="module_geokick.db"): conn = sqlite3.connect(db) c = conn.cursor() if createTable: c.execute('CREATE TABLE IF NOT EXISTS exceptions (hostmask);') conn.commit() return conn, c def command_geo_exempt(bot, user, channel, args): """.geo_exempt nick!ident@hostname | Supports wildca...
open_DB
identifier_name
module_geokick.py
# -*- coding: utf-8 -*- import sys import pygeoip import os.path import socket import sqlite3 import time import re DATAFILE = os.path.join(sys.path[0], "GeoIP.dat") # STANDARD = reload from disk # MEMORY_CACHE = load to memory # MMAP_CACHE = memory using mmap gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE) def ...
def command_geo_remove(bot, user, channel, args): """.geo_remove hostname""" if get_op_status(user): conn, c = open_DB() c.execute("SELECT hostmask FROM exceptions WHERE hostmask = '" + args + "'") if c.fetchone(): conn, c = open_DB() c.execute("DELETE FROM exceptions WHERE hostmask = '" ...
if get_op_status(user): conn, c = open_DB() c.execute('SELECT hostmask FROM exceptions;') rows = c.fetchall() conn.close() if rows: excepts = str("") for i in rows: excepts += "[" + i[0] + "] " return bot.say(channel, "Exceptions: " + excepts) else: return bot.say...
identifier_body
module_geokick.py
# -*- coding: utf-8 -*- import sys import pygeoip import os.path import socket import sqlite3 import time import re DATAFILE = os.path.join(sys.path[0], "GeoIP.dat") # STANDARD = reload from disk # MEMORY_CACHE = load to memory # MMAP_CACHE = memory using mmap gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE) def ...
bot.say(channel, "Success: " + args.encode('utf-8') + " added to exempt list.") return True else: return bot.say(channel, "Error: invalid exempt. See .help geo_exempt") else: return bot.say(channel, "Error: exempt exists already!") def command_geo_list(bot, user, channel, arg...
c.execute(insert) conn.commit() conn.close()
random_line_split
module_geokick.py
# -*- coding: utf-8 -*- import sys import pygeoip import os.path import socket import sqlite3 import time import re DATAFILE = os.path.join(sys.path[0], "GeoIP.dat") # STANDARD = reload from disk # MEMORY_CACHE = load to memory # MMAP_CACHE = memory using mmap gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE) def ...
def command_geo_remove(bot, user, channel, args): """.geo_remove hostname""" if get_op_status(user): conn, c = open_DB() c.execute("SELECT hostmask FROM exceptions WHERE hostmask = '" + args + "'") if c.fetchone(): conn, c = open_DB() c.execute("DELETE FROM exceptions WHERE hostmask = '" ...
conn, c = open_DB() c.execute('SELECT hostmask FROM exceptions;') rows = c.fetchall() conn.close() if rows: excepts = str("") for i in rows: excepts += "[" + i[0] + "] " return bot.say(channel, "Exceptions: " + excepts) else: return bot.say(channel, "Error: no excepti...
conditional_block
notebook-repos.component.ts
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed und...
data.settings[name] = selected; }); this.notebookRepoService.updateRepo(data).subscribe(() => { this.getRepos(); }); } }
settings: {} }; repo.settings.forEach(({ name, selected }) => {
random_line_split
notebook-repos.component.ts
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed und...
implements OnInit { repositories: NotebookRepo[] = []; constructor(private notebookRepoService: NotebookRepoService, private cdr: ChangeDetectorRef) {} ngOnInit() { this.getRepos(); } getRepos() { this.notebookRepoService.getRepos().subscribe(data => { this.repositories = data.sort((a, b) =>...
NotebookReposComponent
identifier_name
notebook-repos.component.ts
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed und...
getRepos() { this.notebookRepoService.getRepos().subscribe(data => { this.repositories = data.sort((a, b) => a.name.charCodeAt(0) - b.name.charCodeAt(0)); this.cdr.markForCheck(); }); } updateRepoSetting(repo: NotebookRepo) { const data = { name: repo.className, settings: {}...
{ this.getRepos(); }
identifier_body
main.py
"""A guestbook sample with sqlite3.""" import logging import os import jinja2 import sqlite3 import webapp2 from google.appengine.api import app_identity from google.appengine.api import modules from google.appengine.api import runtime from google.appengine.api import users from google.appengine.ext import ndb JINJ...
template = JINJA_ENVIRONMENT.get_template('index.html') url, url_linktext = get_signin_navigation(self.request.uri) self.response.out.write(template.render(servers=servers, url=url, url_linktext=url_...
instance_id = key.string_id() servers.append((instance_id, get_url_for_instance(instance_id)))
conditional_block
main.py
"""A guestbook sample with sqlite3.""" import logging import os import jinja2 import sqlite3 import webapp2 from google.appengine.api import app_identity from google.appengine.api import modules from google.appengine.api import runtime from google.appengine.api import users from google.appengine.ext import ndb JINJ...
(cls, instance_id): """Return a key for the given instance_id. Args: An instance id for the server. Returns: A Key object which has a common parent key with the name 'Root'. """ return ndb.Key(cls, 'Root', cls, instance_id) class ListServers(webapp2.Re...
get_instance_key
identifier_name
main.py
"""A guestbook sample with sqlite3.""" import logging import os import jinja2 import sqlite3 import webapp2 from google.appengine.api import app_identity from google.appengine.api import modules from google.appengine.api import runtime from google.appengine.api import users from google.appengine.ext import ndb JINJ...
class Start(webapp2.RequestHandler): """A handler for /_ah/start.""" def get(self): """A handler for /_ah/start, registering myself.""" runtime.set_shutdown_hook(shutdown_hook) con = get_connection() with con: con.execute(CREATE_TABLE_SQL) instance_id = mo...
"""A handler for storing a message.""" def post(self): """A handler for storing a message.""" author = '' if users.get_current_user(): author = users.get_current_user().nickname() con = get_connection() with con: con.execute(INSERT_SQL, (author, self....
identifier_body
main.py
"""A guestbook sample with sqlite3.""" import logging import os import jinja2 import sqlite3 import webapp2 from google.appengine.api import app_identity from google.appengine.api import modules from google.appengine.api import runtime from google.appengine.api import users from google.appengine.ext import ndb JINJ...
self.response.out.write(template.render(servers=servers, url=url, url_linktext=url_linktext)) class MainPage(webapp2.RequestHandler): """A handler for showing the guestbook form.""" def get(self): ...
template = JINJA_ENVIRONMENT.get_template('index.html') url, url_linktext = get_signin_navigation(self.request.uri)
random_line_split
ImagePlugin.tsx
import * as React from 'react'; import * as draftjs from 'draft-js'; import { IContentStateConverter, HtmlEditorController, HtmlEditorPlugin } from "../HtmlEditor" import { HtmlContentStateConverter } from '../HtmlContentStateConverter'; export interface ImageConverter<T extends object> { uploadData(blob: Blob...
return blob; } function ImageComponent(p: { contentState: draftjs.ContentState, block: draftjs.ContentBlock, blockProps: { imageConverter: ImageConverter<any> } }) { const data = p.contentState.getEntity(p.block.getEntityAt(0)).getData(); return p.blockProps.imageConverter!.renderImage(data); }
var blob = new Blob([ab], { type: mimeString });
random_line_split
ImagePlugin.tsx
import * as React from 'react'; import * as draftjs from 'draft-js'; import { IContentStateConverter, HtmlEditorController, HtmlEditorPlugin } from "../HtmlEditor" import { HtmlContentStateConverter } from '../HtmlContentStateConverter'; export interface ImageConverter<T extends object> { uploadData(blob: Blob...
if (oldPasteText) return oldPasteText(text, html, editorState); return "not-handled"; }; props.handleDroppedFiles = (selection, files) => { const imageFiles = files.filter(a => a.type.startsWith("image/")); if (imageFiles.length == 0) return "not-handled"; ...
{ var node = document.createElement('html') node.innerHTML = html; var array = Array.from(node.getElementsByTagName("img")); if (array.length && array.every(a => a.src.startsWith("data:"))) { var blobs = array.map(a => dataURItoBlob(a.src)); Promise.all(blobs.ma...
conditional_block
ImagePlugin.tsx
import * as React from 'react'; import * as draftjs from 'draft-js'; import { IContentStateConverter, HtmlEditorController, HtmlEditorPlugin } from "../HtmlEditor" import { HtmlContentStateConverter } from '../HtmlContentStateConverter'; export interface ImageConverter<T extends object> { uploadData(blob: Blob...
{ const data = p.contentState.getEntity(p.block.getEntityAt(0)).getData(); return p.blockProps.imageConverter!.renderImage(data); }
identifier_body
ImagePlugin.tsx
import * as React from 'react'; import * as draftjs from 'draft-js'; import { IContentStateConverter, HtmlEditorController, HtmlEditorPlugin } from "../HtmlEditor" import { HtmlContentStateConverter } from '../HtmlContentStateConverter'; export interface ImageConverter<T extends object> { uploadData(blob: Blob...
(editorState: draftjs.EditorState, data: Object): draftjs.EditorState { const contentState = editorState.getCurrentContent(); const contentStateWithEntity = contentState.createEntity( 'IMAGE', 'IMMUTABLE', data ); const entityKey = contentStateWithEntity.getLastCreatedEntityKe...
addImage
identifier_name
main.js
var $animText = $("#anim_text"); $animText.html( $animText.html().replace(/./g, "<span>$&</span>").replace(/\s/g, "&nbsp;")); //TweenMax.staggerFromTo( $animText.find("span"), 0.1, {autoAlpha:0}, {autoAlpha:1}, 0.1 ); $animText.find("span").each(function(){ TweenMax.fromTo(this, 2.5, {autoAlpha:0, rotation:rando...
{ return Math.random() * (max - min) + min; }
identifier_body
main.js
var $animText = $("#anim_text"); $animText.html( $animText.html().replace(/./g, "<span>$&</span>").replace(/\s/g, "&nbsp;")); //TweenMax.staggerFromTo( $animText.find("span"), 0.1, {autoAlpha:0}, {autoAlpha:1}, 0.1 ); $animText.find("span").each(function(){ TweenMax.fromTo(this, 2.5, {autoAlpha:0, rotation:rando...
(min, max) { return Math.random() * (max - min) + min; }
randomNum
identifier_name
main.js
var $animText = $("#anim_text"); $animText.html( $animText.html().replace(/./g, "<span>$&</span>").replace(/\s/g, "&nbsp;")); //TweenMax.staggerFromTo( $animText.find("span"), 0.1, {autoAlpha:0}, {autoAlpha:1}, 0.1 ); $animText.find("span").each(function(){ TweenMax.fromTo(this, 2.5, {autoAlpha:0, rotation:rando...
}
function randomNum (min, max) { return Math.random() * (max - min) + min;
random_line_split
browser_tree.ts
'use strict'; var Funnel = require('broccoli-funnel'); var htmlReplace = require('../html-replace'); var jsReplace = require("../js-replace"); var path = require('path'); var stew = require('broccoli-stew'); import compileWithTypescript from '../broccoli-typescript'; import destCopy from '../broccoli-dest-copy'; impo...
var htmlTree = new Funnel(modulesTree, {include: ['*/src/**/*.html'], destDir: '/'}); htmlTree = replace(htmlTree, { files: ['examples*/**/*.html'], patterns: [ {match: /\$SCRIPTS\$/, replacement: htmlReplace('SCRIPTS')}, scriptPathPatternReplacement ] }); htmlTree = replace(htmlTree...
{ let options = {srcDir: '/', destDir: destDir}; funnels.push(new Funnel(vendorScriptsTree, options)); if (destDir.indexOf('benchmarks') > -1) { funnels.push(new Funnel(vendorScripts_benchmark, options)); } if (destDir.indexOf('benchmarks_external') > -1) { funnels.push(new Funnel(vendor...
identifier_body
browser_tree.ts
'use strict'; var Funnel = require('broccoli-funnel'); var htmlReplace = require('../html-replace'); var jsReplace = require("../js-replace"); var path = require('path'); var stew = require('broccoli-stew'); import compileWithTypescript from '../broccoli-typescript'; import destCopy from '../broccoli-dest-copy'; impo...
'node_modules/zone.js/dist/zone-microtask.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', 'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/systemjs/lib/extension-register.js', 'node_modu...
}); var vendorScriptsTree = flatten(new Funnel('.', { files: [
random_line_split
browser_tree.ts
'use strict'; var Funnel = require('broccoli-funnel'); var htmlReplace = require('../html-replace'); var jsReplace = require("../js-replace"); var path = require('path'); var stew = require('broccoli-stew'); import compileWithTypescript from '../broccoli-typescript'; import destCopy from '../broccoli-dest-copy'; impo...
(funnels, destDir) { let options = {srcDir: '/', destDir: destDir}; funnels.push(new Funnel(vendorScriptsTree, options)); if (destDir.indexOf('benchmarks') > -1) { funnels.push(new Funnel(vendorScripts_benchmark, options)); } if (destDir.indexOf('benchmarks_external') > -1) { funnels.pus...
getServedFunnels
identifier_name
browser_tree.ts
'use strict'; var Funnel = require('broccoli-funnel'); var htmlReplace = require('../html-replace'); var jsReplace = require("../js-replace"); var path = require('path'); var stew = require('broccoli-stew'); import compileWithTypescript from '../broccoli-typescript'; import destCopy from '../broccoli-dest-copy'; impo...
if (destDir.indexOf('benchmarks_external') > -1) { funnels.push(new Funnel(vendorScripts_benchmarks_external, options)); } return funnels; } var htmlTree = new Funnel(modulesTree, {include: ['*/src/**/*.html'], destDir: '/'}); htmlTree = replace(htmlTree, { files: ['examples*/**/*.html'], ...
{ funnels.push(new Funnel(vendorScripts_benchmark, options)); }
conditional_block
models.py
import base64 import cPickle as pickle import datetime from email import message_from_string from email.utils import getaddresses from django import forms from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from dja...
class MailingList(models.Model): """ This model contains all options for a mailing list, as well as some helpful methods for accessing subscribers, moderators, etc. """ objects = MailingListManager() MODERATORS = "mod" SUBSCRIBERS = "sub" ANYONE = "all" PERMISSION_CHOICES = ( (MODERATORS, 'Moderators'...
def for_site(self, site): return self.filter(site=site) def for_addresses(self, addresses): """ Takes a an iterable of email addresses and returns a queryset of mailinglists attached to the current site with matching local parts. """ site = Site.objects.get_current() local_parts = [] for addr ...
identifier_body
models.py
import base64 import cPickle as pickle import datetime from email import message_from_string from email.utils import getaddresses from django import forms from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from dja...
(self): # Does this need to be a byte string? return smart_str(u"%s <%s.%s>" % (self.name, self.local_part, self.domain.domain)) def __unicode__(self): return self.name def clean(self): validate_email(self.address) # As per RFC 2919, the list_id_header has a max length of 255 octets. if len(self._l...
_list_id_header
identifier_name
models.py
import base64 import cPickle as pickle import datetime from email import message_from_string from email.utils import getaddresses from django import forms from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from dja...
'Message', related_name = 'mailinglists', blank = True, null = True, through = 'ListMessage' ) @property def address(self): return "%s@%s" % (self.local_part, self.domain.domain) def _list_id_header(self): # Does this need to be a byte string? return smart_str(u"%s <%s.%s>" % (self.name, self.lo...
blank = True, null = True, through = ListUserMetadata ) messages = models.ManyToManyField(
random_line_split
models.py
import base64 import cPickle as pickle import datetime from email import message_from_string from email.utils import getaddresses from django import forms from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from dja...
elif isinstance(email, User): kwargs = {'user': email} else: return False try: self.listusermetadata_set.get(status=status, **kwargs) except ListUserMetadata.DoesNotExist: return False return True def is_subscriber(self, email): return self._is_email_with_status(email, ListUserMetadata.SU...
kwargs = {'user__email__iexact': email}
conditional_block
test_natural.py
from __future__ import unicode_literals from django.core import serializers from django.db import connection from django.test import TestCase from .models import FKDataNaturalKey, NaturalKeyAnchor from .tests import register_tests class NaturalKeySerializerTests(TestCase):
def natural_key_serializer_test(format, self): # Create all the objects defined in the test data with connection.constraint_checks_disabled(): objects = [ NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"), FKDataNaturalKey.objects.create(id=1101, data_id=1100...
pass
identifier_body
test_natural.py
from __future__ import unicode_literals from django.core import serializers from django.db import connection from django.test import TestCase from .models import FKDataNaturalKey, NaturalKeyAnchor from .tests import register_tests class NaturalKeySerializerTests(TestCase): pass def
(format, self): # Create all the objects defined in the test data with connection.constraint_checks_disabled(): objects = [ NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"), FKDataNaturalKey.objects.create(id=1101, data_id=1100), FKDataNaturalKey.ob...
natural_key_serializer_test
identifier_name
test_natural.py
from __future__ import unicode_literals from django.core import serializers from django.db import connection from django.test import TestCase from .models import FKDataNaturalKey, NaturalKeyAnchor from .tests import register_tests class NaturalKeySerializerTests(TestCase): pass def natural_key_serializer_test...
# Assert that the deserialized data is the same # as the original source for obj in objects: instance = obj.__class__.objects.get(id=obj.pk) self.assertEqual( obj.data, instance.data, "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( ...
obj.save()
conditional_block
test_natural.py
from __future__ import unicode_literals from django.core import serializers from django.db import connection from django.test import TestCase from .models import FKDataNaturalKey, NaturalKeyAnchor from .tests import register_tests class NaturalKeySerializerTests(TestCase): pass def natural_key_serializer_test...
# Delete one book (to prove that the natural key generation will only # restore the primary keys of books found in the database via the # get_natural_key manager method). james.delete() # Deserialize and test. books = list(serializers.deserialize(format, string_data)) self.assertEqual(len(...
# Serialize the books. string_data = serializers.serialize( format, NaturalKeyAnchor.objects.all(), indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True, )
random_line_split
unittest.py
# (c) 2014, Toshio Kuratomi <tkuratomi@ansible.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 later...
from unittest import *
conditional_block
unittest.py
# (c) 2014, Toshio Kuratomi <tkuratomi@ansible.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 later...
except ImportError: print('You need unittest2 installed on python2.6.x to run tests') else: from unittest import *
try: # Need unittest2 on python2.6 from unittest2 import *
random_line_split
base.ts
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
public get VectorName() { return this.constructor.name; } public get ArrayType(): T['ArrayType'] { return this.data.ArrayType; } public get values() { return this.data.values; } public get typeIds() { return this.data.typeIds; } public get nullBitmap() { return this.data.nullBitmap; } public ...
{ return this.data.nullCount; }
identifier_body
base.ts
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
(data: Data<T>, children?: Vector[]) { super(); this._children = children; this.numChildren = data.childData.length; this._bindDataAccessors(this.data = data); } public readonly data: Data<T>; public readonly numChildren: number; public get type() { return this.data.typ...
constructor
identifier_name
base.ts
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
public get VectorName() { return this.constructor.name; } public get ArrayType(): T['ArrayType'] { return this.data.ArrayType; } public get values() { return this.data.values; } public get typeIds() { return this.data.typeIds; } public get nullBitmap() { return this.data.nullBitmap; } public g...
random_line_split
base.ts
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
return true; } public getChildAt<R extends DataType = any>(index: number): Vector<R> | null { return index < 0 || index >= this.numChildren ? null : ( (this._children || (this._children = []))[index] || (this._children[index] = Vector.new<R>(this.data.childData[index] a...
{ const idx = this.offset + index; const val = this.nullBitmap[idx >> 3]; const mask = (val & (1 << (idx % 8))); return mask !== 0; }
conditional_block
game.py
from gameinfo import * from porkglobals import * def genGameMap(): """This is an "abstract function" to hold this docstring and information. A GameMap function defines Places and connects all the Places it defines in a graph, but simpler graph than CommandGraph. It simply uses Place.nextnodes. A...
if DEBUG: genGameMap = testGameMap # ghetto map choosing genGameMap = goldenfieldMap
shittystartersword = Weapon("old, rusty sword", "A simple sword, obviously aged and covered in rust.", 2, weight=2) startlocnext = {'e':"There is a wall there."} startloc = Place("You are in a field. Swaying, golden grass surrounds you in all directions.", items=[shittystartersword], next=s...
identifier_body
game.py
from gameinfo import * from porkglobals import * def genGameMap(): """This is an "abstract function" to hold this docstring and information. A GameMap function defines Places and connects all the Places it defines in a graph, but simpler graph than CommandGraph. It simply uses Place.nextnodes. A...
testsword2 = Weapon("rusty elvish sword", "A discarded old blade of Elvish steel.", 2) testsword3 = Weapon("sword elvish rusty", "A mix of adjectives to fuck with you.", 2) startlocnext = {} startloc = Place("Sword testing location.", items=[testsword,testsword2,testsword3], next=startl...
testsword = Weapon("elvish sword", "A blade of Elvish make.", 2, weight=2)
random_line_split
game.py
from gameinfo import * from porkglobals import * def genGameMap(): """This is an "abstract function" to hold this docstring and information. A GameMap function defines Places and connects all the Places it defines in a graph, but simpler graph than CommandGraph. It simply uses Place.nextnodes. A...
# ghetto map choosing genGameMap = goldenfieldMap
genGameMap = testGameMap
conditional_block
game.py
from gameinfo import * from porkglobals import * def
(): """This is an "abstract function" to hold this docstring and information. A GameMap function defines Places and connects all the Places it defines in a graph, but simpler graph than CommandGraph. It simply uses Place.nextnodes. A GameMap function returns the starting location.""" def testGam...
genGameMap
identifier_name
unwind.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 ...
unsafe { let closure: Closure = cast::transmute(f); let ep = rust_try(try_fn, closure.code as *c_void, closure.env as *c_void); if !ep.is_null() { rtdebug!("caught {}", (*ep).exception_class); uw::_Unwind_DeleteEx...
use libc::{c_void};
random_line_split
unwind.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 ...
(code: *c_void, env: *c_void) { unsafe { let closure: || = cast::transmute(Closure { code: code as *(), env: env as *(), }); closure(); } } extern { // Rust's try-catch ...
try_fn
identifier_name
unwind.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 ...
pub fn result(&mut self) -> TaskResult { if self.unwinding { Err(self.cause.take().unwrap()) } else { Ok(()) } } } // Rust's exception class identifier. This is used by personality routines to // determine whether the exception was thrown by their own runtime....
{ rtdebug!("begin_unwind()"); self.unwinding = true; self.cause = Some(cause); rust_fail(); // An uninlined, unmangled function upon which to slap yer breakpoints #[inline(never)] #[no_mangle] fn rust_fail() -> ! { unsafe { l...
identifier_body
html_parser.py
'''A convenient class for parsing HTML pages.''' from __future__ import unicode_literals from HTMLParser import HTMLParser import logging import re from RSSvk.core import Error LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) class HTMLPageParser(HTMLParser): '''A convenient class for parsing HTML...
(?: '[^']*' # LITA-enclosed value |"[^"]*" # LIT-enclosed value ) ) ([^\s>]) # Do not include / to make the preparation replacement for __invalid_tag_attr_regex ''', re.VERBOSE) ...
random_line_split
html_parser.py
'''A convenient class for parsing HTML pages.''' from __future__ import unicode_literals from HTMLParser import HTMLParser import logging import re from RSSvk.core import Error LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) class HTMLPageParser(HTMLParser): '''A convenient class for parsing HTML...
(self, html): '''Fixes various things that may confuse the Python's HTML parser.''' html = self.script_regex.sub('', html) loop_replacements = ( lambda html: self.__invalid_tag_attr_spacing_regex.subn(r'\1 \2', html), lambda html: self.__invalid_tag_attr_regex.subn(r'\1...
__fix_html
identifier_name
html_parser.py
'''A convenient class for parsing HTML pages.''' from __future__ import unicode_literals from HTMLParser import HTMLParser import logging import re from RSSvk.core import Error LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) class HTMLPageParser(HTMLParser): '''A convenient class for parsing HTML...
def handle_entityref(self, name): '''Handles a general entity reference of the form &name;.''' self.__accumulate_data('&' + name + ';') def handle_root_data(self, tag, data): '''Handles data inside of the root of the document.''' LOG.debug('%s', data) def handle_root...
for tag_id in xrange(len(self.__tag_stack) - 1, -1, -1): if self.__tag_stack[tag_id]['name'] == tag_name: for tag in reversed(self.__tag_stack[tag_id + 1:]): self.__close_tag(tag, forced = True) self.__tag_stack.pop() ...
conditional_block
html_parser.py
'''A convenient class for parsing HTML pages.''' from __future__ import unicode_literals from HTMLParser import HTMLParser import logging import re from RSSvk.core import Error LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) class HTMLPageParser(HTMLParser): '''A convenient class for parsing HTML...
def parse(self, html): '''Parses the specified HTML page.''' html = self.__fix_html(html) self.reset() try: # Run the parser self.feed(html) self.close() finally: # Close all unclosed tags for tag in self.__tag...
'''Resets the parser.''' HTMLParser.reset(self) self.__tag_stack = [{ # Add fake root tag 'name': None, 'new_tag_handler': self.handle_root, 'data_handler': self.handle_root_data, 'end_tag_handler': self.handle_root_end,...
identifier_body
results_fetcher_mock.py
# Copyright (C) 2011 Google 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 source code must retain the above copyright # notice, this list of conditions and the f...
return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry...
results = self._canned_results.get(build.build_id) if results: rv.extend(results)
conditional_block
results_fetcher_mock.py
# Copyright (C) 2011 Google 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 source code must retain the above copyright # notice, this list of conditions and the f...
def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self...
step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results
random_line_split
results_fetcher_mock.py
# Copyright (C) 2011 Google 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 source code must retain the above copyright # notice, this list of conditions and the f...
def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name
self._canned_retry_summary_json[build] = content
identifier_body
results_fetcher_mock.py
# Copyright (C) 2011 Google 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 source code must retain the above copyright # notice, this list of conditions and the f...
(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): ...
fetch_results
identifier_name
addresses.rs
use postgres; use ipm::PostgresReqExt; use rustc_serialize::json::{Json, ToJson}; #[derive(ToJson)] pub struct Address { address_id: i32, address: String, postal_code: String, city: String, state: String, country: String, geospot: Json
pub fn get_by_contact_id(req: &PostgresReqExt, contact_id: i32) -> Vec<Address> { let mut vec = Vec::new(); let conn = req.db_conn(); let stmt = conn.prepare( "SELECT * FROM addresses a \ WHERE EXISTS(SELECT * ...
} impl Address {
random_line_split
addresses.rs
use postgres; use ipm::PostgresReqExt; use rustc_serialize::json::{Json, ToJson}; #[derive(ToJson)] pub struct Address { address_id: i32, address: String, postal_code: String, city: String, state: String, country: String, geospot: Json } impl Address { pub fn get_by_contact_id(req: &P...
(&self, req: &PostgresReqExt) -> postgres::Result<u64> { let conn = req.db_conn(); //TODO: trigger for INSERT or UPDATE to remove duplicates. // if address_id is 0, then INSERT else UPDATE. conn.execute( "INSERT INTO addresses \ VALUES($1, $2, $...
commit
identifier_name
fuse.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] #[must_use = "streams do nothing u...
(&self) -> (usize, Option<usize>) { if self.done { (0, Some(0)) } else { self.stream.size_hint() } } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> { type Error = S::Error...
size_hint
identifier_name
fuse.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] #[must_use = "streams do nothing u...
/// Acquires a pinned mutable reference to the underlying stream that this /// combinator is pulling from. /// /// Note that care must be taken to avoid tampering with the state of the /// stream which may otherwise confuse this combinator. pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut ...
{ &mut self.stream }
identifier_body
fuse.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] #[must_use = "streams do nothing u...
else { self.stream.size_hint() } } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> { type Error = S::Error; delegate_sink!(stream, Item); }
{ (0, Some(0)) }
conditional_block
fuse.rs
use core::pin::Pin; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] #[must_use = "streams do nothing u...
impl<St> Fuse<St> { unsafe_pinned!(stream: St); unsafe_unpinned!(done: bool); pub(super) fn new(stream: St) -> Fuse<St> { Fuse { stream, done: false } } /// Returns whether the underlying stream has finished or not. /// /// If this method returns `true`, then all future calls to po...
random_line_split
location-indicator.ts
/** * @module @bldr/media-manager/location-indicator */ // Node packages. import path from 'path' import fs from 'fs' // Project packages. import config from '@bldr/config' import { untildify, findParentFile } from '@bldr/core-node' /** * Indicates in which folder structure a file is located. * * Merge the conf...
export default locationIndicator
random_line_split
location-indicator.ts
/** * @module @bldr/media-manager/location-indicator */ // Node packages. import path from 'path' import fs from 'fs' // Project packages. import config from '@bldr/config' import { untildify, findParentFile } from '@bldr/core-node' /** * Indicates in which folder structure a file is located. * * Merge the conf...
export const locationIndicator = new LocationIndicator() export default locationIndicator
const basePath = this.getBasePath(currentPath) const relPath = this.getRelPath(currentPath) let mirroredBasePath: string | undefined for (const bPath of this.basePaths) { if (basePath !== bPath) { mirroredBasePath = bPath break } } if (mirroredBasePath !== undefined &...
identifier_body
location-indicator.ts
/** * @module @bldr/media-manager/location-indicator */ // Node packages. import path from 'path' import fs from 'fs' // Project packages. import config from '@bldr/config' import { untildify, findParentFile } from '@bldr/core-node' /** * Indicates in which folder structure a file is located. * * Merge the conf...
} /** * Move a file path into a directory relative to the current * presentation directory. * * `/baldr/media/10/10_Jazz/30_Stile/20_Swing/NB/Duke-Ellington.jpg` `BD` -> * `/baldr/media/10/10_Jazz/30_Stile/20_Swing/BD/Duke-Ellington.jpg` * * @param currentPath - The current path. * @param ...
{ return path.dirname(parentFile) }
conditional_block
location-indicator.ts
/** * @module @bldr/media-manager/location-indicator */ // Node packages. import path from 'path' import fs from 'fs' // Project packages. import config from '@bldr/config' import { untildify, findParentFile } from '@bldr/core-node' /** * Indicates in which folder structure a file is located. * * Merge the conf...
{ /** * The base path of the main media folder. */ public main: string /** * Multiple base paths of media collections (the main base path and some * archive base paths) */ public readonly basePaths: string[] constructor () { this.main = config.mediaServer.basePath const basePaths = [...
LocationIndicator
identifier_name
ShareButton.tsx
import * as React from 'react'; import { st, classes } from './ShareButton.st.css'; import { ButtonProps } from '../Button'; import { Omit } from '../../types'; import { TextButton, TextButtonProps, TEXT_BUTTON_PRIORITY, } from '../TextButton'; import { ReactComponent as Share } from '../../assets/icons/Share.svg...
this.props.onClick(sharePromise); }; render() { const { shareData, text, withIcon, className, ...rest } = this.props; return ( <TextButton className={st( classes.root, { withIcon, withText: Boolean(text) }, className, )} priority={TEXT_BUTTON...
{ sharePromise = navigator.share(shareData); }
conditional_block
ShareButton.tsx
import * as React from 'react'; import { st, classes } from './ShareButton.st.css'; import { ButtonProps } from '../Button'; import { Omit } from '../../types'; import { TextButton, TextButtonProps, TEXT_BUTTON_PRIORITY, } from '../TextButton'; import { ReactComponent as Share } from '../../assets/icons/Share.svg...
}
{ const { shareData, text, withIcon, className, ...rest } = this.props; return ( <TextButton className={st( classes.root, { withIcon, withText: Boolean(text) }, className, )} priority={TEXT_BUTTON_PRIORITY.secondary} prefixIcon={withIcon ? <Sha...
identifier_body
ShareButton.tsx
import * as React from 'react'; import { st, classes } from './ShareButton.st.css'; import { ButtonProps } from '../Button'; import { Omit } from '../../types'; import { TextButton, TextButtonProps, TEXT_BUTTON_PRIORITY, } from '../TextButton'; import { ReactComponent as Share } from '../../assets/icons/Share.svg...
() { const { shareData, text, withIcon, className, ...rest } = this.props; return ( <TextButton className={st( classes.root, { withIcon, withText: Boolean(text) }, className, )} priority={TEXT_BUTTON_PRIORITY.secondary} prefixIcon={withIcon ? <...
render
identifier_name
ShareButton.tsx
import * as React from 'react'; import { st, classes } from './ShareButton.st.css'; import { ButtonProps } from '../Button'; import { Omit } from '../../types'; import { TextButton, TextButtonProps, TEXT_BUTTON_PRIORITY, } from '../TextButton'; import { ReactComponent as Share } from '../../assets/icons/Share.svg...
priority={TEXT_BUTTON_PRIORITY.secondary} prefixIcon={withIcon ? <Share className={classes.icon} /> : undefined} {...rest} onClick={this.onButtonClick} data-hook={this.props['data-hook']} > <div className={classes.text}>{text}</div> </TextButton> ); } }
{ withIcon, withText: Boolean(text) }, className, )}
random_line_split
wisp.py
import RPi.GPIO as GPIO import time import subprocess import datetime import time # Added to support voice command import threading import speech_recognition as sr STATE_UNOCCUPIED = 0 STATE_OCCUPIED = 1 OCCUPIED_DISTANCE = 50 UNOCCUPIED_DURATION = 1200 def process_command(self, command): if command.lower() == ...
(): subprocess.call(["raspistill", "-o", "image.jpg"]) def take_picam_video(): subprocess.call(["raspivid", "-o", "video.h264"]) def say(content): subprocess.call(["mpg123", content]) #fswebcam -p YUYV -d /dev/video0 -r 1024x768 --top-banner --title "The Garage" --subtitle "tyler" --info "hello" imag...
take_picam_still
identifier_name
wisp.py
import RPi.GPIO as GPIO import time import subprocess import datetime import time # Added to support voice command import threading import speech_recognition as sr STATE_UNOCCUPIED = 0 STATE_OCCUPIED = 1 OCCUPIED_DISTANCE = 50 UNOCCUPIED_DURATION = 1200 def process_command(self, command): if command.lower() == ...
def check_proximity(): TRIG = 23 ECHO = 24 GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) GPIO.output(TRIG, False) time.sleep(1) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while ...
def callback(recognizer, audio): # received audio data, now we'll recognize it using Google Speech Recognition try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION...
identifier_body
wisp.py
import RPi.GPIO as GPIO import time import subprocess import datetime import time # Added to support voice command import threading import speech_recognition as sr STATE_UNOCCUPIED = 0 STATE_OCCUPIED = 1 OCCUPIED_DISTANCE = 50 UNOCCUPIED_DURATION = 1200 def process_command(self, command): if command.lower() == ...
subprocess.call(["mpg123", content]) #fswebcam -p YUYV -d /dev/video0 -r 1024x768 --top-banner --title "The Garage" --subtitle "tyler" --info "hello" image.jpg def main(argv): state = STATE_UNOCCUPIED unoccupied_start = time.time() GPIO.setmode(GPIO.BCM) logger_level = logging.DEBUG log...
def say(content):
random_line_split
wisp.py
import RPi.GPIO as GPIO import time import subprocess import datetime import time # Added to support voice command import threading import speech_recognition as sr STATE_UNOCCUPIED = 0 STATE_OCCUPIED = 1 OCCUPIED_DISTANCE = 50 UNOCCUPIED_DURATION = 1200 def process_command(self, command): if command.lower() == ...
if prox_distance > OCCUPIED_DISTANCE: if (time.time() - unoccupied_start) > UNOCCUPIED_DURATION: say("goodbye.mp3") state = STATE_UNOCCUPIED logger.info("Workshop Unoccupied") GPIO.cleanup() '''Voice Commands # Information Commands Dat...
if state == STATE_UNOCCUPIED: say("greet.mp3") state = STATE_OCCUPIED logger.info("Workshop Occupied") unoccupied_start = datetime.datetime.now()
conditional_block
PickListSubList.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PickListSubList = void 0; var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _ObjectUtils ...
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return fals...
{ if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
identifier_body
PickListSubList.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PickListSubList = void 0; var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _ObjectUtils ...
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.pro...
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _type...
random_line_split
PickListSubList.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PickListSubList = void 0; var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _ObjectUtils ...
(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } ...
_toConsumableArray
identifier_name
cholesky_op_test.py
"""Tests for tensorflow.ops.tf.Cholesky.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class CholeskyOpTest...
def testBasic(self): self._verifyCholesky(np.array([[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]])) def testBatch(self): simple_array = np.array([[[1., 0.], [0., 5.]]]) # shape (1, 2, 2) self._verifyCholesky(simple_array) self._verifyCholesky(np.vstack((simple_array, simple_array))) odd_sized_a...
with self.test_session() as sess: # Verify that LL^T == x. if x.ndim == 2: chol = tf.cholesky(x) verification = tf.matmul(chol, chol, transpose_a=False, transpose_b=True) else: ch...
identifier_body
cholesky_op_test.py
"""Tests for tensorflow.ops.tf.Cholesky.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class CholeskyOpTest...
(self): simple_array = np.array([[[1., 0.], [0., 5.]]]) # shape (1, 2, 2) self._verifyCholesky(simple_array) self._verifyCholesky(np.vstack((simple_array, simple_array))) odd_sized_array = np.array([[[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]]) self._verifyCholesky(np.vstack((odd_sized_array, odd_s...
testBatch
identifier_name
cholesky_op_test.py
"""Tests for tensorflow.ops.tf.Cholesky.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class CholeskyOpTest...
# The input should be invertible. with self.test_session(): with self.assertRaisesOpError("LLT decomposition was not successful. The " "input might not be valid."): # All rows of the matrix below add to zero self._verifyCholesky(np.array([[1., -1., 0.], ...
random_line_split
cholesky_op_test.py
"""Tests for tensorflow.ops.tf.Cholesky.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class CholeskyOpTest...
def testBasic(self): self._verifyCholesky(np.array([[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]])) def testBatch(self): simple_array = np.array([[[1., 0.], [0., 5.]]]) # shape (1, 2, 2) self._verifyCholesky(simple_array) self._verifyCholesky(np.vstack((simple_array, simple_array))) odd_sized_a...
chol_reshaped = np.reshape(chol_np, (-1, chol_np.shape[-2], chol_np.shape[-1])) for chol_matrix in chol_reshaped: self.assertAllClose(chol_matrix, np.tril(chol_matrix)) self.assertTrue((np.diag(chol_matrix) > 0.0).all())
conditional_block
util.js
/** * utils * * @namespace mix.util * * @author Yang,junlong at 2016-07-28 20:27:54 build. * @version $Id$ */ var fs = require('fs'); var url = require('url'); var pth = require('path'); var util = require('util'); //var iconv = require('iconv-lite'); var crypto = require('crypto'); var PLATFORM = process.pl...
var dirname = pths.dir || '.'; var filename = pths.name; var basename = (pths.base || '').replace(query, ''); var rest = dirname + '/' + filename; var ext = (pths.ext || '').replace(query, ''); return { 'origin': origin, 'dirname': dirname, 'fullname': fullname, ...
var query = urls.search; var fullname = origin.replace(query, '');
random_line_split
util.js
/** * utils * * @namespace mix.util * * @author Yang,junlong at 2016-07-28 20:27:54 build. * @version $Id$ */ var fs = require('fs'); var url = require('url'); var pth = require('path'); var util = require('util'); //var iconv = require('iconv-lite'); var crypto = require('crypto'); var PLATFORM = process.pl...
= false; if (!exports.is(patterns, 'Array')){ patterns = [patterns]; } patterns.every(function(pattern){ if (!pattern){ return true; } matched = matched || str.search(normalize(pattern)) > -1; return !matched; }...
tch (type){ case '[object String]': return exports.glob(pattern); case '[object RegExp]': return pattern; default: mix.log.error('invalid regexp [' + pattern + '].'); } } function match(str, patterns){ var match...
identifier_body
util.js
/** * utils * * @namespace mix.util * * @author Yang,junlong at 2016-07-28 20:27:54 build. * @version $Id$ */ var fs = require('fs'); var url = require('url'); var pth = require('path'); var util = require('util'); //var iconv = require('iconv-lite'); var crypto = require('crypto'); var PLATFORM = process.pl...
(!exports.is(patterns, 'Array')){ patterns = [patterns]; } patterns.every(function(pattern){ if (!pattern){ return true; } matched = matched || str.search(normalize(pattern)) > -1; return !matched; }); return ma...
if
identifier_name
user-experience-list.component.ts
import { Component, OnInit } from '@angular/core'; import { ExperienceService } from '../../services/experience.service'; import { Router } from '@angular/router'; import { Experience } from '../../models/experience-form-data'; import { AuthService } from '../../../login/services/auth.service'; @Component({ selecto...
implements OnInit { experienceList: Experience[]; constructor( private authService: AuthService, private experienceService: ExperienceService, private router: Router) { } ngOnInit() { this.authService.af.auth.onAuthStateChanged( currentUser => { if (currentUser) { this...
UserExperienceListComponent
identifier_name
user-experience-list.component.ts
import { Component, OnInit } from '@angular/core';
@Component({ selector: 'app-user-experience-list', templateUrl: './user-experience-list.component.html', styleUrls: ['./user-experience-list.component.scss'] }) export class UserExperienceListComponent implements OnInit { experienceList: Experience[]; constructor( private authService: AuthService, ...
import { ExperienceService } from '../../services/experience.service'; import { Router } from '@angular/router'; import { Experience } from '../../models/experience-form-data'; import { AuthService } from '../../../login/services/auth.service';
random_line_split
user-experience-list.component.ts
import { Component, OnInit } from '@angular/core'; import { ExperienceService } from '../../services/experience.service'; import { Router } from '@angular/router'; import { Experience } from '../../models/experience-form-data'; import { AuthService } from '../../../login/services/auth.service'; @Component({ selecto...
} ); } }
{ this.experienceService.getExperiencesByUserId(currentUser.uid) .subscribe(experienceList => { let returnExperiences: Experience[] = []; for (let experience of experienceList) { returnExperiences.push(new Experience(experience)); } ...
conditional_block
user-experience-list.component.ts
import { Component, OnInit } from '@angular/core'; import { ExperienceService } from '../../services/experience.service'; import { Router } from '@angular/router'; import { Experience } from '../../models/experience-form-data'; import { AuthService } from '../../../login/services/auth.service'; @Component({ selecto...
}
{ this.authService.af.auth.onAuthStateChanged( currentUser => { if (currentUser) { this.experienceService.getExperiencesByUserId(currentUser.uid) .subscribe(experienceList => { let returnExperiences: Experience[] = []; for (let experience of experienc...
identifier_body
SerialPortChoice.py
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
# with EventGhost. If not, see <http://www.gnu.org/licenses/>. import wx # Local imports import eg class SerialPortChoice(wx.Choice): """ A wx.Choice control that shows all available serial ports on the system. """ def __init__( self, parent, id=-1, pos=wx.DefaultPosit...
# 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 of the GNU General Public License along
random_line_split
SerialPortChoice.py
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
self): """ Return the currently selected serial port. :rtype: int :returns: The serial port as an integer (0 = COM1:) """ try: port = self.ports[self.GetSelection()] except: port = 0 return port
etValue(
identifier_name
SerialPortChoice.py
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
"" A wx.Choice control that shows all available serial ports on the system. """ def __init__( self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.ChoiceNameStr, value=None ...
identifier_body
dashlet-interactions.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { MatDialog } from '@angular/material'; import { Observable } from 'rxjs/Observable'; import { Store } from '@ngrx/store'; import { takeWhile } from 'rxjs/operators'; import { AppState, getMyInteractions, Interaction, CompleteInteractionAction, AuthS...
complete(id: number, checked: boolean): void { // console.log(id, checked); this._store.dispatch(new CompleteInteractionAction({ id: id, complete: checked })); } delete(interaction: Interaction): void { // this._interactionService.remove(interaction.id); } ngOnDestroy(): void { this._alive ...
settingsDlg(): void { // open settings dialog }
random_line_split
dashlet-interactions.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { MatDialog } from '@angular/material'; import { Observable } from 'rxjs/Observable'; import { Store } from '@ngrx/store'; import { takeWhile } from 'rxjs/operators'; import { AppState, getMyInteractions, Interaction, CompleteInteractionAction, AuthS...
(): void { // open settings dialog } complete(id: number, checked: boolean): void { // console.log(id, checked); this._store.dispatch(new CompleteInteractionAction({ id: id, complete: checked })); } delete(interaction: Interaction): void { // this._interactionService.remove(interaction.id); ...
settingsDlg
identifier_name
dashlet-interactions.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { MatDialog } from '@angular/material'; import { Observable } from 'rxjs/Observable'; import { Store } from '@ngrx/store'; import { takeWhile } from 'rxjs/operators'; import { AppState, getMyInteractions, Interaction, CompleteInteractionAction, AuthS...
complete(id: number, checked: boolean): void { // console.log(id, checked); this._store.dispatch(new CompleteInteractionAction({ id: id, complete: checked })); } delete(interaction: Interaction): void { // this._interactionService.remove(interaction.id); } ngOnDestroy(): void { this._alive...
{ // open settings dialog }
identifier_body