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 |
|---|---|---|---|---|
notifications.py | from code_intelligence import graphql
import fire
import github3
import json
import logging
import os
import numpy as np
import pprint
import retrying
import json
TOKEN_NAME_PREFERENCE = ["INPUT_GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_TOKEN"]
for token in TOKEN_NAME_PREFERENCE:
if os.... |
total_issues = None
has_next_issues_page = True
# TODO(jlewi): We should persist the cursors to disk so we can resume
# after errors
issues_cursor = None
while has_next_issues_page:
issues_cursor_text = ""
if issues_cursor:
issues_cursor_text = "after:\"{0}\"".format(issues... | os.makedirs(output) | conditional_block |
notifications.py | from code_intelligence import graphql
import fire
import github3
import json
import logging
import os
import numpy as np
import pprint
import retrying
import json
TOKEN_NAME_PREFERENCE = ["INPUT_GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_TOKEN"]
for token in TOKEN_NAME_PREFERENCE:
if os.... | with open(output, mode="w") as hf:
for n in notifications:
i += 1
hf.write(n.as_json())
hf.write("\n")
logging.info("Wrote %s notifications to %s", i, output)
def fetch_issues(self, org, repo, output):
"""Fetch issues for a repository
Args:
org: The org that own... | """Write all notifications to a file.
Args:
user: Name of the user to get notifications for
output: The file to write notifications to.
Fetches all notifications, including ones marked read,
and writes them to the supplied file.
"""
token = os.getenv(TOKEN_NAME)
if not token:
... | identifier_body |
notifications.py | from code_intelligence import graphql
import fire
import github3
import json
import logging
import os
import numpy as np
import pprint
import retrying
import json
TOKEN_NAME_PREFERENCE = ["INPUT_GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_TOKEN"]
for token in TOKEN_NAME_PREFERENCE:
if os.... | (self, org, repo, output):
"""Fetch issues for a repository
Args:
org: The org that owns the repository
repo: The directory for the repository
output: The directory to write the results
Writes the issues along with the first comments to a file in output
directory.
"""
client ... | fetch_issues | identifier_name |
evaluation.py | import logging
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
import matplotlib.pyplo... | cm = confusion_matrix(Y_true, Y_pred)
logging.info('Confusion Matrix:\n%s' % str(cm))
# fig = plt.figure()
# ax = fig.add_subplot(111)
# cax = ax.matshow(cm)
# fig.colorbar(cax)
#
# ax.set_xticklabels(['']+['-1', '0', '1'])
# ax.set_yticklabel... |
if classification:
report = classification_report(Y_true, Y_pred)
logging.info('Classification report:\n%s' % str(report))
| random_line_split |
evaluation.py | import logging
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
import matplotlib.pyplo... | else:
var = explained_variance_score(Y_true, Y_pred)
logging.info('Explained variance (best=1.0): %f' % var)
mae = mean_absolute_error(Y_true, Y_pred)
logging.info('Mean absolute error (best=0.0): %f' % mae)
mse = mean_squared_error(Y_true, Y_pred)
l... | if classification:
report = classification_report(Y_true, Y_pred)
logging.info('Classification report:\n%s' % str(report))
cm = confusion_matrix(Y_true, Y_pred)
logging.info('Confusion Matrix:\n%s' % str(cm))
# fig = plt.figure()
# ax = fig.add_subplot(111)
... | identifier_body |
evaluation.py | import logging
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
import matplotlib.pyplo... | (Y_true, Y_pred, classification=True):
if classification:
report = classification_report(Y_true, Y_pred)
logging.info('Classification report:\n%s' % str(report))
cm = confusion_matrix(Y_true, Y_pred)
logging.info('Confusion Matrix:\n%s' % str(cm))
# fig = plt.figur... | print_evaluations | identifier_name |
evaluation.py | import logging
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
import matplotlib.pyplo... |
else:
var = explained_variance_score(Y_true, Y_pred)
logging.info('Explained variance (best=1.0): %f' % var)
mae = mean_absolute_error(Y_true, Y_pred)
logging.info('Mean absolute error (best=0.0): %f' % mae)
mse = mean_squared_error(Y_true, Y_pred)
... | report = classification_report(Y_true, Y_pred)
logging.info('Classification report:\n%s' % str(report))
cm = confusion_matrix(Y_true, Y_pred)
logging.info('Confusion Matrix:\n%s' % str(cm))
# fig = plt.figure()
# ax = fig.add_subplot(111)
# cax = ax.matshow(cm)
... | conditional_block |
db.py | import contextlib
import logging
import os.path
import sqlalchemy
from sqlalchemy import schema as sql_schema
from sqlalchemy import types as sql_types
from sqlalchemy.ext import declarative as sql_declarative
from sqlalchemy.orm import session as sql_session
from dancebooks.config import config
_Base = sql_declarat... |
_engine = sqlalchemy.create_engine(
config.db.connection_url,
connect_args=config.db.options
)
_session_maker = sql_session.sessionmaker(bind=_engine)
@contextlib.contextmanager
def make_transaction():
try:
txn = _session_maker()
yield txn
except Exception:
logging.exception("Rolling session back due to ex... | return os.path.basename(self.path) | identifier_body |
db.py | import contextlib
import logging
import os.path
import sqlalchemy
from sqlalchemy import schema as sql_schema
from sqlalchemy import types as sql_types
from sqlalchemy.ext import declarative as sql_declarative
from sqlalchemy.orm import session as sql_session
from dancebooks.config import config
_Base = sql_declarat... | (_Base):
__tablename__ = "backups"
__table_args__ = {"schema": "service"}
id = sql_schema.Column(sql_types.BigInteger, primary_key=True)
path = sql_schema.Column(sql_types.String, nullable=False)
provenance = sql_schema.Column(sql_types.String, nullable=False)
aspect_ratio_x = sql_schema.Column(sql_types.BigInte... | Backup | identifier_name |
db.py | import contextlib
import logging
import os.path
import sqlalchemy
from sqlalchemy import schema as sql_schema
from sqlalchemy import types as sql_types
from sqlalchemy.ext import declarative as sql_declarative
from sqlalchemy.orm import session as sql_session
from dancebooks.config import config
_Base = sql_declarat... | config.db.connection_url,
connect_args=config.db.options
)
_session_maker = sql_session.sessionmaker(bind=_engine)
@contextlib.contextmanager
def make_transaction():
try:
txn = _session_maker()
yield txn
except Exception:
logging.exception("Rolling session back due to exception")
txn.rollback()
finally:
... |
_engine = sqlalchemy.create_engine( | random_line_split |
address.py | # -*- coding:Utf-8 -*-
from django.utils.translation import pgettext_lazy
from mongoengine import EmbeddedDocument, fields
__all__ = (
'Address',
)
class Address(EmbeddedDocument):
"""An address wrapper which can be embedded in any object."""
TYPES = (
("HOME", pgettext_lazy("address type", "H... | """
Returns a concatenated list of :class:`~contacts.models.Address` attributes:
- Street address
- Extended address, post office box
- Postal code, City
- State, Country
"""
ret = [
self.street_address,
Address.concat_fields(self.extended... | identifier_body | |
address.py | # -*- coding:Utf-8 -*-
from django.utils.translation import pgettext_lazy
from mongoengine import EmbeddedDocument, fields
__all__ = (
'Address',
)
class Address(EmbeddedDocument):
"""An address wrapper which can be embedded in any object."""
TYPES = (
("HOME", pgettext_lazy("address type", "H... | )
label = fields.StringField(max_length=64)
type = fields.StringField(choices=TYPES)
postoffice_box = fields.StringField(max_length=64)
street_address = fields.StringField(required=True, max_length=128)
extended_address = fields.StringField(max_length=128)
postal_code = fields.StringField(m... | ("DELIVERY", pgettext_lazy("address type", "Delivery")),
("BILLING", pgettext_lazy("address type", "Billing")),
("OTHER", pgettext_lazy("address type", "Other")) | random_line_split |
address.py | # -*- coding:Utf-8 -*-
from django.utils.translation import pgettext_lazy
from mongoengine import EmbeddedDocument, fields
__all__ = (
'Address',
)
class Address(EmbeddedDocument):
"""An address wrapper which can be embedded in any object."""
TYPES = (
("HOME", pgettext_lazy("address type", "H... |
if field1 and not field2:
return field1
if not field1 and field2:
return field2
if field1 and field2:
return ", ".join([field1, field2])
def get_formatted(self):
"""
Returns a concatenated list of :class:`~contacts.models.Address` attribu... | return None | conditional_block |
address.py | # -*- coding:Utf-8 -*-
from django.utils.translation import pgettext_lazy
from mongoengine import EmbeddedDocument, fields
__all__ = (
'Address',
)
class Address(EmbeddedDocument):
"""An address wrapper which can be embedded in any object."""
TYPES = (
("HOME", pgettext_lazy("address type", "H... | (self):
"""
Returns a concatenated list of :class:`~contacts.models.Address` attributes:
- Street address
- Extended address, post office box
- Postal code, City
- State, Country
"""
ret = [
self.street_address,
Address.concat_fiel... | get_formatted | identifier_name |
clock.component.ts | /*
## Homework 7 ##
Create root component container.
As its first child element create clock container(has clock but not show it).
As clock container timer child create show-time component (It shows time and has button - remember time).
As root container child create element time-capsule.
It can remember time from show... | (params: TimeParams) {
this.startTimer(5);
this.timestamp = params.time;
}
public ngOnInit(): void {
this.updateTime();
this.startTimer();
}
public rememberTime($event: boolean): void {
console.log(`clock emitTime ${$event}`);
this.rememberedTime.emit(this.time);
}
private startTi... | time | identifier_name |
clock.component.ts | /*
## Homework 7 ##
Create root component container.
As its first child element create clock container(has clock but not show it).
As clock container timer child create show-time component (It shows time and has button - remember time).
As root container child create element time-capsule.
It can remember time from show... | }
private startTimer(timeOut: number = 1): void {
clearTimeout(this.timer);
this.timer = window.setTimeout(() => {
this.updateTime();
this.startTimer();
}, timeOut * 1000);
}
private updateTime(): void {
this.timestamp = (new Date()).getTime();
}
public ngOnDestroy(): void {
... | random_line_split | |
profilehandler.py | import sys
import logging
import profile
import pstats
try:
import cStringIO as StringIO
StringIO # pyflakes
except ImportError:
import StringIO
from instrumenting import utils
class BaseProfilingHandler(utils.InstrumentingHandler):
"""
Python logging handler which profiles code.
It can al... | 'and stop for the same log message'
% self.profiler)
self.log(logging.INFO,
'Stopping profiler %r' % self.profiler)
import pdb; pdb.set_trace()
self.disable()
if not starte... | else:
if started:
self.log(logging.ERROR,
'Handler for profiler %r configured to start ' | random_line_split |
profilehandler.py | import sys
import logging
import profile
import pstats
try:
import cStringIO as StringIO
StringIO # pyflakes
except ImportError:
import StringIO
from instrumenting import utils
class BaseProfilingHandler(utils.InstrumentingHandler):
"""
Python logging handler which profiles code.
It can al... |
return stream.getvalues()
# Profiler specific support
def setUpProfiler(self):
"""Set up the selected profiler."""
raise NotImplemented
def enable(self):
raise NotImplemented
def disable(self):
raise NotImplemented
def running(self):
return isins... | getattr(stats, 'print_'+method)(*self.restriction) | conditional_block |
profilehandler.py | import sys
import logging
import profile
import pstats
try:
import cStringIO as StringIO
StringIO # pyflakes
except ImportError:
import StringIO
from instrumenting import utils
class BaseProfilingHandler(utils.InstrumentingHandler):
"""
Python logging handler which profiles code.
It can al... | hook = sys.getprofile()
return (hook is self.profiler.dispatcher
and isinstance(hook.im_self, type(self.profiler))) | identifier_body | |
profilehandler.py | import sys
import logging
import profile
import pstats
try:
import cStringIO as StringIO
StringIO # pyflakes
except ImportError:
import StringIO
from instrumenting import utils
class BaseProfilingHandler(utils.InstrumentingHandler):
"""
Python logging handler which profiles code.
It can al... | (self, stream):
if self.running():
self.log(logging.ERROR,
"Cannot get stats when the profiler from the "
"`profile` module is already running")
return None
import pdb; pdb.set_trace()
stats = pstats.Stats(self.profiler, stream=st... | get_stats | identifier_name |
language.py | __, 'ISO-639-2_utf-8.txt')
# drop the BOM from the beginning of the file
_iso639_contents = _iso639_contents[1:]
language_matrix = [ l.strip().split('|')
for l in _iso639_contents.strip().split('\n') ]
# update information in the language matrix
language_matrix += [['mol', '', 'mo', 'Moldavian',... | log.warning('Unrecognized scheme: "%s" - Proceeding with standard one' % scheme)
# look for ISO language codes
if len(language) == 2:
self.lang = lng2_to_lng3.get(language)
elif len(language) == 3:
self.lang = (language
if language in... | ge = u(language.strip().lower())
with_country = (Language._with_country_regexp.match(language) or
Language._with_country_regexp2.match(language))
if with_country:
self.lang = Language(with_country.group(1)).lang
self.country = Country(with_country.group(2)... | identifier_body |
language.py | __, 'ISO-639-2_utf-8.txt')
# drop the BOM from the beginning of the file
_iso639_contents = _iso639_contents[1:]
language_matrix = [ l.strip().split('|')
for l in _iso639_contents.strip().split('\n') ]
# update information in the language matrix
language_matrix += [['mol', '', 'mo', 'Moldavian',... | msg = 'The given string "%s" could not be identified as a language' % language
if self.lang is None and strict:
raise ValueError(msg)
if self.lang is None:
log.debug(msg)
self.lang = 'und'
@property
def alpha2(self):
return lng3_to_lng2[self.lan... | country = lng_exceptions[language]
self.lang = Language(lang).alpha3
self.country = Country(country) if country else None
| conditional_block |
language.py | __, 'ISO-639-2_utf-8.txt')
# drop the BOM from the beginning of the file
_iso639_contents = _iso639_contents[1:]
language_matrix = [ l.strip().split('|')
for l in _iso639_contents.strip().split('\n') ]
# update information in the language matrix
language_matrix += [['mol', '', 'mo', 'Moldavian',... | :
return lng3_to_lng_fr_name[self.lang]
@property
def opensubtitles(self):
if self.lang == 'por' and self.country and self.country.alpha2 == 'br':
return 'pob'
elif self.lang in ['gre', 'srp']:
return self.alpha3term
return self.alpha3
@property
... | _name(self) | identifier_name |
language.py | for en_name in l[3].split('; '))
# we only return the first given french name, hoping it is the most used one
lng3_to_lng_fr_name = dict((l[0], l[4].split('; ')[0])
for l in language_matrix if l[4])
lng_fr_name_to_lng3 = dict((fr_name.lower(), l[0])
... |
if lang_filter:
lang_filter = lang_set(lang_filter)
slow = ' %s ' % string.lower() | random_line_split | |
TextRank4Sentence.py | #-*- encoding:utf-8 -*-
'''
Created on Dec 1, 2014
@author: letian
'''
import networkx as nx
from Segmentation import Segmentation
import numpy as np
import math
class TextRank4Sentence(object):
def __init__(self, stop_words_file = None, delimiters='?!;?!。;…\n'):
'''
`stop_words_file`:默认值为None... | for index, _ in sorted_scores:
self.key_sentences.append(self.sentences[index])
# print '\n'.join(self.key_sentences)
def _get_similarity_standard(self, word_list1, word_list2):
'''
默认的用于计算两个句子相似度的函数。
word_list1, word_list2: 分别代表两个句子,都是由单词组成的列表
... | sorted_scores = sorted(scores.items(), key = lambda item: item[1], reverse=True)
# print sorted_scores
| conditional_block |
TextRank4Sentence.py | #-*- encoding:utf-8 -*-
'''
Created on Dec 1, 2014
@author: letian
'''
import networkx as nx
from Segmentation import Segmentation
import numpy as np
import math
class TextRank4Sentence(object):
def __init__(self, stop_words_file = None, delimiters='?!;?!。;…\n'):
'''
`stop_words_file`:默认值为None... | _tag_filter=True, lower=True, source = 'all_filters')
print '\n'.join(tr4s.get_key_sentences(num=1))
print '\n'.join(tr4s.sentences)
for wl in tr4s.words_no_filter:
print '[', ', \''.join(wl), ']'
print
for wl in tr4s.words_no_stop_words:
print '[', ', \''.join(wl), ']'
prin... | if count >= num:
break
if len(sentence) >= sentence_min_len:
result.append(sentence)
count += 1
return result
if __name__ == '__main__':
import codecs
# text = codecs.open('../text/03.txt', 'r', 'utf-8').read()
text = "这间酒店位于... | identifier_body |
TextRank4Sentence.py | #-*- encoding:utf-8 -*-
'''
Created on Dec 1, 2014
@author: letian
'''
import networkx as nx
from Segmentation import Segmentation
import numpy as np
import math
class TextRank4Sentence(object):
def | (self, stop_words_file = None, delimiters='?!;?!。;…\n'):
'''
`stop_words_file`:默认值为None,此时内部停止词表为空;可以设置为文件路径(字符串),将从停止词文件中提取停止词。
`delimiters`:默认值是`'?!;?!。;…\n'`,用来将文本拆分为句子。
self.sentences:由句子组成的列表。
self.words_no_filter:对sentences中每个句子分词而得到的两级列表。
self.words_no_sto... | __init__ | identifier_name |
TextRank4Sentence.py | #-*- encoding:utf-8 -*-
'''
Created on Dec 1, 2014
@author: letian
'''
import networkx as nx
from Segmentation import Segmentation
import numpy as np
import math
class TextRank4Sentence(object):
def __init__(self, stop_words_file = None, delimiters='?!;?!。;…\n'):
'''
`stop_words_file`:默认值为None... | self.sentences = None
self.words_no_filter = None # 2维列表
self.words_no_stop_words = None
self.words_all_filters = None
self.graph = None
self.key_sentences = None
def train(self, text, lower = False, speech_tag_filter=True,
source =... | self.words_no_stop_words:去掉words_no_filter中的停止词而得到的两级列表。
self.words_all_filters:保留words_no_stop_words中指定词性的单词而得到的两级列表。
'''
self.seg = Segmentation(stop_words_file=stop_words_file, delimiters=delimiters)
| random_line_split |
http_headers.rs | // Copyright 2020 Google LLC
//
// 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 ... | (&self) -> Option<ContextType> {
Some(ContextType::HttpContext)
}
fn create_http_context(&self, context_id: u32) -> Option<Box<dyn HttpContext>> {
Some(Box::new(HttpHeaders { context_id }))
}
}
struct HttpHeaders {
context_id: u32,
}
impl Context for HttpHeaders {}
impl HttpContext f... | get_type | identifier_name |
http_headers.rs | // Copyright 2020 Google LLC
//
// 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 ... | }
Action::Continue
}
fn on_log(&mut self) {
trace!("#{} completed.", self.context_id);
}
} | fn on_http_response_headers(&mut self, _: usize, _: bool) -> Action {
for (name, value) in &self.get_http_response_headers() {
trace!("#{} <- {}: {}", self.context_id, name, value); | random_line_split |
c.py |
''', re.VERBOSE)
c_funcptr_sig_re = re.compile(
r'''^([^(]+?) # return type
(\( [^()]+ \)) \s* # name in parentheses
\( (.*) \) # arguments
(\s+const)? $ # const specifier
''', re.VERBOSE)
c_funcptr_arg_sig_re = re.compile(
r'''^\s*([^(,]+?) # return t... | 'struct', '_Bool',
}
def _parse_type(self, node, ctype):
# type: (nodes.Element, str) -> None
# add cross-ref nodes for all words
for part in [_f for _f in wsplit_re.split(ctype) if _f]:
tnode = nodes.Text(part, part)
if part[0] in string.ascii_letters + ... | """
Description of a C language object.
"""
doc_field_types = [
TypedField('parameter', label=_('Parameters'),
names=('param', 'parameter', 'arg', 'argument'),
typerolename='type', typenames=('type',)),
Field('returnvalue', label=_('Returns'), has_arg=F... | identifier_body |
c.py |
''', re.VERBOSE)
c_funcptr_sig_re = re.compile(
r'''^([^(]+?) # return type
(\( [^()]+ \)) \s* # name in parentheses
\( (.*) \) # arguments
(\s+const)? $ # const specifier
''', re.VERBOSE)
c_funcptr_arg_sig_re = re.compile(
r'''^\s*([^(,]+?) # return t... |
def before_content(self):
# type: () -> None
self.typename_set = False
if self.name == 'c:type':
if self.names:
self.env.ref_context['c:type'] = self.names[0]
self.typename_set = True
def after_content(self):
# type: () -> None
... | self.indexnode['entries'].append(('single', indextext,
targetname, '', None)) | conditional_block |
c.py | arglist):
# type: (str) -> Iterator[str]
while True:
m = c_funcptr_arg_sig_re.match(arglist)
if m:
yield m.group()
arglist = c_funcptr_arg_sig_re.sub('', arglist)
if ',' in arglist:
_, arglist = arglist.split(',... | get_objects | identifier_name | |
c.py |
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import string
from docutils import nodes
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.locale import _
f... | sphinx.domains.c
~~~~~~~~~~~~~~~~
The C language domain. | random_line_split | |
rephistory.ts | import {ExerciseHistory} from "./exercisehistory";
/**
* Model for rep based history exercises
*/
export class RepHistory extends ExerciseHistory {
private static WEIGHT_BUFFER: number = 10;
private sets: number;
private reps: number;
private weight: number;
constructor(jsonObject: any) {
... |
public getHeight(): number {
return this.reps;
}
public setHeight(value: number): void {
this.reps = value;
}
public getWidth(): number {
return this.weight;
}
public setWidth(newValue: number): void {
this.weight = newValue;
}
public getWidthBuf... | {
this.sets = value;
} | identifier_body |
rephistory.ts | import {ExerciseHistory} from "./exercisehistory";
/**
* Model for rep based history exercises
*/
export class RepHistory extends ExerciseHistory {
private static WEIGHT_BUFFER: number = 10;
private sets: number;
private reps: number;
private weight: number;
constructor(jsonObject: any) {
... | (newValue: number): void {
this.weight = newValue;
}
public getWidthBuffer(): number {
return RepHistory.WEIGHT_BUFFER;
}
}
| setWidth | identifier_name |
rephistory.ts | import {ExerciseHistory} from "./exercisehistory";
/**
* Model for rep based history exercises
*/
export class RepHistory extends ExerciseHistory {
private static WEIGHT_BUFFER: number = 10;
private sets: number;
private reps: number;
private weight: number;
constructor(jsonObject: any) {
... |
public getWidth(): number {
return this.weight;
}
public setWidth(newValue: number): void {
this.weight = newValue;
}
public getWidthBuffer(): number {
return RepHistory.WEIGHT_BUFFER;
}
} | this.reps = value;
} | random_line_split |
handle-email.spec.js | import React from 'react';
import boom from 'boom';
import nodemailer from 'nodemailer';
import stubTransport from 'nodemailer-stub-transport';
import makeHandleEmail from '../handle-email';
describe('handle email requests', () => {
const subject = 'This is a test';
const testComponent = () => (
<mj-te... |
it('should reply success when email is sent', async () => {
const handleEmail = makeHandleEmail(
renderHTML,
() => Promise.resolve('bloop'),
testComponent,
subject
);
await handleEmail(request, reply);
expect(reply).toHaveBeenCalled(... | random_line_split | |
config.js | 'use strict';
var program = require('commander');
var Q = require('q');
var fs = require('fs');
var resolve = require('path').resolve;
var stat = Q.denodeify(fs.stat);
var readFile = Q.denodeify(fs.readFile);
var writeFile = Q.denodeify(fs.writeFile);
var assign = require('./util/assign');
program
.option('--get', ... | })
.catch(function () {
return Q.when(null);
})
.then(function (fileContent) {
fileContent = assign({}, fileContent && JSON.parse(fileContent.toString('utf8')));
if (selectedOpt === 'get') {
return fileContent[args[0]];
}
if (typeof args[1] !== 'undefined') {
fileContent[args[0]... | if (stat.isFile()) {
return readFile(resolve('./fxc.json'));
} | random_line_split |
config.js | 'use strict';
var program = require('commander');
var Q = require('q');
var fs = require('fs');
var resolve = require('path').resolve;
var stat = Q.denodeify(fs.stat);
var readFile = Q.denodeify(fs.readFile);
var writeFile = Q.denodeify(fs.writeFile);
var assign = require('./util/assign');
program
.option('--get', ... |
return arr;
}, [])[0];
if (!args.length) {
process.exit(1);
}
args = [];
args.push(program.args[0].replace(/=.*$/, ''));
args.push(program.args[0].replace(new RegExp(args[0] + '=?'), ''));
if (args[1] === '') {
args[1] = undefined;
}
stat(resolve('./fxc.json'))
.then(function (stat) {
if (stat.isFile... | {
arr.push(next);
} | conditional_block |
status.rs | #![feature(use_extern_macros)]
extern crate tapioca_testutil;
tapioca_testutil::infer_test_api!(httpbin);
use httpbin::redirect_to;
use httpbin::redirect_to::get::QueryParams;
#[test]
fn ok_err_matching() | }
#[test]
fn status_body_matching() {
let auth = httpbin::ServerAuth::new();
let query200 = QueryParams {
url: "http://httpbin.org/status/200".into(),
};
let query400 = QueryParams {
url: "http://httpbin.org/status/400".into(),
};
match redirect_to::get(&query200, auth) {
... | {
let auth = httpbin::ServerAuth::new();
let query200 = QueryParams {
url: "http://httpbin.org/status/200".into(),
};
let query400 = QueryParams {
url: "http://httpbin.org/status/400".into(),
};
match redirect_to::get(&query200, auth) {
Ok(_) => assert!(true),
... | identifier_body |
status.rs | #![feature(use_extern_macros)]
extern crate tapioca_testutil;
tapioca_testutil::infer_test_api!(httpbin);
use httpbin::redirect_to;
use httpbin::redirect_to::get::QueryParams;
#[test]
fn ok_err_matching() {
let auth = httpbin::ServerAuth::new();
let query200 = QueryParams {
url: "http://httpbin.org/... | () {
let auth = httpbin::ServerAuth::new();
let query200 = QueryParams {
url: "http://httpbin.org/status/200".into(),
};
let query400 = QueryParams {
url: "http://httpbin.org/status/400".into(),
};
match redirect_to::get(&query200, auth) {
Ok(response) => match respons... | status_body_matching | identifier_name |
status.rs | #![feature(use_extern_macros)]
extern crate tapioca_testutil;
tapioca_testutil::infer_test_api!(httpbin);
use httpbin::redirect_to;
use httpbin::redirect_to::get::QueryParams;
#[test]
fn ok_err_matching() {
let auth = httpbin::ServerAuth::new();
let query200 = QueryParams {
url: "http://httpbin.org/... | Ok(response) => match response.body() {
redirect_to::get::OkBody::Status200(_) => assert!(true),
_ => assert!(false),
},
Err(_) => assert!(false),
}
match redirect_to::get(&query400, auth) {
Ok(_) => assert!(false),
Err(response) => match response... | url: "http://httpbin.org/status/400".into(),
};
match redirect_to::get(&query200, auth) { | random_line_split |
timestamps_test.py | # Copyright 2011 Google Inc.
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the ho... | ts_file = open(ts_filename, 'r')
self.assertEqual('1970-01-01T00:00:01Z\n', ts_file.read())
if __name__ == '__main__':
unittest.main() | timestamps.WriteTimestamp(good_ts, ts_filename)
self.assertEqual(good_ts, timestamps.ReadTimestamp(ts_filename))
| random_line_split |
timestamps_test.py | # Copyright 2011 Google Inc.
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the ho... | unittest.main() | conditional_block | |
timestamps_test.py | # Copyright 2011 Google Inc.
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the ho... | (self):
# TZ=UTC date -d @1306428781
# Thu May 26 16:53:01 UTC 2011
ts_filename = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts_file.write('2011-05-26T16:53:01Z\n')
ts_file.close()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(time.gmtime(1306428781... | testReadTimestamp | identifier_name |
timestamps_test.py | # Copyright 2011 Google Inc.
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the ho... | ts_filename = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts_file.write('2011-05-26T16:53:01Z\n')
ts_file.close()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(time.gmtime(1306428781), ts)
def testReadTimestampInFuture(self):
ts_filename = os.path.joi... | def setUp(self):
super(TestTimestamps, self).setUp()
self.workdir = tempfile.mkdtemp()
def tearDown(self):
super(TestTimestamps, self).tearDown()
shutil.rmtree(self.workdir)
def testReadTimestamp(self):
ts_filename = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts... | identifier_body |
pilutil.py | """ Helpers for making some things in PIL easier """
from PIL import ImageDraw, ImageFont, ImageStat
from math import ceil
def drawTextWithBorder(draw, text, coords,
fontname="Impact", fontsize=80,
color="#fff", strokecolor="#000"): | """ Draw text with a border. Although PIL doesn't support this, it can be
faked by drawing the text in the border color, with offsets, and then
drawing the text in the center on top.
See http://stackoverflow.com/a/8050556/4414003 """
# 3 looks good for 80px font. This allows for adjusting proporti... | random_line_split | |
pilutil.py | """ Helpers for making some things in PIL easier """
from PIL import ImageDraw, ImageFont, ImageStat
from math import ceil
def drawTextWithBorder(draw, text, coords,
fontname="Impact", fontsize=80,
color="#fff", strokecolor="#000"):
""" Draw text with a border. Althou... | (im, text):
""" Label an image with a string in the bottom left, using a text color
that will ensure appropriate contrast. """
d = ImageDraw.Draw(im)
textsize = ImageFont.load_default().getsize(text)
coords = im.size[0] - textsize[0] - 5, im.size[1] - textsize[1] - 5
# Check color of image where... | labelImage | identifier_name |
pilutil.py | """ Helpers for making some things in PIL easier """
from PIL import ImageDraw, ImageFont, ImageStat
from math import ceil
def drawTextWithBorder(draw, text, coords,
fontname="Impact", fontsize=80,
color="#fff", strokecolor="#000"):
""" Draw text with a border. Althou... |
def findFontSize(text, width, font="Impact", margin=10):
""" Find the largest font size that will fit `text` onto `im`, given a
margin (in percent) that must be left around an image border. """
w = int(width * (1 - margin / 100.0 * 2)) # Width accounting for margin
wAt40 = ImageFont.truetype(font, 4... | """ Resize an image to be a specified width while keeping aspect ratio """
w, h = im.size
aspect = float(h) / float(w)
out = im.resize((width, int(width * aspect))) # Resize to fit width
return out | identifier_body |
pilutil.py | """ Helpers for making some things in PIL easier """
from PIL import ImageDraw, ImageFont, ImageStat
from math import ceil
def drawTextWithBorder(draw, text, coords,
fontname="Impact", fontsize=80,
color="#fff", strokecolor="#000"):
""" Draw text with a border. Althou... |
draw.text(coords, text, font=font, fill=color)
def labelImage(im, text):
""" Label an image with a string in the bottom left, using a text color
that will ensure appropriate contrast. """
d = ImageDraw.Draw(im)
textsize = ImageFont.load_default().getsize(text)
coords = im.size[0] - textsize[... | draw.text(c, text, font=font, fill=strokecolor) | conditional_block |
wheel.ts | ) {
//计算offsetTop,为计算触摸事件的offset使用
var target = event.currentTarget;
that.offsetTop = 0;
while (target){
that.offsetTop += target.offsetTop;
var target = target.parentElement;
}
var offsetY = event.touches ? event.... | ect'){
that.selectedValue = that.selectedValue[that.itemValueKey];
}
if(oldSelectedIndex != that.selectedIndex)
that.toggleSelected(that.selectedIndex, that.selectedValue);
}
};
//启动动画
... | conditional_block | |
wheel.ts | 事件使用
private isDraging = false;
constructor(picker: Picker, col: Col, option: IOptions, index: number){
super()
///////////////////主要属性
//picker对象
this.picker = picker;
//option对象
this.option = option;
//记录当前滚轮是容器中第几个滚轮
this.index = index... | this.setPrefix(col.prefix);
this.setOptions(col.options, null, true)
}
/**
* 开始拖拽
* @param {number} offsetY 当前用户手指(鼠标)的y坐标
*/
startDrag(offsetY: number) {
//记录触摸相关信息,为下一步计算用.计算时候,要将坐标系移至中心,并将单位转为em
this.lastY = (constant.WHEEL_HEIGHT / 2 - offsetY / this.em... | this.setSuffix(col.suffix); | random_line_split |
wheel.ts | 事件使用
private isDraging = false;
constructor(picker: Picker, col: Col, option: IOptions, index: number){
super()
///////////////////主要属性
//picker对象
this.picker = picker;
//option对象
this.option = option;
//记录当前滚轮是容器中第几个滚轮
this.index = index... | * @param {*} selectedValue 默认值
* @param {boolean} [isInti=false] 是否是初始化,初始化不执行设置默认值操作
*/
setOptions(list: any[], selectedValue: any, isInti: boolean = false) {
var that = this;
list = list || [];
if(Array.isArray(list)){
//清空容器
that.co... | 4是根据偏移效果经验得到的
var changeDistance = this.speed * Math.abs( this.speed) * 8 * constant.WHEEL_TRANSITION_TIME;
var distance = changeDistance + this.distance;
//根据位移计算最终的被选值
var selectedIndex = this.calcSelectedIndexByDistance(distance);
//开启动画,选中被选中
this.selectIndex(select... | identifier_body |
wheel.ts | 事件使用
private isDraging = false;
constructor(picker: Picker, col: Col, option: IOptions, index: number){
super()
///////////////////主要属性
//picker对象
this.picker = picker;
//option对象
this.option = option;
//记录当前滚轮是容器中第几个滚轮
this.index = index... | 开始拖拽
* @param {number} offsetY 当前用户手指(鼠标)的y坐标
*/
startDrag(offsetY: number) {
//记录触摸相关信息,为下一步计算用.计算时候,要将坐标系移至中心,并将单位转为em
this.lastY = (constant.WHEEL_HEIGHT / 2 - offsetY / this.em()) * -1 ;
this.timeStamp = Date.now();
this.isDraging = true;
this.offsetTop = thi... | * | identifier_name |
data-store.ts | string): Promise<DataHandleRead | null> {
const data = this.handles.filter(x => x.key === key)[0];
return data || null;
}
}
export abstract class DataStoreView extends DataStoreViewReadonly {
public abstract get BaseUri(): string;
public abstract Write(key: string): Promise<DataHandleWrite>;
public ... | {
return await this.write(data, sourceMapFactory);
} | identifier_body | |
data-store.ts | : string]: Data };
/********************************************
* Central data controller
* - one stop for creating data
* - ensures WRITE ONCE model
********************************************/
export abstract class DataStoreViewReadonly {
public abstract Enum(): Promise<string[]>;
public abstract Read(ur... | CreateInputSourceMapFor | identifier_name | |
data-store.ts | : string]: Data };
/********************************************
* Central data controller
* - one stop for creating data
* - ensures WRITE ONCE model
********************************************/
export abstract class DataStoreViewReadonly {
public abstract Enum(): Promise<string[]>;
public abstract Read(ur... | }
public Blame(absoluteUri: string, position: SmartPosition): BlameTree {
const data = this.ReadStrictSync(absoluteUri);
const resolvedPosition = CompilePosition(position, data);
return BlameTree.Create(this, {
source: absoluteUri,
column: resolvedPosition.column,
line: resolvedPositi... | public async Enum(): Promise<string[]> {
return Object.getOwnPropertyNames(this.store); | random_line_split |
data-store.ts | : string]: Data };
/********************************************
* Central data controller
* - one stop for creating data
* - ensures WRITE ONCE model
********************************************/
export abstract class DataStoreViewReadonly {
public abstract Enum(): Promise<string[]>;
public abstract Read(ur... |
// populate cache
let data: string | null = null;
try {
data = await this.fs.ReadFile(uri) || await ReadUri(uri);
} finally {
if (!data) {
return null;
}
}
const writeHandle = await this.slave.Write(uri);
const readHandle = await writeHandle.WriteData(data);
t... | {
this.uris.push(uri);
return existingData;
} | conditional_block |
upload.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dropbox upload daemon.
"""
from fnmatch import fnmatch
from operator import itemgetter
from os import listdir, path, mknod, stat
from time import strptime, sleep, time
from dropbox.client import DropboxClient, DropboxOAuth2FlowNoRedirect
from dropbox.rest import ... | except KeyboardInterrupt:
print()
except SystemExit:
pass
finally:
print("No longer uploading from {} to Dropbox.".format(self.directory), flush=True)
if __name__ == '__main__':
my_daemon = UploadDaemon(settings.config.working_dir)
init(my_daemon)
| f._upload(client)
files = self._get(client)
if files is not None:
self._rotate(client, files)
print("Going idle...", end='', flush=True)
sleep(2 * 60)
print("DONE", flush=True)
| conditional_block |
upload.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dropbox upload daemon.
"""
from fnmatch import fnmatch
from operator import itemgetter
from os import listdir, path, mknod, stat
from time import strptime, sleep, time
from dropbox.client import DropboxClient, DropboxOAuth2FlowNoRedirect
from dropbox.rest import ... | ient: DropboxClient) -> list:
""" Get files from Dropbox.
"""
try:
metadata = client.metadata('/')
except (MaxRetryError, ErrorResponse):
return None
return [
{
'file': m['path'],
'modified': strptime(m['modi... | t(cl | identifier_name |
upload.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dropbox upload daemon.
"""
from fnmatch import fnmatch
from operator import itemgetter
from os import listdir, path, mknod, stat
from time import strptime, sleep, time
from dropbox.client import DropboxClient, DropboxOAuth2FlowNoRedirect
from dropbox.rest import ... | print("No longer uploading from {} to Dropbox.".format(self.directory), flush=True)
if __name__ == '__main__':
my_daemon = UploadDaemon(settings.config.working_dir)
init(my_daemon) | except KeyboardInterrupt:
print()
except SystemExit:
pass
finally: | random_line_split |
upload.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dropbox upload daemon.
"""
from fnmatch import fnmatch
from operator import itemgetter
from os import listdir, path, mknod, stat
from time import strptime, sleep, time
from dropbox.client import DropboxClient, DropboxOAuth2FlowNoRedirect
from dropbox.rest import ... | def _upload(self, client: DropboxClient):
""" Upload new files from directory.
"""
now = time()
for filename in listdir(self.directory):
if fnmatch(filename, '*.upl'):
continue
local_name = '/' + filename
full_name = path.join(se... | Get files from Dropbox.
"""
try:
metadata = client.metadata('/')
except (MaxRetryError, ErrorResponse):
return None
return [
{
'file': m['path'],
'modified': strptime(m['modified'], '%a, %d %b %Y %H:%M:%S %z'),
... | identifier_body |
Logo.py | #
# ttkiosk - table tennis club touch screen based kiosk.
# Copyright (C) 2009 Sergey Satskiy
#
# 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 2
# of the License, or (at your op... | # Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
#
# $Id$
#
# Generated by PyQt4 UI code generator 4.5.4 and then customized
#
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL
import ui
from utils import debugMsg, GlobalData
class ClickableLogoLabel( QtGui.QLabel ):... | # along with this program; if not, write to the Free Software | random_line_split |
Logo.py | #
# ttkiosk - table tennis club touch screen based kiosk.
# Copyright (C) 2009 Sergey Satskiy
#
# 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 2
# of the License, or (at your op... | def __init__(self, path, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.path = path
self.setupUi(self, path)
self.connect( GlobalData().application,
SIGNAL( "connectionStatus" ),
self.onConnectionChanged... | identifier_body | |
Logo.py | #
# ttkiosk - table tennis club touch screen based kiosk.
# Copyright (C) 2009 Sergey Satskiy
#
# 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 2
# of the License, or (at your op... | ( QtGui.QLabel ):
""" The class is only for the club logo label """
def __init__( self, firstLabel ):
QtGui.QLabel.__init__( self, firstLabel )
def mouseReleaseEvent( self, event ):
""" go home """
ui.navigateHome()
if GlobalData().isAdmin:
ui.hideForm( 'TopBar... | ClickableLogoLabel | identifier_name |
Logo.py | #
# ttkiosk - table tennis club touch screen based kiosk.
# Copyright (C) 2009 Sergey Satskiy
#
# 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 2
# of the License, or (at your op... |
else:
pictureName = path + 'warning.png'
self.logoPicture.setPixmap(QtGui.QPixmap(pictureName))
return
class Logo(QtGui.QWidget, Ui_Logo):
def __init__(self, path, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.path = pat... | pictureName = path + 'logo.gif' | conditional_block |
project-fn-ret-contravariant.rs | // Copyright 2012 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 ... |
//[ok]~^ ERROR compilation successful
//[oneuse]~^^ ERROR compilation successful
| { } | identifier_body |
project-fn-ret-contravariant.rs | // Copyright 2012 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 ... | <'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, y);
let b = bar(foo, x);
(a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623]
//[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623]
}
#[rustc_error]
fn main() { }
//[ok]~^ ERROR compilation successful
//[oneuse]~^... | transmute | identifier_name |
project-fn-ret-contravariant.rs | // Copyright 2012 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 ... | fn main() { }
//[ok]~^ ERROR compilation successful
//[oneuse]~^^ ERROR compilation successful | (a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623]
//[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623]
}
#[rustc_error] | random_line_split |
virtual_hardware_option.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualHardwareOption(vim, *args, **kwargs):
| if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
| '''The VirtualHardwareOption data object contains the options available for all
virtual devices.'''
obj = vim.client.factory.create('ns0:VirtualHardwareOption')
# do some validation checking...
if (len(args) + len(kwargs)) < 14:
raise IndexError('Expected at least 15 arguments got: %d' % l... | identifier_body |
virtual_hardware_option.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def | (vim, *args, **kwargs):
'''The VirtualHardwareOption data object contains the options available for all
virtual devices.'''
obj = vim.client.factory.create('ns0:VirtualHardwareOption')
# do some validation checking...
if (len(args) + len(kwargs)) < 14:
raise IndexError('Expected at lea... | VirtualHardwareOption | identifier_name |
virtual_hardware_option.py | import logging |
log = logging.getLogger(__name__)
def VirtualHardwareOption(vim, *args, **kwargs):
'''The VirtualHardwareOption data object contains the options available for all
virtual devices.'''
obj = vim.client.factory.create('ns0:VirtualHardwareOption')
# do some validation checking...
if (len(args) +... | from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
######################################## | random_line_split |
virtual_hardware_option.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualHardwareOption(vim, *args, **kwargs):
'''The VirtualHardwareOption data object... |
required = [ 'deviceListReadonly', 'hwVersion', 'memoryMB', 'numCoresPerSocket', 'numCPU',
'numCpuReadonly', 'numIDEControllers', 'numPCIControllers',
'numPS2Controllers', 'numSIOControllers', 'numUSBControllers',
'numUSBXHCIControllers', 'resourceConfigOption', 'virtualDeviceOption' ]
... | raise IndexError('Expected at least 15 arguments got: %d' % len(args)) | conditional_block |
plugin_class.rs | use node::inner_node::node_from_ptr;
use node::{String, Uri};
use world::World;
#[derive(Clone)]
pub struct PluginClass<'w> {
pub(crate) ptr: *const ::lilv_sys::LilvPluginClass,
pub(crate) world: &'w World,
}
impl<'w> PluginClass<'w> {
pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &Wor... | (&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) }
}
pub fn uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) }
}
pub fn label(&self) -> &String<'w> {
unsafe { node_from_ptr(::lil... | parent_uri | identifier_name |
plugin_class.rs | use node::inner_node::node_from_ptr;
use node::{String, Uri};
use world::World;
#[derive(Clone)]
pub struct PluginClass<'w> {
pub(crate) ptr: *const ::lilv_sys::LilvPluginClass,
pub(crate) world: &'w World,
}
impl<'w> PluginClass<'w> {
pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &Wor... |
pub fn parent_uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) }
}
pub fn uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) }
}
pub fn label(&self) -> &String<'w> {
unsaf... | {
PluginClass { ptr, world }
} | identifier_body |
plugin_class.rs | use node::inner_node::node_from_ptr;
use node::{String, Uri};
use world::World;
#[derive(Clone)]
pub struct PluginClass<'w> {
pub(crate) ptr: *const ::lilv_sys::LilvPluginClass,
pub(crate) world: &'w World,
}
impl<'w> PluginClass<'w> { | unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) }
}
pub fn uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) }
}
pub fn label(&self) -> &String<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_cla... | pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &World) -> PluginClass {
PluginClass { ptr, world }
}
pub fn parent_uri(&self) -> &Uri<'w> { | random_line_split |
tree.rs | use std::io::{File, BufReader};
use std::container::Container;
use std::io::{BufferedWriter};
use std::fmt::{Show, Formatter, FormatError}; | pub trait TreeNode : Show {
fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>;
}
#[deriving(PartialEq,Eq)]
pub struct Tree<I> {
instructions: Vec<I>,
}
pub struct TreeIterator<'a, I> {
tree: &'a Tree<I>,
i: uint,
}
impl<I: TreeNode> Tree<I> {
pub fn new() -> Tree<I> {
... | use syntax::tokenize::{Tokenizer};
use result::BancResult;
| random_line_split |
tree.rs | use std::io::{File, BufReader};
use std::container::Container;
use std::io::{BufferedWriter};
use std::fmt::{Show, Formatter, FormatError};
use syntax::tokenize::{Tokenizer};
use result::BancResult;
pub trait TreeNode : Show {
fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>;
}
#[deri... |
}
| {
for inst in self.instructions.iter() {
inst.fmt(formatter);
formatter.write_char('\n');
}
Ok(())
} | identifier_body |
tree.rs | use std::io::{File, BufReader};
use std::container::Container;
use std::io::{BufferedWriter};
use std::fmt::{Show, Formatter, FormatError};
use syntax::tokenize::{Tokenizer};
use result::BancResult;
pub trait TreeNode : Show {
fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>;
}
#[deri... | (file: File) -> BancResult<Tree<I>> {
let mut tokenizer = Tokenizer::<File>::from_file(file);
Tree::parse(&mut tokenizer)
}
pub fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Tree<I>> {
let mut tree = Tree::new();
while ! tokenizer.eof() {
let node: ... | parse_file | identifier_name |
demo.js | : availableTags
});
$("#mws-jui-dialog").dialog({
autoOpen: false,
title: "jQuery-UI Dialog",
modal: true,
width: "640",
buttons: [{
text: "Close Dialog",
click: function() {
$( this ).dialog( "close" );
}}]
});
$("#mws-form-dialog").dialog({
autoOpen: false,
title: "jQuery-UI... | {
$("#mws-wizard-form").mwsWizard({
forwardOnly: false,
onLeaveStep: function(index, elem) {
return v.form();
},
onBeforeSubmit: function() {
return v.form();
}
});
} | conditional_block | |
demo.js | mws-dtpicker").datetimepicker();
$(".mws-tpicker").timepicker({});
$(".mws-slider").slider({range: "min"});
$(".mws-progressbar").progressbar({value: 37});
$(".mws-range-slider").slider({range: true, min:0, max: 500, values: [75, 300]});
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
... | }
},
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("#mws-validate-error").html(message).show(... | spinner: {
required: true,
max: 5 | random_line_split |
wizards-tower.ts | /**
* Copyright (c) 2017 Virtue Studios
*
* Permission is hereby granted, free of charge, to any person obtaining a copy | * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright noti... | * of this software and associated documentation files (the "Software"), to deal | random_line_split |
delete_user_form.py | # -*- coding: utf-8 -*-
from django import forms
from datetime import date
from dateutil.relativedelta import *
from django.contrib.auth.models import User
from custom_form_app.forms.base_form_class import *
from account_app.models import *
from website.exceptions import *
import logging, sys
# force utf8 read data
r... |
def form_actions(self):
"""Function to perform form actions"""
return_var = False
# delete user and related data
if self.delete_user():
return_var = True
return return_var
| """Function to delete user"""
return_var = False
logged_user_id = self.request_data.user.id
user_id = self.form_validated_data.get("user_id")
account_obj = Account()
try:
account_obj.delete_user(user_id=user_id, logged_user_id=logged_user_id)
except UserDelete... | identifier_body |
delete_user_form.py | # -*- coding: utf-8 -*-
from django import forms
from datetime import date
from dateutil.relativedelta import *
from django.contrib.auth.models import User
from custom_form_app.forms.base_form_class import *
from account_app.models import *
from website.exceptions import *
import logging, sys
# force utf8 read data
r... | # parent forms.Form init
super(DeleteUserForm, self).__init__(*args, **kwargs)
FormCommonUtils.__init__(self)
# current form instance
self.validation_form = super(DeleteUserForm, self)
def clean(self):
super(DeleteUserForm, self).clean_form_custom()
return True
def d... | 'check_all_fields_valid',
)
def __init__(self, *args, **kwargs): | random_line_split |
delete_user_form.py | # -*- coding: utf-8 -*-
from django import forms
from datetime import date
from dateutil.relativedelta import *
from django.contrib.auth.models import User
from custom_form_app.forms.base_form_class import *
from account_app.models import *
from website.exceptions import *
import logging, sys
# force utf8 read data
r... | (forms.Form, FormCommonUtils):
user_id = forms.IntegerField(label='User id', required=True)
# list of validator for this form
custom_validation_list = (
'check_all_fields_valid',
)
def __init__(self, *args, **kwargs):
# parent forms.Form init
super(DeleteUserForm, self).__... | DeleteUserForm | identifier_name |
delete_user_form.py | # -*- coding: utf-8 -*-
from django import forms
from datetime import date
from dateutil.relativedelta import *
from django.contrib.auth.models import User
from custom_form_app.forms.base_form_class import *
from account_app.models import *
from website.exceptions import *
import logging, sys
# force utf8 read data
r... |
return return_var
def form_actions(self):
"""Function to perform form actions"""
return_var = False
# delete user and related data
if self.delete_user():
return_var = True
return return_var
| return_var = True | conditional_block |
api.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/toPromise';
import { CookieService } from 'angular2-cookie/services/cookies.service';
@Injectable()
export class ApiService {
constructor(... | .catch(this.handleError);
}
post(path, data): Promise<any> {
let headers = new Headers()
headers.append('X-4S-Token', this.token())
return this.http.post(this.apiRoot + path, data, { headers: headers })
.toPromise()
.then(response => response.json())
.catch(this.handleError);
... | .toPromise()
.then(response => response.json()) | random_line_split |
api.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/toPromise';
import { CookieService } from 'angular2-cookie/services/cookies.service';
@Injectable()
export class ApiService {
constructor(... |
}
| {
console.error(error.message || error);
return Promise.reject(error.message || error);
} | identifier_body |
api.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/toPromise';
import { CookieService } from 'angular2-cookie/services/cookies.service';
@Injectable()
export class ApiService {
constructor(... | (path): Promise<any> {
let headers = new Headers()
headers.append('X-4S-Token', this.token())
return this.http.get(this.apiRoot + path, { headers: headers })
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
post(path, data): Promise<any> {
let headers = ... | get | identifier_name |
ToggleSwitch.js | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import uniqueId from 'lodash/uniqueId';
import WixComponent from '../BaseComponents/WixComponent';
import styles from './ToggleSwitch.scss';
/**
* Controlled switch
*/
class ToggleSwitch extends WixComponent {
co... | () {
const {checked, onChange, size, disabled} = this.props;
const id = this.id;
const rootClassName = classnames(styles.toggleSwitch, {
[styles.toggleSwitchSmall]: size === 'small',
[styles.toggleSwitchXSmall]: size === 'x-small',
[styles.disabled]: disabled
});
const outerLabel ... | render | identifier_name |
ToggleSwitch.js | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import uniqueId from 'lodash/uniqueId';
import WixComponent from '../BaseComponents/WixComponent';
import styles from './ToggleSwitch.scss';
/**
* Controlled switch
*/ | constructor(params) {
super(params);
this.id = uniqueId();
}
render() {
const {checked, onChange, size, disabled} = this.props;
const id = this.id;
const rootClassName = classnames(styles.toggleSwitch, {
[styles.toggleSwitchSmall]: size === 'small',
[styles.toggleSwitchXSmall]: si... | class ToggleSwitch extends WixComponent { | random_line_split |
application-model.js | import { Class, Enum } from 'meteor/jagi:astronomy'
import 'jagi:astronomy-timestamp-behavior'
export const ApplicationStatus = Enum.create({
name: 'ApplicationStatus',
identifiers: {
DRAFT: 0,
ACTIVE: 1,
INACTIVE: 2
}
})
export const Application = Class.create({
name: 'Application',
collection:... | userId: String,
status: {
type: ApplicationStatus,
default: ApplicationStatus.DRAFT
}
},
behaviors: {
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
},
timestamp: {
hasCreatedField: true,
createdFi... | optional: true,
validators: [{
type: 'maxLength', param: 500, message: 'application_description_max_length'
}]
}, | random_line_split |
filemanager_thread.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 ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Debug, Deserialize, Serialize)]... | #[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(IpcSender<FileManagerResult<Vec<SelectedFi... | // https://w3c.github.io/FileAPI/#dfn-type
pub type_string: String,
}
| random_line_split |
filemanager_thread.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 ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Debug, Deserialize, Serialize)]... | {
pub id: Uuid,
pub filename: PathBuf,
pub modified: u64,
// https://w3c.github.io/FileAPI/#dfn-type
pub type_string: String,
}
#[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(IpcSender<Fi... | SelectedFile | identifier_name |
project_task.py | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api, fields
class ProjectTask(models.Model):
... |
childs = []
copy_data_default['project_id'] = self.subtask_project_id.id
for child in self.template_task_id.child_ids:
childs.append((0, 0, child.copy_data(copy_data_default)[0]))
self.child_ids = childs
# We overwrite this function because it is not possible to inheri... | self[k] = v | conditional_block |
project_task.py | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api, fields
class ProjectTask(models.Model):
... | (self):
if not self.template_task_id:
return
copy_data_default = {
'project_id': self.project_id.id,
'partner_id': self.partner_id.id,
'company_id': self.company_id.id,
'child_ids': False,
}
data = self.template_task_id.copy_dat... | onchange_template | identifier_name |
project_task.py | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api, fields
class ProjectTask(models.Model):
... | @api.onchange('template_task_id')
def onchange_template(self):
if not self.template_task_id:
return
copy_data_default = {
'project_id': self.project_id.id,
'partner_id': self.partner_id.id,
'company_id': self.company_id.id,
'child_ids':... | _inherit = 'project.task'
template_task = fields.Boolean(
copy=False,
string="Is task template?",
)
template_task_id = fields.Many2one(
'project.task',
compute="_compute_template_task_id",
domain=[('template_task', '=', True)],
string='Template Task',
... | identifier_body |
project_task.py | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api, fields
class ProjectTask(models.Model):
... | ('stage_id', '=', False)]) | random_line_split | |
gzip_util.py | import zlib
import struct
import time
def parse_encoding_header(header):
"""
Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form,
{'encoding-name':qvalue}.
"""
encodings = {'identity':1.0}
for encoding in header.split(","):
if(encoding.find(";") > -1):
encodi... |
else:
encodings[encoding] = 1
return encodings
def gzip_requested(accept_encoding_header):
"""
Check to see if the client can accept gzipped output, and whether or
not it is even the preferred method. If `identity` is higher, then no
gzipping should occur.
"""
encodin... | encodings[encoding] = 1 | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.