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 |
|---|---|---|---|---|
events.py | #
# Copyright 2015-2016 Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distr... | (self):
with self._lock:
self.events.clear()
root = Handler(name='root')
def fire(event_id, dom, *args):
global root
root.fire(event_id, dom, *args)
| clear | identifier_name |
events.py | #
# Copyright 2015-2016 Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distr... |
# TODO: debug?
self._log.warning('[%s] unhandled event %r', self._name, event_id)
return self._null
@property
def registered(self):
with self._lock:
return tuple(self.events.keys())
# for testing purposes
def clear(self):
with self._lock:
... | self._log.warning('[%s] unknown event %r',
self._name, event_id)
return self._parent.get_callbacks(event_id) | conditional_block |
ircbot.js | 'use strict';
var _ = require('underscore'),
Irc = require('irc');
var IrcBot = function(config) {
if (!(this instanceof IrcBot)) {
return new IrcBot(config);
}
this.config = _.defaults(config, {
server: 'irc.freenode.com', // IRC server
username: 'slackbot', // Bot IRC nickname
nick: '... | ];
this.irc = {
userName: this.config.username,
password: this.config.password,
channels: Object.keys(this.config.channels),
floodProtection: true
};
nodeIrcOptions.forEach(function(opt) {
if (this.config[opt]) {
this.irc[opt] = this.config[opt];
}
}.bind(this));
};
IrcBot.pro... | 'channelPrefixes', 'messageSplit' | random_line_split |
ircbot.js | 'use strict';
var _ = require('underscore'),
Irc = require('irc');
var IrcBot = function(config) {
if (!(this instanceof IrcBot)) {
return new IrcBot(config);
}
this.config = _.defaults(config, {
server: 'irc.freenode.com', // IRC server
username: 'slackbot', // Bot IRC nickname
nick: '... |
}.bind(this));
}
IrcBot.prototype._handleErrors = function() {
this.client.addListener('error', function(message) {
var
channel = message.args[1],
errorMessage = this.mapPronouns(message.args[2]||'');
this.systemSpeak(channel, 'I don\'t feel so well because ' + errorMessage);
}.bind(this));
};
... | {
this.speak(dest, Object.keys(this.slackRes.userMap).map(function (a) { return this.slackRes.userMap[a] }.bind(this)).join(", "));
} | conditional_block |
import.py | #!/usr/bin/env python
# -*- coding, utf-8 -*-
# FIDATA. Open-source system for analysis of financial and economic data
# Copyright © 2013 Basil Peace
# This file is part of FIDATA.
#
# FIDATA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | # reader = DictReader(open('currencies.csv', 'r', encoding = 'UTF8'), delimiter = ';')
# for row in reader:
# row['instr_type'] = InstrumentType.Currency
# FIDATA.instrument(row = row, write = True, tryGetFromDB = False)
# del reader
# commit()
# logging.info('Importing instruments')
# reader = DictReader(open('inst... | # commit()
# classes += [Issuer]
# logging.info('Importing currencies') | random_line_split |
import.py | #!/usr/bin/env python
# -*- coding, utf-8 -*-
# FIDATA. Open-source system for analysis of financial and economic data
# Copyright © 2013 Basil Peace
# This file is part of FIDATA.
#
# FIDATA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | l reader
commit()
classes += [Script]
logging.info('Importing countries')
reader = DictReader(open('countries.csv', 'r', encoding = 'UTF8'), delimiter = ';')
for row in reader:
# parent_country
# associated_with
if row['alpha2_code'] == '':
row['alpha2_code'] = None
else:
flagFilename = 'flags\{:s}.png'.format... | ipt(FIDATA, row = row, write = True, tryGetFromDB = False)
de | conditional_block |
css_section.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOr... |
}
| {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
}
} | identifier_body |
css_section.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOr... | (&self) -> Option<gio::File> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_file(self.to_glib_none().0))
}
}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
... | get_file | identifier_name |
css_section.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOr... | }
}
} | pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0) | random_line_split |
utils.rs | // Copyright 2015 click2stream, 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 law or agreed... | (sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000) != 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!checksum as u16
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[rep... | sum_to_checksum | identifier_name |
utils.rs | // Copyright 2015 click2stream, 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 law or agreed... | impl Serialize for Box<[u8]> {
fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {
w.write_all(self.as_ref())
}
}
/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.
pub fn sum_type<T: Sized>(data: &T) -> u32 {
let size = mem::size_of::<T>();
let ptr = data as *con... | pub trait Serialize {
/// Serialize this object using a given writer.
fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;
}
| random_line_split |
utils.rs | // Copyright 2015 click2stream, 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 law or agreed... | else {
sum
}
}
/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.
pub fn sum_to_checksum(sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000) != 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!c... | {
sum.wrapping_add((slice[size - 1] as u32) << 8)
} | conditional_block |
utils.rs | // Copyright 2015 click2stream, 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 law or agreed... |
}
| {
assert_eq!(!0x0000_3333, sum_to_checksum(0x1111_2222));
} | identifier_body |
broadcast.ts | /*
* LiskHQ/lisk-commander
* Copyright © 2017–2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be c... | throw new ValidationError(
'Could not parse signature JSON. Did you use the `--json` option?',
);
}
const client = getAPIClient(this.userConfig.api);
const response = await client.signatures.broadcast(signatureObject);
this.print(response.data);
}
} | signatureObject = JSON.parse(signatureInput);
} catch (error) { | random_line_split |
broadcast.ts | /*
* LiskHQ/lisk-commander
* Copyright © 2017–2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be c... | return data;
} catch (e) {
throw new ValidationError('No signature was provided.');
}
};
export default class BroadcastCommand extends BaseCommand {
static args = [
{
name: 'signature',
description: 'Signature to broadcast.',
},
];
static description = `
Broadcasts a signature for a transaction fro... | throw new ValidationError('No signature was provided.');
}
| conditional_block |
broadcast.ts | /*
* LiskHQ/lisk-commander
* Copyright © 2017–2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be c... | Promise<void> {
const { args } = this.parse(BroadcastCommand);
const { signature }: Args = args;
const signatureInput = signature || (await getSignatureInput());
// tslint:disable-next-line no-let
let signatureObject: object;
try {
signatureObject = JSON.parse(signatureInput);
} catch (error) {
thr... | (): | identifier_name |
cookie.py | from __future__ import absolute_import, unicode_literals
from django.utils.encoding import force_str
from django.utils import six
from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = http_cookies.SimpleCookie().value_enc... |
return cookiedict
| cookiedict[key] = c.get(key).value | conditional_block |
cookie.py | from __future__ import absolute_import, unicode_literals
from django.utils.encoding import force_str
from django.utils import six
from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = http_cookies.SimpleCookie().value_enc... | encoded = '"' + encoded + '"'
return val, encoded
if not _cookie_allows_colon_in_names:
def load(self, rawdata):
self.bad_cookies = set()
if six.PY2 and isinstance(rawdata, six.text_type):
rawdata = force_str(r... | if "\\" in encoded and not encoded.startswith('"'): | random_line_split |
cookie.py | from __future__ import absolute_import, unicode_literals
from django.utils.encoding import force_str
from django.utils import six
from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = http_cookies.SimpleCookie().value_enc... | if cookie == '':
return {}
if not isinstance(cookie, http_cookies.BaseCookie):
try:
c = SimpleCookie()
c.load(cookie)
except http_cookies.CookieError:
# Invalid cookie
return {}
else:
c = cookie
cookiedict = {}
for key in c.... | identifier_body | |
cookie.py | from __future__ import absolute_import, unicode_literals
from django.utils.encoding import force_str
from django.utils import six
from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = http_cookies.SimpleCookie().value_enc... | (http_cookies.SimpleCookie):
if not _cookie_encodes_correctly:
def value_encode(self, val):
# Some browsers do not support quoted-string from RFC 2109,
# including some versions of Safari and Internet Explorer.
# These browsers split on ';', and some v... | SimpleCookie | identifier_name |
OnDemandTypeInfo.ts | -2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
impo... |
return;
}
/**
* Return all own properties
*/
getOwnProperties(): ReadonlyArray<PropertyInfo> {
const found = new Array<PropertyInfo>();
const type = this.typeAnnotation;
if (type && type.properties) {
for (const key of type.properties.keys()) {
found.push(this.property(key));... | {
if (propertyAnnotation.target === this.target) {
return this.getOwnProperty(key);
} else {
return OnDemandTypeInfo.find(propertyAnnotation.target).getOwnProperty(key);
}
} | conditional_block |
OnDemandTypeInfo.ts | -2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
impo... |
protected getBase(): TypeInfo | null | undefined {
const base = Reflect.getPrototypeOf(this.target);
let result;
if (!base) {
result = null;
}
// ignore object as base type
else if (base === Function.prototype || base === Object.prototype || IsAgent(base)) {
result = null;
} ... | {
if (this.target === this.declaringType) {
return MemberKinds.StaticClass;
}
return MemberKinds.Class;
} | identifier_body |
OnDemandTypeInfo.ts | from './TypeInfo';
import { PropertyInfo } from './PropertyInfo';
import { Filter } from './Filter';
import { Attribute } from '../Attribute';
import { Remember } from '../Decorators/Remember/Remember';
import { AddAttributeToConstructor } from '../../../dependencies/core';
import { CONSTRUCTOR } from '../WellKnown';
... | addAttribute | identifier_name | |
OnDemandTypeInfo.ts | { TypeInfo } from './TypeInfo';
import { PropertyInfo } from './PropertyInfo';
import { Filter } from './Filter';
import { Attribute } from '../Attribute';
import { Remember } from '../Decorators/Remember/Remember';
import { AddAttributeToConstructor } from '../../../dependencies/core';
import { CONSTRUCTOR } from '..... | random_line_split | ||
models.py | from time import time
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_delete
from django.dispatch import receiver
import os
def upload_path(instance, filename):
return 'uploads/user_{0}/{1}_{2}'.format(
instance.owner.id,
str(time... | # split the image part
filepath, ext = os.path.splitext(image_path)
# create the filtered image path
new_filepath = filepath + "filtered" + ext
# delete from file directory
if os.path.exists(image_path):
# delete image
os.remove(image_path)
if os.path.exists(new_filepath):
... |
image_path = instance.image.path
| random_line_split |
models.py | from time import time
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_delete
from django.dispatch import receiver
import os
def upload_path(instance, filename):
return 'uploads/user_{0}/{1}_{2}'.format(
instance.owner.id,
str(time... | (sender, instance, **kwargs):
image_path = instance.image.path
# split the image part
filepath, ext = os.path.splitext(image_path)
# create the filtered image path
new_filepath = filepath + "filtered" + ext
# delete from file directory
if os.path.exists(image_path):
# delete image... | delete_from_file_system | identifier_name |
models.py | from time import time
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_delete
from django.dispatch import receiver
import os
def upload_path(instance, filename):
return 'uploads/user_{0}/{1}_{2}'.format(
instance.owner.id,
str(time... | os.remove(new_filepath) | conditional_block | |
models.py | from time import time
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_delete
from django.dispatch import receiver
import os
def upload_path(instance, filename):
|
class UserProfile(models.Model):
user = models.OneToOneField(User)
photo = models.TextField()
class Images(models.Model):
owner = models.ForeignKey(User)
image = models.ImageField(upload_to=upload_path)
image_file_name = models.CharField(max_length=100, null=True)
date_created = models.Date... | return 'uploads/user_{0}/{1}_{2}'.format(
instance.owner.id,
str(time()).replace('.', '_'),
filename
) | identifier_body |
token.rs | DotDotDot,
Comma,
Semi,
Colon,
ModSep,
RArrow,
LArrow,
FatArrow,
Pound,
Dollar,
Question,
/// An opening delimeter, eg. `{`
OpenDelim(DelimToken),
/// A closing delimeter, eg. `}`
CloseDelim(DelimToken),
/* Literals */
LitByte(ast::Name),
LitChar(... | /* Structural symbols */
At,
Dot,
DotDot, | random_line_split | |
token.rs | => true,
_ => false,
}
}
/// Returns `true` if the token is any literal
pub fn is_lit(&self) -> bool {
match *self {
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
... |
/// Returns `true` if the token is an interpolated path.
pub fn is_path(&self) -> bool {
match *self {
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is a path that is not followed by a `::`
//... | {
match *self {
Ident(_, _) => true,
_ => false,
}
} | identifier_body |
token.rs | {
/// `::` follows the identifier with no whitespace in-between.
ModName,
Plain,
}
#[allow(non_camel_case_types)]
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
pub enum Token {
/* Expression-operator symbols. */
Eq,
Lt,
Le,
EqEq,
Ne,
Ge,
Gt,
AndAnd... | IdentStyle | identifier_name | |
utils.py | # -*- coding: utf-8 -*-
import os
from codecs import encode, decode
import re
LINUX_ROOT = u"/"
def trim_quote(text):
|
def to_unicode(text, encoding="utf8"):
if type(text) == unicode:
return text
elif type(text) == str:
return decode(text, encoding)
else:
return unicode(text)
def remove_bom(input_filename, output_filename):
fp = open(input_filename, "rb")
bom = fp.read(3)
if bom !=... | if len(text) > 2 and text[0] == '"' and text[-1] == '"':
text = text[1:-1]
return text | identifier_body |
utils.py | # -*- coding: utf-8 -*-
import os
from codecs import encode, decode
import re
LINUX_ROOT = u"/"
def trim_quote(text):
if len(text) > 2 and text[0] == '"' and text[-1] == '"':
text = text[1:-1]
return text
def to_unicode(text, encoding="utf8"):
if type(text) == unicode:
return text
... | (input_filename, output_filename, encoding, overwrite=False):
fp = open(input_filename, "rb")
ansi_content = fp.read()
fp.close()
if not overwrite:
if os.path.exists(output_filename):
return
with open(output_filename, "w") as fp:
if encoding.lower() in ["utf8", "utf-8", "... | iconv_file | identifier_name |
utils.py | # -*- coding: utf-8 -*-
import os
from codecs import encode, decode
import re
LINUX_ROOT = u"/"
def trim_quote(text):
if len(text) > 2 and text[0] == '"' and text[-1] == '"':
text = text[1:-1]
return text
def to_unicode(text, encoding="utf8"):
if type(text) == unicode:
return text
... | except OSError, e:
if e.errno != os.errno.EEXIST:
raise
def command_copy_to(files, folder, base_command=u"cp"):
if len(files) == 0:
return u"echo"
if not folder:
folder = u"."
arguments = [base_command]
arguments.append(u"-n")
for f in files:
arg... | try:
os.makedirs(parent_folder(path), mode=0755) | random_line_split |
utils.py | # -*- coding: utf-8 -*-
import os
from codecs import encode, decode
import re
LINUX_ROOT = u"/"
def trim_quote(text):
if len(text) > 2 and text[0] == '"' and text[-1] == '"':
text = text[1:-1]
return text
def to_unicode(text, encoding="utf8"):
if type(text) == unicode:
return text
... |
return text
def parent_folder(path):
parts = path.split(u"/")
if path == LINUX_ROOT:
raise ValueError(u"Can't get parent folder from linux dir /")
if parts[-1] == u"":
del parts[-1]
if parts[-1] == u".":
parts[-1] = u".."
elif parts[-1] == u"..":
parts.appen... | text = text.replace(ch, u'''\\%s''' % ch) | conditional_block |
route_recognizer.d.ts | import { PathRecognizer } from './path_recognizer';
/**
* `RouteRecognizer` is responsible for recognizing routes for a single component.
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
* components.
*/
export declare class RouteRecognizer {
names: Map<string, PathRecogn... | specificity?: number;
handler?: StringMap<string, any>;
params?: StringMap<string, string>;
matchedUrl?: string;
unmatchedUrl?: string;
});
}
export declare var __esModule: boolean; | unmatchedUrl: string;
constructor({specificity, handler, params, matchedUrl, unmatchedUrl}?: { | random_line_split |
route_recognizer.d.ts | import { PathRecognizer } from './path_recognizer';
/**
* `RouteRecognizer` is responsible for recognizing routes for a single component.
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
* components.
*/
export declare class RouteRecognizer {
names: Map<string, PathRecogn... | {
specificity: number;
handler: StringMap<string, any>;
params: StringMap<string, string>;
matchedUrl: string;
unmatchedUrl: string;
constructor({specificity, handler, params, matchedUrl, unmatchedUrl}?: {
specificity?: number;
handler?: StringMap<string, any>;
params?: ... | RouteMatch | identifier_name |
filister.py | # -*- coding: utf-8 -*-
'''
Flixnet Add-on
Copyright (C) 2017 homik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... |
from resources.lib.modules import cleantitle
from resources.lib.modules import client
class source:
def __init__(self):
self.priority = 1
self.language = ['pl']
self.domains = ['filiser.tv']
self.base_link = 'http://filiser.tv/'
self.url_transl = 'embed?salt=%s'
s... | import urllib, urlparse, re | random_line_split |
filister.py | # -*- coding: utf-8 -*-
'''
Flixnet Add-on
Copyright (C) 2017 homik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | (self, url):
try:
url_to_exec = urlparse.urljoin(self.base_link, self.url_transl) % url
result = client.request(url_to_exec)
m = re.search("(?<=var url = ')(.*\n?)(?=')", result)
result_url = m.group(0)
result_url = result_url.replace('#WIDTH', '100'... | resolve | identifier_name |
filister.py | # -*- coding: utf-8 -*-
'''
Flixnet Add-on
Copyright (C) 2017 homik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | result = [x for x in result if x[3].startswith(search_type)]
# filter by year
result = [x for x in result if x[3].endswith(str(year))]
if len(result) > 0:
return result[0][0]
else:
return
except :
return
... | try:
url = urlparse.urljoin(self.base_link, self.search_link)
url = url % urllib.quote(title)
result = client.request(url)
result = result.decode('utf-8')
result = client.parseDOM(result, 'ul', attrs={'id': 'resultList2'})
result = client.parseDOM... | identifier_body |
filister.py | # -*- coding: utf-8 -*-
'''
Flixnet Add-on
Copyright (C) 2017 homik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... |
except :
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
if url == None: return sources
url = urlparse.urljoin(self.base_link, url)
result = client.request(url)
result = client.parseDOM(result, 'div'... | return client.parseDOM(i, 'a', attrs={'class': 'episodeNum'}, ret='href')[0] | conditional_block |
cursor.py | from django.conf import settings
from .locals import get_cid
DEFAULT_CID_SQL_COMMENT_TEMPLATE = 'cid: {cid}'
class CidCursorWrapper:
"""
A cursor wrapper that attempts to add a cid comment to each query
"""
def __init__(self, cursor):
self.cursor = cursor
def __getattr__(self, attr):
... |
def executemany(self, sql, param_list):
sql = self.add_comment(sql)
return self.cursor.executemany(sql, param_list) | random_line_split | |
cursor.py | from django.conf import settings
from .locals import get_cid
DEFAULT_CID_SQL_COMMENT_TEMPLATE = 'cid: {cid}'
class | :
"""
A cursor wrapper that attempts to add a cid comment to each query
"""
def __init__(self, cursor):
self.cursor = cursor
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
return getattr(self.cursor, attr)
def __iter__(self... | CidCursorWrapper | identifier_name |
cursor.py | from django.conf import settings
from .locals import get_cid
DEFAULT_CID_SQL_COMMENT_TEMPLATE = 'cid: {cid}'
class CidCursorWrapper:
"""
A cursor wrapper that attempts to add a cid comment to each query
"""
def __init__(self, cursor):
self.cursor = cursor
def __getattr__(self, attr):
... |
return getattr(self.cursor, attr)
def __iter__(self):
return iter(self.cursor)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def add_comment(self, sql):
cid_sql_template = getattr(
settings, 'CID... | return self.__dict__[attr] | conditional_block |
cursor.py | from django.conf import settings
from .locals import get_cid
DEFAULT_CID_SQL_COMMENT_TEMPLATE = 'cid: {cid}'
class CidCursorWrapper:
"""
A cursor wrapper that attempts to add a cid comment to each query
"""
def __init__(self, cursor):
self.cursor = cursor
def __getattr__(self, attr):
... |
def executemany(self, sql, param_list):
sql = self.add_comment(sql)
return self.cursor.executemany(sql, param_list)
| sql = self.add_comment(sql)
return self.cursor.execute(sql, params) | identifier_body |
PipelineGraphModel.tsx | /**
* @deprecated Don't use this, the latest version exists in the ux-widgets repo, and Blue Ocean also uses that now
*/
export enum Result {
success = 'success',
failure = 'failure',
running = 'running',
queued = 'queued',
paused = 'paused',
unstable = 'unstable',
aborted = 'aborted',
... |
export const MATRIOSKA_PATHS = false;
// Dimensions used for layout, px
export const defaultLayout = {
nodeSpacingH: 120,
parallelSpacingH: 120,
nodeSpacingV: 70,
nodeRadius: 12,
terminalRadius: 7,
curveRadius: 12,
connectorStrokeWidth: 3.5,
labelOffsetV: 20,
smallLabelOffsetV: 15... | {
const lcase = String(resultMaybe).toLowerCase();
for (const enumKey of Object.keys(Result)) {
const enumValue = Result[enumKey as any];
if (enumKey.toLowerCase() === lcase || enumValue.toLowerCase() === lcase) {
return enumValue as Result;
}
}
return Result.unknown... | identifier_body |
PipelineGraphModel.tsx | /**
* @deprecated Don't use this, the latest version exists in the ux-widgets repo, and Blue Ocean also uses that now
*/
export enum Result {
success = 'success',
failure = 'failure',
running = 'running',
queued = 'queued',
paused = 'paused',
unstable = 'unstable',
aborted = 'aborted',
... | seqContainerName: string; //used within a parallel branch to denote the name of the container of the parallel sequential stages
}
// TODO: Refactor these into a common base, and some discerning "typeof" funcs
export interface BaseNodeInfo {
key: string;
x: number;
y: number;
id: number;
name: ... | random_line_split | |
PipelineGraphModel.tsx | /**
* @deprecated Don't use this, the latest version exists in the ux-widgets repo, and Blue Ocean also uses that now
*/
export enum Result {
success = 'success',
failure = 'failure',
running = 'running',
queued = 'queued',
paused = 'paused',
unstable = 'unstable',
aborted = 'aborted',
... | (resultMaybe: any): Result {
const lcase = String(resultMaybe).toLowerCase();
for (const enumKey of Object.keys(Result)) {
const enumValue = Result[enumKey as any];
if (enumKey.toLowerCase() === lcase || enumValue.toLowerCase() === lcase) {
return enumValue as Result;
}
}... | decodeResultValue | identifier_name |
PipelineGraphModel.tsx | /**
* @deprecated Don't use this, the latest version exists in the ux-widgets repo, and Blue Ocean also uses that now
*/
export enum Result {
success = 'success',
failure = 'failure',
running = 'running',
queued = 'queued',
paused = 'paused',
unstable = 'unstable',
aborted = 'aborted',
... |
}
return Result.unknown;
}
export const MATRIOSKA_PATHS = false;
// Dimensions used for layout, px
export const defaultLayout = {
nodeSpacingH: 120,
parallelSpacingH: 120,
nodeSpacingV: 70,
nodeRadius: 12,
terminalRadius: 7,
curveRadius: 12,
connectorStrokeWidth: 3.5,
labelOf... | {
return enumValue as Result;
} | conditional_block |
release_activity_updater.rs | use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn update_release_activity() -> Result<()> {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::w... | let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
... | random_line_split | |
release_activity_updater.rs | use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn | () -> Result<()> {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
let rows = conn.query(
&format!(
"SELECT COUNT(*)
... | update_release_activity | identifier_name |
release_activity_updater.rs | use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn update_release_activity() -> Result<()> | "SELECT COUNT(*)
FROM releases
WHERE is_library = TRUE AND
build_status = FALSE AND
release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
... | {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases... | identifier_body |
cache.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/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... | <K,V> {
entries: Vec<Option<(K,V)>>,
k0: u64,
k1: u64,
}
impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> {
pub fn new(cache_size: usize) -> SimpleHashCache<K,V> {
let mut r = rand::thread_rng();
SimpleHashCache {
entries: repeat(None).take(cache_size).collect(),
... | SimpleHashCache | identifier_name |
cache.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/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... |
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: usize,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: usize) -> LRUCache<K, V> {
LRUCache {
entries: vec!(),
... | {
(*vacant.insert(blk(key))).clone()
} | conditional_block |
cache.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/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... | impl<K, V> HashCache<K,V>
where K: Clone + PartialEq + Eq + Hash,
V: Clone,
{
pub fn new() -> HashCache<K,V> {
HashCache {
entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()),
}
}
pub fn insert(&mut self, key: K, value: V) {
sel... | pub struct HashCache<K, V> {
entries: HashMap<K, V, DefaultState<SipHasher>>,
}
| random_line_split |
cache.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/. */
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... |
pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> {
self.entries.iter()
}
pub fn insert(&mut self, key: K, val: V) {
if self.entries.len() == self.cache_size {
self.entries.remove(0);
}
self.entries.push((key, val));
}
pub fn find(&mut self, key: &K) -> Opti... | {
let last_index = self.entries.len() - 1;
if pos != last_index {
let entry = self.entries.remove(pos);
self.entries.push(entry);
}
self.entries[last_index].1.clone()
} | identifier_body |
gamepad.js | /*
* This file is part of huborcid.
*
* huborcid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* huborcid is distrib... | * GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
// GamePad API
// https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html
// By Eric Bidelman
// FF has Gam... | random_line_split | |
Action2005.py | """2005_叫地主接口"""
import clr, sys
from action import *
from lang import Lang
clr.AddReference('ZyGames.Framework.Game')
| from ZyGames.Doudizhu.Model import *
from ZyGames.Doudizhu.Bll.Logic import *
class UrlParam(HttpParam):
def __init__(self):
HttpParam.__init__(self)
self.op = 0
class ActionResult(DataResult):
def __init__(self):
DataResult.__init__(self)
def getUrlElement(httpGet, pa... | clr.AddReference('ZyGames.Doudizhu.Lang')
clr.AddReference('ZyGames.Doudizhu.Model')
clr.AddReference('ZyGames.Doudizhu.Bll')
from ZyGames.Framework.Game.Service import *
from ZyGames.Doudizhu.Lang import *
| random_line_split |
Action2005.py | """2005_叫地主接口"""
import clr, sys
from action import *
from lang import Lang
clr.AddReference('ZyGames.Framework.Game')
clr.AddReference('ZyGames.Doudizhu.Lang')
clr.AddReference('ZyGames.Doudizhu.Model')
clr.AddReference('ZyGames.Doudizhu.Bll')
from ZyGames.Framework.Game.Service import *
from ZyGames.Doudizh... | if table.IsCallEnd:
parent.ErrorCode = Lang.getLang("ErrorCode")
parent.ErrorInfo = Lang.getLang("St2005_CalledIsEnd")
actionResult.Result = False
return actionResult
position = GameTable.Current.GetUserPosition(user, table)
if not position:
parent.ErrorCode = Lang... | Code = Lang.getLang("ErrorCode")
parent.ErrorInfo = Lang.getLang("LoadError")
actionResult.Result = False
return actionResult
| conditional_block |
Action2005.py | """2005_叫地主接口"""
import clr, sys
from action import *
from lang import Lang
clr.AddReference('ZyGames.Framework.Game')
clr.AddReference('ZyGames.Doudizhu.Lang')
clr.AddReference('ZyGames.Doudizhu.Model')
clr.AddReference('ZyGames.Doudizhu.Bll')
from ZyGames.Framework.Game.Service import *
from ZyGames.Doudizh... | arent):
actionResult = ActionResult()
user = parent.Current.User
table = GameRoom.Current.GetTableData(user)
if not table or not user:
parent.ErrorCode = Lang.getLang("ErrorCode")
parent.ErrorInfo = Lang.getLang("LoadError")
actionResult.Result = False
return acti... | rlParam, p | identifier_name |
Action2005.py | """2005_叫地主接口"""
import clr, sys
from action import *
from lang import Lang
clr.AddReference('ZyGames.Framework.Game')
clr.AddReference('ZyGames.Doudizhu.Lang')
clr.AddReference('ZyGames.Doudizhu.Model')
clr.AddReference('ZyGames.Doudizhu.Bll')
from ZyGames.Framework.Game.Service import *
from ZyGames.Doudizh... | ActionResult(DataResult):
def __init__(self):
DataResult.__init__(self)
def getUrlElement(httpGet, parent):
urlParam = UrlParam()
if httpGet.Contains("op"):
urlParam.op = httpGet.GetIntValue("op")
else:
urlParam.Result = False
return urlParam
def takeAction(... | (self):
HttpParam.__init__(self)
self.op = 0
class | identifier_body |
refresher.unit.js | describe('ionRefresher directive', function() {
beforeEach(module('ionic'));
function | (attrs, scopeProps) {
var el;
inject(function($compile, $rootScope) {
var scope = $rootScope.$new();
var ionicScrollCtrl = {
_setRefresher: jasmine.createSpy('setRefresher'),
scrollView: {
finishPullToRefresh: jasmine.createSpy('finishPullToRefresh')
}
};
... | setup | identifier_name |
refresher.unit.js | describe('ionRefresher directive', function() {
beforeEach(module('ionic'));
function setup(attrs, scopeProps) | return el;
}
it('should error without ionicScroll', inject(function($compile, $rootScope) {
expect(function() {
$compile('<ion-refresher>')($rootScope);
}).toThrow();
}));
it('should bind $onRefresh', function() {
var refreshSpy = jasmine.createSpy('onRefresh');
var el = setup('on-r... | {
var el;
inject(function($compile, $rootScope) {
var scope = $rootScope.$new();
var ionicScrollCtrl = {
_setRefresher: jasmine.createSpy('setRefresher'),
scrollView: {
finishPullToRefresh: jasmine.createSpy('finishPullToRefresh')
}
};
angular.extend(sc... | identifier_body |
refresher.unit.js | describe('ionRefresher directive', function() {
beforeEach(module('ionic'));
function setup(attrs, scopeProps) {
var el;
inject(function($compile, $rootScope) {
var scope = $rootScope.$new();
var ionicScrollCtrl = {
_setRefresher: jasmine.createSpy('setRefresher'),
scrollView: {... | el = angular.element('<ion-refresher '+(attrs||'')+'></ion-refresher>');
el.data('$$ionicScrollController', ionicScrollCtrl);
$compile(el)(scope);
ionic.requestAnimationFrame = function() {};
$rootScope.$apply();
});
return el;
}
it('should error without ionicScroll', inject(... | };
angular.extend(scope, scopeProps || {});
| random_line_split |
lib.rs | //
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits... |
}
pub fn into_box(self) -> ::boxed::Box<[T]> {
todo!("into_box");
}
pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool {
self.cap() != ::core::mem::POST_DROP_USIZE
}
}
}
| {
let newcap = self.cap() * 2;
self.0.resize(newcap);
} | conditional_block |
lib.rs | //
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits... | (&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn reserve_exact(&mut self, cur_used: usize, extra: usize) {
let newcap = cur... | shrink_to_fit | identifier_name |
lib.rs | //
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits... |
pub fn ptr(&self) -> *mut T {
self.0.get_base() as *mut T
}
pub fn shrink_to_fit(&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
... | {
self.0.count()
} | identifier_body |
lib.rs | // | #![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits)] // For !Send
#![feature(fill... | //
//
#![crate_type="rlib"] | random_line_split |
edit_server.rs | // Copyright 2016 Matthew Collins
//
// 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... | elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name: &str, address: &str) {
let mut servers_info = match fs::File::open("servers.json") {
Ok(val) => serde_json::from_reader(val).unwrap(),
Err(_) => {
... | pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry { | random_line_split |
edit_server.rs | // Copyright 2016 Matthew Collins
//
// 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... | {
logo: ui::logo::Logo,
elements: ui::Collection,
}
impl EditServerEntry {
pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry {
elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name:... | UIElements | identifier_name |
edit_server.rs | // Copyright 2016 Matthew Collins
//
// 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... |
}
| {
true
} | identifier_body |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -... | (query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len() != 2 {
... | parse_query | identifier_name |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -... | "Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let ... | random_line_split | |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -... |
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}
| {
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
} | identifier_body |
util.rs | use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -... |
None => {
return Err(format_err!("Timed out waiting"));
}
},
Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super:... | {
time_left = sub;
thread::sleep(sleep_time);
} | conditional_block |
comparisonOperatorWithSubtypeObjectOnProperty.js | //// [comparisonOperatorWithSubtypeObjectOnProperty.ts]
class Base {
public a: string;
}
class Derived extends Base {
public b: string;
}
class A1 {
public a: Base;
public b: Base;
}
class B1 {
public a: Base;
public b: Derived;
}
class A2 {
private a;
}
class B2 extends A2 {
priva... |
return B1;
}());
var A2 = /** @class */ (function () {
function A2() {
}
return A2;
}());
var B2 = /** @class */ (function (_super) {
__extends(B2, _super);
function B2() {
return _super !== null && _super.apply(this, arguments) || this;
}
return B2;
}(A2));
var a... | {
} | identifier_body |
comparisonOperatorWithSubtypeObjectOnProperty.js | //// [comparisonOperatorWithSubtypeObjectOnProperty.ts]
class Base {
public a: string;
}
class Derived extends Base {
public b: string;
}
class A1 {
public a: Base;
public b: Base;
}
class | {
public a: Base;
public b: Derived;
}
class A2 {
private a;
}
class B2 extends A2 {
private b;
}
var a1: A1;
var a2: A2;
var b1: B1;
var b2: B2;
// operator <
var ra1 = a1 < b1;
var ra2 = a2 < b2;
var ra3 = b1 < a1;
var ra4 = b2 < a2;
// operator >
var rb1 = a1 > b1;
var rb2 = a2 > b2;
var rb3 = ... | B1 | identifier_name |
comparisonOperatorWithSubtypeObjectOnProperty.js | //// [comparisonOperatorWithSubtypeObjectOnProperty.ts]
class Base {
public a: string;
}
class Derived extends Base {
public b: string;
}
class A1 {
public a: Base;
public b: Base;
} | public a: Base;
public b: Derived;
}
class A2 {
private a;
}
class B2 extends A2 {
private b;
}
var a1: A1;
var a2: A2;
var b1: B1;
var b2: B2;
// operator <
var ra1 = a1 < b1;
var ra2 = a2 < b2;
var ra3 = b1 < a1;
var ra4 = b2 < a2;
// operator >
var rb1 = a1 > b1;
var rb2 = a2 > b2;
var rb3 = b1 ... |
class B1 { | random_line_split |
main.py | #!/usr/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Greg Aitkenhead
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... |
"""
bead-calculator
============
A simple Python script to help peyote stitch beadworkers start their projects.
BeadCalculator checks to make sure the number of beads used in a project will
work out mathematically and lets the beadworker know what design elements
will be possible for the number of starting beads ente... | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. | random_line_split |
main.py | #!/usr/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Greg Aitkenhead
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... |
class CalcBeadResults(webapp2.RequestHandler):
"""
Run all logic and create templates depending on value of beads_entered.
Value 'beads_entered/ comes from textarea value of main-form in base.html.
"""
def get(self):
"""Gets number of beads entered from base.html form input."""
be... | """Renders the root of the web-app using base.html as the template."""
def get(self):
"""Create main web page."""
template = ENV.get_template('base.html')
self.response.write(template.render()) | identifier_body |
main.py | #!/usr/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Greg Aitkenhead
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... | (request, response, exception):
"""Create custom error responses."""
logging.exception(exception)
response.write('Oops! This is a 500 error. ')
response.write('This program can only process numbers. ')
response.write('Please use the back arrow and try again.')
response.set_status(500)
APP.error... | handle_500 | identifier_name |
main.py | #!/usr/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Greg Aitkenhead
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... |
# Also, find the next usable number lower than beads.
lower_list = pass_list
low_bead = int(bead_input)
# Make sure number of beads is >12 to avoid low numbers.
while len(lower_list) == 0 and low_bead > 12:
# Check to... | high_bead = str(high_bead)
higher_list = ", ".join(repr(e) for e in
sorted(higher_list)) | conditional_block |
clustering4.py | #!/usr/bin/python
# script find clusters of small RNA reads in the genome
# version 3 - 24-12-2013 evolution to multiprocessing
# Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size>
#... | return "%s\t%s\t%s\t%s" % (location[0], location[1], location[2], readcount)
cluster_size = downstream_coord - upstream_coord + 1
if folding == "yes" and cluster_size < 151:
foldEnergy = Instance.foldEnergy(upstream_coord=upstream_coord, downstream_coord=downstream_coord) ## be careful, test... | location = [Instance.gene.split()[0], upstream_coord, downstream_coord]
if output_format == "intervals": | random_line_split |
clustering4.py | #!/usr/bin/python
# script find clusters of small RNA reads in the genome
# version 3 - 24-12-2013 evolution to multiprocessing
# Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size>
#... |
if __name__ == '__main__':
start_time = time.time()
fasta_dic = get_fasta (sys.argv[3])
objDic = {}
number_of_reads = 0
F = open (sys.argv[1], "r") # F is the bowtie output taken as input
for line in F:
number_of_reads += 1
fields = line.split()
polarity = fields[1]
gene = fields[2]
... | global number_of_clusters
if results:
number_of_clusters += len(results)
LOG.append(results)
return | identifier_body |
clustering4.py | #!/usr/bin/python
# script find clusters of small RNA reads in the genome
# version 3 - 24-12-2013 evolution to multiprocessing
# Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size>
#... | (results):
global number_of_clusters
if results:
number_of_clusters += len(results)
LOG.append(results)
return
if __name__ == '__main__':
start_time = time.time()
fasta_dic = get_fasta (sys.argv[3])
objDic = {}
number_of_reads = 0
F = open (sys.argv[1], "r") # F is the bowtie output taken as... | logtask | identifier_name |
clustering4.py | #!/usr/bin/python
# script find clusters of small RNA reads in the genome
# version 3 - 24-12-2013 evolution to multiprocessing
# Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size>
#... |
else:
print >> OUT, "#ID\t#chrom\tStart\tEnd\tLength\tReadCount\tForwardReads\tReverseReads\tDensity\tMedian\tFoldEnergy\tForBar\tRevBar\tz-score_signature\tHannon_signature\tUfreq_in_24-28RNAs\tUfreq_in_20-21RNs"
dist = int(sys.argv[4])
min_median_size = int(sys.argv[6])
minimum_reads = int(sys.argv[5])
... | print >> OUT, "##gff-version 3" | conditional_block |
bundle_edges.py | ()) * (v1.x() - v0.x())) / (length**2)
return QgsPoint(v0.x() + r * (v1.x() - v0.x()), v0.y() + r * (v1.y() - v0.y()))
# ------------------------------------ EDGE-CLUSTER ------------------------------------ #
class EdgeCluster():
def __init__(self, edges):
self.S = initial_step_size # Wei... |
# For each cycle
for c in range(cycles):
print 'Cycle {0}'.format(c)
# New number of subdivision points
current_num = self.EP
currentindeces = []
for i in range(current_num):
idx = int((float(i) / float(current_num - ... | vertices = edge.geometry().asPolyline()
self.epm_x[e_idx, 0] = vertices[0].x()
self.epm_y[e_idx, 0] = vertices[0].y()
self.epm_x[e_idx, self.N-1] = vertices[1].x()
self.epm_y[e_idx, self.N-1] = vertices[1].y() | conditional_block |
bundle_edges.py |
# ------------------------------------ EDGE-CLUSTER ------------------------------------ #
class EdgeCluster():
def __init__(self, edges):
self.S = initial_step_size # Weighting factor (needs to be cached, because will be decreased in every cycle)
self.I = iterations # Number of i... | """ Projects point onto line, needed for compatibility computation """
v0 = line.vertexAt(0)
v1 = line.vertexAt(1)
length = max(line.length(), 10**(-6))
r = ((v0.y() - pt.y()) * (v0.y() - v1.y()) -
(v0.x() - pt.x()) * (v1.x() - v0.x())) / (length**2)
return QgsPoint... | identifier_body | |
bundle_edges.py | * (v1.x() - v0.x())) / (length**2)
return QgsPoint(v0.x() + r * (v1.x() - v0.x()), v0.y() + r * (v1.y() - v0.y()))
# ------------------------------------ EDGE-CLUSTER ------------------------------------ #
class EdgeCluster():
def __init__(self, edges):
self.S = initial_step_size # Weight... | for e_idx, edge in enumerate(self.edges):
geom = edge.geometry()
edges_as_geom.append(geom)
edges_as_vect.append(QgsVector(geom.vertexAt(1).x() - geom.vertexAt(0).x(),
geom.vertexAt(1).y() - geom.vertexAt(0).y()))
self.e... | edges_as_geom = []
edges_as_vect = [] | random_line_split |
bundle_edges.py | * (v1.x() - v0.x())) / (length**2)
return QgsPoint(v0.x() + r * (v1.x() - v0.x()), v0.y() + r * (v1.y() - v0.y()))
# ------------------------------------ EDGE-CLUSTER ------------------------------------ #
class EdgeCluster():
def __init__(self, edges):
self.S = initial_step_size # Weight... | (self):
"""
Compatibility is stored in a matrix (rows = edges, columns = edges).
Every coordinate in the matrix tells whether the two edges (r,c)/(c,r)
are compatible, or not. The diagonal is always zero, and the other fields
are filled with either -1 (not compatible) or 1 (co... | compute_compatibilty_matrix | identifier_name |
setup.py | #!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... |
def generate_cython():
cwd = os.path.abspath(os.path.dirname(__file__))
print("Cythonizing sources")
p = subprocess.call([sys.executable,
os.path.join(cwd, 'tools', 'cythonize.py'),
'scipy'],
cwd=cwd)
if p != 0:
raise... | ret = subprocess.call([sys.executable, sys.argv[0], 'build_ext', '-i'])
if ret != 0:
raise RuntimeError("Building Scipy failed!")
BuildDoc.run(self) | identifier_body |
setup.py | #!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... |
return FULLVERSION, GIT_REVISION
def write_version_py(filename='scipy/version.py'):
cnt = """
# THIS FILE IS GENERATED FROM SCIPY SETUP.PY
short_version = '%(version)s'
version = '%(version)s'
full_version = '%(full_version)s'
git_revision = '%(git_revision)s'
release = %(isrelease)s
if not release:
ve... | FULLVERSION += '.dev-' + GIT_REVISION[:7] | conditional_block |
setup.py | #!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... | Programming Language :: C
Programming Language :: Python
Programming Language :: Python :: 3
Topic :: Software Development
Topic :: Scientific/Engineering
Operating System :: Microsoft :: Windows
Operating System :: POSIX
Operating System :: Unix
Operating System :: MacOS
"""
MAJOR = 0
MINOR ... | License :: OSI Approved | random_line_split |
setup.py | #!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... | (cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
... | _minimal_ext_cmd | identifier_name |
cell.js | /**
* Created by Dzianis on 25/08/2016.
*/
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
class Cell extends Component {
static propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
ball: PropTypes.any,
onClick: PropTypes.func.isReq... |
}
return <div className={css}
onClick={() => this.props.onClick(this.props.x, this.props.y)}
style={color}></div>
}
}
export default connect(Cell.mapStateToProps, null)(Cell);
| {
css += "m5-active-ball";
} | conditional_block |
cell.js | /**
* Created by Dzianis on 25/08/2016.
*/
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
class Cell extends Component {
static propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
ball: PropTypes.any,
onClick: PropTypes.func.isReq... | () {
let css = "m5-cell-content ";
let color = {};
if (this.props.ball) {
css += "m5-ball ";
color = {
backgroundColor: this.props.ball.color,
};
if(this.props.activeBall &&
this.props.activeBall.x === this.props.x &&
this.props.activeBall.y === this.pr... | render | identifier_name |
cell.js | /**
* Created by Dzianis on 25/08/2016.
*/
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
class Cell extends Component {
static propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
ball: PropTypes.any,
onClick: PropTypes.func.isReq... | };
if(this.props.activeBall &&
this.props.activeBall.x === this.props.x &&
this.props.activeBall.y === this.props.y) {
css += "m5-active-ball";
}
}
return <div className={css}
onClick={() => this.props.onClick(this.props.x, this.props.y)}
... | random_line_split | |
test_import_wallet.py | import pytest
from indy import IndyError
from indy import did
from indy import wallet
from indy.error import ErrorCode
@pytest.mark.asyncio
@pytest.mark.parametrize("wallet_handle_cleanup", [False])
async def test_import_wallet_works(wallet_handle, wallet_config, credentials, export_config):
|
@pytest.mark.asyncio
async def test_import_wallet_works_for_not_exit_path(wallet_config, credentials, export_config):
with pytest.raises(IndyError) as e:
await wallet.import_wallet(wallet_config, credentials, export_config)
assert ErrorCode.CommonIOError == e.value.error_code
| (_did, _verkey) = await did.create_and_store_my_did(wallet_handle, "{}")
await did.set_did_metadata(wallet_handle, _did, "metadata")
did_with_meta_before = await did.get_my_did_with_meta(wallet_handle, _did)
await wallet.export_wallet(wallet_handle, export_config)
await wallet.close_wallet(wallet_han... | identifier_body |
test_import_wallet.py | import pytest
from indy import IndyError
from indy import did
from indy import wallet
from indy.error import ErrorCode
@pytest.mark.asyncio
@pytest.mark.parametrize("wallet_handle_cleanup", [False])
async def | (wallet_handle, wallet_config, credentials, export_config):
(_did, _verkey) = await did.create_and_store_my_did(wallet_handle, "{}")
await did.set_did_metadata(wallet_handle, _did, "metadata")
did_with_meta_before = await did.get_my_did_with_meta(wallet_handle, _did)
await wallet.export_wallet(wallet_... | test_import_wallet_works | identifier_name |
test_import_wallet.py | import pytest
from indy import IndyError
from indy import did
from indy import wallet
from indy.error import ErrorCode
@pytest.mark.asyncio
@pytest.mark.parametrize("wallet_handle_cleanup", [False])
async def test_import_wallet_works(wallet_handle, wallet_config, credentials, export_config):
(_did, _verkey) = aw... | with pytest.raises(IndyError) as e:
await wallet.import_wallet(wallet_config, credentials, export_config)
assert ErrorCode.CommonIOError == e.value.error_code | @pytest.mark.asyncio
async def test_import_wallet_works_for_not_exit_path(wallet_config, credentials, export_config): | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.