file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
__init__.py | from django.conf import settings, UserSettingsHolder
from django.contrib.auth.models import User
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test.client import Client
from django.utils.functional import wraps
from django.utils.importlib import import_module
import constance.config
... | (object):
"""
See http://djangosnippets.org/snippets/2437/
Acts as either a decorator, or a context manager. If it's a decorator it
takes a function and returns a wrapped function. If it's a contextmanager
it's used with the ``with`` statement. In either event entering/exiting
are called bef... | overrider | identifier_name |
__init__.py | from django.conf import settings, UserSettingsHolder
from django.contrib.auth.models import User
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test.client import Client
from django.utils.functional import wraps
from django.utils.importlib import import_module
import constance.config
... |
def get_user(username='testuser'):
"""Return a django user or raise FixtureMissingError"""
try:
return User.objects.get(username=username)
except User.DoesNotExist:
raise FixtureMissingError(
'Username "%s" not found. You probably forgot to import a'
' users fixtur... | eq_(v, getattr(received, k)) | conditional_block |
index.js | 'use strict';
var ruleMap = {
'es3-member-expression-literals': [],
'es3-property-literals': [],
'es5-property-mutators': [],
'es2015-arrow-functions': ['arrowFunctions'],
'es2015-block-scoping': ['blockBindings'],
'es2015-classes': ['classes'],
'es2015-computed-properties': ['objectLiteralComputedProper... |
return ruleMap[pluginName];
};
| {
return [];
} | conditional_block |
index.js | 'use strict';
var ruleMap = {
'es3-member-expression-literals': [],
'es3-property-literals': [],
'es5-property-mutators': [],
'es2015-arrow-functions': ['arrowFunctions'], | 'es2015-destructuring': ['destructuring'],
'es2015-for-of': ['forOf'],
'es2015-function-name': [],
'es2015-literals': ['binaryLiterals', 'octalLiterals'],
'es2015-object-super': ['superInFunctions'],
'es2015-parameters': ['defaultParams'],
'es2015-shorthand-properties': ['objectLiteralShorthandProperties'... | 'es2015-block-scoping': ['blockBindings'],
'es2015-classes': ['classes'],
'es2015-computed-properties': ['objectLiteralComputedProperties'],
'es2015-constants': ['blockBindings'], | random_line_split |
windowToggle.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
export function window... |
_complete() {
const contexts = this.contexts;
while (contexts.length > 0) {
const context = contexts.shift();
context.window.complete();
context.subscription.unsubscribe();
}
this.destination.complete();
}
openWindow(value: O) {
const closingSelector = this.closingSelector... | {
const contexts = this.contexts;
while (contexts.length > 0) {
contexts.shift().window.error(err);
}
this.destination.error(err);
} | identifier_body |
windowToggle.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
export function window... | }
}
closeWindow(context: WindowContext<T>) {
const { window, subscription } = context;
const contexts = this.contexts;
contexts.splice(contexts.indexOf(context), 1);
window.complete();
this.remove(subscription);
subscription.unsubscribe();
}
}
class WindowClosingNotifierSubscriber<T,... | const subscription = closingNotifier._subscribe(subscriber);
this.add(context.subscription.add(subscription)); | random_line_split |
windowToggle.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
export function window... |
this.destination.complete();
}
openWindow(value: O) {
const closingSelector = this.closingSelector;
let closingNotifier = tryCatch(closingSelector)(value);
if (closingNotifier === errorObject) {
this.error(closingNotifier.e);
} else {
let context = {
window: new Subject<T>(... | {
const context = contexts.shift();
context.window.complete();
context.subscription.unsubscribe();
} | conditional_block |
windowToggle.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
export function window... | (err: any) {
const contexts = this.contexts;
while (contexts.length > 0) {
contexts.shift().window.error(err);
}
this.destination.error(err);
}
_complete() {
const contexts = this.contexts;
while (contexts.length > 0) {
const context = contexts.shift();
context.window.comp... | _error | identifier_name |
test_reference_bind.py | # Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.test... |
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.... | plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.matc... | identifier_body |
test_reference_bind.py | # Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.test... | ():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, N... | test_reconciled_entry | identifier_name |
test_reference_bind.py | # Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.test... |
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries()... | from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind | random_line_split |
settings.py | # Django settings for ssssss project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
import os
if 'SERVER_SOFTWARE' in os.environ:
from sae.const import (
MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB
)
else:
# Make `... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_DB,
'USER': MYSQL_USER,
'PASSWORD': MYSQL_PASS,
'HOST': MYSQL_HOST,
'PORT': MYSQL_PORT,
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https:... | MYSQL_HOST = 'localhost'
MYSQL_PORT = '3306'
MYSQL_USER = 'root'
MYSQL_PASS = 'root'
MYSQL_DB = 'app_pylabs' | conditional_block |
settings.py | # Django settings for ssssss project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
import os
if 'SERVER_SOFTWARE' in os.environ:
from sae.const import (
MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB
)
else:
# Make `... | # Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/to... | # Uncomment the next line to enable the admin:
'django.contrib.admin', | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import platform
import re
import sys
import subprocess
from distutils.sysconfig import get_python_lib
from setuptools import setup, find_packages
from voiceplay import (__title__,
__version__,
__description_... | setup(name='voiceplay',
version=__version__,
description=__description__,
author=__author__,
author_email=__author_email__,
url='https://github.com/tb0hdan/voiceplay',
packages=find_packages(exclude=['snowboy', 'vlcpython', 'docs', 'tests*']),
package_data={'': ['snowboydetect/... | random_line_split | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import platform
import re
import sys
import subprocess
from distutils.sysconfig import get_python_lib
from setuptools import setup, find_packages
from voiceplay import (__title__,
__version__,
__description_... |
else:
readme = ''
system_specific_packages = ['pyobjc'] if platform.system() == 'Darwin' else ['pyfestival', 'Skype4Py']
# hook to pip install for package sideloading
# broken pyaudio package
# snowboy extension
if sys.argv[1] in ['bdist_wheel', 'install']:
# pyaudio
if platform.system() == 'Darwin':
... | readme = io.open('README.rst', mode='r', encoding='utf8').read() | conditional_block |
weakref.rs | None` in its own
//! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT`
//! slot. When all associated `WeakRef` values are dropped, the
//! `WeakBox` itself is dropped too.
use core::nonzero::NonZero;
use dom::bindings::js::Root;
use dom::bindings::reflector::DomObject;
use dom::bindings::trace::JSTraceab... | /// Remove the entry from the underlying vector of weak references.
pub fn remove(self) -> WeakRef<T> {
let ref_ = self.vec.swap_remove(*self.index); | random_line_split | |
weakref.rs | //!
//! IDL interfaces marked as `weakReferenceable` in `Bindings.conf`
//! automatically implement the `WeakReferenceable` trait in codegen.
//! The instance object is responsible for setting `None` in its own
//! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT`
//! slot. When all associated `WeakRef` v... | else {
self.vec.swap_remove(i);
}
}
}
/// Clears the vector of its dead references.
pub fn retain_alive(&mut self) {
self.update(|_| ());
}
}
impl<T: WeakReferenceable> Deref for WeakRefVec<T> {
type Target = Vec<WeakRef<T>>;
fn deref(&self) -> &Ve... | {
f(WeakRefEntry { vec: self, index: &mut i });
} | conditional_block |
weakref.rs | //!
//! IDL interfaces marked as `weakReferenceable` in `Bindings.conf`
//! automatically implement the `WeakReferenceable` trait in codegen.
//! The instance object is responsible for setting `None` in its own
//! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT`
//! slot. When all associated `WeakRef` v... |
}
impl<T: WeakReferenceable> Drop for WeakRef<T> {
fn drop(&mut self) {
unsafe {
let (count, value) = {
let weak_box = &*self.ptr.get();
assert!(weak_box.count.get() > 0);
let count = weak_box.count.get() - 1;
weak_box.count.set(c... | {
// Do nothing.
} | identifier_body |
weakref.rs | //!
//! IDL interfaces marked as `weakReferenceable` in `Bindings.conf`
//! automatically implement the `WeakReferenceable` trait in codegen.
//! The instance object is responsible for setting `None` in its own
//! own `WeakBox` when it is collected, through the `DOM_WEAK_SLOT`
//! slot. When all associated `WeakRef` v... | <T: WeakReferenceable> {
vec: Vec<WeakRef<T>>,
}
impl<T: WeakReferenceable> WeakRefVec<T> {
/// Create a new vector of weak references.
pub fn new() -> Self {
WeakRefVec { vec: vec![] }
}
/// Calls a function on each reference which still points to a
/// live object. The order of the r... | WeakRefVec | identifier_name |
local.py |
# class attributes __module__, __name__ and __doc__ to the real
# object, but these needs to be a string when accessed from
# the Proxy class directly. This is a hack to make that work.
# -- See Issue #1087.
def __new__(cls, getter):
instance = type_.__new__(cls, cls_value)
instan... | try:
object.__delattr__(self, attr)
except AttributeError: # pragma: no cover
# May mask errors so ignore
pass | conditional_block | |
local.py | is Copyright by Werkzeug Team.
"""
from __future__ import absolute_import
import importlib
import sys
from .five import string
__all__ = ['Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate']
__module__ = __name__ # used by Proxy class body
PY3 = sys.version_info[0] == 3
def _default_cls_attr(name, type_, ... | (self):
return self._get_class()
def _get_current_object(self):
"""Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
loc = obj... | __class__ | identifier_name |
local.py | is Copyright by Werkzeug Team.
"""
from __future__ import absolute_import
import importlib
import sys
from .five import string
__all__ = ['Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate']
__module__ = __name__ # used by Proxy class body
PY3 = sys.version_info[0] == 3
def _default_cls_attr(name, type_, ... |
if not PY3:
__cmp__ = lambda x, o: cmp(x._get_current_object(), o) # noqa
__long__ = lambda x: long(x._get_current_object()) # noqa
class PromiseProxy(Proxy):
"""This is a proxy to an object that has not yet been evaulated.
:class:`Proxy` will evaluate the object each time, while t... | __enter__ = lambda x: x._get_current_object().__enter__()
__exit__ = lambda x, *a, **kw: x._get_current_object().__exit__(*a, **kw)
__reduce__ = lambda x: x._get_current_object().__reduce__() | random_line_split |
local.py | is Copyright by Werkzeug Team.
"""
from __future__ import absolute_import
import importlib
import sys
from .five import string
__all__ = ['Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate']
__module__ = __name__ # used by Proxy class body
PY3 = sys.version_info[0] == 3
def _default_cls_attr(name, type_, ... |
def __repr__(self):
try:
obj = self._get_current_object()
except RuntimeError: # pragma: no cover
return '<{0} unbound>'.format(self.__class__.__name__)
return repr(obj)
def __bool__(self):
try:
return bool(self._get_current_object())
... | try:
return self._get_current_object().__dict__
except RuntimeError: # pragma: no cover
raise AttributeError('__dict__') | identifier_body |
protomol_functions.py | #!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
import random
import math
#-------------------------------Constants-----------------------------------
DEFAULT_MONTE_CARLO_STEPS = 100
DEFAULT_OUTPUT_PATH = '.'
DEFAULT_MDSTEPS = 10000
DEFAULT_BOUNDARY_CONDITIONS = "Vacuum"
DEFAULT_OUTPUT_FREQ = 10000
DEFA... | dcd_file_name = ""
boundary_conditions = DEFAULT_BOUNDARY_CONDITIONS
monte_carlo_steps = DEFAULT_MONTE_CARLO_STEPS
md_steps = DEFAULT_MDSTEPS
output_freq = DEFAULT_OUTPUT_FREQ
output_path = DEFAULT_OUTPUT_PATH
replica_list = []
#------------------------Initialize random generator----------------------------
random.se... | #-----------------------------Global Data-------------------------------------
pdb_file = ""
psf_file = ""
par_file = ""
xyz_file_name = "" | random_line_split |
protomol_functions.py | #!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
import random
import math
#-------------------------------Constants-----------------------------------
DEFAULT_MONTE_CARLO_STEPS = 100
DEFAULT_OUTPUT_PATH = '.'
DEFAULT_MDSTEPS = 10000
DEFAULT_BOUNDARY_CONDITIONS = "Vacuum"
DEFAULT_OUTPUT_FREQ = 10000
DEFA... | (self, id, temp):
self.id = id
self.temp = temp
self.exchgd_replica_id = -1
self.potential_energy = None
self.prev_temp = None
self.exch_steps = []
self.running = 0
self.last_seen_step = -1
def __str__(self):
return "Replica %d at temp %f" % (self.id, self.temp)
#Function to generate a config file... | __init__ | identifier_name |
protomol_functions.py | #!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
import random
import math
#-------------------------------Constants-----------------------------------
DEFAULT_MONTE_CARLO_STEPS = 100
DEFAULT_OUTPUT_PATH = '.'
DEFAULT_MDSTEPS = 10000
DEFAULT_BOUNDARY_CONDITIONS = "Vacuum"
DEFAULT_OUTPUT_FREQ = 10000
DEFA... |
acceptProb = math.exp(-deltaE)
randNum = random.random()
if( randNum < acceptProb ):
return True
else:
return False
| return True | conditional_block |
protomol_functions.py | #!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
import random
import math
#-------------------------------Constants-----------------------------------
DEFAULT_MONTE_CARLO_STEPS = 100
DEFAULT_OUTPUT_PATH = '.'
DEFAULT_MDSTEPS = 10000
DEFAULT_BOUNDARY_CONDITIONS = "Vacuum"
DEFAULT_OUTPUT_FREQ = 10000
DEFA... | K_b = 0.001987191 #Constants.boltzmann()
deltaE = (1 / (K_b * t_i) - 1/ (K_b * t_j) ) - (u_j - u_i)
if( deltaE < 0 ):
return True
acceptProb = math.exp(-deltaE)
randNum = random.random()
if( randNum < acceptProb ):
return True
else:
return False | identifier_body | |
locale_nl.js | /*
@license
dhtmlxScheduler v.4.3.1 | This software is covered by GPL license. You also can obtain Commercial or Enterprise license to use it in non-GPL project - please contact sales@dhtmlx.com. Usage without proper license is prohibited.
(c) Dinamenta, UAB.
*/
scheduler.locale={date:{month_full:["Januari","Februari","Maart","April","Mei","Juni","Juli","... | random_line_split | |
precacheAndRoute.ts | /*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {addRoute} from './addRoute.js';
import {precache} from './precache.js';
import {PrecacheRouteOptions, PrecacheEntry} from './_typ... | (
entries: Array<PrecacheEntry | string>,
options?: PrecacheRouteOptions,
): void {
precache(entries);
addRoute(options);
}
export {precacheAndRoute};
| precacheAndRoute | identifier_name |
precacheAndRoute.ts | /*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style | */
import {addRoute} from './addRoute.js';
import {precache} from './precache.js';
import {PrecacheRouteOptions, PrecacheEntry} from './_types.js';
import './_version.js';
/**
* This method will add entries to the precache list and add a route to
* respond to fetch events.
*
* This is a convenience method that wi... | license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT. | random_line_split |
precacheAndRoute.ts | /*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {addRoute} from './addRoute.js';
import {precache} from './precache.js';
import {PrecacheRouteOptions, PrecacheEntry} from './_typ... |
export {precacheAndRoute};
| {
precache(entries);
addRoute(options);
} | identifier_body |
infrastructure_stack.py | # Copyright 2014 - Numergy
#
# 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, s... | """Represent a list of infrastructure_stacks in sqlalchemy."""
@classmethod
def get_all(cls, context):
return InfrastructureStackList(sql.model_query(context,
InfrastructureStack)) | identifier_body | |
infrastructure_stack.py | # Copyright 2014 - Numergy
#
# 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, s... | (cls, context):
return InfrastructureStackList(sql.model_query(context,
InfrastructureStack))
| get_all | identifier_name |
infrastructure_stack.py | # Copyright 2014 - Numergy
#
# 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, s... | from solum.objects.sqlalchemy import models as sql
class InfrastructureStack(sql.Base, abstract.InfrastructureStack):
"""Represent an infrastructure_stack in sqlalchemy."""
__tablename__ = 'infrastructure_stack'
__resource__ = 'infrastructure/stacks'
__table_args__ = sql.table_args()
id = sa.Col... |
import sqlalchemy as sa
from solum.objects import infrastructure_stack as abstract | random_line_split |
views.py | import logging
from django.views import generic
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.mail import send_mail
from django import http
from django.core.urlresolvers import reverse
from django.template.loader import get_template
from django.template import Context... | (self, real_email, user, password):
msg = get_template('gateway/email.txt').render(Context({
'email': user.email,
'password': password
}))
send_mail('Dashboard access to Oscar sandbox',
msg, 'blackhole@sandbox.qa.tangentlabs.co.uk',
[re... | send_confirmation_email | identifier_name |
views.py | import logging
from django.views import generic
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.mail import send_mail
from django import http
from django.core.urlresolvers import reverse
from django.template.loader import get_template
from django.template import Context... | msg = get_template('gateway/email.txt').render(Context({
'email': user.email,
'password': password
}))
send_mail('Dashboard access to Oscar sandbox',
msg, 'blackhole@sandbox.qa.tangentlabs.co.uk',
[real_email]) | def send_confirmation_email(self, real_email, user, password): | random_line_split |
views.py | import logging
from django.views import generic
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.mail import send_mail
from django import http
from django.core.urlresolvers import reverse
from django.template.loader import get_template
from django.template import Context... | msg = get_template('gateway/email.txt').render(Context({
'email': user.email,
'password': password
}))
send_mail('Dashboard access to Oscar sandbox',
msg, 'blackhole@sandbox.qa.tangentlabs.co.uk',
[real_email]) | identifier_body | |
ex-walking-01.js | // Copyright © 2014 John Watson
// Licensed under the terms of the MIT License
var GameState = function(game) {
};
// Load images and sounds
GameState.prototype.preload = function() {
this.game.load.image('ground', 'assets/gfx/ground.png');
this.game.load.image('player', 'assets/gfx/player.png');
};
// Setup... | // Define movement constants
this.MAX_SPEED = 500; // pixels/second
// Create a player sprite
this.player = this.game.add.sprite(this.game.width/2, this.game.height - 64, 'player');
// Enable physics on the player
this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
// Make playe... | random_line_split | |
ex-walking-01.js | // Copyright © 2014 John Watson
// Licensed under the terms of the MIT License
var GameState = function(game) {
};
// Load images and sounds
GameState.prototype.preload = function() {
this.game.load.image('ground', 'assets/gfx/ground.png');
this.game.load.image('player', 'assets/gfx/player.png');
};
// Setup... | else {
// Stop the player from moving horizontally
this.player.body.velocity.x = 0;
}
};
// This function should return true when the player activates the "go left" control
// In this case, either holding the right arrow or tapping or clicking on the left
// side of the screen.
GameState.prototype.... |
// If the RIGHT key is down, set the player velocity to move right
this.player.body.velocity.x = this.MAX_SPEED;
} | conditional_block |
setup-win.py | from setuptools import setup
import py2exe
import os
import glob
__import__('gtk')
__import__('jinja2')
__import__('docutils')
setup_dict = dict(
name='regenerate',
version='1.0.0',
license='License.txt',
author='Donald N. Allingham',
author_email='dallingham@gmail.com',
description='Reg... | 'MSVCP90.dll',
'api-ms-win-core-string-l1-1-0.dll',
'api-ms-win-core-registry-l1-1-0.dll',
'api-ms-win-core-errorhandling-l1-1-1.dll',
'api-ms-win-core-string-l2-1-0.dll',
... | 'includes' : 'cairo, pango, pangocairo, atk, gobject, gio, gtk.keysyms, jinja2',
'skip_archive' : True,
'dll_excludes': [ | random_line_split |
DeleteModal-test.tsx | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | organization: 'org',
q: 'bla',
qualifiers: 'TRK'
});
await new Promise(setImmediate);
expect(onConfirm).toBeCalled();
});
it('deletes selected projects', async () => {
const onConfirm = jest.fn();
const wrapper = shallowRender({ onConfirm, selection: ['proj1', 'proj2'] });
(wrapper.instance() ... | expect(wrapper).toMatchSnapshot();
expect(bulkDeleteProjects).toBeCalledWith({
analyzedBefore: '2017-04-08T00:00:00+0000',
onProvisionedOnly: undefined, | random_line_split |
pull-request-hotkey.tsx | import select from 'select-dom';
import features from '../libs/features';
function init(): void |
features.add({
id: __featureName__,
description: 'Adds keyboard shortcuts to cycle through PR tabs: `g` `←` and `g` `→`, or `g` `1`, `g` `2`, `g` `3` and `g` `4`',
screenshot: false,
include: [
features.isPR
],
load: features.onAjaxedPages,
shortcuts: {
'g 1': 'Go to Conversation',
'g 2': 'Go to Commits'... | {
const tabs = select.all('.tabnav-pr .tabnav-tab');
const selectedIndex = tabs.indexOf(select('.tabnav-pr .selected')!);
const lastTab = tabs.length - 1;
for (const [index, tab] of tabs.entries()) {
const keys = [`g ${index + 1}`];
if (index === selectedIndex - 1 || (selectedIndex === 0 && index === lastTab))... | identifier_body |
pull-request-hotkey.tsx | import select from 'select-dom';
import features from '../libs/features';
function | (): void {
const tabs = select.all('.tabnav-pr .tabnav-tab');
const selectedIndex = tabs.indexOf(select('.tabnav-pr .selected')!);
const lastTab = tabs.length - 1;
for (const [index, tab] of tabs.entries()) {
const keys = [`g ${index + 1}`];
if (index === selectedIndex - 1 || (selectedIndex === 0 && index === ... | init | identifier_name |
pull-request-hotkey.tsx | import select from 'select-dom';
import features from '../libs/features';
function init(): void {
const tabs = select.all('.tabnav-pr .tabnav-tab'); | const keys = [`g ${index + 1}`];
if (index === selectedIndex - 1 || (selectedIndex === 0 && index === lastTab)) {
keys.push('g ArrowLeft');
} else if (index === selectedIndex + 1 || (selectedIndex === lastTab && index === 0)) {
keys.push('g ArrowRight');
}
tab.dataset.hotkey = String(keys);
}
}
featu... | const selectedIndex = tabs.indexOf(select('.tabnav-pr .selected')!);
const lastTab = tabs.length - 1;
for (const [index, tab] of tabs.entries()) { | random_line_split |
pull-request-hotkey.tsx | import select from 'select-dom';
import features from '../libs/features';
function init(): void {
const tabs = select.all('.tabnav-pr .tabnav-tab');
const selectedIndex = tabs.indexOf(select('.tabnav-pr .selected')!);
const lastTab = tabs.length - 1;
for (const [index, tab] of tabs.entries()) {
const keys = [`g... |
tab.dataset.hotkey = String(keys);
}
}
features.add({
id: __featureName__,
description: 'Adds keyboard shortcuts to cycle through PR tabs: `g` `←` and `g` `→`, or `g` `1`, `g` `2`, `g` `3` and `g` `4`',
screenshot: false,
include: [
features.isPR
],
load: features.onAjaxedPages,
shortcuts: {
'g 1': 'Go... | {
keys.push('g ArrowRight');
} | conditional_block |
c_comm_init_op_mlu.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | unittest.main() | conditional_block | |
c_comm_init_op_mlu.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | (self):
self.endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS").split(',')
self.current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
self.nranks = len(self.endpoints)
self.rank = self.endpoints.index(self.current_endpoint)
self.mlu_id = int(os.getenv("FLAGS_selected_mlus"))
... | setUp | identifier_name |
c_comm_init_op_mlu.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | block.append_op(
type='c_gen_cncl_id',
inputs={},
outputs={'Out': cncl_id_var},
attrs={
'rank': self.rank,
'endpoint': self.current_endpoint,
'other_endpoints': self.other_endpoints
})
block.appen... | def setUp(self):
self.endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS").split(',')
self.current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
self.nranks = len(self.endpoints)
self.rank = self.endpoints.index(self.current_endpoint)
self.mlu_id = int(os.getenv("FLAGS_selected_ml... | identifier_body |
c_comm_init_op_mlu.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | self.current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
self.nranks = len(self.endpoints)
self.rank = self.endpoints.index(self.current_endpoint)
self.mlu_id = int(os.getenv("FLAGS_selected_mlus"))
self.place = fluid.MLUPlace(self.mlu_id)
self.exe = fluid.Executor(se... | def setUp(self):
self.endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS").split(',') | random_line_split |
nukeStub.py | #!/usr/bin/python2.5
import sys
import time
import os
import nuke
def launchSubmit():
|
menubar = nuke.menu("Nuke")
m = menubar.addMenu("&Render")
m.addCommand("Submit to Farm", "nukeStub.launchSubmit()", "Up")
| print("nukeStub(): launch submitter dialog")
submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (os.environ['DRD_JOB'], os.environ['DRD_DEPT'])
# root.name holds the path to the nuke script
submitCmd += " %s" % nuke.val... | identifier_body |
nukeStub.py | #!/usr/bin/python2.5
import sys
import time
import os
import nuke
def launchSubmit():
print("nukeStub(): launch submitter dialog") | submitCmd += " %s" % nuke.value("root.name")
submitCmd += " %s" % nuke.Root.firstFrame(nuke.root())
submitCmd += " %s" % nuke.Root.lastFrame(nuke.root())
writeNodes = [i for i in nuke.allNodes() if i.Class() == "Write"]
for i in writeNodes:
submitCmd += " %s %s" % (i['name'].value(), nuke.filename(i))
print( "... | submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (os.environ['DRD_JOB'], os.environ['DRD_DEPT'])
# root.name holds the path to the nuke script | random_line_split |
nukeStub.py | #!/usr/bin/python2.5
import sys
import time
import os
import nuke
def launchSubmit():
print("nukeStub(): launch submitter dialog")
submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (os.environ['DRD_JOB'], os.environ[... |
print( "nukeStub(): %s" % submitCmd )
os.system(submitCmd)
menubar = nuke.menu("Nuke")
m = menubar.addMenu("&Render")
m.addCommand("Submit to Farm", "nukeStub.launchSubmit()", "Up")
| submitCmd += " %s %s" % (i['name'].value(), nuke.filename(i)) | conditional_block |
nukeStub.py | #!/usr/bin/python2.5
import sys
import time
import os
import nuke
def | ():
print("nukeStub(): launch submitter dialog")
submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (os.environ['DRD_JOB'], os.environ['DRD_DEPT'])
# root.name holds the path to the nuke script
submitCmd += " %s" % nuk... | launchSubmit | identifier_name |
main-tab-entry.js | function openTab(value) {
var colours = new Object();
colours.one = 'rgba(126, 173, 199, 0.95)';
colours.two = 'rgba(95, 255, 249, 0.95)';
colours.three = 'rgba(242, 187, 255, 0.95)';
var borders = new Object();
borders.one = '#2790B9';
borders.two = '#0CE6E6';
borders.three = '#E6A4CB';
var tab... | {
var diary_box = document.getElementById('tabs-calendar-main-entry-tab-top-box');
if (diary_box.style.display == 'block') {
diary_box.style.display = 'none';
} else {
diary_box.style.display = 'block';
}
} | identifier_body | |
main-tab-entry.js | function openTab(value) {
var colours = new Object();
colours.one = 'rgba(126, 173, 199, 0.95)';
colours.two = 'rgba(95, 255, 249, 0.95)';
colours.three = 'rgba(242, 187, 255, 0.95)';
var borders = new Object();
borders.one = '#2790B9';
borders.two = '#0CE6E6';
borders.three = '#E6A4CB';
var tab... | $(tab3).css('z-index', 2);
$(tab1).css('z-index', 1);
$(tab2).css('z-index', 1);
}
document.getElementById('tabs-calendar-main-entry-tab-'+value).style.zIndex = 3;
document.getElementById('tabs-calendar-main-entry-tab-'+value+'-box').style.display = 'block';
var calendar = $('#tabs-calendar-m... | $(tab2).css('z-index', 2);
$(tab1).css('z-index', 1);
$(tab3).css('z-index', 1);
} else if(z3 == 3) {
| random_line_split |
main-tab-entry.js | function openTab(value) {
var colours = new Object();
colours.one = 'rgba(126, 173, 199, 0.95)';
colours.two = 'rgba(95, 255, 249, 0.95)';
colours.three = 'rgba(242, 187, 255, 0.95)';
var borders = new Object();
borders.one = '#2790B9';
borders.two = '#0CE6E6';
borders.three = '#E6A4CB';
var tab... | else if(z2 == 3) {
$(tab2).css('z-index', 2);
$(tab1).css('z-index', 1);
$(tab3).css('z-index', 1);
} else if(z3 == 3) {
$(tab3).css('z-index', 2);
$(tab1).css('z-index', 1);
$(tab2).css('z-index', 1);
}
document.getElementById('tabs-calendar-main-entry-tab-'+value).style.zIndex = 3... | {
$(tab1).css('z-index', 2);
$(tab1).css('z-index', 1);
$(tab3).css('z-index', 1);
} | conditional_block |
main-tab-entry.js | function openTab(value) {
var colours = new Object();
colours.one = 'rgba(126, 173, 199, 0.95)';
colours.two = 'rgba(95, 255, 249, 0.95)';
colours.three = 'rgba(242, 187, 255, 0.95)';
var borders = new Object();
borders.one = '#2790B9';
borders.two = '#0CE6E6';
borders.three = '#E6A4CB';
var tab... | () {
var diary_box = document.getElementById('tabs-calendar-main-entry-tab-top-box');
if (diary_box.style.display == 'block') {
diary_box.style.display = 'none';
} else {
diary_box.style.display = 'block';
}
} | openTabTop | identifier_name |
app.js | var win = Ti.UI.createWindow({
backgroundColor:'white'
});
win.open();
var GA = require('analytics.google');
//GA.optOut = true;
GA.debug = true;
GA.trackUncaughtExceptions = true;
var tracker = GA.getTracker("UA-XXXXXX-X");
tracker.trackEvent({
category: "category",
action: "test",
label: "label",
value: 1
});
... | target: "target"
});
tracker.trackTiming({
category: "",
time: 10,
name: "",
label: ""
});
tracker.trackScreen("Home");
var transaction = GA.makeTransaction({
id: "hi",
tax: 0.6,
shipping: 0,
revenue: 24.99 * 0.7
});
transaction.addItem({
sku: "ABC123",
name: "My Alphabet",
category: "product category",
p... | action: "action", | random_line_split |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... | (&self) -> Temporary<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Temporary::from_unrooted(Unroo... | to_temporary | identifier_name |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... | pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_v... | /// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance. | random_line_split |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... |
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.scrip... | {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Temporary::from_unrooted(Unrooted::from_raw(self.ptr a... | identifier_body |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... |
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(cx: *mut JSContext, raw_reflectable: TrustedReference) {
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references =... | {
unsafe {
let rootable = (*ptr).reflector().rootable();
JS_AddObjectRoot(cx, rootable);
}
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
} | conditional_block |
__init__.py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
class HT... | '''
def __init__(self):
self.host = ''
self.method = ''
self.path = ''
self.query = {} # list of (name, value)
self.headers = {} # list of (header name, header value)
self.body = '' | :ivar dict headers:
header values
:ivar bytes body:
the body of the request. | random_line_split |
__init__.py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
class HT... | (object):
'''
Represents a response from an HTTP request.
:ivar int status:
the status code of the response
:ivar str message:
the message
:ivar dict headers:
the returned headers
:ivar bytes body:
the body of the response
'''
def __init__(self, stat... | HTTPResponse | identifier_name |
__init__.py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
class HT... |
class HTTPResponse(object):
'''
Represents a response from an HTTP request.
:ivar int status:
the status code of the response
:ivar str message:
the message
:ivar dict headers:
the returned headers
:ivar bytes body:
the body of the response
'''
de... | self.status = status
self.respheader = respheader
self.respbody = respbody
Exception.__init__(self, message) | identifier_body |
RuneOfTheFallenCrusader.tsx | import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import Statistic from ... |
const UNHOLY_STRENGTH_STRENGTH = 0.15; // 15% Str buff while active
class RuneOfTheFallenCrusader extends Analyzer {
healing: number = 0;
overhealing: number = 0;
constructor(options: Options) {
super(options);
const active = this.selectedCombatant.hasWeaponEnchant(SPELLS.RUNE_OF_THE_FALLEN_CRUSADER);... | random_line_split | |
RuneOfTheFallenCrusader.tsx | import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import Statistic from ... |
this.addEventListener(
Events.heal.to(SELECTED_PLAYER).spell(SPELLS.UNHOLY_STRENGTH_BUFF),
this._onHeal,
);
}
_onHeal(event: HealEvent) {
if (event.overheal) {
this.overhealing += event.overheal;
}
this.healing += event.amount + event.absorb;
}
get overhealPercentage() ... | {
return;
} | conditional_block |
RuneOfTheFallenCrusader.tsx | import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import Statistic from ... | () {
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL(2)}
size="flexible"
tooltip={
<>
<strong>Uptime: </strong> {formatPercentage(this.uptime)}% <br />
<strong>Healing: </strong> {formatNumber(this.healing)} <br />
<strong>Overhealin... | statistic | identifier_name |
RuneOfTheFallenCrusader.tsx | import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import Statistic from ... | );
}
}
export default RuneOfTheFallenCrusader;
| {
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL(2)}
size="flexible"
tooltip={
<>
<strong>Uptime: </strong> {formatPercentage(this.uptime)}% <br />
<strong>Healing: </strong> {formatNumber(this.healing)} <br />
<strong>Overhealing: ... | identifier_body |
basic.js | import test from 'ava';
import debounce from 'lodash.debounce';
import webpack from 'webpack';
import 'babel-core/register';
import helper from './_helper';
import expected from './basic/expected.json';
test.beforeEach(t => {
const config = helper.getSuiteConfig('basic');
t.context.config = config
t.context.e... |
setTimeout(() => {
const output = require(t.context.extractOpts.outputFile);
t.same(output, expected);
t.end();
}, t.context.extractOpts.writeDebounceMs);
}
webpack(t.context.config, callback);
})
test('basic (onOutput)', t => {
t.plan(1);
const onOutput = debounce((filename, blo... | { t.fail(err); t.end(); } | conditional_block |
basic.js | import test from 'ava';
import debounce from 'lodash.debounce';
import webpack from 'webpack';
import 'babel-core/register';
import helper from './_helper';
import expected from './basic/expected.json';
test.beforeEach(t => {
const config = helper.getSuiteConfig('basic');
t.context.config = config
t.context.e... | t.end();
}, t.context.extractOpts.writeDebounceMs);
}
webpack(t.context.config, callback);
})
test('basic (onOutput)', t => {
t.plan(1);
const onOutput = debounce((filename, blob, total) => {
t.same(total, expected);
t.end();
}, t.context.extractOpts.writeDebounceMs);
const config = ... | if (err) { t.fail(err); t.end(); }
setTimeout(() => {
const output = require(t.context.extractOpts.outputFile);
t.same(output, expected); | random_line_split |
mod.rs | // Copyright 2015 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 ... | //! other fns cycle around. The handoff works like this:
//!
//! - `into(place)` -> fallback is to create a rvalue with `as_rvalue` and assign it to `place`
//! - `as_rvalue` -> fallback is to create an Operand with `as_operand` and use `Rvalue::use`
//! - `as_operand` -> either invokes `as_constant` or `as_temp`
//! -... | random_line_split | |
screenshot-asynchronous.rs | vector of (u8, u8, u8, u8).
// This is used to take data from PixelBuffer and move it to another thread
// with minimum conversions done on main thread.
pub struct RGBAImageData {
pub data: Vec<(u8, u8, u8, u8)>,
pub width: u32,
pub height: u32,
}
impl glium::texture::Textu... | else {
None
}
}
}
pub struct AsyncScreenshotTaker {
screenshot_delay: u64,
frame: u64,
screenshot_tasks: VecDeque<AsyncScreenshotTask>,
}
impl AsyncScreenshotTaker {
pub fn new(screenshot_delay: u64) -> Self {
AsyncScreen... | {
let task = self.0.screenshot_tasks.pop_front().unwrap();
Some(task.read_image_data())
} | conditional_block |
screenshot-asynchronous.rs | {
pub data: Vec<(u8, u8, u8, u8)>,
pub width: u32,
pub height: u32,
}
impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData {
fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self {
RGBAImageData {
data:... | // Convert (u8, u8, u8, u8) given by glium's PixelBuffer to flat u8 required by
// image's ImageBuffer. | random_line_split | |
screenshot-asynchronous.rs | vector of (u8, u8, u8, u8).
// This is used to take data from PixelBuffer and move it to another thread
// with minimum conversions done on main thread.
pub struct RGBAImageData {
pub data: Vec<(u8, u8, u8, u8)>,
pub width: u32,
pub height: u32,
}
impl glium::texture::Textu... | framebuffer.blit_from_frame(&rect,
&blit_target,
glium::uniforms::MagnifySamplerFilter::Nearest);
// Read the texture into new pixel buffer
let pixel_buffer = texture.read_to_pixel_buffer();
... | {
// Get information about current framebuffer
let dimensions = facade.get_context().get_framebuffer_dimensions();
let rect = glium::Rect {
left: 0,
bottom: 0,
width: dimensions.0,
height: dimensions.1,
};
... | identifier_body |
screenshot-asynchronous.rs | vector of (u8, u8, u8, u8).
// This is used to take data from PixelBuffer and move it to another thread
// with minimum conversions done on main thread.
pub struct | {
pub data: Vec<(u8, u8, u8, u8)>,
pub width: u32,
pub height: u32,
}
impl glium::texture::Texture2dDataSink<(u8, u8, u8, u8)> for RGBAImageData {
fn from_raw(data: Cow<'_, [(u8, u8, u8, u8)]>, width: u32, height: u32) -> Self {
RGBAImageData {
data:... | RGBAImageData | identifier_name |
__init__.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ] | random_line_split | |
dirtree.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilities for getting directory tree."""
import os
from pathlib import Path
import crayons
from nuke.utils import parse_ignore_file
def fg(text, color):
"""Set text to foregound color."""
return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def bg(tex... | elif path.is_mount():
return crayons.red(name)
elif path.is_symlink():
return crayons.cyan(name)
elif path.is_socket():
return crayons.magenta(name)
else:
return crayons.white(name)
def get_dirtree(directory):
"""
Get the directory tree of the `directory`.
:... | return crayons.blue(name)
elif path.is_file():
return crayons.green(name) | random_line_split |
dirtree.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilities for getting directory tree."""
import os
from pathlib import Path
import crayons
from nuke.utils import parse_ignore_file
def fg(text, color):
"""Set text to foregound color."""
return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def bg(tex... |
else:
return crayons.white(name)
def get_dirtree(directory):
"""
Get the directory tree of the `directory`.
:param directory: The root directory from where to generate the directory tree.
:return: The list of paths with appropriate indenting
"""
element_list = []
ignore_patter... | return crayons.magenta(name) | conditional_block |
dirtree.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilities for getting directory tree."""
import os
from pathlib import Path
import crayons
from nuke.utils import parse_ignore_file
def | (text, color):
"""Set text to foregound color."""
return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def bg(text, color):
"""Set text to background color."""
return "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def get_colorized(path: Path):
"""Colorize path name based on type."""
na... | fg | identifier_name |
dirtree.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilities for getting directory tree."""
import os
from pathlib import Path
import crayons
from nuke.utils import parse_ignore_file
def fg(text, color):
"""Set text to foregound color."""
return "\33[38;5;" + str(color) + "m" + text + "\33[0m"
def bg(tex... |
def get_dirtree(directory):
"""
Get the directory tree of the `directory`.
:param directory: The root directory from where to generate the directory tree.
:return: The list of paths with appropriate indenting
"""
element_list = []
ignore_patterns = []
file_link = fg("├── ", 241) # u... | """Colorize path name based on type."""
name = path.name
if path.is_dir():
return crayons.blue(name)
elif path.is_file():
return crayons.green(name)
elif path.is_mount():
return crayons.red(name)
elif path.is_symlink():
return crayons.cyan(name)
elif path.is_socke... | identifier_body |
value.component.ts | import { Component, Input, OnInit } from "@angular/core";
import { TreeLeaf } from "../class/tree/tree-leaf";
import { Soap } from "../class/helper/soap";
@Component({
selector: 'my-value',
templateUrl: 'value.component.html',
styleUrls: ['value.component.scss']
})
export class | implements OnInit{
@Input() leaf: TreeLeaf;
@Input() showFullName: boolean = false;
private initVal: any;
private currVal: any;
private boolVal: boolean;
constructor(){
}
ngOnInit(): void {
this.leaf.value.subscribe(val => {
this.currVal=val;
this.initVal=val;
if(this.leaf.type... | ValueComponent | identifier_name |
value.component.ts | import { Component, Input, OnInit } from "@angular/core";
import { TreeLeaf } from "../class/tree/tree-leaf";
import { Soap } from "../class/helper/soap";
@Component({
selector: 'my-value',
templateUrl: 'value.component.html',
styleUrls: ['value.component.scss']
})
export class ValueComponent implements OnInit{... |
}
private sendBool(e: MouseEvent){
e.stopPropagation();
this.leaf.send(!this.boolVal);
setTimeout(()=>this.leaf.query(),135);
}
} | this.initVal=val;
if(this.leaf.type == 'xsd:boolean'){
this.boolVal = this.initVal == 1;
}
}); | random_line_split |
value.component.ts | import { Component, Input, OnInit } from "@angular/core";
import { TreeLeaf } from "../class/tree/tree-leaf";
import { Soap } from "../class/helper/soap";
@Component({
selector: 'my-value',
templateUrl: 'value.component.html',
styleUrls: ['value.component.scss']
})
export class ValueComponent implements OnInit{... |
});
}
private sendBool(e: MouseEvent){
e.stopPropagation();
this.leaf.send(!this.boolVal);
setTimeout(()=>this.leaf.query(),135);
}
}
| {
this.boolVal = this.initVal == 1;
} | conditional_block |
condvar.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, mutex: &Mutex, dur: Duration) -> bool {
let r = ffi::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
dur.num_milliseconds() as DWORD,
0);
if... | wait_timeout | identifier_name |
condvar.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[inline]
pub unsafe fn notify_one(&self) {
ffi::WakeConditionVariable(self.inner.get())
}
#[inline]
pub unsafe fn notify_all(&self) {
ffi::WakeAllConditionVariable(self.inner.get())
}
pub unsafe fn destroy(&self) {
// ...
}
}
| {
let r = ffi::SleepConditionVariableSRW(self.inner.get(),
mutex::raw(mutex),
dur.num_milliseconds() as DWORD,
0);
if r == 0 {
const ERROR_TIMEOUT: DWO... | identifier_body |
condvar.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | inner: UnsafeCell { value: ffi::CONDITION_VARIABLE_INIT }
};
impl Condvar {
#[inline]
pub unsafe fn new() -> Condvar { CONDVAR_INIT }
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = ffi::SleepConditionVariableSRW(self.inner.get(),
... | unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
pub const CONDVAR_INIT: Condvar = Condvar { | random_line_split |
condvar.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
#[inline]
pub unsafe fn notify_one(&self) {
ffi::WakeConditionVariable(self.inner.get())
}
#[inline]
pub unsafe fn notify_all(&self) {
ffi::WakeAllConditionVariable(self.inner.get())
}
pub unsafe fn destroy(&self) {
// ...
}
}
| {
true
} | conditional_block |
Lepton.py |
from .ioctl_numbers import _IOR, _IOW
from fcntl import ioctl
SPI_IOC_MAGIC = ord("k")
SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B")
SP... |
else:
count = messages
iow = _IOW(SPI_IOC_MAGIC, 0, xs_size * count)
ret = ioctl(handle, iow, xs_buf[xs_size * (60 - messages):], True)
if ret < 1:
raise IOError("can't send {0} spi messages ({1})".format(60, ret))
messages -= count
def capture(self, data_buffer = None,... | count = Lepton.SPIDEV_MESSAGE_LIMIT | conditional_block |
Lepton.py |
from .ioctl_numbers import _IOR, _IOW
from fcntl import ioctl
SPI_IOC_MAGIC = ord("k")
SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B")
SP... | (self):
# "In Python 3 the only way to open /dev/tty under Linux appears to be 1) in binary mode and 2) with buffering disabled."
self.__handle = open(self.__spi_dev, "wb+", buffering=0)
ioctl(self.__handle, SPI_IOC_RD_MODE, struct.pack("=B", Lepton.MODE))
ioctl(self.__handle, SPI_IOC_WR_MODE, struct.p... | __enter__ | identifier_name |
Lepton.py |
from .ioctl_numbers import _IOR, _IOW
from fcntl import ioctl
SPI_IOC_MAGIC = ord("k")
SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B")
SP... |
def __exit__(self, type, value, tb):
self.__handle.close()
@staticmethod
def capture_segment(handle, xs_buf, xs_size, capture_buf):
messages = Lepton.ROWS
iow = _IOW(SPI_IOC_MAGIC, 0, xs_size)
ioctl(handle, iow, xs_buf, True)
while (capture_buf[0] & 0x000f) == 0x000f: # byteswapped 0x0f00... | self.__handle = open(self.__spi_dev, "wb+", buffering=0)
ioctl(self.__handle, SPI_IOC_RD_MODE, struct.pack("=B", Lepton.MODE))
ioctl(self.__handle, SPI_IOC_WR_MODE, struct.pack("=B", Lepton.MODE))
ioctl(self.__handle, SPI_IOC_RD_BITS_PER_WORD, struct.pack("=B", Lepton.BITS))
ioctl(self.__handle, SPI_I... | identifier_body |
Lepton.py | from .ioctl_numbers import _IOR, _IOW |
SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, "=B")
SPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_I... | from fcntl import ioctl
SPI_IOC_MAGIC = ord("k") | random_line_split |
encode.ts | import { Operation } from 'express-openapi';
import IEncodeApiModel from '../../api/encode/IEncodeApiModel';
import container from '../../ModelContainer';
import * as api from '../api';
export const get: Operation = async (req, res) => {
const encodeApiModel = container.get<IEncodeApiModel>('IEncodeApiModel');
... | content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Error',
},
},
},
},
},
}; | },
},
},
default: {
description: '予期しないエラー', | random_line_split |
sessioncontainer.js | descendants of this
* component.
* @private {!Array.<!goog.ui.Tab>}
*/
this.pendingTabs_ = [];
/**
* Key for the interval that updates the content of the pending session tabs.
* @private {number}
*/
this.updateKey_ = setInterval(goog.bind(this.updatePendingTabs_, this), 300);
this.addChild(... | * @extends {goog.ui.Tab}
* @private
*/ | random_line_split | |
sessioncontainer.js | .ui.TabBar(goog.ui.TabBar.Location.START, null);
/**
* Widget for viewing details on an individual session.
* @private {!remote.ui.SessionView}
*/
this.view_ = new remote.ui.SessionView();
/**
* Dialog for creating a new session.
* @private {!remote.ui.CreateSessionDialog}
*/
this.createSess... | {
this.view_.update(null);
} | conditional_block | |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import itertools
import tempfile
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
callable_default_counter = itertools.count()
callable_def... |
def __str__(self):
return 'ChoiceOption %d' % self.pk
class ChoiceFieldModel(models.Model):
"""Model with ForeignKey to another model, for testing ModelForm
generation with ModelChoiceField."""
choice = models.ForeignKey(ChoiceOptionModel, blank=False,
default=... | ordering = ('name',) | identifier_body |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import itertools
import tempfile
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
callable_default_counter = itertools.count()
callable_def... | class FileModel(models.Model):
file = models.FileField(storage=temp_storage, upload_to='tests')
@python_2_unicode_compatible
class Group(models.Model):
name = models.CharField(max_length=10)
def __str__(self):
return '%s' % self.name
class Cheese(models.Model):
name = models.CharField(max_l... | random_line_split | |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import itertools
import tempfile
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
callable_default_counter = itertools.count()
callable_def... | (models.Model):
"""For ModelChoiceField and ModelMultipleChoiceField tests."""
CHOICES = [
('', 'No Preference'),
('f', 'Foo'),
('b', 'Bar'),
]
INTEGER_CHOICES = [
(None, 'No Preference'),
(1, 'Foo'),
(2, 'Bar'),
]
STRING_CHOICES_WITH_NONE = [
... | ChoiceModel | identifier_name |
calendar.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//<script>
$(document).ready(function() {
var curSource = "/alliance/dutylist/calendarsearch";
$('#dutylsitCale... | },
eventRender: function eventRender(event, eventElement, element, view) {
if (event.imageurl) {
eventElement.find("div.fc-content").prepend("<div class='text-center' style='padding: 1px;'><img class='img-rounded' src='" + event.imageurl +"' width='50' height... | left: 'prev,today,next',
center: 'title,filter',
right: 'month,agendaWeek,agendaDay', | random_line_split |
calendar.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//<script>
$(document).ready(function() {
var curSource = "/alliance/dutylist/calendarsearch";
$('#dutylsitCale... |
function hideSideBar() {
document.getElementById("sidebar").style.display = "none";
}
// $('#filterStatus').multiselect({
// numberDisplayed: 2,
// enableFiltering: false,
// includeSelectAllOption: true,
// nonSelectedText: 'Статус',
// }); | hiddenDays: [1, 2, 3, 4, 5],
});
}
var showDays = function()
{
$('#dutylsitCalendar').fullCalendar('option', {
hiddenDays: [],
});
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.