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
config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SECRET_KEY = os.getenv('APP_SECRET_KEY', '') # db config DB_PORT = os.getenv('DB_PORT', '') DB_HOST = os.getenv('DB_HOST', '') DB_ROLE = os.getenv('DB_...
DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
class StagingConfig(Config):
random_line_split
config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SECRET_KEY = os.getenv('APP_SECRET_KEY', '') # db config DB_PORT = os.getenv('DB_PORT', '') DB_HOST = os.getenv('DB_HOST', '') DB_ROLE = os.getenv('DB_...
class TestingConfig(Config): TESTING = True
DEVELOPMENT = True DEBUG = True
identifier_body
project_compassion.py
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
_inherit = "compassion.project" def suspend_funds(self): """ Remove children from the website when FCP Suspension occurs. """ children = self.env["compassion.child"].search( [("project_id", "in", self.ids), ("state", "=", "I")] ) if children: wp_config = self...
identifier_body
project_compassion.py
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
class CompassionProject(models.Model): _inherit = "compassion.project" def suspend_funds(self): """ Remove children from the website when FCP Suspension occurs. """ children = self.env["compassion.child"].search( [("project_id", "in", self.ids), ("state", "=", "I")] ) ...
from odoo import models from ..tools.wp_sync import WPSync
random_line_split
project_compassion.py
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
return super(CompassionProject, self).suspend_funds()
wp_config = self.env["wordpress.configuration"].get_config() wp = WPSync(wp_config) wp.remove_children(children)
conditional_block
project_compassion.py
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
(self): """ Remove children from the website when FCP Suspension occurs. """ children = self.env["compassion.child"].search( [("project_id", "in", self.ids), ("state", "=", "I")] ) if children: wp_config = self.env["wordpress.configuration"].get_config() ...
suspend_funds
identifier_name
example.ts
// βšͺ Initialization let canvas = document.getElementById('game') as HTMLCanvasElement; var gl = canvas.getContext('webgl'); if (!gl) { throw new Error('Could not create WebGL Context!'); } // πŸ”² Create NDC Space Quad (attribute vec2 position) let ndcQuad = [ 1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ]; let indices ...
ayer = loadTexture('https://alain.xyz/blog/image-editor-effects/assets/cover.jpg'); let topLayer = loadTexture('https://alain.xyz/blog/unreal-engine-architecture/assets/cover.png'); // πŸ“ Draw function draw() { // Bind Shaders gl.useProgram(program); // Bind Vertex Layout let loc = gl.getAttribLocation(program, '...
gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); const pixel = new Uint8Array([ 0, 0, 0, 255 ]); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixel); let img = new Image(); img.src = url; img.onload = () => { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BY...
identifier_body
example.ts
// βšͺ Initialization let canvas = document.getElementById('game') as HTMLCanvasElement; var gl = canvas.getContext('webgl'); if (!gl) { throw new Error('Could not create WebGL Context!'); } // πŸ”² Create NDC Space Quad (attribute vec2 position) let ndcQuad = [ 1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ]; let indices ...
t fs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fs, fsSource); gl.compileShader(fs); if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) { console.error('An error occurred compiling the shader: ' + gl.getShaderInfoLog(fs)); } let program = gl.createProgram(); gl.attachShader(program, vs); gl.attach...
onsole.error('An error occurred compiling the shader: ' + gl.getShaderInfoLog(vs)); } le
conditional_block
example.ts
// βšͺ Initialization let canvas = document.getElementById('game') as HTMLCanvasElement; var gl = canvas.getContext('webgl'); if (!gl) { throw new Error('Could not create WebGL Context!'); } // πŸ”² Create NDC Space Quad (attribute vec2 position) let ndcQuad = [ 1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ]; let indices ...
aders gl.useProgram(program); // Bind Vertex Layout let loc = gl.getAttribLocation(program, 'aPosition'); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 4 * 2, 0); gl.enableVertexAttribArray(loc); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Bind Uniforms var shaderTexNumber = 0; let bottomLayerL...
d Sh
identifier_name
example.ts
// βšͺ Initialization let canvas = document.getElementById('game') as HTMLCanvasElement; var gl = canvas.getContext('webgl'); if (!gl) { throw new Error('Could not create WebGL Context!'); } // πŸ”² Create NDC Space Quad (attribute vec2 position) let ndcQuad = [ 1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ]; let indices ...
vec4 colorDodge(vec4 col, vec4 blend) { return vec4(mix(col.rgb / clamp(1.0 - blend.rgb, 0.00001, 1.0), col.rgb, blend.a), col.a); } void main() { vec2 uv = vFragCoord; vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0); vec4 bottomColor = texture2D(tBottomLayer, uv); vec4 topColor = texture2D(tTopLayer, uv); outC...
uniform sampler2D tTopLayer; // πŸŒ… Color Dodge
random_line_split
jsonSchema.js
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'], function (Property, Model, declare, jsonSchemaValidator) { // module: // dstore/extensions/JsonSchema // summary: // This module generates a dstore schema from a JSON Schema to enabled validation of objects // and property c...
checkForErrors: checkForErrors }); if (typeof jsDefinition.type === 'string') { // copy the type so it can be used for coercion definition.type = jsDefinition.type; } if (typeof jsDefinition['default'] === 'string') { // and copy the default definition['default'] = jsDefinition['default'...
random_line_split
jsonSchema.js
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'], function (Property, Model, declare, jsonSchemaValidator) { // module: // dstore/extensions/JsonSchema // summary: // This module generates a dstore schema from a JSON Schema to enabled validation of objects // and property c...
() { var value = this.valueOf(); var key = this.name; // get the current value and test it against the property's definition var validation = jsonSchemaValidator.validate(value, properties[key]); // set any errors var errors = validation.errors; if (errors) { // assign the property names to the...
checkForErrors
identifier_name
jsonSchema.js
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'], function (Property, Model, declare, jsonSchemaValidator) { // module: // dstore/extensions/JsonSchema // summary: // This module generates a dstore schema from a JSON Schema to enabled validation of objects // and property c...
} return errors; } // iterate through the schema properties, creating property validators for (var i in properties) { var jsDefinition = properties[i]; var definition = modelSchema[i] = new Property({ checkForErrors: checkForErrors }); if (typeof jsDefinition.type === 'string') { // co...
{ errors[i].property = key; }
conditional_block
jsonSchema.js
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'], function (Property, Model, declare, jsonSchemaValidator) { // module: // dstore/extensions/JsonSchema // summary: // This module generates a dstore schema from a JSON Schema to enabled validation of objects // and property c...
// iterate through the schema properties, creating property validators for (var i in properties) { var jsDefinition = properties[i]; var definition = modelSchema[i] = new Property({ checkForErrors: checkForErrors }); if (typeof jsDefinition.type === 'string') { // copy the type so it can be us...
{ var value = this.valueOf(); var key = this.name; // get the current value and test it against the property's definition var validation = jsonSchemaValidator.validate(value, properties[key]); // set any errors var errors = validation.errors; if (errors) { // assign the property names to the er...
identifier_body
setup.py
#!/usr/bin/env python """ Hiveary https://hiveary.com Licensed under Simplified BSD License (see LICENSE) (C) Hiveary, Inc. 2013-2014 all rights reserved """ import platform import sys from hiveary import __version__ as version current_platform = platform.system() FROZEN_NAME = 'hiveary-agent' AUTHOR = "Hiveary"...
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages # Include all files from the package. install_requires = [ 'amqplib>=1.0.2', 'kombu>=3.0.8', 'netifaces-merged>=0...
conditional_block
setup.py
#!/usr/bin/env python """ Hiveary https://hiveary.com Licensed under Simplified BSD License (see LICENSE) (C) Hiveary, Inc. 2013-2014 all rights reserved """ import platform import sys from hiveary import __version__ as version current_platform = platform.system() FROZEN_NAME = 'hiveary-agent' AUTHOR = "Hiveary"...
script = Target( description='Hiveary Agent Service Launcher', modules=["HivearyService"], cmdline_style='pywin32') data_files = [] # Build the service setuptools.setup(name='HivearyService', version=version, options={'py2exe': {}}, ...
self.__dict__.update(kw) self.version = version self.company_name = 'Hiveary' self.name = "HivearyService"
identifier_body
setup.py
#!/usr/bin/env python """ Hiveary https://hiveary.com Licensed under Simplified BSD License (see LICENSE) (C) Hiveary, Inc. 2013-2014 all rights reserved """ import platform import sys from hiveary import __version__ as version current_platform = platform.system() FROZEN_NAME = 'hiveary-agent' AUTHOR = "Hiveary"...
('Microsoft.VC90.CRT', glob(r'C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*')), r'hiveary\ca-bundle.pem', ('monitors', glob(r'monitors\*.py')) ] script = Executable('hiveary-agent', gui_only=False) options = { 'bdist_esky': { 'freezer_m...
sys.path.append('C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC90.CRT') # Add in Visual Studio C++ compiler library data_files = [
random_line_split
setup.py
#!/usr/bin/env python """ Hiveary https://hiveary.com Licensed under Simplified BSD License (see LICENSE) (C) Hiveary, Inc. 2013-2014 all rights reserved """ import platform import sys from hiveary import __version__ as version current_platform = platform.system() FROZEN_NAME = 'hiveary-agent' AUTHOR = "Hiveary"...
(self, **kw): self.__dict__.update(kw) self.version = version self.company_name = 'Hiveary' self.name = "HivearyService" script = Target( description='Hiveary Agent Service Launcher', modules=["HivearyService"], cmdline_style='pywin32') data_files = [] # Build the serv...
__init__
identifier_name
lib.rs
//! # Elektra //! Safe bindings for [libelektra](https://www.libelektra.org). //! //! See the [project's readme](https://master.libelektra.org/src/bindings/rust) for an introduction and examples. //! //! The crate consists of three major parts. //! //! - The [keys](key/index.html) that encapsulate name, value and metai...
pub mod kdb; pub use self::key::{BinaryKey, StringKey, MetaIter, NameIter, KeyNameInvalidError, KeyNameReadOnlyError, KeyNotFoundError, CopyOption}; pub use self::keybuilder::KeyBuilder; pub use self::readable::ReadableKey; pub use self::readonly::ReadOnly; pub use self::writeable::WriteableKey; pub use self::keyset::...
/// Trait to write values to a key. pub mod writeable; pub mod keyset;
random_line_split
readers.py
import tensorflow as tf import tensorflow.contrib.slim as slim class BaseReader(object): def read(self): raise NotImplementedError() class ImageReader(BaseReader): def __init__(self): self.width = None self.height = None def get_image_size(self): return self.width, self....
def read(self, filename, num_classes, batch_size=256, feature_map=None): assert(self.width is not None and self.height is not None) assert(self.width > 0 and self.height > 0) reader = tf.TFRecordReader() tf.add_to_collection(filename, batch_size) # is this really needed? ke...
self.height = height
random_line_split
readers.py
import tensorflow as tf import tensorflow.contrib.slim as slim class BaseReader(object): def read(self): raise NotImplementedError() class ImageReader(BaseReader): def __init__(self): self.width = None self.height = None def get_image_size(self):
def set_image_size(self, width, height): self.width = width self.height = height def read(self, filename, num_classes, batch_size=256, feature_map=None): assert(self.width is not None and self.height is not None) assert(self.width > 0 and self.height > 0) reader = tf.T...
return self.width, self.height
identifier_body
readers.py
import tensorflow as tf import tensorflow.contrib.slim as slim class BaseReader(object): def read(self): raise NotImplementedError() class ImageReader(BaseReader): def __init__(self): self.width = None self.height = None def get_image_size(self): return self.width, self....
empty_labels = tf.reduce_sum(tf.zeros_like(images), axis=1) return empty_labels, images
labels = tf.cast(features['label'], tf.int32) one_hot = tf.map_fn(lambda x: tf.cast(slim.one_hot_encoding(x, num_classes), tf.int32), labels) one_hot = tf.reshape(one_hot, [-1, num_classes]) return one_hot, images
conditional_block
readers.py
import tensorflow as tf import tensorflow.contrib.slim as slim class BaseReader(object): def read(self): raise NotImplementedError() class
(BaseReader): def __init__(self): self.width = None self.height = None def get_image_size(self): return self.width, self.height def set_image_size(self, width, height): self.width = width self.height = height def read(self, filename, num_classes, batch_size=256...
ImageReader
identifier_name
ConfirmXferPacket.ts
import { Collection } from '../../utilities' import Packet from './Packet' import * as Types from '../types' /** * ConfirmXferPacket Packet */ class ConfirmXferPacket extends Packet {
* method of Packet, plus the buffer helper of the network namespace for * generating a lookup codes. * * @type {number} */ public static id: number = 19 /** * Packet frequency. This value determines whether the message ID is 8, 16, or * 32 bits. There can be unique 254 messages IDs in the "Hig...
/** * Packet ID, this value is only unique per-frequency range, see key get
random_line_split
ConfirmXferPacket.ts
import { Collection } from '../../utilities' import Packet from './Packet' import * as Types from '../types' /** * ConfirmXferPacket Packet */ class ConfirmXferPacket extends Packet { /** * Packet ID, this value is only unique per-frequency range, see key get * method of Packet, plus the buffer helper of th...
(data = {}) { super(data) } } export default ConfirmXferPacket
constructor
identifier_name
create.js
import { Duration, isDuration } from './constructor'; import toInt from '../utils/to-int'; import hasOwnProp from '../utils/has-own-prop'; import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; import { cloneWithOffset } from '../units/offset'; import { createLocal } from '../create/local'; // A...
function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clon...
{ // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }
identifier_body
create.js
import { Duration, isDuration } from './constructor'; import toInt from '../utils/to-int'; import hasOwnProp from '../utils/has-own-prop'; import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; import { cloneWithOffset } from '../units/offset'; import { createLocal } from '../create/local'; // A...
(base, other) { var res; if (!(base.isValid() && other.isValid())) { return {milliseconds: 0, months: 0}; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, bas...
momentsDifference
identifier_name
create.js
import { Duration, isDuration } from './constructor'; import toInt from '../utils/to-int'; import hasOwnProp from '../utils/has-own-prop'; import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; import { cloneWithOffset } from '../units/offset'; import { createLocal } from '../create/local'; // A...
else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : 0, d : toInt(match[DATE]) * sign, h : toInt(match[HOUR]) * sign, m : toInt(match[MINUTE]) * sign, s : toInt(match[SECO...
{ duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } }
conditional_block
create.js
import { Duration, isDuration } from './constructor'; import toInt from '../utils/to-int'; import hasOwnProp from '../utils/has-own-prop'; import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; import { cloneWithOffset } from '../units/offset'; import { createLocal } from '../create/local'; // A...
} other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; }
return {milliseconds: 0, months: 0};
random_line_split
publisher.py
from __future__ import absolute_import from werkzeug.exceptions import ServiceUnavailable, NotFound from r5d4.flask_redis import get_conf_db def publish_transaction(channel, tr_type, payload): conf_db = get_conf_db() if tr_type not in ["insert", "delete"]:
subscribed = conf_db.scard("Subscriptions:%s:ActiveAnalytics" % channel) if subscribed == 0: raise NotFound(("Channel not found", "Channel '%(channel)s' is not found or has 0 " "subscriptions" % locals())) listened = conf_db.publish( channel, ...
raise ValueError("Unknown transaction type", tr_type)
conditional_block
publisher.py
from __future__ import absolute_import from werkzeug.exceptions import ServiceUnavailable, NotFound from r5d4.flask_redis import get_conf_db def publish_transaction(channel, tr_type, payload): conf_db = get_conf_db() if tr_type not in ["insert", "delete"]: raise ValueError("Unknown transaction type", ...
"Subscription-Listened mismatch", "Listened count = %d doesn't match Subscribed count = %d" % ( listened, subscribed ) ))
if listened != subscribed: raise ServiceUnavailable((
random_line_split
publisher.py
from __future__ import absolute_import from werkzeug.exceptions import ServiceUnavailable, NotFound from r5d4.flask_redis import get_conf_db def publish_transaction(channel, tr_type, payload):
conf_db = get_conf_db() if tr_type not in ["insert", "delete"]: raise ValueError("Unknown transaction type", tr_type) subscribed = conf_db.scard("Subscriptions:%s:ActiveAnalytics" % channel) if subscribed == 0: raise NotFound(("Channel not found", "Channel '%(channel)...
identifier_body
publisher.py
from __future__ import absolute_import from werkzeug.exceptions import ServiceUnavailable, NotFound from r5d4.flask_redis import get_conf_db def
(channel, tr_type, payload): conf_db = get_conf_db() if tr_type not in ["insert", "delete"]: raise ValueError("Unknown transaction type", tr_type) subscribed = conf_db.scard("Subscriptions:%s:ActiveAnalytics" % channel) if subscribed == 0: raise NotFound(("Channel not found", ...
publish_transaction
identifier_name
FeatureAKGApp.tsx
import { Col, Row } from "@artsy/palette" import { FeatureAKGApp_viewer } from "v2/__generated__/FeatureAKGApp_viewer.graphql" import { Footer } from "v2/Components/Footer" import * as React from "react"; import { Title } from "react-head" import { createFragmentContainer, graphql } from "react-relay" import { FeatureF...
...Feature_viewer @arguments( articleIDs: $articleIDs selectedWorksSetID: $selectedWorksSetID collectionRailItemIDs: $collectionRailItemIDs auctionRailItemIDs: $auctionRailItemIDs fairRailItemIDs: $fairRailItemIDs hasCollectionRai...
) {
random_line_split
FeedbackWindow.js
Ext.ns('CMS'); /** * A window with a form that users can utilize for sending feedback */ CMS.FeedbackWindow = Ext.extend(Ext.Window, { modal: true, width: 500, height: 400, resizable: false, layout: 'fit', closable: false, padding: 10, initComponent: function () { this.items = ...
}, this); } }, /** * @private */ gatherData: function () { var result = this.formpanel.getForm().getFieldValues(); result.errors = CMS.app.ErrorManager.getErrorHistory(); result.userAgent = navigator.userAgent; result.platform = navigator.platform; ...
this.destroy(); }
conditional_block
FeedbackWindow.js
Ext.ns('CMS'); /** * A window with a form that users can utilize for sending feedback */ CMS.FeedbackWindow = Ext.extend(Ext.Window, { modal: true, width: 500, height: 400, resizable: false, layout: 'fit', closable: false, padding: 10, initComponent: function () { this.items = ...
}, /** * @private * Handler for close button */ closeHandler: function () { if (!this.formpanel.getForm().isValid()) { this.destroy(); } else { Ext.MessageBox.confirm(CMS.i18n('Mitteilung senden?'), CMS.i18n('Die Mitteilung wurde noch nicht versandt. Soll...
failureTitle: CMS.i18n('Konnte Feedback nicht versenden') }); this.destroy();
random_line_split
common.py
# # common.py # # Copyright (C) 2009 Justin Noah <justinnoah@gmail.com> # # Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Damien Churchill <damoxc@gmail.com> # # Deluge is free software. # #...
(filename): import pkg_resources, os return pkg_resources.resource_filename("autobot", os.path.join("data", filename))
get_resource
identifier_name
common.py
# # common.py # # Copyright (C) 2009 Justin Noah <justinnoah@gmail.com> #
# Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Damien Churchill <damoxc@gmail.com> # # Deluge is free software. # # You may redistribute it and/or modify it under the terms of the # GNU Gen...
random_line_split
common.py
# # common.py # # Copyright (C) 2009 Justin Noah <justinnoah@gmail.com> # # Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Damien Churchill <damoxc@gmail.com> # # Deluge is free software. # #...
import pkg_resources, os return pkg_resources.resource_filename("autobot", os.path.join("data", filename))
identifier_body
lookups.py
from django.db.models import Q from django.utils.html import escape from django.contrib.auth.models import User from ajax_select import LookupChannel class BuyerLookup(LookupChannel): """ This class suggests user names (AJAX Effect) while filling client name for a purchase order """ model = User ...
(self, obj): result = User.objects.values('first_name','last_name', 'customer__title','customer__address__street_address', 'customer__address__district','customer__company').filter(id = obj.id)[0] return "<b>Name or Title:</b> %s <br> <b>Company:</b> %s <br> <b>Address:</b> %s <b...
format_item_display
identifier_name
lookups.py
from django.db.models import Q from django.utils.html import escape from django.contrib.auth.models import User from ajax_select import LookupChannel class BuyerLookup(LookupChannel): """ This class suggests user names (AJAX Effect) while filling client name for a purchase order """ model = User ...
return user[0:15] def get_result(self, obj): return unicode(obj.username) def format_match(self, obj): return self.format_item_display(obj) def format_item_display(self, obj): result = User.objects.values('first_name','last_name', 'customer__title','customer__...
user = user.filter(Q(username__icontains=value)| \ Q(first_name__icontains=value) \ | Q(last_name__icontains=value) \ |Q(customer__address__street_address__icontains=value)\ |Q(customer__address__district__icontains=value)\ |Q(customer__add...
conditional_block
lookups.py
from django.db.models import Q from django.utils.html import escape from django.contrib.auth.models import User from ajax_select import LookupChannel class BuyerLookup(LookupChannel): """ This class suggests user names (AJAX Effect) while filling client name for a purchase order """ model = User ...
def get_result(self, obj): return unicode(obj.username) def format_match(self, obj): return self.format_item_display(obj) def format_item_display(self, obj): result = User.objects.values('first_name','last_name', 'customer__title','customer__address__street_address', ...
random_line_split
lookups.py
from django.db.models import Q from django.utils.html import escape from django.contrib.auth.models import User from ajax_select import LookupChannel class BuyerLookup(LookupChannel): """ This class suggests user names (AJAX Effect) while filling client name for a purchase order """ model = User ...
result = User.objects.values('first_name','last_name', 'customer__title','customer__address__street_address', 'customer__address__district','customer__company').filter(id = obj.id)[0] return "<b>Name or Title:</b> %s <br> <b>Company:</b> %s <br> <b>Address:</b> %s <br> %s \ <hr>"...
identifier_body
lda_preprocessing.py
from optparse import OptionParser import re import os import sys import numpy as np from ..util import dirs from ..util import file_handling as fh from ..preprocessing import data_splitting as ds from ..feature_extractors.vocabulary_with_counts import VocabWithCounts def main(): usage = "%prog project" pars...
pronouns = {"i", 'you', 'he', 'his', 'she', 'her', 'hers', 'it', 'its', 'we', 'you', 'your', 'they', 'them', 'their'} determiners = {'a', 'an', 'the', 'this', 'that', 'these', 'those'} prepositions = {'at', 'by', 'for', 'from', 'in', 'into', 'of', 'on', 'than', 'to', 'with'} transitional = {'and', 'also...
vocab_size = int(options.vocab_size) suffixes = {"'s", "n't"}
random_line_split
lda_preprocessing.py
from optparse import OptionParser import re import os import sys import numpy as np from ..util import dirs from ..util import file_handling as fh from ..preprocessing import data_splitting as ds from ..feature_extractors.vocabulary_with_counts import VocabWithCounts def main():
def tokenize(sentences, documents_to_tokenize, stopwords=set()): print "Tokenizing" vocab = VocabWithCounts('', add_oov=False) tokenized = {} for k in documents_to_tokenize: text = sentences[k].lower() text = re.sub('\d', '#', text) tokens = text.split() tokens = [t fo...
usage = "%prog project" parser = OptionParser(usage=usage) parser.add_option('-v', dest='vocab_size', default=10000, help='Vocabulary size (most frequent words): default=%default') parser.add_option('--seed', dest='seed', default=42, help='Random seed: default=%de...
identifier_body
lda_preprocessing.py
from optparse import OptionParser import re import os import sys import numpy as np from ..util import dirs from ..util import file_handling as fh from ..preprocessing import data_splitting as ds from ..feature_extractors.vocabulary_with_counts import VocabWithCounts def main(): usage = "%prog project" pars...
assert count == n_words output_filename = os.path.join(dirs.lda_dir, 'word_num.json') fh.write_to_json(list(vocab_assignments), output_filename, sort_keys=False) output_filename = os.path.join(dirs.lda_dir, 'word_doc.json') fh.write_to_json(list(doc_assignments), output_filename, sort_keys=False...
v_index = vocab.get_index(t) assert v_index >= 0 #w_topic = np.random.randint(n_topics) vocab_assignments[count] = v_index #topic_assignments[count] = w_topic doc_assignments[count] = d_i #topic_counts[w_topic] += 1 #vocab_topics[v_in...
conditional_block
lda_preprocessing.py
from optparse import OptionParser import re import os import sys import numpy as np from ..util import dirs from ..util import file_handling as fh from ..preprocessing import data_splitting as ds from ..feature_extractors.vocabulary_with_counts import VocabWithCounts def
(): usage = "%prog project" parser = OptionParser(usage=usage) parser.add_option('-v', dest='vocab_size', default=10000, help='Vocabulary size (most frequent words): default=%default') parser.add_option('--seed', dest='seed', default=42, help='Random seed: def...
main
identifier_name
trackModel.js
var WO = WO || {}; WO.Track = Backbone.Model.extend({ urlRoot: '/api/tracks', idAttribute: '_id', defaults: { notes: "", title: 'Acoustic Piano', isMuted: false, solo: false, octave: 4, volume: 0.75, instrument: "", type: 'MIDI' }, initialize : function(){ this.set('not...
} }, saveTrack: function(){ var instrument = this.get('instrument'); var mRender = this.get('mRender'); this.set('instrument', ''); this.set('mRender', ''); var that = this; var newlySaveTrack = $.when(that.save()).done(function(){ that.set('instrument', instrument); that.se...
random_line_split
trackModel.js
var WO = WO || {}; WO.Track = Backbone.Model.extend({ urlRoot: '/api/tracks', idAttribute: '_id', defaults: { notes: "", title: 'Acoustic Piano', isMuted: false, solo: false, octave: 4, volume: 0.75, instrument: "", type: 'MIDI' }, initialize : function(){ this.set('not...
() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function() { return s4() + s4() + s4(); }; })(), changeInstrument: function(instrumentName) { var instType = { 'Acoustic Piano': 'MIDI', 'Audio File': 'Audio', ...
s4
identifier_name
trackModel.js
var WO = WO || {}; WO.Track = Backbone.Model.extend({ urlRoot: '/api/tracks', idAttribute: '_id', defaults: { notes: "", title: 'Acoustic Piano', isMuted: false, solo: false, octave: 4, volume: 0.75, instrument: "", type: 'MIDI' }, initialize : function(){ this.set('not...
} else { this.set('notes', []); $('.active-track .track-notes').html(''); this.set('instrument', WO.InstrumentFactory(instrumentName, this)); } }, saveTrack: function(){ var instrument = this.get('instrument'); var mRender = this.get('mRender'); this.set('instrument', ''); ...
{ $('.active-track .track-notes').html(''); this.set('mRender', new WO.MidiRender(this.cid + ' .track-notes')); }
conditional_block
trackModel.js
var WO = WO || {}; WO.Track = Backbone.Model.extend({ urlRoot: '/api/tracks', idAttribute: '_id', defaults: { notes: "", title: 'Acoustic Piano', isMuted: false, solo: false, octave: 4, volume: 0.75, instrument: "", type: 'MIDI' }, initialize : function(){ this.set('not...
return function() { return s4() + s4() + s4(); }; })(), changeInstrument: function(instrumentName) { var instType = { 'Acoustic Piano': 'MIDI', 'Audio File': 'Audio', 'Microphone': 'Microphone', 'Acoustic Guitar Steel': 'MIDI', 'Alto Sax': 'MIDI', 'Church O...
{ return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }
identifier_body
test_serialization.py
import os import shutil import tempfile import numpy as np import pytest import torch from spotlight.cross_validation import random_train_test_split from spotlight.datasets import movielens from spotlight.evaluation import mrr_score, sequence_mrr_score from spotlight.evaluation import rmse_score from spotlight.factor...
def test_explicit_serialization(data): train, test = data model = ExplicitFactorizationModel(loss='regression', n_iter=3, batch_size=1024, learning_rate=1e-3, ...
interactions = movielens.get_movielens_dataset('100K') train, test = random_train_test_split(interactions, random_state=RANDOM_STATE) return train, test
identifier_body
test_serialization.py
import os import shutil import tempfile import numpy as np import pytest import torch from spotlight.cross_validation import random_train_test_split from spotlight.datasets import movielens from spotlight.evaluation import mrr_score, sequence_mrr_score from spotlight.evaluation import rmse_score from spotlight.factor...
try: fname = os.path.join(dirname, "model.pkl") torch.save(model, fname) model = torch.load(fname) finally: shutil.rmtree(dirname) return model @pytest.fixture(scope="module") def data(): interactions = movielens.get_movielens_dataset('100K') train, test = ran...
dirname = tempfile.mkdtemp()
random_line_split
test_serialization.py
import os import shutil import tempfile import numpy as np import pytest import torch from spotlight.cross_validation import random_train_test_split from spotlight.datasets import movielens from spotlight.evaluation import mrr_score, sequence_mrr_score from spotlight.evaluation import rmse_score from spotlight.factor...
(model): dirname = tempfile.mkdtemp() try: fname = os.path.join(dirname, "model.pkl") torch.save(model, fname) model = torch.load(fname) finally: shutil.rmtree(dirname) return model @pytest.fixture(scope="module") def data(): interactions = movielens.get_moviel...
_reload
identifier_name
runtime_display_panel.py
''' Created on Dec 23, 2013 @author: Chris ''' import sys import wx from gooey.gui.lang import i18n from gooey.gui.message_event import EVT_MSG class
(object): def __init__(self): # self.queue = queue self.stdout = sys.stdout # Overrides stdout's write method def write(self, text): raise NotImplementedError class RuntimeDisplay(wx.Panel): def __init__(self, parent, build_spec, **kwargs): wx.Panel.__init__(self, parent, **kwargs) sel...
MessagePump
identifier_name
runtime_display_panel.py
''' Created on Dec 23, 2013 @author: Chris ''' import sys import wx from gooey.gui.lang import i18n from gooey.gui.message_event import EVT_MSG class MessagePump(object): def __init__(self): # self.queue = queue self.stdout = sys.stdout # Overrides stdout's write method def write(self, text): ...
def _init_properties(self): self.SetBackgroundColour('#F0F0F0') def _init_components(self): self.text = wx.StaticText(self, label=i18n._("status")) self.cmd_textbox = wx.TextCtrl( self, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH) if self.build_spec.get('monospace_displ...
random_line_split
runtime_display_panel.py
''' Created on Dec 23, 2013 @author: Chris ''' import sys import wx from gooey.gui.lang import i18n from gooey.gui.message_event import EVT_MSG class MessagePump(object): def __init__(self): # self.queue = queue self.stdout = sys.stdout # Overrides stdout's write method def write(self, text): ...
def _do_layout(self): sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddSpacer(10) sizer.Add(self.text, 0, wx.LEFT, 30) sizer.AddSpacer(10) sizer.Add(self.cmd_textbox, 1, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 30) sizer.AddSpacer(20) self.SetSizer(sizer) self.Bind(EVT_MSG, self.OnMsg) ...
self.text = wx.StaticText(self, label=i18n._("status")) self.cmd_textbox = wx.TextCtrl( self, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH) if self.build_spec.get('monospace_display'): pointsize = self.cmd_textbox.GetFont().GetPointSize() font = wx.Font(pointsize, wx.FONTF...
identifier_body
runtime_display_panel.py
''' Created on Dec 23, 2013 @author: Chris ''' import sys import wx from gooey.gui.lang import i18n from gooey.gui.message_event import EVT_MSG class MessagePump(object): def __init__(self): # self.queue = queue self.stdout = sys.stdout # Overrides stdout's write method def write(self, text): ...
def _do_layout(self): sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddSpacer(10) sizer.Add(self.text, 0, wx.LEFT, 30) sizer.AddSpacer(10) sizer.Add(self.cmd_textbox, 1, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 30) sizer.AddSpacer(20) self.SetSizer(sizer) self.Bind(EVT_MSG, self.OnMsg) ...
pointsize = self.cmd_textbox.GetFont().GetPointSize() font = wx.Font(pointsize, wx.FONTFAMILY_MODERN, wx.FONTWEIGHT_NORMAL, wx.FONTWEIGHT_BOLD, False) self.cmd_textbox.SetFont(font)
conditional_block
lib.rs
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern c...
{ // Init router let mut routes = Router::new(); // Add routes frontend::add_routes(&mut routes); admin::add_routes(&mut routes); // Add static router let mut mount = Mount::new(); mount .mount("/", routes) .mount("/assets/", Static::new(Path::new("static"))); // ....
identifier_body
lib.rs
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern c...
/// // Start applocation and other actions /// // Iron::new(chain).http("localhost:3000").unwrap(); /// } /// ``` pub fn routes() -> Mount { // Init router let mut routes = Router::new(); // Add routes frontend::add_routes(&mut routes); admin::add_routes(&mut routes); // Add static route...
/// chain.link_after(iron_cms::middleware::template_render(paths)); /// // Add error-404 handler /// chain.link_after(iron_cms::middleware::Error404);
random_line_split
lib.rs
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern c...
() -> Mount { // Init router let mut routes = Router::new(); // Add routes frontend::add_routes(&mut routes); admin::add_routes(&mut routes); // Add static router let mut mount = Mount::new(); mount .mount("/", routes) .mount("/assets/", Static::new(Path::new("static"))...
routes
identifier_name
SpellInfo.js
import SPELLS from 'common/SPELLS'; /* * Fields: * int: spell scales with Intellect * crit: spell scales with (is able to or procced from) Critical Strike * hasteHpm: spell does more healing due to Haste, e.g. HoTs that gain more ticks * hasteHpct: spell can be cast more frequently due to Haste, basically any spe...
export default { [SPELLS.OCEANS_EMBRACE.id]: { // Sea Star of the Depthmother int: false, crit: true, hasteHpct: true, // until LoD's CD is below 8 sec, this speeds up the deck cycle time mastery: false, vers: true, }, [SPELLS.GUIDING_HAND.id]: { // The Deceiver's Grand Design int: false, ...
*/ // This only works with actual healing events; casts are not recognized.
random_line_split
harfbuzz.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/. */ extern crate harfbuzz; use font::{Font, FontHandleMethods, FontTableMethods, FontTableTag}; use platform::font::F...
(font: &mut Font) -> Shaper { unsafe { // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended let font_ptr = font as *mut Font; let hb_face: *mut hb_face_t = hb_face_create_for_tables(get_font_table_func, ...
new
identifier_name
harfbuzz.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/. */ extern crate harfbuzz; use font::{Font, FontHandleMethods, FontTableMethods, FontTableTag}; use platform::font::F...
// processed. while glyph_span.begin() < glyph_count { // start by looking at just one glyph. glyph_span.extend_by(1); debug!("Processing glyph at idx={}", glyph_span.begin()); let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin()); ...
let mut y_pos = Au(0); // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be
random_line_split
harfbuzz.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/. */ extern crate harfbuzz; use font::{Font, FontHandleMethods, FontTableMethods, FontTableTag}; use platform::font::F...
// shift up our working spans past things we just handled. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end();; // FIXME: borrow checker workaround char_byte_span.reset(end, 0); ...
{ // collect all glyphs to be assigned to the first character. let mut datas = vec!(); for glyph_i in glyph_span.each_index() { let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos); datas.push(GlyphData::new(shape.codepo...
conditional_block
setup.py
################################ # These variables are overwritten by Zenoss when the ZenPack is exported # or saved. Do not modify them directly here. # NB: PACKAGES is deprecated NAME = 'ZenPacks.community.DistributedCollectors' VERSION = '1.7' AUTHOR = 'Egor Puzanov' LICENSE = '' NAMESPACE_PACKAGES = ['ZenPacks', '...
version = VERSION, author = AUTHOR, license = LICENSE, # This is the version spec which indicates what versions of Zenoss # this ZenPack is compatible with compatZenossVers = COMPAT_ZENOSS_VERS, # previousZenPackName is a facility for telling Zenoss that the name # of this ZenPack has ...
# This ZenPack metadata should usually be edited with the Zenoss # ZenPack edit page. Whenever the edit page is submitted it will # overwrite the values below (the ones it knows about) with new values. name = NAME,
random_line_split
dispatcher.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mtcp is distributed in the...
// fn skip_tun_incoming(connection: Connection) -> bool { // let tun_ip: IpAddr = IpAddr::from_str("10.0.0.1").unwrap(); // let source_ip = connection.source.ip(); // let destination_ip = connection.destination.ip(); // debug!("comparing {:#?} -> {:#?}, {:#?}", source_ip, destination_ip, tun_ip); /...
{ while let Ok(Some(received)) = tun_in_receiver.recv() { match parse_packet(&received) { Some(Packet::UDP(udp)) => { // debug!("Dispatch UDP: {:#?}", udp.connection); match udp_sender { None => {} Some(ref sender) => { ...
identifier_body
dispatcher.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mtcp is distributed in the...
( tun_in_receiver: TunReceiver, udp_sender: Option<mpsc::Sender<UDP>>, tcp_sender: Option<mpsc::Sender<TCP>>, ) { while let Ok(Some(received)) = tun_in_receiver.recv() { match parse_packet(&received) { Some(Packet::UDP(udp)) => { // debug!("Dispa...
dispatch
identifier_name
dispatcher.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mtcp is distributed in the...
} } Some(Packet::TCP(tcp)) => { // debug!("Dispatch TCP: {:#?}", tcp.connection); match tcp_sender { None => {} Some(ref sender) => { let _ = sender.send(tcp); } ...
random_line_split
shave.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.shave = factory()); }(this, (function () { 'use strict'; function shave(target, maxHeight, opts)
var plugin = window.$ || window.jQuery || window.Zepto; if (plugin) { plugin.fn.extend({ shave: function shaveFunc(maxHeight, opts) { return shave(this, maxHeight, opts); } }); } return shave; })));
{ if (!maxHeight) throw Error('maxHeight is required'); var els = typeof target === 'string' ? document.querySelectorAll(target) : target; if (!('length' in els)) els = [els]; var defaults = { character: '…', classname: 'js-shave', spaces: true }; var character = opts && opts.character || defau...
identifier_body
shave.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.shave = factory()); }(this, (function () { 'use strict'; function
(target, maxHeight, opts) { if (!maxHeight) throw Error('maxHeight is required'); var els = typeof target === 'string' ? document.querySelectorAll(target) : target; if (!('length' in els)) els = [els]; var defaults = { character: '…', classname: 'js-shave', spaces: true }; var character = opts ...
shave
identifier_name
shave.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.shave = factory()); }(this, (function () { 'use strict'; function shave(target, maxHeight, opts) { if (!maxHeight) thr...
for (var i = 0; i < els.length; i++) { var el = els[i]; var span = el.querySelector('.' + classname); // If element text has already been shaved if (span) { // Remove the ellipsis to recapture the original text el.removeChild(el.querySelector('.js-shave-char')); el.textContent = el...
var character = opts && opts.character || defaults.character; var classname = opts && opts.classname || defaults.classname; var spaces = opts && opts.spaces === false ? false : defaults.spaces; var charHtml = '<span class="js-shave-char">' + character + '</span>';
random_line_split
banner.ts
import { readFile, writeFile } from "fs-extra"; import log from "loglevel"; import { BuiltInParserName } from "prettier"; import { CopyConfig, COPY_BANNER } from "../../constants"; import { format } from "../format"; /** * Copies a file with a banner showing it should not be manually updated. */ export async functi...
( files: readonly CopyConfig[] ): Promise<void> { await Promise.all( files.map(({ src, dest }) => copyFileWithBanner(src, dest).catch((e) => { log.error(e); process.exit(1); }) ) ); }
copyFilesWithBanner
identifier_name
banner.ts
import { readFile, writeFile } from "fs-extra"; import log from "loglevel"; import { BuiltInParserName } from "prettier"; import { CopyConfig, COPY_BANNER } from "../../constants"; import { format } from "../format"; /** * Copies a file with a banner showing it should not be manually updated. */ export async functi...
(e) => { log.error(e); process.exit(1); } ); } export async function copyFilesWithBanner( files: readonly CopyConfig[] ): Promise<void> { await Promise.all( files.map(({ src, dest }) => copyFileWithBanner(src, dest).catch((e) => { log.error(e); process.exit(1); ...
): Promise<void> { const contents = await readFile(src, "utf8"); return writeFile(dest, format(`${COPY_BANNER}${contents}`, parser)).catch(
random_line_split
banner.ts
import { readFile, writeFile } from "fs-extra"; import log from "loglevel"; import { BuiltInParserName } from "prettier"; import { CopyConfig, COPY_BANNER } from "../../constants"; import { format } from "../format"; /** * Copies a file with a banner showing it should not be manually updated. */ export async functi...
{ await Promise.all( files.map(({ src, dest }) => copyFileWithBanner(src, dest).catch((e) => { log.error(e); process.exit(1); }) ) ); }
identifier_body
networks.py
# coding=utf-8 # Copyright 2022 The TensorFlow GAN Authors. # # 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 applicabl...
return 'progressive_gan_block_{}'.format(block_id) def min_total_num_images(stable_stage_num_images, transition_stage_num_images, num_blocks): """Returns the minimum total number of images. Computes the minimum total number of images required to reach the desired `resolution`. Arg...
def block_name(block_id): """Returns the scope name for the network block `block_id`."""
random_line_split
networks.py
# coding=utf-8 # Copyright 2022 The TensorFlow GAN Authors. # # 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 applicabl...
return self._scale_base**(self._num_resolutions - block_id) def block_name(block_id): """Returns the scope name for the network block `block_id`.""" return 'progressive_gan_block_{}'.format(block_id) def min_total_num_images(stable_stage_num_images, transition_stage_num_images, num...
raise ValueError('`block_id` must be in [1, {}]'.format( self._num_resolutions))
conditional_block
networks.py
# coding=utf-8 # Copyright 2022 The TensorFlow GAN Authors. # # 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 applicabl...
(x, block_id): return _conv2d('from_rgb', x, 1, num_filters_fn(block_id)) end_points = {} with tf.variable_scope(scope, reuse=reuse): x0 = x end_points['rgb'] = x0 lods = [] for block_id in range(num_blocks, 0, -1): with tf.variable_scope(block_name(block_id)): scale = resolutio...
_from_rgb
identifier_name
networks.py
# coding=utf-8 # Copyright 2022 The TensorFlow GAN Authors. # # 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 applicabl...
@property def final_resolutions(self): """Returns the final resolutions.""" return tuple([ r * self._scale_base**(self._num_resolutions - 1) for r in self._start_resolutions ]) def scale_factor(self, block_id): """Returns the scale factor for network block `block_id`.""" if ...
return self._num_resolutions
identifier_body
geopolygon.js
/** * Pimcore *
* http://www.pimcore.org/license * * @copyright Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at) * @license http://www.pimcore.org/license New BSD License */ pimcore.registerNS('pimcore.object.classes.data.geopolygon'); pimcore.object.classes.data.geopolygon = C...
* LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL:
random_line_split
test-stream-writable-samecb-singletick.js
'use strict'; const common = require('../common'); const { Console } = require('console'); const { Writable } = require('stream'); const async_hooks = require('async_hooks'); // Make sure that repeated calls to console.log(), and by extension // stream.write() for the underlying stream, allocate exactly 1 tick object....
})); for (let i = 0; i < 100; i++) console.log(i);
random_line_split
test-stream-writable-samecb-singletick.js
'use strict'; const common = require('../common'); const { Console } = require('console'); const { Writable } = require('stream'); const async_hooks = require('async_hooks'); // Make sure that repeated calls to console.log(), and by extension // stream.write() for the underlying stream, allocate exactly 1 tick object....
}).enable(); const console = new Console(new Writable({ write: common.mustCall((chunk, encoding, cb) => { cb(); }, 100) })); for (let i = 0; i < 100; i++) console.log(i);
{ if (type === 'TickObject') checkTickCreated(); }
identifier_body
test-stream-writable-samecb-singletick.js
'use strict'; const common = require('../common'); const { Console } = require('console'); const { Writable } = require('stream'); const async_hooks = require('async_hooks'); // Make sure that repeated calls to console.log(), and by extension // stream.write() for the underlying stream, allocate exactly 1 tick object....
(id, type, triggerId, resoure) { if (type === 'TickObject') checkTickCreated(); } }).enable(); const console = new Console(new Writable({ write: common.mustCall((chunk, encoding, cb) => { cb(); }, 100) })); for (let i = 0; i < 100; i++) console.log(i);
init
identifier_name
__init__.py
import logging from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from corehq.apps.adm.dispatcher import ADMSectionDispatcher from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSort...
return self.adm_report.columns return [] @property def headers(self): if self.subreport_slug is None: raise ValueError("Cannot render this report. A subreport_slug is required.") header = DataTablesHeader(DataTablesColumn(_("FLW Name"))) for col in self....
col.set_report_values(**column_config)
conditional_block
__init__.py
import logging from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from corehq.apps.adm.dispatcher import ADMSectionDispatcher from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSort...
return True
random_line_split
__init__.py
import logging from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from corehq.apps.adm.dispatcher import ADMSectionDispatcher from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSort...
class DefaultReportADMSectionView(GenericTabularReport, ADMSectionView, ProjectReportParametersMixin, DatespanMixin): section_name = ugettext_noop("Active Data Management") base_template = "reports/base_template.html" dispatcher = ADMSectionDispatcher fix_left_col = True fields = ['corehq.apps....
section_name = ugettext_noop("Active Data Management") base_template = "reports/base_template.html" dispatcher = ADMSectionDispatcher hide_filters = True emailable = True # adm-specific stuff adm_slug = None def __init__(self, request, base_context=None, domain=None, **kwargs): ...
identifier_body
__init__.py
import logging from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from corehq.apps.adm.dispatcher import ADMSectionDispatcher from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSort...
(cls, domain=None, render_as=None, **kwargs): subreport = kwargs.get('subreport') url = super(ADMSectionView, cls).get_url(domain=domain, render_as=render_as, **kwargs) return "%s%s" % (url, "%s/" % subreport if subreport else "") class DefaultReportADMSectionView(GenericTabularReport, ADMSect...
get_url
identifier_name
call-cache.ts
import { Call } from '@grpc/grpc-js'; // A call can also emit 'metadata' and 'status' events let _calls: Record<string, Call> = {}; const activeCount = () => Object.keys(_calls).length; const get = (requestId: string): Call | undefined => { const call: Call = _calls[requestId]; if (!call) { console.log(`[gR...
channel.close(); } else { console.log(`[gRPC] failed to close channel for req=${requestId} because it was not found`); } }; const clear = (requestId: string): void => { _tryCloseChannel(requestId); delete _calls[requestId]; }; const reset = (): void => { _calls = {}; }; const callCache = { activ...
if (channel) {
random_line_split
call-cache.ts
import { Call } from '@grpc/grpc-js'; // A call can also emit 'metadata' and 'status' events let _calls: Record<string, Call> = {}; const activeCount = () => Object.keys(_calls).length; const get = (requestId: string): Call | undefined => { const call: Call = _calls[requestId]; if (!call)
return call; }; const set = (requestId: string, call: Call): void => { _calls[requestId] = call; }; const _tryCloseChannel = (requestId: string) => { // @ts-expect-error -- TSCONVERSION channel not found in call const channel = get(requestId)?.call?.call.channel; if (channel) { channel.close(); } e...
{ console.log(`[gRPC] client call for req=${requestId} not found`); }
conditional_block
replace_wrapped.js
// Expects to be preceeded by javascript that creates a variable called selectRange that // defines the segment to be wrapped and replaced. // create custom range object for wrapSelection var replaceRange = $.fn.range; replaceRange.ClearVariables(); replaceRange.startContainer = selectRange.startContainer; ...
if(n==0){ $(this).data('undo', $(this).html()); $(this).html("$ESCAPED_TEXT_HERE"); } else { $(this).data('undo', $(this).html()); // Assign an id so that this element isn't automatically deleted. $(this).attr("id",selectMarker+n); $(this).html(''); } }); // We need to normalize the text nod...
// insert the new text in the first element of the wrapped range and clear the rest. $('.'+selectMarker).each(function(n) {
random_line_split
replace_wrapped.js
// Expects to be preceeded by javascript that creates a variable called selectRange that // defines the segment to be wrapped and replaced. // create custom range object for wrapSelection var replaceRange = $.fn.range; replaceRange.ClearVariables(); replaceRange.startContainer = selectRange.startContainer; ...
}); // We need to normalize the text nodes since they're screwed up now selectRange.startContainer.parentNode.normalize(); // Set the cursor to point to the end of the replaced text. selectRange.collapse( false ); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(selectRange); ...
{ $(this).data('undo', $(this).html()); // Assign an id so that this element isn't automatically deleted. $(this).attr("id",selectMarker+n); $(this).html(''); }
conditional_block
index.d.ts
// Type definitions for babel-core 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-core // Definitions by: Troy Gerwien <https://github.com/yortus> // Marvin Hagemeister <https://github.com/marvinhagemeister> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /...
filename?: string; /** Filename relative to `sourceRoot`. */ filenameRelative?: string; /** An object containing the options to be passed down to the babel code generator, babel-generator. Default: `{}` */ generatorOpts?: GeneratorOptions; /** * Specify a custom callback to generate a mo...
random_line_split
labelrenderer.ts
import { CSS2DRenderer } from "./css2drenderer"; import { CSS2DObject } from "./css2dobject"; export class LabelRenderer extends CSS2DRenderer { renderer; private _root: THREE.Group; constructor(public element: HTMLElement)
create() { let bounds = this.element.getBoundingClientRect(); this.setSize(bounds.width, bounds.height); this.domElement.style.position = "absolute"; this.domElement.style.top = "0"; this.domElement.style.pointerEvents = "none"; this.element.appendChild(this.domElement); ...
{ super(); this._root = new THREE.Group(); }
identifier_body
labelrenderer.ts
import { CSS2DRenderer } from "./css2drenderer"; import { CSS2DObject } from "./css2dobject"; export class LabelRenderer extends CSS2DRenderer { renderer; private _root: THREE.Group;
(public element: HTMLElement) { super(); this._root = new THREE.Group(); } create() { let bounds = this.element.getBoundingClientRect(); this.setSize(bounds.width, bounds.height); this.domElement.style.position = "absolute"; this.domElement.style.top = "0"; this.domElem...
constructor
identifier_name
labelrenderer.ts
import { CSS2DRenderer } from "./css2drenderer"; import { CSS2DObject } from "./css2dobject";
constructor(public element: HTMLElement) { super(); this._root = new THREE.Group(); } create() { let bounds = this.element.getBoundingClientRect(); this.setSize(bounds.width, bounds.height); this.domElement.style.position = "absolute"; this.domElement.style.top = "0"; ...
export class LabelRenderer extends CSS2DRenderer { renderer; private _root: THREE.Group;
random_line_split
_guajacum.py
# -*- Mode:Python -*- ########################################################################## # # # Guacamole Tree printer # # ...
def __printRecursively(self, node, cur_depth, args, cur_path=[], is_grouped=False): # return if current node name matches user-specified exclude pattern if None != args['exclude_pattern'] and re.search( args['exclude_pattern'], ...
""" Print Avango scene graph recursively. @param args: dict of arguments for the tree generation. Possible keys are: - int max_depth: reduce maximum tree depth (-1 means full tree traversal) - str exclude_pattern: regular expression to exclude cer...
identifier_body
_guajacum.py
# -*- Mode:Python -*- ########################################################################## # # # Guacamole Tree printer # # ...
else: raise Exception( "Invalid tree structure, missing attributes 'Root' or 'Children'") self.__printRecursively(_root, 0, joined_args) def __printRecursively(self, node, cur_depth, args, cur_path=[], is_grouped=Fa...
_root = self._root
conditional_block
_guajacum.py
# -*- Mode:Python -*- ########################################################################## # # # Guacamole Tree printer # # ...
""" # check given arguments for i in list(args.keys()): if i not in self._treeOpts: print(self._colorize('error', "Invalid argument '" + i + "'"), file=sys.stderr) return joined_args = dict(list(self._treeOpts.items()) ...
- bool print_field_names: show field names for each node - bool print_field_values: show values of fields for each node (implies print_field_names) @type args: dict @throws Exception: Invalid tree structure
random_line_split
_guajacum.py
# -*- Mode:Python -*- ########################################################################## # # # Guacamole Tree printer # # ...
(self, graph): self._root = graph def printTree(self, args): """ Print Avango scene graph recursively. @param args: dict of arguments for the tree generation. Possible keys are: - int max_depth: reduce maximum tree depth (-1 means full tree traversal)...
__init__
identifier_name
etherpad.js
(function( $ ){ $.fn.pad = function( options ) { var settings = { 'host' : 'http://172.19.220.122:9001', 'baseUrl' : '/p/', 'showControls' : true, 'showChat' : false, 'showLineNumbers' : false, 'userName' : 'unnamed', 'useM...
$self .hide() .after($toggleLink) .after($iFrameLink) ; } else { $self.html(iFrameLink); } } // This reads the etherpad contents if required else { var frameUrl = $('#'+ epframeId).attr('src').split('?')[0]; var conte...
$this.toggleClass('active'); if ($this.hasClass('active')) $this.text(settings.toggleTextOff); $self.pad({getContents: true}); return false; });
random_line_split