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 |
|---|---|---|---|---|
pydevd_xml.py | import pydev_log
import traceback
import pydevd_resolver
from pydevd_constants import * #@UnusedWildImport
from types import * #@UnusedWildImport
try:
from urllib import quote
except:
from urllib.parse import quote #@UnresolvedImport
try:
from xml.sax.saxutils import escape
def makeValidXmlValue(s):
... | is_exception_on_eval = isinstance(val, ExceptionOnEvaluate)
if is_exception_on_eval:
v = val.result
else:
v = val
type, typeName, resolver = getType(v)
try:
if hasattr(v, '__class__'):
try:
cName = str(v.__class__)
if cName.find(... | """ single variable or dictionary to xml representation """
| random_line_split |
pydevd_xml.py | import pydev_log
import traceback
import pydevd_resolver
from pydevd_constants import * #@UnusedWildImport
from types import * #@UnusedWildImport
try:
from urllib import quote
except:
from urllib.parse import quote #@UnresolvedImport
try:
from xml.sax.saxutils import escape
def makeValidXmlValue(s):
... |
def getType(o):
""" returns a triple (typeObject, typeString, resolver
resolver != None means that variable is a container,
and should be displayed as a hierarchy.
Use the resolver to get its attributes.
All container objects should have a resolver.
"""
try:
type... | from org.python import core #@UnresolvedImport
typeMap = [
(core.PyNone, None),
(core.PyInteger, None),
(core.PyLong, None),
(core.PyFloat, None),
(core.PyComplex, None),
(core.PyString, None),
(core.PyTuple, pydevd_resolver.tupleR... | conditional_block |
pydevd_xml.py | import pydev_log
import traceback
import pydevd_resolver
from pydevd_constants import * #@UnusedWildImport
from types import * #@UnusedWildImport
try:
from urllib import quote
except:
from urllib.parse import quote #@UnresolvedImport
try:
from xml.sax.saxutils import escape
def makeValidXmlValue(s):
... | :
def __init__(self, result):
self.result = result
#------------------------------------------------------------------------------------------------------ resolvers in map
if not sys.platform.startswith("java"):
typeMap = [
#None means that it should not be treated as a compound variable
... | ExceptionOnEvaluate | identifier_name |
models.py | certain status or publication date."
Three basic permissions -- add, change and delete -- are automatically
created for each Django model.
"""
name = models.CharField(_('name'), max_length=255)
content_type = models.ForeignKey(ContentType)
codename = models.CharField(_('codename'), max_length=... | self.save(update_fields=["password"])
return check_password(raw_password, self.password, setter)
def set_unusable_password(self):
# Sets a value that will never be a valid hash
self.password = make_password(None)
def has_usable_password(self):
return is_password_usa... | Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password) | random_line_split |
models.py | _FIELD)
def __str__(self):
return self.get_username()
def natural_key(self):
return (self.get_username(),)
def is_anonymous(self):
"""
Always returns False. This is a way of comparing User objects to
anonymous users.
"""
return False
def is_aut... | if not self.has_perm(perm, obj):
return False | conditional_block | |
models.py | , **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email=None, password=None, **extra_fields):
return self._create_user(username, email, password, False, False,
**extra_fields)
def... | raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") | identifier_body | |
models.py | (self, codename, app_label, model):
return self.get(
codename=codename,
content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(app_label, model),
)
@python_2_unicode_compatible
class Permission(models.Model):
"""
The permissions system provides a way to... | get_by_natural_key | identifier_name | |
addict.py | from inspect import isgenerator
import re
import copy
class | (dict):
"""
Dict is a subclass of dict, which allows you to get AND SET(!!)
items in the dict using the attribute syntax!
When you previously had to write:
my_dict = {'a': {'b': {'c': [1, 2, 3]}}}
you can now do the same simply by:
my_Dict = Dict()
my_Dict.a.b.c = [1, 2, 3]
Or ... | Dict | identifier_name |
addict.py | from inspect import isgenerator
import re
import copy
class Dict(dict):
"""
Dict is a subclass of dict, which allows you to get AND SET(!!)
items in the dict using the attribute syntax!
When you previously had to write:
my_dict = {'a': {'b': {'c': [1, 2, 3]}}}
you can now do the same simpl... |
def __setitem__(self, name, value):
"""
This is called when trying to set a value of the Dict using [].
E.g. some_instance_of_Dict['b'] = val. If 'val
"""
value = self._hook(value)
super(Dict, self).__setitem__(name, value)
@classmethod
def _hook(cls, item)... | if hasattr(Dict, name):
raise AttributeError("'Dict' object attribute "
"'{0}' is read-only".format(name))
else:
self[name] = value | random_line_split |
addict.py | from inspect import isgenerator
import re
import copy
class Dict(dict):
"""
Dict is a subclass of dict, which allows you to get AND SET(!!)
items in the dict using the attribute syntax!
When you previously had to write:
my_dict = {'a': {'b': {'c': [1, 2, 3]}}}
you can now do the same simpl... |
def copy(self):
"""
Return a disconnected deep copy of self. Children of type Dict, list
and tuple are copied recursively while values that are instances of
other mutable objects are not copied.
"""
return Dict(self.to_dict())
def __deepcopy__(self, memo):
... | """ Recursively turn your addict Dicts into dicts. """
base = {}
for key, value in self.items():
if isinstance(value, type(self)):
base[key] = value.to_dict()
elif isinstance(value, (list, tuple)):
base[key] = type(value)(
item.... | identifier_body |
addict.py | from inspect import isgenerator
import re
import copy
class Dict(dict):
"""
Dict is a subclass of dict, which allows you to get AND SET(!!)
items in the dict using the attribute syntax!
When you previously had to write:
my_dict = {'a': {'b': {'c': [1, 2, 3]}}}
you can now do the same simpl... |
elif isinstance(item, Dict):
item.prune(prune_zero, prune_empty_list)
if item:
new_iter.append(item)
elif isinstance(item, (list, tuple)):
new_item = type(item)(
cls._prune_iter(item, prune_zero, prune_empty... | continue | conditional_block |
udp.py | '''
Created on 9 jan. 2013
@author: sander
'''
from bitstring import BitStream, ConstBitStream, Bits
from ipaddress import IPv4Address, IPv6Address
from pylisp.packet.ip import protocol_registry
from pylisp.packet.ip.protocol import Protocol
from pylisp.utils import checksum
import numbers
class UDPMessage(Protocol)... |
else:
raise ValueError("No LISP content found")
def get_lisp_data_packet(self):
return self.get_lisp_message(only_data=True)
def get_lisp_control_message(self):
return self.get_lisp_message(only_control=True)
@classmethod
def from_bytes(cls, bitstream):
'... | lisp_data = (self.source_port == 4341
or self.destination_port == 4341)
lisp_control = (self.source_port == 4342
or self.destination_port == 4342)
if lisp_data and lisp_control:
raise ValueError("Cannot mix LISP data and control ports")
... | identifier_body |
udp.py | '''
Created on 9 jan. 2013
@author: sander
'''
from bitstring import BitStream, ConstBitStream, Bits
from ipaddress import IPv4Address, IPv6Address
from pylisp.packet.ip import protocol_registry
from pylisp.packet.ip.protocol import Protocol
from pylisp.utils import checksum
import numbers
class UDPMessage(Protocol)... | raise ValueError('Invalid source port')
if not isinstance(self.destination_port, numbers.Integral) \
or self.destination_port < 0 \
or self.destination_port >= 2 ** 16:
raise ValueError('Invalid destination port')
# We can't calculate the checksum because we don... | or self.source_port < 0 \
or self.source_port >= 2 ** 16: | random_line_split |
udp.py | '''
Created on 9 jan. 2013
@author: sander
'''
from bitstring import BitStream, ConstBitStream, Bits
from ipaddress import IPv4Address, IPv6Address
from pylisp.packet.ip import protocol_registry
from pylisp.packet.ip.protocol import Protocol
from pylisp.utils import checksum
import numbers
class UDPMessage(Protocol)... | (self):
return self.get_lisp_message(only_control=True)
@classmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
packet = cls()
# Convert to ConstBitStream (if not already provided)
if not isinstance(b... | get_lisp_control_message | identifier_name |
udp.py | '''
Created on 9 jan. 2013
@author: sander
'''
from bitstring import BitStream, ConstBitStream, Bits
from ipaddress import IPv4Address, IPv6Address
from pylisp.packet.ip import protocol_registry
from pylisp.packet.ip.protocol import Protocol
from pylisp.utils import checksum
import numbers
class UDPMessage(Protocol)... |
# Verify that the properties make sense
packet.sanitize()
return packet
def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that the properties make sense
self.sanitize()
# Write the source and destination ports
bitst... | raise ValueError('Bits remaining after processing packet') | conditional_block |
BaseShape.ts | //@ts-nocheck
import { IClone } from "../../../IClone"
import { BoundBox } from "../../../../math/BoundBox"
import { Rand } from "../../../../math/Rand"
import { Vector2 } from "../../../../math/Vector2"
import { Vector3 } from "../../../../math/Vector3"
export enum ParticleSystemShapeType {
/**盒体 */
Box = 0,
/**环形... | Vector3.add(boundBox.min, maxSpeedMin, maxSpeedMin);
Vector3.add(boundBox.max, maxSpeedMax, maxSpeedMax);
Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
var minSpeedBound: BoundBox = new BoundBox(new Vector3(), new Vector3());
var minSpeedMin: ... | min, emitterPosScale, min);
Vector3.multiply(max, emitterPosScale, max);
var speedBounds: BoundBox = new BoundBox(new Vector3(), new Vector3());
if (this.randomDirection/* && (m_Type != kCone) && (m_Type != kConeShell)*/)//TODO:randomDirection应换成0到1
{
speedBounds.min = new Vector3(-1, -1, -1);
speedBound... | identifier_body |
BaseShape.ts | //@ts-nocheck
import { IClone } from "../../../IClone"
import { BoundBox } from "../../../../math/BoundBox"
import { Rand } from "../../../../math/Rand"
import { Vector2 } from "../../../../math/Vector2"
import { Vector3 } from "../../../../math/Vector3"
export enum ParticleSystemShapeType {
/**盒体 */
Box = 0,
/**环形... |
/**
* @internal
*/
_calculateProceduralBounds(boundBox: BoundBox, emitterPosScale: Vector3, minMaxBounds: Vector2): void {
this._getShapeBoundBox(boundBox);
var min: Vector3 = boundBox.min;
var max: Vector3 = boundBox.max;
Vector3.multiply(min, emitterPosScale, min);
Vector3.multiply(max, emitterPos... | throw new Error("BaseShape: must override it.");
} | random_line_split |
BaseShape.ts | //@ts-nocheck
import { IClone } from "../../../IClone"
import { BoundBox } from "../../../../math/BoundBox"
import { Rand } from "../../../../math/Rand"
import { Vector2 } from "../../../../math/Vector2"
import { Vector3 } from "../../../../math/Vector3"
export enum ParticleSystemShapeType {
/**盒体 */
Box = 0,
/**环形... |
*/
clone(): any {
var destShape: BaseShape = new BaseShape();
this.cloneTo(destShape);
return destShape;
}
}
| 克隆副本。 | identifier_name |
BaseShape.ts | //@ts-nocheck
import { IClone } from "../../../IClone"
import { BoundBox } from "../../../../math/BoundBox"
import { Rand } from "../../../../math/Rand"
import { Vector2 } from "../../../../math/Vector2"
import { Vector3 } from "../../../../math/Vector3"
export enum ParticleSystemShapeType {
/**盒体 */
Box = 0,
/**环形... | r maxSpeedMin: Vector3 = maxSpeedBound.min;
var maxSpeedMax: Vector3 = maxSpeedBound.max;
Vector3.scale(speedBounds.min, minMaxBounds.y, maxSpeedMin);
Vector3.scale(speedBounds.max, minMaxBounds.y, maxSpeedMax);
Vector3.add(boundBox.min, maxSpeedMin, maxSpeedMin);
Vector3.add(boundBox.max, maxSpeedMax, maxSpe... | else {
this._getSpeedBoundBox(speedBounds);
}
var maxSpeedBound: BoundBox = new BoundBox(new Vector3(), new Vector3());
va | conditional_block |
0007_auto_20170211_0802.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-11 08:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
| field=models.DateTimeField(default=django.utils.timezone.now),
),
]
| dependencies = [
('multiexplorer', '0006_pullhistory'),
]
operations = [
migrations.CreateModel(
name='PushHistory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('last_pushed'... | identifier_body |
0007_auto_20170211_0802.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-11 08:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class | (migrations.Migration):
dependencies = [
('multiexplorer', '0006_pullhistory'),
]
operations = [
migrations.CreateModel(
name='PushHistory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | Migration | identifier_name |
page.rs | , either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Contains Parquet Page definitions and page reader interface.
use crate::basic::{Encoding, PageType};
use crate::errors::Result;
use crate::file::{metadata::ColumnChunkMetaData, st... | (&self) -> &ByteBufferPtr {
match self {
&Page::DataPage { ref buf, .. } => &buf,
&Page::DataPageV2 { ref buf, .. } => &buf,
&Page::DictionaryPage { ref buf, .. } => &buf,
}
}
/// Returns number of values in this page.
pub fn num_values(&self) -> u32 {
... | buffer | identifier_name |
page.rs | either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Contains Parquet Page definitions and page reader interface.
use crate::basic::{Encoding, PageType};
use crate::errors::Result;
use crate::file::{metadata::ColumnChunkMetaData, sta... |
/// Returns page type.
pub fn page_type(&self) -> PageType {
self.compressed_page.page_type()
}
/// Returns underlying page with potentially compressed buffer.
pub fn compressed_page(&self) -> &Page {
&self.compressed_page
}
/// Returns uncompressed size in bytes.
pub... | {
Self {
compressed_page,
uncompressed_size,
}
} | identifier_body |
page.rs | , either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Contains Parquet Page definitions and page reader interface.
use crate::basic::{Encoding, PageType};
use crate::errors::Result;
use crate::file::{metadata::ColumnChunkMetaData, st... | pub trait PageIterator: Iterator<Item = Result<Box<PageReader>>> {
/// Get schema of parquet file.
fn schema(&mut self) -> Result<SchemaDescPtr>;
/// Get column schema of this page iterator.
fn column_schema(&mut self) -> Result<ColumnDescPtr>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]... |
/// An iterator over pages of some specific column in a parquet file. | random_line_split |
a02307.js | 9e75a0fb30f0118774d7fa5621", null ],
[ "bool_binary_search", "a02307.html#a8c261f66a24da67aac1acca7aa8f650a", null ],
[ "choose_nth_item", "a02307.html#a5c4218ef833d0fe5db9b9749abd81ea5", null ],
[ "choose_nth_item", "a02307.html#ae1e555b0cdded2c36dd6cf15345f659f", null ],
[ "clear", "a02307.html#a9cdbf... | [ "Serialize", "a02307.html#a206a6fe71c3780d862d97ef7c5fc9546", null ],
[ "Serialize", "a02307.html#a3e994fd938468ff4fc4b4a902e970876", null ],
[ "SerializeClasses", "a02307.html#ad0e8164e4c5c82e9e367c8a6d9b755b1", null ],
[ "SerializeClasses", "a02307.html#a7d0060c687429049a0ea5cf21d067b8e", null ],
... | [ "reverse", "a02307.html#a58f6d73009cc3c56d0efb0d96ad35b5b", null ], | random_line_split |
test_dist_metrics.py | 1, x2, p):
return np.sum((x1 - x2) ** p) ** (1.0 / p)
rng = check_random_state(0)
d = 4
n1 = 20
n2 = 25
X1 = rng.random_sample((n1, d)).astype("float64", copy=False)
X2 = rng.random_sample((n2, d)).astype("float64", copy=False)
[X1_mmap, X2_mmap] = create_memmap_backed_data([X1, X2])
# make boolean arrays: ones... | (metric):
argdict = METRICS_DEFAULT_PARAMS[metric]
keys = argdict.keys()
for vals in itertools.product(*argdict.values()):
kwargs = dict(zip(keys, vals))
check_pickle(metric, kwargs)
@pytest.mark.parametrize("metric", BOOL_METRICS)
@pytest.mark.parametrize("X1_bool", [X1_bool, X1_bool_mmap... | test_pickle | identifier_name |
test_dist_metrics.py | 1, x2, p):
return np.sum((x1 - x2) ** p) ** (1.0 / p)
rng = check_random_state(0)
d = 4
n1 = 20
n2 = 25
X1 = rng.random_sample((n1, d)).astype("float64", copy=False)
X2 = rng.random_sample((n2, d)).astype("float64", copy=False)
[X1_mmap, X2_mmap] = create_memmap_backed_data([X1, X2])
# make boolean arrays: ones... |
check_cdist(metric, kwargs, D_true)
@pytest.mark.parametrize("metric", BOOL_METRICS)
@pytest.mark.parametrize(
"X1_bool, X2_bool", [(X1_bool, X2_bool), (X1_bool_mmap, X2_bool_mmap)]
)
def test_cdist_bool_metric(metric, X1_bool, X2_bool):
D_true = cdist(X1_bool, X2_bool, metric)
check_cdist_bool(... | D_true = cdist(X1, X2, metric, **kwargs) | conditional_block |
test_dist_metrics.py | 1, x2, p):
return np.sum((x1 - x2) ** p) ** (1.0 / p)
rng = check_random_state(0)
d = 4
n1 = 20
n2 = 25
X1 = rng.random_sample((n1, d)).astype("float64", copy=False)
X2 = rng.random_sample((n2, d)).astype("float64", copy=False)
[X1_mmap, X2_mmap] = create_memmap_backed_data([X1, X2])
# make boolean arrays: ones... | def test_pdist(metric, X1, X2):
argdict = METRICS_DEFAULT_PARAMS[metric]
keys = argdict.keys()
for vals in itertools.product(*argdict.values()):
kwargs = dict(zip(keys, vals))
if metric == "mahalanobis":
# See: https://github.com/scipy/scipy/issues/13861
pytest.xfail(... |
@pytest.mark.parametrize("metric", METRICS_DEFAULT_PARAMS)
@pytest.mark.parametrize("X1, X2", [(X1, X2), (X1_mmap, X2_mmap)]) | random_line_split |
test_dist_metrics.py | 1, x2, p):
return np.sum((x1 - x2) ** p) ** (1.0 / p)
rng = check_random_state(0)
d = 4
n1 = 20
n2 = 25
X1 = rng.random_sample((n1, d)).astype("float64", copy=False)
X2 = rng.random_sample((n2, d)).astype("float64", copy=False)
[X1_mmap, X2_mmap] = create_memmap_backed_data([X1, X2])
# make boolean arrays: ones... |
def test_bad | X = np.random.random((10, 3))
euclidean = DistanceMetric.get_metric("euclidean")
pyfunc = DistanceMetric.get_metric("pyfunc", func=dist_func, p=2)
# Check if both callable metric and predefined metric initialized
# DistanceMetric object is picklable
euclidean_pkl = pickle.loads(pickle.dumps(euclid... | identifier_body |
babyNameUpvote.js | var doc = require('dynamodb-doc');
var dynamodb = new doc.DynamoDB();
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
var bname = event.name.replace(/\W/g, '');
bname = bname.charAt(0).toUpperCase() + bname.slice(1);
dynamodb.updateItem({
"... | "ExpressionAttributeValues" : {
":a" : 1
}
}, function(err, data) {
if (err) {
context.done('error putting item into dynamodb failed: '+err);
} else {
console.log('success: '+JSON.stringify(data, null, ' '));
context.done();
}
});
}; | random_line_split | |
babyNameUpvote.js | var doc = require('dynamodb-doc');
var dynamodb = new doc.DynamoDB();
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
var bname = event.name.replace(/\W/g, '');
bname = bname.charAt(0).toUpperCase() + bname.slice(1);
dynamodb.updateItem({
"... |
});
}; | {
console.log('success: '+JSON.stringify(data, null, ' '));
context.done();
} | conditional_block |
dev.config.js | var path = require('path');
var webpack = require('webpack');
var writeStats = require('./utils/writeStats');
var notifyStats = require('./utils/notifyStats');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = 'localhost';
var port = parseInt(process.env.PORT) + 1 || 3001;
module.exports = {
dev... | new webpack.WatchIgnorePlugin([/\.json$/]),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: true,
__DEVTOOLS__: true // <-------- DISABLE redux-devtools HERE
}),
// stats
function () {
this.plugin('don... | // hot reload
new webpack.HotModuleReplacementPlugin(), | random_line_split |
8.06.py | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 7 18:08:41 2011
@author: steven
"""
# word = 'banana'
# count = 0
# for letter in word:
# if letter == 'a':
# count = count + 1
# print count
# Rewrite this function so that instead of traversing the string, it uses the
# three-parameter version of find from ... |
print count("n", "Think Python")
| counter = 0
index = 0
while index < len(word):
result = find(letter, word, index)
if result == -1:
return counter
else:
counter += 1
index = result + 1
return counter | identifier_body |
8.06.py | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 7 18:08:41 2011
@author: steven
"""
# word = 'banana'
# count = 0
# for letter in word:
# if letter == 'a':
# count = count + 1
# print count
# Rewrite this function so that instead of traversing the string, it uses the
# three-parameter version of find from ... | (letter, word):
counter = 0
index = 0
while index < len(word):
result = find(letter, word, index)
if result == -1:
return counter
else:
counter += 1
index = result + 1
return counter
print count("n", "Think Python")
| count | identifier_name |
8.06.py | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 7 18:08:41 2011
@author: steven
"""
# word = 'banana'
# count = 0
# for letter in word:
# if letter == 'a':
# count = count + 1
# print count
# Rewrite this function so that instead of traversing the string, it uses the
# three-parameter version of find from ... | result = find(letter, word, index)
if result == -1:
return counter
else:
counter += 1
index = result + 1
return counter
print count("n", "Think Python") | random_line_split | |
8.06.py | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 7 18:08:41 2011
@author: steven
"""
# word = 'banana'
# count = 0
# for letter in word:
# if letter == 'a':
# count = count + 1
# print count
# Rewrite this function so that instead of traversing the string, it uses the
# three-parameter version of find from ... |
index += 1
return -1
def count(letter, word):
counter = 0
index = 0
while index < len(word):
result = find(letter, word, index)
if result == -1:
return counter
else:
counter += 1
index = result + 1
return counter
print count("n"... | return index | conditional_block |
tags-input.ts | import { Component, Input, ElementRef, forwardRef, ViewChild } from '@angular/core';
import { ControlValueAccessor, NgModel, NG_VALUE_ACCESSOR, Validators, ValidatorFn, FormControl } from '@angular/forms';
@Component({
selector: 'lsu-tagsInput',
styles: [
`
.tags-input.invalid {
border-top: 2px s... | else {
this.isBackspaceDown = false;
}
}
tagInputKeyUp(event: any) {
let value = event.srcElement.value;
if (event.keyCode === 8 && !value && this.tags.length > 0 && this.isBackspaceDown) {
this.delTarget = this.tags[this.tags.length - 1];
event.stopPropagation();
this.rootEle.... | {
this.isBackspaceDown = true;
} | conditional_block |
tags-input.ts | import { Component, Input, ElementRef, forwardRef, ViewChild } from '@angular/core';
import { ControlValueAccessor, NgModel, NG_VALUE_ACCESSOR, Validators, ValidatorFn, FormControl } from '@angular/forms';
@Component({
selector: 'lsu-tagsInput',
styles: [
`
.tags-input.invalid {
border-top: 2px s... |
registerOnTouched(fn: () => {}): void {
this._onTouched = fn;
}
topKeyup(event: any) {
if (event.keyCode === 8 && this.delTarget) {
let index = this.tags.indexOf(this.delTarget);
if (index !== -1) {
this.tags.splice(index, 1);
}
this.delTarget = '';
}
}
setDelta... | {
this._onChange = fn;
} | identifier_body |
tags-input.ts | import { Component, Input, ElementRef, forwardRef, ViewChild } from '@angular/core';
import { ControlValueAccessor, NgModel, NG_VALUE_ACCESSOR, Validators, ValidatorFn, FormControl } from '@angular/forms';
@Component({
selector: 'lsu-tagsInput',
styles: [
`
.tags-input.invalid {
border-top: 2px s... | (fn: () => {}): void {
this._onTouched = fn;
}
topKeyup(event: any) {
if (event.keyCode === 8 && this.delTarget) {
let index = this.tags.indexOf(this.delTarget);
if (index !== -1) {
this.tags.splice(index, 1);
}
this.delTarget = '';
}
}
setDeltarget(tag: string, evn... | registerOnTouched | identifier_name |
tags-input.ts | import { Component, Input, ElementRef, forwardRef, ViewChild } from '@angular/core';
import { ControlValueAccessor, NgModel, NG_VALUE_ACCESSOR, Validators, ValidatorFn, FormControl } from '@angular/forms';
@Component({
selector: 'lsu-tagsInput',
styles: [
`
.tags-input.invalid {
border-top: 2px s... | border: none;
}
.tags-input .ui.input input:focus {
border-radius: inherit;
}
.deleteTarget:hover,
.deleteTarget {
border: 0 solid tomato;
background-color: tomato !important;
color: white !important;
}
`
],
template: `
... |
.tags-input .ui.input input {
height: 30px;
padding: 0 5px; | random_line_split |
process.py | # This file is part of Pebble.
# Copyright (c) 2013-2021, Matteo Cafasso
# Pebble 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, or (at your option) any later versio... | """Searches the function between the registered ones.
If not found, it imports the module forcing its registration.
"""
try:
return _registered_functions[name]
except KeyError: # force function registering
__import__(module)
mod = sys.modules[module]
function = getattr(... | identifier_body | |
process.py | # This file is part of Pebble.
# Copyright (c) 2013-2021, Matteo Cafasso
# Pebble 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, or (at your option) any later versio... |
if mp_context is not None and not isinstance(
mp_context, multiprocessing.context.BaseContext):
raise TypeError('Context expected to be None or multiprocessing.context')
################################################################################
# Spawn process start method handling logi... | raise TypeError('Daemon expected to be None or bool') | conditional_block |
process.py | # This file is part of Pebble.
# Copyright (c) 2013-2021, Matteo Cafasso
# Pebble 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, or (at your option) any later versio... |
def _process_wrapper(function, timeout, name, daemon, mp_context):
if isinstance(function, types.FunctionType):
_register_function(function)
if hasattr(mp_context, 'get_start_method'):
start_method = mp_context.get_start_method()
else:
start_method = 'spawn' if os.name == 'nt' els... |
return decorating_function | random_line_split |
process.py | # This file is part of Pebble.
# Copyright (c) 2013-2021, Matteo Cafasso
# Pebble 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, or (at your option) any later versio... | (function):
_registered_functions[function.__qualname__] = function
return function
def _trampoline(name, module, *args, **kwargs):
"""Trampoline function for decorators.
Lookups the function between the registered ones;
if not found, forces its registering and then executes it.
"""
fun... | _register_function | identifier_name |
externalFormatterTests.ts | /*
* Copyright 2013 Palantir Technologies, Inc.
*
* 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 l... | const expectedResult = dedent`
${getPositionString(1, 1)}${TEST_FILE}
${getPositionString(2, 11)}${TEST_FILE}
${getPositionString(9, 2)}${TEST_FILE}\n`.slice(1); // remove leading newline
const actualResult = formatter.format(failures);
assert.equal(actualRes... | random_line_split | |
externalFormatterTests.ts | /*
* Copyright 2013 Palantir Technologies, Inc.
*
* 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 l... |
});
| {
return `[${line}, ${character}]`;
} | identifier_body |
externalFormatterTests.ts | /*
* Copyright 2013 Palantir Technologies, Inc.
*
* 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 l... | (line: number, character: number) {
return `[${line}, ${character}]`;
}
});
| getPositionString | identifier_name |
tslint-json.ts | /**
* This module defines the `tslint-json` project task.
*
* @module project-tasks/tslint-json
* @internal
*/
/** (Placeholder comment, see TypeStrong/typedoc#603) */
import { Furi, join as furiJoin } from "furi";
import Undertaker from "undertaker";
import { DEFAULT_UNTYPED_TSLINT_CONFIG } from "../options/tsl... | else {
relativePath = "tslint.json";
}
const absolutePath: Furi = furiJoin(project.absRoot, [relativePath]);
return async function () {
return writeJsonFile(absolutePath, DEFAULT_UNTYPED_TSLINT_CONFIG);
};
}
export function getTaskName(): string {
return "tslint.json";
}
export function registerTa... | {
relativePath = project.tslint.tslintJson;
} | conditional_block |
tslint-json.ts | /**
* This module defines the `tslint-json` project task.
*
* @module project-tasks/tslint-json
* @internal
*/
/** (Placeholder comment, see TypeStrong/typedoc#603) */
import { Furi, join as furiJoin } from "furi";
import Undertaker from "undertaker";
import { DEFAULT_UNTYPED_TSLINT_CONFIG } from "../options/tsl... |
export function getTaskName(): string {
return "tslint.json";
}
export function registerTask(taker: Undertaker, project: ResolvedProject): Undertaker.TaskFunction {
const taskName: string = getTaskName();
const task: Undertaker.TaskFunction = generateTask(project);
taker.task(taskName, task);
return task;
... | {
let relativePath: string;
if (project.tslint !== undefined && project.tslint.tslintJson !== undefined) {
relativePath = project.tslint.tslintJson;
} else {
relativePath = "tslint.json";
}
const absolutePath: Furi = furiJoin(project.absRoot, [relativePath]);
return async function () {
return w... | identifier_body |
tslint-json.ts | /**
* This module defines the `tslint-json` project task.
*
* @module project-tasks/tslint-json
* @internal
*/
/** (Placeholder comment, see TypeStrong/typedoc#603) */
import { Furi, join as furiJoin } from "furi";
import Undertaker from "undertaker";
import { DEFAULT_UNTYPED_TSLINT_CONFIG } from "../options/tsl... | (taker: Undertaker, project: ResolvedProject): Undertaker.TaskFunction {
const taskName: string = getTaskName();
const task: Undertaker.TaskFunction = generateTask(project);
taker.task(taskName, task);
return task;
}
| registerTask | identifier_name |
tslint-json.ts | /**
* This module defines the `tslint-json` project task.
*
* @module project-tasks/tslint-json
* @internal
*/
/** (Placeholder comment, see TypeStrong/typedoc#603) */
import { Furi, join as furiJoin } from "furi";
import Undertaker from "undertaker";
import { DEFAULT_UNTYPED_TSLINT_CONFIG } from "../options/tsl... |
export function getTaskName(): string {
return "tslint.json";
}
export function registerTask(taker: Undertaker, project: ResolvedProject): Undertaker.TaskFunction {
const taskName: string = getTaskName();
const task: Undertaker.TaskFunction = generateTask(project);
taker.task(taskName, task);
return task;
} | } | random_line_split |
dstr-let-obj-ptrn-id-init-throws.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-throws.case
// - src/dstr-binding/error/for-of-let.template
/*---
description: Error thrown when evaluating the initializer (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevalu... | 3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
3. Let destructuring be IsDestructuring of lhs.
[...]
5. Repeat
[...]
h. If destructuring is false, then
[.... | for ( ForDeclaration of AssignmentExpression ) Statement
[...] | random_line_split |
dstr-let-obj-ptrn-id-init-throws.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-throws.case
// - src/dstr-binding/error/for-of-let.template
/*---
description: Error thrown when evaluating the initializer (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevalu... |
assert.throws(Test262Error, function() {
for (let { x = thrower() } of [{}]) {
return;
}
});
| {
throw new Test262Error();
} | identifier_body |
dstr-let-obj-ptrn-id-init-throws.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-throws.case
// - src/dstr-binding/error/for-of-let.template
/*---
description: Error thrown when evaluating the initializer (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevalu... | () {
throw new Test262Error();
}
assert.throws(Test262Error, function() {
for (let { x = thrower() } of [{}]) {
return;
}
});
| thrower | identifier_name |
assignment.rs | // Test assignment
fn main() |
fn break_meee() {
{
(block_start, block_size, margin_block_start, margin_block_end) =
match (block_start, block_end, block_size) {
x => 1,
_ => 2,
};
}
}
| {
let some_var: Type;
let mut mutable;
let variable =
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA::BBBBBBBBBBBBBBBBBBBBBB::CCCCCCCCCCCCCCCCCCCCCC::EEEEEE;
variable =
LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG;
let single_line_fit = DDDDDDD... | identifier_body |
assignment.rs | // Test assignment
fn main() {
let some_var: Type;
let mut mutable;
let variable =
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA::BBBBBBBBBBBBBBBBBBBBBB::CCCCCCCCCCCCCCCCCCCCCC::EEEEEE;
variable =
LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG;
... | () {
{
(block_start, block_size, margin_block_start, margin_block_end) =
match (block_start, block_end, block_size) {
x => 1,
_ => 2,
};
}
}
| break_meee | identifier_name |
assignment.rs | // Test assignment
fn main() {
let some_var: Type;
let mut mutable;
let variable =
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA::BBBBBBBBBBBBBBBBBBBBBB::CCCCCCCCCCCCCCCCCCCCCC::EEEEEE; |
single_line_fit = 5;
single_lit_fit >>= 10;
}
fn break_meee() {
{
(block_start, block_size, margin_block_start, margin_block_end) =
match (block_start, block_end, block_size) {
x => 1,
_ => 2,
};
}
} |
variable =
LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG;
let single_line_fit = DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD; | random_line_split |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
na... |
class UniqueForDateModel(models.Model):
start_date = models.DateField()
end_date = models.DateTimeField()
count = models.IntegerField(unique_for_date="start_date", unique_for_year="end_date")
order = models.IntegerField(unique_for_month="end_date")
name = models.CharField(max_length=100)
class Cu... | unique_together = (('ifield', 'cfield',), ['ifield', 'efield']) | identifier_body |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
na... |
class UniqueFieldsModel(models.Model):
unique_charfield = models.CharField(max_length=100, unique=True)
unique_integerfield = models.IntegerField(unique=True)
non_unique_field = models.IntegerField()
class CustomPKModel(models.Model):
my_pk_field = models.CharField(max_length=100, primary_key=True)
... | raise ValidationError('Invalid number supplied!') | conditional_block |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
na... |
def clean(self):
super(ModelToValidate, self).clean()
if self.number == 11:
raise ValidationError('Invalid number supplied!')
class UniqueFieldsModel(models.Model):
unique_charfield = models.CharField(max_length=100, unique=True)
unique_integerfield = models.IntegerField(unique... | parent = models.ForeignKey('self', blank=True, null=True, limit_choices_to={'number': 10})
email = models.EmailField(blank=True)
url = models.URLField(blank=True)
f_with_custom_validator = models.IntegerField(blank=True, null=True, validators=[validate_answer_to_universe]) | random_line_split |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
na... | (models.Model):
cfield = models.CharField(max_length=100)
ifield = models.IntegerField()
efield = models.EmailField()
class Meta:
unique_together = (('ifield', 'cfield',), ['ifield', 'efield'])
class UniqueForDateModel(models.Model):
start_date = models.DateField()
end_date = models.Da... | UniqueTogetherModel | identifier_name |
setup.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
return io.open(
... | # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
... | random_line_split | |
setup.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
|
setup(
name='hqueue',
version='0.2.0',
license='BSD',
description='asyncio.Queue with history',
long_description='%s\n\n%s' % (
re.compile('^.. start-badges.*^.. end-badges', re.M | re.S).sub('', read('README.rst')),
re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst'))
... | return io.open(
join(dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf8')
).read() | identifier_body |
setup.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def | (*names, **kwargs):
return io.open(
join(dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf8')
).read()
setup(
name='hqueue',
version='0.2.0',
license='BSD',
description='asyncio.Queue with history',
long_description='%s\n\n%s' % (
re.compile('^.. star... | read | identifier_name |
PrimaryGeneratedColumn.ts | import {ColumnOptions} from "../options/ColumnOptions";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {getMetadataArgsStorage} from "../../index";
import {PrimaryColumnCannotBeNullableError} from "../error/PrimaryColumnCannotBeNullableError";
import {ColumnMetadataArgs} from "../../metadata-args/... | // implicitly set a primary and generated to column options
options = Object.assign({ primary: true, generated: true } as ColumnOptions, options);
// create and register a new column metadata
const args: ColumnMetadataArgs = {
target: object.constructor,
property... | throw new PrimaryColumnCannotBeNullableError(object, propertyName);
| random_line_split |
PrimaryGeneratedColumn.ts | import {ColumnOptions} from "../options/ColumnOptions";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {getMetadataArgsStorage} from "../../index";
import {PrimaryColumnCannotBeNullableError} from "../error/PrimaryColumnCannotBeNullableError";
import {ColumnMetadataArgs} from "../../metadata-args/... | (options?: ColumnOptions): Function {
return function (object: Object, propertyName: string) {
// const reflectedType = ColumnTypes.typeToString((Reflect as any).getMetadata("design:type", object, propertyName));
// if column options are not given then create a new empty options
if (!option... | PrimaryGeneratedColumn | identifier_name |
PrimaryGeneratedColumn.ts | import {ColumnOptions} from "../options/ColumnOptions";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {getMetadataArgsStorage} from "../../index";
import {PrimaryColumnCannotBeNullableError} from "../error/PrimaryColumnCannotBeNullableError";
import {ColumnMetadataArgs} from "../../metadata-args/... | target: object.constructor,
propertyName: propertyName,
// propertyType: reflectedType,
mode: "regular",
options: options
};
getMetadataArgsStorage().columns.add(args);
};
}
| {
return function (object: Object, propertyName: string) {
// const reflectedType = ColumnTypes.typeToString((Reflect as any).getMetadata("design:type", object, propertyName));
// if column options are not given then create a new empty options
if (!options) options = {} as ColumnOptions;
... | identifier_body |
travel_time_hbw_am_drive_alone_from_home_to_work_alt.py | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.abstract_variables.abstract_travel_time_variable import abstract_travel_time_variable
class | (abstract_travel_time_variable):
"""travel_time_hbw_am_drive_alone_from_home_to_work"""
agent_zone_id = "psrc.household.home_zone_id_from_grid_id"
location_zone_id = "urbansim.zone.zone_id"
travel_data_attribute = "urbansim.travel_data.am_single_vehicle_to_work_travel_time"
from numpy import ma... | travel_time_hbw_am_drive_alone_from_home_to_work_alt | identifier_name |
travel_time_hbw_am_drive_alone_from_home_to_work_alt.py | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.abstract_variables.abstract_travel_time_variable import abstract_travel_time_variable
class travel_time_hbw_am_drive_alone_from_home_to_work_alt(abstract_travel_time_variable):
... | "zone_id":array([1, 2, 3]),
},
"travel_data":{
"from_zone_id": array([3, 3, 1, 1, 1, 2, 2, 3, 2]),
"to_zone_id": array([1, 3, 1, 3, 2, 1, 3, 2, 2]),
... | "household":{
"household_id":array([1,2,3,4,5]),
"home_zone_id_from_grid_id":array([3, 1, 1, 1, 2]),
},
"zone":{
| random_line_split |
travel_time_hbw_am_drive_alone_from_home_to_work_alt.py | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.abstract_variables.abstract_travel_time_variable import abstract_travel_time_variable
class travel_time_hbw_am_drive_alone_from_home_to_work_alt(abstract_travel_time_variable):
... | opus_unittest.main() | conditional_block | |
travel_time_hbw_am_drive_alone_from_home_to_work_alt.py | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.abstract_variables.abstract_travel_time_variable import abstract_travel_time_variable
class travel_time_hbw_am_drive_alone_from_home_to_work_alt(abstract_travel_time_variable):
... |
from numpy import ma, array
from opus_core.tests import opus_unittest
from urbansim.variable_test_toolbox import VariableTestToolbox
from psrc.opus_package_info import package
from urbansim.datasets.zone_dataset import ZoneDataset
from urbansim.datasets.household_dataset import HouseholdDataset
from psrc.data... | """travel_time_hbw_am_drive_alone_from_home_to_work"""
agent_zone_id = "psrc.household.home_zone_id_from_grid_id"
location_zone_id = "urbansim.zone.zone_id"
travel_data_attribute = "urbansim.travel_data.am_single_vehicle_to_work_travel_time" | identifier_body |
__init__.py | # Copyright (c) 2011 OpenStack Foundation.
# 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... | (weight.BaseWeigher):
"""Base class for host weights."""
pass
class HostWeightHandler(weight.BaseWeightHandler):
object_class = WeighedHost
def __init__(self, namespace):
super(HostWeightHandler, self).__init__(BaseHostWeigher, namespace)
| BaseHostWeigher | identifier_name |
__init__.py | # Copyright (c) 2011 OpenStack Foundation.
# 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... | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Scheduler host weights
"""
from cinder.openstack.common.scheduler import weight
class WeighedHost(weight.WeighedObject):
def to_... | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | random_line_split |
__init__.py | # Copyright (c) 2011 OpenStack Foundation.
# 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... | super(HostWeightHandler, self).__init__(BaseHostWeigher, namespace) | identifier_body | |
cliffs.vert.ts | const shader = `
uniform mat4 u_VP;
uniform sampler2D u_heightMap;
uniform vec2 u_pixel;
uniform vec2 u_centerOffset;
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_uv;
attribute vec3 a_instancePosition;
attribute float a_instanceTexture;
varying vec3 v_normal;
varying vec2 v_uv;
varying float v... | float top = mix(topRight, topLeft, -a_position.x / 128.0);
float height = mix(bottom, top, a_position.y / 128.0);
v_normal = a_normal;
v_uv = a_uv;
v_texture = a_instanceTexture;
v_position = a_position + vec3(a_instancePosition.xy, a_instancePosition.z + height * 128.0);
gl_Position = u_VP * vec4(v_pos... | float topRight = texture2D(u_heightMap, (corner + vec2(1.0, 1.0)) * u_pixel + halfPixel).a;
// Do a bilinear interpolation between the heights to get the final value.
float bottom = mix(bottomRight, bottomLeft, -a_position.x / 128.0); | random_line_split |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# RoundTM - A Round based Tournament Manager
# Copyright (c) 2013 Rémi Alvergnat <toilal.dev@gmail.com>
#
# RoundTM is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Fo... | self):
"""Display current ranking"""
i = 1
for stat in self._event.ranking:
print "[%s] %s" % (i, stat)
i += 1
def load(path):
"""Load a project in console mode.
:return: class `Console`, a control object for console usage (IPython)
"""
return Console(E... | anking( | identifier_name |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# RoundTM - A Round based Tournament Manager
# Copyright (c) 2013 Rémi Alvergnat <toilal.dev@gmail.com>
# | # (at your option) any later version.
#
# RoundTM is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Lesser GNU General Public License for more details.
#
# You should have received a copy ... | # RoundTM is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or | random_line_split |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# RoundTM - A Round based Tournament Manager
# Copyright (c) 2013 Rémi Alvergnat <toilal.dev@gmail.com>
#
# RoundTM is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Fo... |
def load(path):
"""Load a project in console mode.
:return: class `Console`, a control object for console usage (IPython)
"""
return Console(Event(path))
| ""Controls an Event with console."""
def __init__(self, event):
self._event = event
@property
def next_round(self):
"""Go to next round, using the provided strategy"""
return self._event.next_round()
@property
def ranking(self):
"""Display current ranking"""
... | identifier_body |
console.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# RoundTM - A Round based Tournament Manager
# Copyright (c) 2013 Rémi Alvergnat <toilal.dev@gmail.com>
#
# RoundTM is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Fo... |
def load(path):
"""Load a project in console mode.
:return: class `Console`, a control object for console usage (IPython)
"""
return Console(Event(path))
| rint "[%s] %s" % (i, stat)
i += 1
| conditional_block |
growl-alert.component.ts | import { Component, OnInit, Input, ViewChild } from '@angular/core';
import {IGrowlAlertOptions, IGrowlAlertApi} from './growl-alert.model';
import {Message, Growl} from 'primeng/primeng';
@Component({
moduleId: module.id,
selector: 'growl-alert',
template: `<p-growl [value]="alerts" #growlNSticky></... | (message: string, title?: string,sticky?: boolean, life?: number) : void {
if(sticky) {
this.stickyAlerts.push({severity:'warn', summary: title, detail: message});
} else {
this.alerts.push({severity:'warn', summary: title, detail: message});
}
... | warn | identifier_name |
growl-alert.component.ts | import { Component, OnInit, Input, ViewChild } from '@angular/core';
import {IGrowlAlertOptions, IGrowlAlertApi} from './growl-alert.model';
import {Message, Growl} from 'primeng/primeng';
@Component({
moduleId: module.id, | selector: 'growl-alert',
template: `<p-growl [value]="alerts" #growlNSticky></p-growl><p-growl [value]="stickyAlerts" #growlSticky [sticky]="true"></p-growl>`,
styles : [
`.ui-error-growl {
position: fixed;
top: 0 !important;
right: 0 ... | random_line_split | |
growl-alert.component.ts | import { Component, OnInit, Input, ViewChild } from '@angular/core';
import {IGrowlAlertOptions, IGrowlAlertApi} from './growl-alert.model';
import {Message, Growl} from 'primeng/primeng';
@Component({
moduleId: module.id,
selector: 'growl-alert',
template: `<p-growl [value]="alerts" #growlNSticky></... |
info(message: string, title?: string, sticky?: boolean, life?: number) : void {
if(sticky) {
this.stickyAlerts.push({severity:'info', summary: title, detail: message});
} else {
this.alerts.push({severity:'info', summary: title, detail: message});
... | {
if(sticky) {
this.stickyAlerts.push({severity:'success', summary: title, detail: message});
} else {
this.alerts.push({severity:'success', summary: title, detail: message});
}
} | identifier_body |
growl-alert.component.ts | import { Component, OnInit, Input, ViewChild } from '@angular/core';
import {IGrowlAlertOptions, IGrowlAlertApi} from './growl-alert.model';
import {Message, Growl} from 'primeng/primeng';
@Component({
moduleId: module.id,
selector: 'growl-alert',
template: `<p-growl [value]="alerts" #growlNSticky></... |
}
warn(message: string, title?: string,sticky?: boolean, life?: number) : void {
if(sticky) {
this.stickyAlerts.push({severity:'warn', summary: title, detail: message});
} else {
this.alerts.push({severity:'warn', summary: title, detail: message})... | {
this.alerts.push({severity:'info', summary: title, detail: message});
} | conditional_block |
handshake.js | "use strict"
var util = require('util')
var MessageEvent = require('./messageevent')
var Config = require('./config')
/**
* Coordinate the connection of a new chat client to the server.
* Different chat clients send the information differently, so far this chat server supports: TinTin++, mudjs, MudMaster, MudMaste... |
// get the name and ip from the second part of the result
this.name = result[1].split('\n')[0]
this.ip = this.socket.remoteAddress
this.port = this.socket.remotePort
}
/**
* Send the chat servers name to the client
* @param {String} name the name of the chat server
... | {
// Unknown protocol
this.protocol = 'unknown'
} | conditional_block |
handshake.js | "use strict"
var util = require('util')
var MessageEvent = require('./messageevent')
var Config = require('./config')
/**
* Coordinate the connection of a new chat client to the server.
* Different chat clients send the information differently, so far this chat server supports: TinTin++, mudjs, MudMaster, MudMaste... | {
/**
* Handshake constructor
* Constructs a new handshake object to process new connections to the chatserver
* @param {Socket} socket nodejs net socket object
* @param {Function} callback the callback that will be processed once the handshake has completed
* @todo Ge... | Handshake | identifier_name |
handshake.js | "use strict"
var util = require('util')
var MessageEvent = require('./messageevent')
var Config = require('./config')
/**
* Coordinate the connection of a new chat client to the server.
* Different chat clients send the information differently, so far this chat server supports: TinTin++, mudjs, MudMaster, MudMaste... |
// set the connection's protocol information
this.setProtocol(str)
// send the chat name of the server to the client
this.setName('chatserver')
// send the version of the chatserver to the client
this.setVersion(`chatserv... | // check if our handshake data contains the expected :
if (str.indexOf(':') > -1) { | random_line_split |
utils.py | """
A misc set of utilities useful in the data-import domain.
"""
import logging
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from open_municipio.people.models import Person, municipality
from open_municipio.data_import.models import LookupInstitutionCharge, LookupCompanyCharge, Lookup... |
logger = logging.getLogger("import")
def lookup_charge(self, external, provider, as_of=None):
# if already mapped, return the result from the cache
found_internal = ChargeMapCache.lookup(external, provider, as_of)
if not found_internal:
try:
... | method
""" | random_line_split |
utils.py | """
A misc set of utilities useful in the data-import domain.
"""
import logging
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from open_municipio.people.models import Person, municipality
from open_municipio.data_import.models import LookupInstitutionCharge, LookupCompanyCharge, Lookup... | (self, external, provider):
return LookupPerson.lookup(external, provider)
class ChargeMapCache:
cache = {}
@staticmethod
def lookup(external, provider, as_of):
if provider in ChargeMapCache.cache:
if external in ChargeMapCache.cache[provider]:
if as_of... | lookup_person | identifier_name |
utils.py | """
A misc set of utilities useful in the data-import domain.
"""
import logging
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from open_municipio.people.models import Person, municipality
from open_municipio.data_import.models import LookupInstitutionCharge, LookupCompanyCharge, Lookup... |
elif charge_type == 'mayor':
institution = municipality.mayor.as_institution
else:
self.logger.error("Warning: charge with id %s has wrong charge attribute %s. Skipping." %
(ds_charge_id, c... | institution = municipality.gov.as_institution | conditional_block |
utils.py | """
A misc set of utilities useful in the data-import domain.
"""
import logging
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from open_municipio.people.models import Person, municipality
from open_municipio.data_import.models import LookupInstitutionCharge, LookupCompanyCharge, Lookup... | self.logger.warning("charge with id %s has no charge attribute. Skipping." % ds_charge_id)
return None
# institution is grabbed from charge attribute, in acts import
# since mayor and deputies may sign acts, not only counselor
... | """
look for the correct open municipio charge, or return None
starting from an internal, domain-specific, charge id
using the mapping in people_tree (lxml.etree)
if the moment parameter is not passed, then current charges are looked up
"""
try:
people_charges... | identifier_body |
send-data.ts | import * as http from 'http';
import { URL } from 'url';
import { CodedError } from '@carnesen/coded-error';
export const sendData = (href: string, data: string): Promise<string> => {
return new Promise((resolve, reject) => {
const url = new URL(href);
const req = http.request({
hostname: url.hostname... | if (res.statusCode !== 200) {
const err = new CodedError(
`http response code was ${res.statusCode}, "${res.statusMessage}"`,
res.statusCode,
);
reject(err);
return;
}
res.on('data', chunk => {
responseData += chunk;
});
res.on('... | random_line_split | |
send-data.ts | import * as http from 'http';
import { URL } from 'url';
import { CodedError } from '@carnesen/coded-error';
export const sendData = (href: string, data: string): Promise<string> => {
return new Promise((resolve, reject) => {
const url = new URL(href);
const req = http.request({
hostname: url.hostname... |
res.on('data', chunk => {
responseData += chunk;
});
res.on('end', () => {
resolve(responseData);
});
});
req.on('error', (err: NodeJS.ErrnoException) => {
reject(new CodedError(`http request failed "${err.message}"`, err.code));
});
req.end(data);
});... | {
const err = new CodedError(
`http response code was ${res.statusCode}, "${res.statusMessage}"`,
res.statusCode,
);
reject(err);
return;
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = safe_get_config("mysql.connection", "mysql://root:root@localhost/hackathon")
app.config['SECRET_KEY'] = safe_get_config("app.secret_key", "secret_key")
app.config['DEBUG_TB_ENABLED'] = False
toolbar = DebugToolbarExtension(app)
class Context(object):
... |
# flask | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | (self, name):
if name in self.__dict__:
return self.__dict__[name]
raise AttributeError()
def __setattr__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, item):
return self.__getattr__(item)
def __setitem__(self, key, value):
return... | __getattr__ | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... |
@staticmethod
def from_object(arg):
"""Convert JSON-like object to Context recursively
:returns list of Context if arg is list
instance of Context if arg is dict
the original arg otherwise
"""
if isinstance(arg, list):
return [Cont... | if key in self.__dict__:
return self.__dict__[key]
else:
return default_value | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... |
elif isinstance(arg, dict):
ctx = Context()
for k, v in arg.iteritems():
if isinstance(v, dict):
setattr(ctx, k, Context.from_object(v))
elif isinstance(v, list):
setattr(ctx, k, [Context.from_object(vv) for vv in v... | return [Context.from_object(a) for a in arg] | conditional_block |
__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | This package includes the internal APIs for PySpark about interoperability
between pandas, PySpark and PyArrow. This package should not be directly
imported and used.
""" | random_line_split | |
sorted-list.py | # -----------------------------------------------------------
# compares the creation of sorted lists using the python
# bisect module, and the "usual" way
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email frank.hofmann@efho.de
# --------------------------------------------... | ():
# define empty list, and fill with 200000 randomized integers
sortedNumbers = []
for element in range(200000):
# choose a number between 0 and 1000
newNumber = random.randint(0, 1000)
#print ("adding %i to list ... " %newNumber)
# insert into sorted list
bisect.insort(sortedNumbers, newNumber)
retu... | sortListBisect | identifier_name |
sorted-list.py | # -----------------------------------------------------------
# compares the creation of sorted lists using the python
# bisect module, and the "usual" way
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email frank.hofmann@efho.de
# --------------------------------------------... |
# evaluate default sort
startTime1 = time.time()
listPosition = sortListDefault()
endTime1 = time.time()
# calculate and output interval time
seconds = endTime1 - startTime1
print ("default sort took %.8f seconds" % seconds)
# evaluate bisect sort
startTime1 = time.time()
listPosition = sortListBisect()
endTime1 = ... | sortedNumbers = []
for element in range(200000):
# choose a number between 0 and 1000
newNumber = random.randint(0, 1000)
#print ("adding %i to list ... " %newNumber)
# insert into sorted list
bisect.insort(sortedNumbers, newNumber)
return | identifier_body |
sorted-list.py | # -----------------------------------------------------------
# compares the creation of sorted lists using the python
# bisect module, and the "usual" way
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email frank.hofmann@efho.de
# --------------------------------------------... | print ("bisect sort took %.8f seconds" % seconds) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.