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 |
|---|---|---|---|---|
model.py | import codecs
import os
import re
import json
from . import WIKI_DIR
from collections import defaultdict
def _get_filename(slug):
return os.path.join(WIKI_DIR, '%s.md' % (slug,))
class Index(object):
def __init__(self):
self.texts, self.words = {}, set()
self.finvindex = defaultdict(set)
... |
if len(wordsinphrase) < 2:
firstword, otherwords = wordsinphrase[0], wordsinphrase[1:]
else:
firstword, otherwords = wordsinphrase[0], []
found = []
for txt in self.term_search(wordsinphrase):
for firstindx in (indx for t,indx in self.finvindex[fir... | return set() | conditional_block |
model.py | import codecs
import os
import re
import json
from . import WIKI_DIR
from collections import defaultdict
def _get_filename(slug):
return os.path.join(WIKI_DIR, '%s.md' % (slug,))
class Index(object):
def __init__(self):
self.texts, self.words = {}, set()
self.finvindex = defaultdict(set)
... | body = []
header = False
for line in data.split('\n'):
if line == '<!---':
header = True
elif line == '--->':
header = False
elif header:
(k, v) = [v.strip() for v in line.split('=')]
tmp[k] = v
... | return re.sub(r'[\.!,;/\?#\ ]+', '-', title).strip().lower()
@staticmethod
def build(data, title=None):
tmp = {} | random_line_split |
model.py | import codecs
import os
import re
import json
from . import WIKI_DIR
from collections import defaultdict
def _get_filename(slug):
return os.path.join(WIKI_DIR, '%s.md' % (slug,))
class Index(object):
def __init__(self):
self.texts, self.words = {}, set()
self.finvindex = defaultdict(set)
... | (self, doc_id):
for k, v in self.finvindex.items():
to_delete = []
for w in v:
if w[0] == doc_id:
to_delete.append(w)
for t in to_delete:
v.remove(t)
def term_search(self, terms):
if not set(terms).issubset(set... | remove | identifier_name |
model.py | import codecs
import os
import re
import json
from . import WIKI_DIR
from collections import defaultdict
def _get_filename(slug):
return os.path.join(WIKI_DIR, '%s.md' % (slug,))
class Index(object):
def __init__(self):
self.texts, self.words = {}, set()
self.finvindex = defaultdict(set)
... |
def serialize(self):
buf = ['<!---']
for k, v in self.__dict__.items():
if k not in ['body', 'slug', 'tags']:
buf.append('='.join((str(k), str(v))))
elif k == 'tags':
buf.append('%s=%s' % (k, ','.join(self.tags)))
buf.append('--->')
... | if not other:
return -1
return (int(self.created > other.created) or -1) if self.created != other.created else 0 | identifier_body |
misc.py | # Copyright (c) 2016, Genevolv LLC. All rights reserved.
''' A module for miscellaneous utility functions.'''
import logging
LOG = logging.getLogger(__name__)
# LOG.setLevel(logging.INFO)
import decimal
import re
import string
import sys
import os
#-------------------
# Type translations
#-------------------
def ... | for key, val in dct.items():
LOG.log(lvl, str(key) + " : " + str(val))
LOG.log(lvl, '---')
def union_dict(mutate, access):
''' Mutates the first dict by adding the second. For now, it
raises an exception if multiple values exist in both dicts,
but this could be extended to handle a... | # Dict
#------
def log_dict(dct, lvl=logging.DEBUG):
'''pretty print a dict to the logger'''
LOG.log(lvl, '---') | random_line_split |
misc.py |
# Copyright (c) 2016, Genevolv LLC. All rights reserved.
''' A module for miscellaneous utility functions.'''
import logging
LOG = logging.getLogger(__name__)
# LOG.setLevel(logging.INFO)
import decimal
import re
import string
import sys
import os
#-------------------
# Type translations
#-------------------
def... |
if not increase_precision:
if sign < 0:
digits.append('-')
digits.reverse()
rtn = ''.join(digits)
test = int(rtn, base)
# LOG.debug('rtn: ' + rtn)
# LOG.debug('num: ' + hex(num))
# LOG.debug('tst: ' + hex(test))... | try:
dig = base_chars[int(reduct % base)]
except decimal.InvalidOperation:
increase_precision = True
break
# LOG.debug('dig: ' + str(dig))
digits.append(dig)
reduct /= base
# LOG.debug('reduct: ' + str(reduct)) | conditional_block |
misc.py |
# Copyright (c) 2016, Genevolv LLC. All rights reserved.
''' A module for miscellaneous utility functions.'''
import logging
LOG = logging.getLogger(__name__)
# LOG.setLevel(logging.INFO)
import decimal
import re
import string
import sys
import os
#-------------------
# Type translations
#-------------------
def... | (haystack, needle, num):
''' Find the starting index of the nth occurrance of a string. '''
start = haystack.find(needle)
while start >= 0 and num > 1:
start = haystack.find(needle, start+len(needle))
num -= 1
return start
#------
# List
#------
def log_list(lst, lvl=logging.DEBUG):
... | find_nth | identifier_name |
misc.py |
# Copyright (c) 2016, Genevolv LLC. All rights reserved.
''' A module for miscellaneous utility functions.'''
import logging
LOG = logging.getLogger(__name__)
# LOG.setLevel(logging.INFO)
import decimal
import re
import string
import sys
import os
#-------------------
# Type translations
#-------------------
def... |
def union_dict(mutate, access):
''' Mutates the first dict by adding the second. For now, it
raises an exception if multiple values exist in both dicts,
but this could be extended to handle adding associations.
'''
check_set = set(mutate.keys()) & set(access.keys())
if len(check_set) ... | '''pretty print a dict to the logger'''
LOG.log(lvl, '---')
for key, val in dct.items():
LOG.log(lvl, str(key) + " : " + str(val))
LOG.log(lvl, '---') | identifier_body |
tag.py | """Tag / Tags Object"""
# standard library
import json
from typing import Optional, Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.tags.tag_filter import T... |
# validate parent an id is available
self._validate_id(parent_unique_id, url)
self._request(
method=method,
url=url,
body=body,
headers={'content-type': 'application/json'},
params=params,
)
return self.request
| """Remove a nested object."""
method = 'PUT'
unique_id = self._calculate_unique_id()
# validate an id is available
self._validate_id(unique_id.get('value'), '')
body = json.dumps(
{
self._nested_field_name: {
'data': [{unique_id.g... | identifier_body |
tag.py | """Tag / Tags Object"""
# standard library
import json
from typing import Optional, Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.tags.tag_filter import T... | # get the unique id value for id, xid, summary, etc ...
parent_api_endpoint = self._parent_data.get('api_endpoint')
parent_unique_id = self._parent_data.get('unique_id')
url = f'{parent_api_endpoint}/{parent_unique_id}'
# validate parent an id is available
self._validate... | }
)
| random_line_split |
tag.py | """Tag / Tags Object"""
# standard library
import json
from typing import Optional, Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.tags.tag_filter import T... |
elif isinstance(data, dict):
# provided data is raw response, load the model
self._model = type(self.model)(**data)
else:
raise RuntimeError(f'Invalid data type: {type(data)} provided.')
def remove(self, params: Optional[dict] = None) -> None:
"""Remove ... | self._model = data | conditional_block |
tag.py | """Tag / Tags Object"""
# standard library
import json
from typing import Optional, Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.tags.tag_filter import T... | (self, **kwargs) -> None:
"""Initialize class properties."""
super().__init__(kwargs.pop('session', None))
# properties
self._model = TagModel(**kwargs)
self._nested_field_name = 'tags'
self._nested_filter = 'has_tag'
self.type_ = 'Tag'
@property
def _ap... | __init__ | identifier_name |
test_views.py | # -*- coding: utf-8 -*-
#
# This file is part of the VecNet OpenMalaria Portal.
# For copyright and licensing information about this package, see the | # This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 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/.
from django.test.testcases import TestCase
from django.urls.base import reverse
class Http500Test(TestCase)... | # NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/om
# | random_line_split |
test_views.py | # -*- coding: utf-8 -*-
#
# This file is part of the VecNet OpenMalaria Portal.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/om
#
# This Source Code Form is subject to the terms of t... | (self):
response = self.client.get(reverse("index"))
self.assertEqual(response.status_code, 200)
| test | identifier_name |
test_views.py | # -*- coding: utf-8 -*-
#
# This file is part of the VecNet OpenMalaria Portal.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/om
#
# This Source Code Form is subject to the terms of t... | def test(self):
response = self.client.get(reverse("index"))
self.assertEqual(response.status_code, 200) | identifier_body | |
Global.ts | //OptionScene全局相关///////////////////////////////////////////////////////////////////
let isPlaySoundEffect: boolean = true;
let bulletCountMin: number = 500;
let bulletCountIncremental: number = 100;
let bulletCountTimesOfIncremental: number = 5;
let bulletCountMax: number = bulletCountMin + bulletCountIncremental ... | 相交是一样的,只是用u判断交点是否在线段上
//根据摇杆特点简化算法,令P1=P3,此时相交的5种情况只存在2、3两种可能性,优化算法,代码如下:
function clacJokstickPosition(cx: number, cy: number, r: number, touchX: number, touchY: number): cc.Vec2 {
let distanceX = touchX - cx;
let distanceY = touchY - cy;
let A = distanceX * distanceX + distanceY * distanceY;
//let B ... | 推导,基本思路跟直线和圆 | identifier_name |
Global.ts | //OptionScene全局相关///////////////////////////////////////////////////////////////////
let isPlaySoundEffect: boolean = true;
let bulletCountMin: number = 500;
let bulletCountIncremental: number = 100;
let bulletCountTimesOfIncremental: number = 5;
let bulletCountMax: number = bulletCountMin + bulletCountIncremental ... | getRandomInt: getRandomInt,
getRandomArbitrary: getRandomArbitrary,
clacJokstickPosition: clacJokstickPosition,
},
}
| dBulletCount,
getBulletCount: getBulletCount,
},
data: {
gameTime: gameTime,
},
table: {
appraise: appraise,
},
EventType: EventType,
math: {
| conditional_block |
Global.ts | //OptionScene全局相关///////////////////////////////////////////////////////////////////
let isPlaySoundEffect: boolean = true;
let bulletCountMin: number = 500;
let bulletCountIncremental: number = 100;
let bulletCountTimesOfIncremental: number = 5;
let bulletCountMax: number = bulletCountMin + bulletCountIncremental ... |
let EventType = {
BulletOffScreen: "子弹离开屏幕",
BulletHitPlane: "子弹命中飞机",
PlaneExplosionFinished: "飞机爆炸结束",
PlusTimeHitPlane: "加时间道具命中飞机",
};
//数学///////////////////////////////////////////////////////////////////
function getRandomInt(min: number, max: number): number {
return Math.floor(Math.random... |
//事件/////////////////////////////////////////////////////////////////// | random_line_split |
Global.ts | //OptionScene全局相关///////////////////////////////////////////////////////////////////
let isPlaySoundEffect: boolean = true;
let bulletCountMin: number = 500;
let bulletCountIncremental: number = 100;
let bulletCountTimesOfIncremental: number = 5;
let bulletCountMax: number = bulletCountMin + bulletCountIncremental ... | on addBulletCount() {
bulletCount += bulletCountIncremental;
if (bulletCount > bulletCountMax) {
bulletCount = bulletCountMin;
}
}
function getBulletCount(): number {
return bulletCount;
}
//GameScene全局相关///////////////////////////////////////////////////////////////////
let gameTime: number =... | turn isPlaySoundEffect;
}
functi | identifier_body |
optionsFactory.ts | import { IFilterOptionDef } from '../../interfaces/iFilter';
import { IScalarFilterParams } from './scalarFilter';
import { ISimpleFilterParams } from './simpleFilter';
import { every } from '../../utils/array';
/* Common logic for options, used by both filters and floating filters. */
export class OptionsFactory {
... |
const requiredProperties: (keyof IFilterOptionDef)[] = ['displayKey', 'displayName', 'test'];
if (every(requiredProperties, key => {
if (!filterOption[key]) {
console.warn(`ag-Grid: ignoring FilterOptionDef as it doesn't contain a '${key}'`);
... | { return; } | conditional_block |
optionsFactory.ts | import { IFilterOptionDef } from '../../interfaces/iFilter';
import { IScalarFilterParams } from './scalarFilter';
import { ISimpleFilterParams } from './simpleFilter';
import { every } from '../../utils/array';
/* Common logic for options, used by both filters and floating filters. */
export class OptionsFactory {
... | (params: ISimpleFilterParams): void {
if (params.defaultOption) {
this.defaultOption = params.defaultOption;
} else if (this.filterOptions.length >= 1) {
const firstFilterOption = this.filterOptions[0];
if (typeof firstFilterOption === 'string') {
thi... | selectDefaultItem | identifier_name |
optionsFactory.ts | import { IFilterOptionDef } from '../../interfaces/iFilter';
import { IScalarFilterParams } from './scalarFilter';
import { ISimpleFilterParams } from './simpleFilter';
import { every } from '../../utils/array';
/* Common logic for options, used by both filters and floating filters. */
export class OptionsFactory {
... |
private selectDefaultItem(params: ISimpleFilterParams): void {
if (params.defaultOption) {
this.defaultOption = params.defaultOption;
} else if (this.filterOptions.length >= 1) {
const firstFilterOption = this.filterOptions[0];
if (typeof firstFilterOption === ... | {
if (!this.filterOptions) { return; }
this.filterOptions.forEach(filterOption => {
if (typeof filterOption === 'string') { return; }
const requiredProperties: (keyof IFilterOptionDef)[] = ['displayKey', 'displayName', 'test'];
if (every(requiredProperties, key => ... | identifier_body |
optionsFactory.ts | import { IFilterOptionDef } from '../../interfaces/iFilter';
import { IScalarFilterParams } from './scalarFilter';
import { ISimpleFilterParams } from './simpleFilter';
import { every } from '../../utils/array';
/* Common logic for options, used by both filters and floating filters. */
export class OptionsFactory {
... | } | random_line_split | |
javax.sql.rowset.serial.SerialClob.d.ts | declare namespace javax {
namespace sql {
namespace rowset {
namespace serial {
class SerialClob implements java.sql.Clob, java.io.Serializable, java.lang.Cloneable {
static readonly serialVersionUID: long | public getAsciiStream(): java.io.InputStream
public getSubString(arg0: number | java.lang.Long, arg1: number | java.lang.Integer): java.lang.String
public position(arg0: java.lang.String | string, arg1: number | java.lang.Long): number
public position(arg0: java.sql.Clob, arg1: n... | public constructor(arg0: string[] | java.lang.Character[])
public constructor(arg0: java.sql.Clob)
public length(): number
public getCharacterStream(): java.io.Reader | random_line_split |
javax.sql.rowset.serial.SerialClob.d.ts | declare namespace javax {
namespace sql {
namespace rowset {
namespace serial {
class | implements java.sql.Clob, java.io.Serializable, java.lang.Cloneable {
static readonly serialVersionUID: long
public constructor(arg0: string[] | java.lang.Character[])
public constructor(arg0: java.sql.Clob)
public length(): number
public getCharacterStream(): java.io.... | SerialClob | identifier_name |
views.py | # -*- coding:utf-8 -*-
from django.shortcuts import render
import models
# Create your views here.
class Pager(object):
def __init__(self,current_page):
self.current_page = current_page
@property
def start(self):
return (self.current_page-1)*10
@property
def end(self):
r... | # # page_str += temp
if all_page<=11:
start =1
end = all_page+1
else:
if self.current_page<=6:
start = 1
end =12
else:
start = self.current_page-5
end = self.current_page+6
... | # # else:
# # temp = '<a href="/user_list/?page=%d"> %d </a>' % (i,i) | random_line_split |
views.py | # -*- coding:utf-8 -*-
from django.shortcuts import render
import models
# Create your views here.
class Pager(object):
def __init__(self,current_page):
self.current_page = current_page
@property
def start(self):
return (self.current_page-1)*10
@property
def end(self):
|
def page_str(self,all_item,base_url):
all_page, div = divmod(all_item,10)
if div>0:
all_page += 1
page_list=[]
# # start = self.current_page-5
# # end = self.current_page+6
# #
# # page_str = ""
# # for i in range(start,end):
# #... | return self.current_page*10 | identifier_body |
views.py | # -*- coding:utf-8 -*-
from django.shortcuts import render
import models
# Create your views here.
class Pager(object):
def __init__(self,current_page):
self.current_page = current_page
@property
def start(self):
return (self.current_page-1)*10
@property
def end(self):
r... | next_page = '<a href="%s%d"> 下一页 </a>' % (base_url,self.current_page+1)
page_list.insert(0,pre_page)
page_list.append(next_page)
return "".join(page_list)
def user_list(request):
# for item in range(100):
# models.user_list.objects.create(username="user%d" % item ,ag... | '<a href="javascript:void(0)"> 下一页 </a>'
else:
| conditional_block |
views.py | # -*- coding:utf-8 -*-
from django.shortcuts import render
import models
# Create your views here.
class Pager(object):
def __init__(self,current_page):
self.current_page = current_page
@property
def start(self):
return (self.current_page-1)*10
@property
def end(self):
r... | (self,all_item,base_url):
all_page, div = divmod(all_item,10)
if div>0:
all_page += 1
page_list=[]
# # start = self.current_page-5
# # end = self.current_page+6
# #
# # page_str = ""
# # for i in range(start,end):
# # if i == self.... | page_str | identifier_name |
twitter.py | # -*- coding: utf-8 -*-
from flask.ext.rq import job
from tweepy import OAuthHandler, API
import bitlyapi
import urllib2
import json
import re
from hasjob import app
@job('hasjob')
def tweet(title, url, location=None, parsed_location=None, username=None):
auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], a... |
if not locationtag and location:
# Make a hashtag from the first word in the location. This catches
# locations like 'Anywhere' which have no geonameid but are still valid
locationtag = u'#' + re.split('\W+', location)[0]
maxlength -= len(locationtag) + 1
if len(title) > maxlen... | maxlength -= len(locationtag) + 1 | conditional_block |
twitter.py | # -*- coding: utf-8 -*-
from flask.ext.rq import job
from tweepy import OAuthHandler, API
import bitlyapi
import urllib2
import json
import re
from hasjob import app
@job('hasjob')
def tweet(title, url, location=None, parsed_location=None, username=None):
| # locations like 'Anywhere' which have no geonameid but are still valid
locationtag = u'#' + re.split('\W+', location)[0]
maxlength -= len(locationtag) + 1
if len(title) > maxlength:
text = title[:maxlength - 1] + u'…'
else:
text = title[:maxlength]
text = text + ' '... | auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(app.config['TWITTER_ACCESS_KEY'], app.config['TWITTER_ACCESS_SECRET'])
api = API(auth)
urllength = 23 # Current Twitter standard for HTTPS (as of Oct 2014)
maxlength = 140 - urllength - ... | identifier_body |
twitter.py | # -*- coding: utf-8 -*-
from flask.ext.rq import job
from tweepy import OAuthHandler, API
import bitlyapi
import urllib2
import json
import re
from hasjob import app
@job('hasjob')
def tweet(title, url, location=None, parsed_location=None, username=None):
auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], a... | if locationtag:
text = text + ' ' + locationtag
if username:
text = text + ' @' + username
api.update_status(text)
def shorten(url):
if app.config['BITLY_KEY']:
b = bitlyapi.BitLy(app.config['BITLY_USER'], app.config['BITLY_KEY'])
res = b.shorten(longUrl=url)
re... | else:
text = title[:maxlength]
text = text + ' ' + url # Don't shorten URLs, now that there's t.co | random_line_split |
twitter.py | # -*- coding: utf-8 -*-
from flask.ext.rq import job
from tweepy import OAuthHandler, API
import bitlyapi
import urllib2
import json
import re
from hasjob import app
@job('hasjob')
def | (title, url, location=None, parsed_location=None, username=None):
auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(app.config['TWITTER_ACCESS_KEY'], app.config['TWITTER_ACCESS_SECRET'])
api = API(auth)
urllength = 23 # Current Twitter ... | tweet | identifier_name |
managers.py | import re
import random
import hashlib
from django.db import models
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generati... | activation_key = hashlib.sha1(salt+username).hexdigest()
return self.create(user=user, activation_key=activation_key) | username = username.encode('utf-8')
| random_line_split |
managers.py | import re
import random
import hashlib
from django.db import models
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generati... |
activation_key = hashlib.sha1(salt+username).hexdigest()
return self.create(user=user, activation_key=activation_key)
| username = username.encode('utf-8') | conditional_block |
managers.py | import re
import random
import hashlib
from django.db import models
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class | (models.Manager):
"""Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generation and emailing of activation
keys), and for cleaning out expired inactive accounts.
"""
def activate_user(self, activatio... | RegistrationManager | identifier_name |
managers.py | import re
import random
import hashlib
from django.db import models
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generati... | """Create a ``RegistrationProfile`` for a given ``User``, and return
the ``RegistrationProfile``.
The activation key for the ``RegistrationProfile`` will be a SHA1 hash,
generated from a combination of the ``User``'s username and a random
salt.
"""
salt = hashlib.sha1(st... | identifier_body | |
recurrence_analysis_speleo_raw.py | arshim", "Qunf", "Hoti", "Mawmluh", "Tianmen", "Dongge",
"Lianhua", "Heshang", "Jiuxian", "Liang-Luar"]
# Specify symbol used for commenting in data file
COMMENT_SYMBOL = "%"
# Settings for the time dependent recurrence plot
# Window length [a] / [ka]
T_TIME = [750., 750., 750., 750., 750., 750., 750., ... |
# Update progress bar every step
progress.update(int(100 * j / float(t_steps)))
# Terminate progress bar
progress.finish()
# Store window mid-point
step_sequence.append(local_step_sequence)
# Store results
for measure in symbols.keys():
results[measure].append(loc... | #local_result["Autocorrelation"][j] = autocorrelation(time_series, lag=1)
#local_result["Mean"][j] = time_series.mean()
#local_result["Standard deviation"][j] = time_series.std() | random_line_split |
recurrence_analysis_speleo_raw.py | arshim", "Qunf", "Hoti", "Mawmluh", "Tianmen", "Dongge",
"Lianhua", "Heshang", "Jiuxian", "Liang-Luar"]
# Specify symbol used for commenting in data file
COMMENT_SYMBOL = "%"
# Settings for the time dependent recurrence plot
# Window length [a] / [ka]
T_TIME = [750., 750., 750., 750., 750., 750., 750., ... | (data, lag):
"""Return autocorrelation of data at specified lag."""
return np.corrcoef(data[lag:], data[:-lag])[0,1]
#
# The main script
#
print "Recurrence network analysis of paleoclimate records"
print "---------------------------------------------------"
#
# Import data
#
time_list = []
data_list = []... | autocorrelation | identifier_name |
recurrence_analysis_speleo_raw.py | Dimarshim", "Qunf", "Hoti", "Mawmluh", "Tianmen", "Dongge",
"Lianhua", "Heshang", "Jiuxian", "Liang-Luar"]
# Specify symbol used for commenting in data file
COMMENT_SYMBOL = "%"
# Settings for the time dependent recurrence plot
# Window length [a] / [ka]
T_TIME = [750., 750., 750., 750., 750., 750., 750... |
detrended_data[j] = data[j] - data[j - half_size:j + half_size + 1].mean()
return detrended_data
def autocorrelation(data, lag):
"""Return autocorrelation of data at specified lag."""
return np.corrcoef(data[lag:], data[:-lag])[0,1]
#
# The main script
#
print "Recurrence network analysis of ... | half_size = window_size / 2 | conditional_block |
recurrence_analysis_speleo_raw.py | Dimarshim", "Qunf", "Hoti", "Mawmluh", "Tianmen", "Dongge",
"Lianhua", "Heshang", "Jiuxian", "Liang-Luar"]
# Specify symbol used for commenting in data file
COMMENT_SYMBOL = "%"
# Settings for the time dependent recurrence plot
# Window length [a] / [ka]
T_TIME = [750., 750., 750., 750., 750., 750., 750... |
def autocorrelation(data, lag):
"""Return autocorrelation of data at specified lag."""
return np.corrcoef(data[lag:], data[:-lag])[0,1]
#
# The main script
#
print "Recurrence network analysis of paleoclimate records"
print "---------------------------------------------------"
#
# Import data
#
time_lis... | """
"""
# Get length of data array
n = data.shape[0]
# Initialize a local copy of data array
detrended_data = np.empty(n)
# Detrend data
for j in xrange(n):
# Get distance of sample from boundaries of time series
dist = min(j, n - 1 - j)
if window_size / 2 > dis... | identifier_body |
imdb.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | words, _ = list(zip(*dictionary))
word_idx = dict(list(zip(words, six.moves.range(len(words)))))
word_idx['<unk>'] = len(words)
return word_idx
def reader_creator(pos_pattern, neg_pattern, word_idx):
UNK = word_idx['<unk>']
INS = []
def load(pattern, out, label):
for doc in tokeni... | random_line_split | |
imdb.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
return reader
def train(word_idx):
"""
IMDB training set creator.
It returns a reader creator, each sample in the reader is an zero-based ID
sequence and label in [0, 1].
:param word_idx: word dictionary
:type word_idx: dict
:return: Training reader creator
:rtype: callable
... | yield doc, label | conditional_block |
imdb.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
def build_dict(pattern, cutoff):
"""
Build a word dictionary from the corpus. Keys of the dictionary are words,
and values are zero-based IDs of these words.
"""
word_freq = collections.defaultdict(int)
for doc in tokenize(pattern):
for word in doc:
word_freq[word] += 1
... | """
Read files that match the given pattern. Tokenize and yield each file.
"""
with tarfile.open(paddle.dataset.common.download(URL, 'imdb', MD5)) as tarf:
# Note that we should use tarfile.next(), which does
# sequential access of member files, other than
# tarfile.extractfile, wh... | identifier_body |
imdb.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | ():
for doc, label in INS:
yield doc, label
return reader
def train(word_idx):
"""
IMDB training set creator.
It returns a reader creator, each sample in the reader is an zero-based ID
sequence and label in [0, 1].
:param word_idx: word dictionary
:type word_idx: dic... | reader | identifier_name |
webpack.dev.js | const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
* Webpack Plugins
*/
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
cons... | 'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
}
}),
new AddAssetHtmlPlugin([
{ filepath: helpers.root('src/assets/js', 'jquery-3.1.0.min.js'), includeSourcemap: false },
{ fi... | 'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR, | random_line_split |
autobahn-tests.ts | import autobahn = require("autobahn");
class MyClass {
add2Count: number = 0;
session: autobahn.Session;
constructor(session: autobahn.Session) {
this.session = session;
}
add2(args: Array<number>): number {
this.add2Count++;
return args[0] + args[1];
}
onEvent(ar... | (message: any[]) {},
close(errorCode: number, reason?: string) {},
info: {type: 'custom'}
};
}
type: autobahn.TransportType = 'custom'
}
| send | identifier_name |
autobahn-tests.ts | import autobahn = require("autobahn");
class MyClass {
add2Count: number = 0;
session: autobahn.Session;
constructor(session: autobahn.Session) {
this.session = session;
}
add2(args: Array<number>): number {
this.add2Count++;
return args[0] + args[1];
}
onEvent(ar... |
var { isConnected, transport: { info: { protocol, type, url } }, defer } = connection;
console.log(isConnected, protocol, type, url, defer);
}
function test_custom_transport_factory() {
autobahn.transports.register('custom', CustomTransportFactory)
var CustomFactoryFactory = autobahn.transports.... | {
connection.open();
} | conditional_block |
autobahn-tests.ts | import autobahn = require("autobahn");
class MyClass {
add2Count: number = 0;
session: autobahn.Session;
constructor(session: autobahn.Session) {
this.session = session;
}
add2(args: Array<number>): number {
this.add2Count++;
return args[0] + args[1];
}
onEvent(ar... | // 1) subscribe to a topic
session.subscribe('com.myapp.hello', myInstance.onEvent);
// 2) publish an event
session.publish('com.myapp.hello', ['Hello, world!']);
// 3) register a procedure for remoting
session.register('com.myapp.add2', myInstance.add2, { invoke: 'roun... | connection.onopen = session => {
var myInstance = new MyClass(session);
| random_line_split |
__init__.py |
process_thread_part = process_thread_part_filler = ""
has_process = hasattr(record, "processName") and record.processName != "MainProcess"
has_thread = hasattr(record, "threadName") and record.threadName != "MainThread"
if has_process:
process_thread_par... | success | identifier_name | |
__init__.py | ')
if hasattr(record, "stack_info") and record.stack_info: # py2 doesn't have .stack_info
if s[-1:] != "\n":
s += "\n"
s = s + record.stack_info # py3: self.formatStack()
record.message = s
return self.colored(record)
# end def
def usesTime(sel... | # end def
# end class
| random_line_split | |
__init__.py | # log level
level = "{level:8}".format(level=record.levelname)
level_filler = "{:{}}".format("", len(level))
# file/function name
filepart = record.name if record.name else ""
filepart += "." + record.funcName if record.funcName != "<module>" else... |
# end for
return "\n".join(lines)
# end def
def __init__(self, date_formatter=None):
super(ColoredFormatter, self).__init__(datefmt=date_formatter)
self.color_instance = self.Color(self)
def colored(self, record):
return self.color_instance.colored(... | if first_line is None: # single line
lines.append(
"{color_on}{inverse_on}{level}{inverse_off}{color_on}{date}{color_off}{file_color_on}{process_thread_part} {file_color_on}{filepart}:{color_off} {color_on}{message}{color_off}{background_off}{all_off}".format(
... | conditional_block |
__init__.py | (
thread=record.processName, **formatter)
# end if
if has_process and has_thread:
process_thread_part += " ".format(**formatter)
# end if
if has_thread:
process_thread_part += "{inverse_on}{file_color_on}{process}{invers... | """
Log 'msg % args' with severity 'SUCCESS'.
To pass exception information, use the keyword argument exc_info with
a true value.
logger.debug("Houston, we landed in the %s", "moon", exc_info=False)
"""
self._success(msg, *args, **kwargs) | identifier_body | |
og-navigator-serviceworker.ts | import type {
ServiceWorkerMock,
WindowMock
} from "mocks/node-modules/angular/types";
import type MockDependenciesProvider from "mocks/loot/mockdependencies";
import type OgNavigatorServiceWorkerService from "og-components/og-navigator-serviceworker/services/og-navigator-serviceworker";
import angular from "angular"... | $window.console.log.should.have.been.calledWith("ServiceWorker registration failed: test error");
});
});
}); | random_line_split | |
commands.py | if len(related) > 1:
print colored('Too many linked issues found, please specify one.', None, attrs=['reverse'])
for issueid in related:
print colored(textwrap.fill('Issue: %s' % issueid,
initial_indent=' ', subsequent_indent=' '), None, attrs=[])
print col... | if issue.get('diff'):
for changeset in issue['diff'][0].iteritems():
print 'Added: %s - %s' % (changeset[0].upper(), changeset[1])
for changeset in issue['diff'][1].iteritems():
print 'Removed: %s' % changeset[0].upper()
for changeset in issue['diff'][2].iteritems():
... | if not args.id:
args.id = guess_issue_id(issuedb)
issuedata = issuedb.issue(id=args.id, detail=args.detail)
if not issuedata or not issuedata[0].get('data'):
print 'No such issue found'
return
issue = issuedata[0]['data']
print '\nIssue: %s' % args.id
if 'title' in issue:
... | identifier_body |
commands.py | if len(related) > 1:
print colored('Too many linked issues found, please specify one.', None, attrs=['reverse'])
for issueid in related:
print colored(textwrap.fill('Issue: %s' % issueid,
initial_indent=' ', subsequent_indent=' '), None, attrs=[])
print col... | def main():
"""Parse the command line options and react to them."""
try:
issuedb = IssueDB(os.getcwd())
except NoRepository:
# This means that there was no repository here.
print 'Unable to find a repository.'
import sys
sys.exit(1)
except NoIssueDB:
# Thi... | random_line_split | |
commands.py | if len(related) > 1:
print colored('Too many linked issues found, please specify one.', None, attrs=['reverse'])
for issueid in related:
print colored(textwrap.fill('Issue: %s' % issueid,
initial_indent=' ', subsequent_indent=' '), None, attrs=[])
print col... | (issuedb, args):
if not args.id:
args.id = guess_issue_id(issuedb)
skeleton = issuedb.skeleton
issue = issuedb.issue(id=args.id, detail=False)[0]['data']
newissue = {}
for field in skeleton:
newissue[field] = getattr(args, field, None) or issue.get(field, skeleton[field])
issuedb... | unpack_edit | identifier_name |
commands.py | if len(related) > 1:
print colored('Too many linked issues found, please specify one.', None, attrs=['reverse'])
for issueid in related:
print colored(textwrap.fill('Issue: %s' % issueid,
initial_indent=' ', subsequent_indent=' '), None, attrs=[])
print col... |
if version.get('diff'):
for changeset in version['diff'][0].iteritems():
print 'Added: %s - %s' % (changeset[0].upper(), changeset[1])
for changeset in version['diff'][1].iteritems():
print 'Removed: %s' % changeset[0].upper()
for changeset in... | print ' %s' % filename | conditional_block |
IteratorAlgebra.py | """
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/492216
Iterator algebra implementations of join algorithms: hash join, merge
join, and nested loops join, as well as a variant I dub "bisect join".
Requires Python 2.4.
Author: Jim Baker, jbaker@zyasoft.com
"""
import operator
from rdflib import py3compat... | S_grouped = advancer(sorted((predicate(s), s) for s in S))
# in the join we need to distinguish rp from rk in the unpack, so
# just use rk, sk
rk, R_matched = next(R_grouped) if py3compat.PY3 else R_grouped.next()
sk, S_matched = next(S_grouped) if py3compat.PY3 else S_grouped.next()
while R_g... | """
For obvious reasons, we depend on the predicate providing a
sortable relation.
Compare this presentation using iterator algebra with the much
more difficult to follow presentation (IMHO) in
http://en.wikipedia.org/wiki/Sort-Merge_Join
"""
from itertools import groupby
def advancer... | identifier_body |
IteratorAlgebra.py | """
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/492216
Iterator algebra implementations of join algorithms: hash join, merge
join, and nested loops join, as well as a variant I dub "bisect join".
Requires Python 2.4.
Author: Jim Baker, jbaker@zyasoft.com
"""
import operator
from rdflib import py3compat... |
R_grouped = advancer(sorted((predicate(r), r) for r in R))
S_grouped = advancer(sorted((predicate(s), s) for s in S))
# in the join we need to distinguish rp from rk in the unpack, so
# just use rk, sk
rk, R_matched = next(R_grouped) if py3compat.PY3 else R_grouped.next()
sk, S_matched = next... | yield k, list(g) | conditional_block |
IteratorAlgebra.py | """
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/492216
Iterator algebra implementations of join algorithms: hash join, merge
join, and nested loops join, as well as a variant I dub "bisect join".
Requires Python 2.4.
Author: Jim Baker, jbaker@zyasoft.com
"""
import operator
from rdflib import py3compat... | (R, S, predicate=identity, join=inner,
combine=operator.concat, theta=operator.eq):
Sp = [(predicate(s), s) for s in S]
for r in R:
rp = predicate(r)
for s in join(s for sp, s in Sp if theta(rp, sp)):
yield combine(r, s)
def bisect_join(R, S, predicate=identit... | nested_loops_join | identifier_name |
IteratorAlgebra.py | """
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/492216
Iterator algebra implementations of join algorithms: hash join, merge
join, and nested loops join, as well as a variant I dub "bisect join".
Requires Python 2.4.
Author: Jim Baker, jbaker@zyasoft.com
"""
import operator
from rdflib import py3compat... | for s in join(consume(Sp, si, rp)):
yield combine(r, s)
def merge_join(R, S, predicate=identity, join=inner, combine=operator.concat):
"""
For obvious reasons, we depend on the predicate providing a
sortable relation.
Compare this presentation using iterator algebra with the much
... | for rp, r in Rp:
si = bisect_left(Sp, (rp,)) | random_line_split |
extractor.py | import json, codecs, re
from abc import ABCMeta, abstractmethod
from PIL import Image, ExifTags
from witica.util import throw, sstr, suni
#regular expressions regarding item ids
RE_METAFILE = r'^meta\/[^\n]+$'
RE_FIRST_ITEMID = r'(?!meta\/)[^\n?@.]+'
RE_ITEMFILE_EXTENSION = r'[^\n?@\/]+'
RE_ITEMID = r'^' + RE_FIRST_... |
@abstractmethod
def extract_metadata(self, filename):
"""Extract metadata from filename and return metadata as json"""
pass
class JSONExtractor(MetadataExtractor):
__metaclass__ = ABCMeta
"""Extracts metadata from item or json file"""
supported_extensions = ["item", "json"];
def __init__(self):
pass
... | pass | identifier_body |
extractor.py | import json, codecs, re
from abc import ABCMeta, abstractmethod
from PIL import Image, ExifTags
from witica.util import throw, sstr, suni
#regular expressions regarding item ids
RE_METAFILE = r'^meta\/[^\n]+$'
RE_FIRST_ITEMID = r'(?!meta\/)[^\n?@.]+'
RE_ITEMFILE_EXTENSION = r'[^\n?@\/]+'
RE_ITEMID = r'^' + RE_FIRST_... | #print("registered: " + extension + " " + sstr(extractor))
def register_default_extractors():
register("item", JSONExtractor)
register("json", JSONExtractor)
register("md", MDExtractor)
register("txt", MDExtractor)
register("jpg", ImageExtractor)
register("jpeg", ImageExtractor)
def is_supported(extension):
f... | raise ValueError("A metadata extractor for extension '" + extension + "' is already registered.")
#TODO: check type of extractor
registered_extractors.append((extension,extractor)) | random_line_split |
extractor.py | import json, codecs, re
from abc import ABCMeta, abstractmethod
from PIL import Image, ExifTags
from witica.util import throw, sstr, suni
#regular expressions regarding item ids
RE_METAFILE = r'^meta\/[^\n]+$'
RE_FIRST_ITEMID = r'(?!meta\/)[^\n?@.]+'
RE_ITEMFILE_EXTENSION = r'[^\n?@\/]+'
RE_ITEMID = r'^' + RE_FIRST_... |
if ("GPSInfo" in exif):
lat, lon = self.get_lat_lon(exif["GPSInfo"])
if lat and lon:
meta["lat"] = lat
meta["lon"] = lon
return meta
except Exception, e:
throw(IOError, "Extracting metadata from file '" + sstr(filename) + "' failed.", e)
# This remaining functions in the ImageExtracot... | meta["flash"] = exif["Flash"] | conditional_block |
extractor.py | import json, codecs, re
from abc import ABCMeta, abstractmethod
from PIL import Image, ExifTags
from witica.util import throw, sstr, suni
#regular expressions regarding item ids
RE_METAFILE = r'^meta\/[^\n]+$'
RE_FIRST_ITEMID = r'(?!meta\/)[^\n?@.]+'
RE_ITEMFILE_EXTENSION = r'[^\n?@\/]+'
RE_ITEMID = r'^' + RE_FIRST_... | (extension):
for (ext,extractor) in registered_extractors:
if extension == ext:
return True
return False
def extract_metadata(filename):
extension = filename.rpartition(".")[2]
for (ext,extractor) in registered_extractors:
if extension == ext:
return extractor().extract_metadata(filename)
raise ValueErr... | is_supported | identifier_name |
CommunityServices.tsx | person to do so.',
},
{
title: 'Community Structure and Design',
options: ['Do not Include', 'Include'],
prices: ['$0', '$2,000 - $3,000'],
initOption: 0,
description:
"We believe the content you publish (and how you want readers to understand and interact with it) should inform the structure an... | const selectedOptionIndex = formDetails[curr];
const isManagingEditor = curr === 'Embedded Managing Editor';
const currentContentProductionSelection =
services[0].options[formDetails['Content Production']];
const options = isManagingEditor
? service.options[currentContentProductionSelection]
: serv... | return prev;
}
| conditional_block |
CommunityServices.tsx | prices: ['$0', '$2,000 - $3,000'],
initOption: 0,
description:
"We believe the content you publish (and how you want readers to understand and interact with it) should inform the structure and design of your community on PubPub. We'll work with you to understand your content—from traditional journal articl... | 'We assign one person from our team to work as your dedicated production point person. This work includes regular calls, communication with authors, and providing general publication strategy as well as insights. Teams who find this service most useful include those that publish on a regular basis but do not have t... | random_line_split | |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
_ => {
span_err!(self.tcx.sess, item.span, E0118,
"no base type found for inherent implementation; \
implement a trait or new type instead");
}
}
... | {
let def_id = ast_util::local_def(item.id);
match item.node {
ast::ItemImpl(_, _, _, None, _, _) => {
// For inherent impls, self type must be a nominal type
// defined in this crate.
debug!("coherence2::orphan check: inherent impl {}", item.r... | identifier_body |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (tcx: &ty::ctxt) {
let mut orphan = OrphanChecker { tcx: tcx };
visit::walk_crate(&mut orphan, tcx.map.krate());
}
struct OrphanChecker<'cx, 'tcx:'cx> {
tcx: &'cx ty::ctxt<'tcx>
}
impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> {
fn check_def_id(&self, span: Span, def_id: ast::DefId) {
if def_id.krat... | check | identifier_name |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
visit::walk_item(self, item);
}
}
| {
// Not an impl
} | conditional_block |
orphan.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
ast::ItemImpl(_, _, _, Some(_), _, _) => {
// "Trait" impl
debug!("coherence2::orphan check: trait impl {}", item.repr(self.tcx));
let trait_def_id = ty::impl_trait_ref(self.tcx, def_id).unwrap().def_id;
match traits::orphan_check... | implement a trait or new type instead");
}
} | random_line_split |
errors.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | (error: SQLError) -> MentatError {
MentatError::SQLError(error)
}
}
#[cfg(feature = "syncable")]
impl From<TolstoyError> for MentatError {
fn from(error: TolstoyError) -> MentatError {
MentatError::TolstoyError(error)
}
}
#[cfg(feature = "syncable")]
impl From<serde_json::Error> for Mentat... | from | identifier_name |
errors.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | MentatError::EdnParseError(error)
}
}
impl From<DbError> for MentatError {
fn from(error: DbError) -> MentatError {
MentatError::DbError(error)
}
}
impl From<AlgebrizerError> for MentatError {
fn from(error: AlgebrizerError) -> MentatError {
MentatError::AlgebrizerError(error)
... | random_line_split | |
errors.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
}
impl From<DbError> for MentatError {
fn from(error: DbError) -> MentatError {
MentatError::DbError(error)
}
}
impl From<AlgebrizerError> for MentatError {
fn from(error: AlgebrizerError) -> MentatError {
MentatError::AlgebrizerError(error)
}
}
impl From<ProjectorError> for MentatEr... | {
MentatError::EdnParseError(error)
} | identifier_body |
foo-test.js | /* jshint expr:true */ | import Ember from 'ember';
const {
run
} = Ember;
import { expect } from 'chai';
import { describeModel, it } from 'ember-mocha';
import { beforeEach } from 'mocha';
let store;
let m;
describeModel(
'parent',
'Unit | Model | foo',
{
// Specify the other units that are required for this test.
needs: ... | random_line_split | |
s3_assetstore_adapter.py | (upload))
if key.size < upload['size']:
bucket.delete_key(key)
raise ValidationException('Uploads of this length must be sent '
'in a single chunk.')
upload['received'] = key.size
return upload
def requestO... | continue | conditional_block | |
s3_assetstore_adapter.py | boto.s3.key.Key):
name = obj.name.rsplit('/', 1)[-1]
if not name:
continue
if parentType != 'folder':
raise ValidationException(
'Keys cannot be imported directly underneath a %s.' %
... | path = ''
if bucket:
path = '/' + bucket
return path + '/' + key | identifier_body | |
s3_assetstore_adapter.py | =0, headers=True, endByte=None,
contentDisposition=None, **kwargs):
"""
When downloading a single file with HTTP, we redirect to S3. Otherwise,
e.g. when downloading as part of a zip stream, we connect to S3 and
pipe the bytes from S3 through the server to the user a... | :param headers: if present, a dictionary of headers to encode in the
request. | random_line_split | |
s3_assetstore_adapter.py | name']
mime = file.get('mimeType') or ''
if key.content_type != mime or key.content_disposition != disp:
key.set_remote_metadata(metadata_plus={
'Content-Type': mime,
'Content-Disposition': disp.encode('utf8')
}, metadata_minus=[], preserve_acl=Tr... | _deleteFileImpl | identifier_name | |
default.py | import os,sys,urllib2
import xbmcplugin,xbmcgui
import xml.etree.ElementTree as ET
__addon__ = "SomaFM"
__addonid__ = "plugin.audio.somafm"
__version__ = "0.0.2"
def log(msg):
print "[PLUGIN] '%s (%s)' " % (__addon__, __version__) + str(msg)
log("Initialized!")
log(sys.argv)
rootURL = "http://soma... | (withReferrer=None):
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'
if withReferrer:
headers['Referrer'] = withReferrer
return headers
def getHTMLFor(url, withData=None, withReferrer=None):
url = rootUR... | getHeaders | identifier_name |
default.py | import os,sys,urllib2
import xbmcplugin,xbmcgui
import xml.etree.ElementTree as ET
__addon__ = "SomaFM"
__addonid__ = "plugin.audio.somafm"
__version__ = "0.0.2"
def log(msg):
print "[PLUGIN] '%s (%s)' " % (__addon__, __version__) + str(msg)
log("Initialized!")
log(sys.argv)
rootURL = "http://soma... |
def getHTMLFor(url, withData=None, withReferrer=None):
url = rootURL + url
log("Get HTML for URL: " + url)
req = urllib2.Request(url, withData, getHeaders(withReferrer))
response = urllib2.urlopen(req)
data = response.read()
response.close()
return data
def addEntries():
s... | headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'
if withReferrer:
headers['Referrer'] = withReferrer
return headers | identifier_body |
default.py | import os,sys,urllib2
import xbmcplugin,xbmcgui
import xml.etree.ElementTree as ET
__addon__ = "SomaFM"
__addonid__ = "plugin.audio.somafm"
__version__ = "0.0.2"
def log(msg):
print "[PLUGIN] '%s (%s)' " % (__addon__, __version__) + str(msg)
log("Initialized!")
log(sys.argv)
rootURL = "http://soma... |
addEntries()
xbmcplugin.endOfDirectory(handle)
| title = stations.find('title').text
description = stations.find('description').text
if stations.find('largeimage') is not None:
img = rootURL + stations.find('largeimage').text.replace(rootURL,"")
else:
img = rootURL + stations.find('image').text.replace(rootURL,"")
... | conditional_block |
default.py | import os,sys,urllib2
import xbmcplugin,xbmcgui
import xml.etree.ElementTree as ET
__addon__ = "SomaFM"
__addonid__ = "plugin.audio.somafm"
__version__ = "0.0.2"
def log(msg):
print "[PLUGIN] '%s (%s)' " % (__addon__, __version__) + str(msg)
log("Initialized!")
log(sys.argv)
rootURL = "http://soma... |
def getHeaders(withReferrer=None):
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'
if withReferrer:
headers['Referrer'] = withReferrer
return headers
def getHTMLFor(url, withData=None, withReferrer=None):
... | #pluginPath = sys.argv[0]
handle = int(sys.argv[1])
query = sys.argv[2]
| random_line_split |
incoming.rs | use super::{
limits::{channels_per_key::MaxChannelsPerKey, requests_per_channel::MaxRequestsPerChannel},
Channel,
};
use futures::prelude::*;
use std::{fmt, hash::Hash};
#[cfg(feature = "tokio1")]
use super::{tokio::TokioServerExecutor, Serve};
/// An extension trait for [streams](futures::prelude::Stream) of... |
/// [Executes](Channel::execute) each incoming channel. Each channel will be handled
/// concurrently by spawning on tokio's default executor, and each request will be also
/// be spawned on tokio's default executor.
#[cfg(feature = "tokio1")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio1")))]
... | {
MaxRequestsPerChannel::new(self, n)
} | identifier_body |
incoming.rs | use super::{
limits::{channels_per_key::MaxChannelsPerKey, requests_per_channel::MaxRequestsPerChannel},
Channel,
};
use futures::prelude::*;
use std::{fmt, hash::Hash};
#[cfg(feature = "tokio1")]
use super::{tokio::TokioServerExecutor, Serve};
/// An extension trait for [streams](futures::prelude::Stream) of... | where
Self: Sized + Stream<Item = C>,
C: Channel,
{
/// Enforces channel per-key limits.
fn max_channels_per_key<K, KF>(self, n: u32, keymaker: KF) -> MaxChannelsPerKey<Self, K, KF>
where
K: fmt::Display + Eq + Hash + Clone + Unpin,
KF: Fn(&C) -> K,
{
MaxChannelsPerKey::n... | random_line_split | |
incoming.rs | use super::{
limits::{channels_per_key::MaxChannelsPerKey, requests_per_channel::MaxRequestsPerChannel},
Channel,
};
use futures::prelude::*;
use std::{fmt, hash::Hash};
#[cfg(feature = "tokio1")]
use super::{tokio::TokioServerExecutor, Serve};
/// An extension trait for [streams](futures::prelude::Stream) of... | <S>(self, serve: S) -> TokioServerExecutor<Self, S>
where
S: Serve<C::Req, Resp = C::Resp>,
{
TokioServerExecutor::new(self, serve)
}
}
impl<S, C> Incoming<C> for S
where
S: Sized + Stream<Item = C>,
C: Channel,
{
}
| execute | identifier_name |
SvgViewBoxFilter.js | 'use strict';
/**
* Requirements
* @ignore
*/
const Filter = require('./Filter.js').Filter;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const pathes = require('../../utils/pathe... | ()
{
return 'nunjucks.filter/SvgViewBoxFilter';
}
/**
* @inheritDocs
*/
static get injections()
{
return { 'parameters': [PathesConfiguration, 'nunjucks.filter/SvgViewBoxFilter.basePath'] };
}
/**
* @type {String}
*/
get basePath()
{
re... | className | identifier_name |
SvgViewBoxFilter.js | 'use strict';
/**
* Requirements
* @ignore
*/
const Filter = require('./Filter.js').Filter;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const pathes = require('../../utils/pathe... |
return scope.applyCallbacks(result, arguments);
};
}
}
/**
* Exports
* @ignore
*/
module.exports.SvgViewBoxFilter = SvgViewBoxFilter;
| {
scope.logger.warn('Could not locate svg <' + filename + '>');
} | conditional_block |
SvgViewBoxFilter.js | 'use strict';
/**
* Requirements
* @ignore
*/
const Filter = require('./Filter.js').Filter;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const pathes = require('../../utils/pathe... | return 'nunjucks.filter/SvgViewBoxFilter';
}
/**
* @inheritDocs
*/
static get injections()
{
return { 'parameters': [PathesConfiguration, 'nunjucks.filter/SvgViewBoxFilter.basePath'] };
}
/**
* @type {String}
*/
get basePath()
{
return this... | /**
* @inheritDocs
*/
static get className()
{ | random_line_split |
SvgViewBoxFilter.js | 'use strict';
/**
* Requirements
* @ignore
*/
const Filter = require('./Filter.js').Filter;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const pathes = require('../../utils/pathe... |
/**
* @type {model.configuration.PathesConfiguration}
*/
get pathesConfiguration()
{
return this._pathesConfiguration;
}
/**
* @inheritDocs
*/
filter(value)
{
const scope = this;
return function(value)
{
let result = '0 0 0... | {
let result = this._basePath;
if (this.environment &&
this.environment.buildConfiguration)
{
result = this.environment.buildConfiguration.get('filters.svgPath', this._basePath);
}
return templateString(result, globals.location || {});
} | identifier_body |
resources.py |
import locale
import gettext
import profile
import ConfigParser as configparser
if sys.platform.startswith('darwin'):
try:
#Foundation import can crash on some MacOS installs
from Foundation import *
except:
pass
if sys.platform.startswith('darwin'):
if hasattr(sys, 'frozen'):
try:
resourceBasePath = ... | windll = ctypes.windll.kernel32
defaultLocale = locale.windows_locale[windll.GetUserDefaultUILanguage()]
except:
pass
if defaultLocale is None:
try:
defaultLocale = locale.getdefaultlocale()[0]
except:
pass
return defaultLocale
class ProfileIni(object):
@staticmethod
def str2bool(str):
ret... | try:
import ctypes
| random_line_split |
resources.py |
import locale
import gettext
import profile
import ConfigParser as configparser
if sys.platform.startswith('darwin'):
try:
#Foundation import can crash on some MacOS installs
from Foundation import *
except:
pass
if sys.platform.startswith('darwin'):
if hasattr(sys, 'frozen'):
try:
resourceBasePath = ... | (self, ini_file):
super(PrintMaterial, self).__init__(ini_file)
self.profiles = []
self.options = []
self.types = []
types = self._getProfileInfo(self.ini, 'material_types')
if types != None:
for type in types.split('|'):
self.types.append(type.strip())
# Comment for the profile
self.descriptio... | __init__ | identifier_name |
resources.py |
import locale
import gettext
import profile
import ConfigParser as configparser
if sys.platform.startswith('darwin'):
try:
#Foundation import can crash on some MacOS installs
from Foundation import *
except:
pass
if sys.platform.startswith('darwin'):
if hasattr(sys, 'frozen'):
try:
resourceBasePath = ... |
else:
return self.ini
def _getProfileInfo(self, ini_file, key):
cp = configparser.ConfigParser()
cp.read(ini_file)
disabled = False
if cp.has_option('info', key):
return cp.get('info', key)
return None
def _isInList(self, list):
""" Check if an option with the same base name already exists in... | return os.path.join(self.path, profile_file) | conditional_block |
resources.py |
import locale
import gettext
import profile
import ConfigParser as configparser
if sys.platform.startswith('darwin'):
try:
#Foundation import can crash on some MacOS installs
from Foundation import *
except:
pass
if sys.platform.startswith('darwin'):
if hasattr(sys, 'frozen'):
try:
resourceBasePath = ... |
def __cmp__(self, cmp):
if self.order < cmp.order:
return -1
elif self.order > cmp.order:
return 1
else:
if self.name < cmp.name:
return -1
elif self.name == cmp.name:
return 0
else:
return 1
def __str__ (self):
return "%s%s: %d" % (self.name, "(disabled)" if self.disabled else "... | profile_dict = {}
cp = configparser.ConfigParser()
cp.read(self.profile_file)
for setting in profile.settingsList:
section = 'profile' if setting.isProfile() else 'alterations'
if setting.isProfile() or setting.isAlteration():
if cp.has_option(section, setting.getName()):
profile_dict[setting.getNa... | identifier_body |
authenticator.service.ts | ///<reference path="../coreReferences.ts"/>
/**
* Created by Johanna on 2015-08-28.
*/
module Moosetrail.Core.Authentication {
export class Authenticator {
authData: Authentication.TokenAuthorization;
http: DataAccess.HttpDataFactory;
q: ng.IQService;
localStroage : ng.local.stor... | (): void {
this.authData = new TokenAuthorization("", null);
}
login(username: string, password: string): ng.IPromise<DataAccess.DataResult> {
var deferred = this.q.defer();
const data = `grant_type=password&username=${username}&password=${password}`;
co... | clearAuthData | identifier_name |
authenticator.service.ts | ///<reference path="../coreReferences.ts"/>
/**
* Created by Johanna on 2015-08-28.
*/
module Moosetrail.Core.Authentication {
export class Authenticator {
authData: Authentication.TokenAuthorization;
http: DataAccess.HttpDataFactory;
q: ng.IQService;
localStroage : ng.local.stor... | }
private clearAuthData(): void {
this.authData = new TokenAuthorization("", null);
}
login(username: string, password: string): ng.IPromise<DataAccess.DataResult> {
var deferred = this.q.defer();
const data = `grant_type=password&username=${usernam... | this.clearAuthData(); | random_line_split |
authenticator.service.ts | ///<reference path="../coreReferences.ts"/>
/**
* Created by Johanna on 2015-08-28.
*/
module Moosetrail.Core.Authentication {
export class Authenticator {
authData: Authentication.TokenAuthorization;
http: DataAccess.HttpDataFactory;
q: ng.IQService;
localStroage : ng.local.stor... | else {
authData.setRoles([UserRole.User]);
}
this.localStroage.set("authorizationData", authData);
this.setAuthData(authData);
def.resolve(result);
}
private setAuthData(authData : TokenAuthorization) {
this.authData = authDa... | {
authData.setRoles([UserRole.Admin, UserRole.User]);
} | conditional_block |
authenticator.service.ts | ///<reference path="../coreReferences.ts"/>
/**
* Created by Johanna on 2015-08-28.
*/
module Moosetrail.Core.Authentication {
export class Authenticator {
authData: Authentication.TokenAuthorization;
http: DataAccess.HttpDataFactory;
q: ng.IQService;
localStroage : ng.local.stor... |
private setAuthData(authData : TokenAuthorization) {
this.authData = authData;
}
private handleFailedLogin(reason: Core.DataAccess.DataResult, def: angular.IDeferred<Object>) {
this.logout();
def.reject(reason);
}
logout() {
thi... | {
const authData = new TokenAuthorization(username, result.data.access_token);
if (result.data.roles.indexOf("Admin") > -1) {
authData.setRoles([UserRole.Admin, UserRole.User]);
} else {
authData.setRoles([UserRole.User]);
}
... | identifier_body |
conf.py | All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import sphinx.environment
from docutils.utils import get_source_line
def _warn_node(self, msg, node):
if not msg.startswith('nonlocal image URI found:'):
self._warnfunc(ms... | # Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Speedcurvepy.tex', u'Speedcurve.py Documentation',
u'Matt C... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.